1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.18.2.  By combining all the individual C code files into this
4** single large file, the entire code can be compiled as a single translation
5** unit.  This allows many compilers to do optimizations that would not be
6** possible if the files were compiled separately.  Performance improvements
7** of 5% or more are commonly seen when SQLite is compiled as a single
8** translation unit.
9**
10** This file is all you need to compile SQLite.  To use SQLite in other
11** programs, you need this file and the "sqlite3.h" header file that defines
12** the programming interface to the SQLite library.  (If you do not have
13** the "sqlite3.h" header file at hand, you will find a copy embedded within
14** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15** of the embedded sqlite3.h header file.) Additional code files may be needed
16** if you want a wrapper to interface SQLite with your choice of programming
17** language. The code for the "sqlite3" command-line shell is also in a
18** separate file. This file contains only code for the core SQLite library.
19*/
20#define SQLITE_CORE 1
21#define SQLITE_AMALGAMATION 1
22#ifndef SQLITE_PRIVATE
23# define SQLITE_PRIVATE static
24#endif
25/************** Begin file sqliteInt.h ***************************************/
26/*
27** 2001 September 15
28**
29** The author disclaims copyright to this source code.  In place of
30** a legal notice, here is a blessing:
31**
32**    May you do good and not evil.
33**    May you find forgiveness for yourself and forgive others.
34**    May you share freely, never taking more than you give.
35**
36*************************************************************************
37** Internal interface definitions for SQLite.
38**
39*/
40#ifndef SQLITEINT_H
41#define SQLITEINT_H
42
43/* Special Comments:
44**
45** Some comments have special meaning to the tools that measure test
46** coverage:
47**
48**    NO_TEST                     - The branches on this line are not
49**                                  measured by branch coverage.  This is
50**                                  used on lines of code that actually
51**                                  implement parts of coverage testing.
52**
53**    OPTIMIZATION-IF-TRUE        - This branch is allowed to alway be false
54**                                  and the correct answer is still obtained,
55**                                  though perhaps more slowly.
56**
57**    OPTIMIZATION-IF-FALSE       - This branch is allowed to alway be true
58**                                  and the correct answer is still obtained,
59**                                  though perhaps more slowly.
60**
61**    PREVENTS-HARMLESS-OVERREAD  - This branch prevents a buffer overread
62**                                  that would be harmless and undetectable
63**                                  if it did occur.
64**
65** In all cases, the special comment must be enclosed in the usual
66** slash-asterisk...asterisk-slash comment marks, with no spaces between the
67** asterisks and the comment text.
68*/
69
70/*
71** Make sure the Tcl calling convention macro is defined.  This macro is
72** only used by test code and Tcl integration code.
73*/
74#ifndef SQLITE_TCLAPI
75#  define SQLITE_TCLAPI
76#endif
77
78/*
79** Make sure that rand_s() is available on Windows systems with MSVC 2005
80** or higher.
81*/
82#if defined(_MSC_VER) && _MSC_VER>=1400
83#  define _CRT_RAND_S
84#endif
85
86/*
87** Include the header file used to customize the compiler options for MSVC.
88** This should be done first so that it can successfully prevent spurious
89** compiler warnings due to subsequent content in this file and other files
90** that are included by this file.
91*/
92/************** Include msvc.h in the middle of sqliteInt.h ******************/
93/************** Begin file msvc.h ********************************************/
94/*
95** 2015 January 12
96**
97** The author disclaims copyright to this source code.  In place of
98** a legal notice, here is a blessing:
99**
100**    May you do good and not evil.
101**    May you find forgiveness for yourself and forgive others.
102**    May you share freely, never taking more than you give.
103**
104******************************************************************************
105**
106** This file contains code that is specific to MSVC.
107*/
108#ifndef SQLITE_MSVC_H
109#define SQLITE_MSVC_H
110
111#if defined(_MSC_VER)
112#pragma warning(disable : 4054)
113#pragma warning(disable : 4055)
114#pragma warning(disable : 4100)
115#pragma warning(disable : 4127)
116#pragma warning(disable : 4130)
117#pragma warning(disable : 4152)
118#pragma warning(disable : 4189)
119#pragma warning(disable : 4206)
120#pragma warning(disable : 4210)
121#pragma warning(disable : 4232)
122#pragma warning(disable : 4244)
123#pragma warning(disable : 4305)
124#pragma warning(disable : 4306)
125#pragma warning(disable : 4702)
126#pragma warning(disable : 4706)
127#endif /* defined(_MSC_VER) */
128
129#endif /* SQLITE_MSVC_H */
130
131/************** End of msvc.h ************************************************/
132/************** Continuing where we left off in sqliteInt.h ******************/
133
134/*
135** Special setup for VxWorks
136*/
137/************** Include vxworks.h in the middle of sqliteInt.h ***************/
138/************** Begin file vxworks.h *****************************************/
139/*
140** 2015-03-02
141**
142** The author disclaims copyright to this source code.  In place of
143** a legal notice, here is a blessing:
144**
145**    May you do good and not evil.
146**    May you find forgiveness for yourself and forgive others.
147**    May you share freely, never taking more than you give.
148**
149******************************************************************************
150**
151** This file contains code that is specific to Wind River's VxWorks
152*/
153#if defined(__RTP__) || defined(_WRS_KERNEL)
154/* This is VxWorks.  Set up things specially for that OS
155*/
156#include <vxWorks.h>
157#include <pthread.h>  /* amalgamator: dontcache */
158#define OS_VXWORKS 1
159#define SQLITE_OS_OTHER 0
160#define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
161#define SQLITE_OMIT_LOAD_EXTENSION 1
162#define SQLITE_ENABLE_LOCKING_STYLE 0
163#define HAVE_UTIME 1
164#else
165/* This is not VxWorks. */
166#define OS_VXWORKS 0
167#define HAVE_FCHOWN 1
168#define HAVE_READLINK 1
169#define HAVE_LSTAT 1
170#endif /* defined(_WRS_KERNEL) */
171
172/************** End of vxworks.h *********************************************/
173/************** Continuing where we left off in sqliteInt.h ******************/
174
175/*
176** These #defines should enable >2GB file support on POSIX if the
177** underlying operating system supports it.  If the OS lacks
178** large file support, or if the OS is windows, these should be no-ops.
179**
180** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
181** system #includes.  Hence, this block of code must be the very first
182** code in all source files.
183**
184** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
185** on the compiler command line.  This is necessary if you are compiling
186** on a recent machine (ex: Red Hat 7.2) but you want your code to work
187** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
188** without this option, LFS is enable.  But LFS does not exist in the kernel
189** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
190** portability you should omit LFS.
191**
192** The previous paragraph was written in 2005.  (This paragraph is written
193** on 2008-11-28.) These days, all Linux kernels support large files, so
194** you should probably leave LFS enabled.  But some embedded platforms might
195** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
196**
197** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
198*/
199#ifndef SQLITE_DISABLE_LFS
200# define _LARGE_FILE       1
201# ifndef _FILE_OFFSET_BITS
202#   define _FILE_OFFSET_BITS 64
203# endif
204# define _LARGEFILE_SOURCE 1
205#endif
206
207/* The GCC_VERSION and MSVC_VERSION macros are used to
208** conditionally include optimizations for each of these compilers.  A
209** value of 0 means that compiler is not being used.  The
210** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
211** optimizations, and hence set all compiler macros to 0
212**
213** There was once also a CLANG_VERSION macro.  However, we learn that the
214** version numbers in clang are for "marketing" only and are inconsistent
215** and unreliable.  Fortunately, all versions of clang also recognize the
216** gcc version numbers and have reasonable settings for gcc version numbers,
217** so the GCC_VERSION macro will be set to a correct non-zero value even
218** when compiling with clang.
219*/
220#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
221# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
222#else
223# define GCC_VERSION 0
224#endif
225#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
226# define MSVC_VERSION _MSC_VER
227#else
228# define MSVC_VERSION 0
229#endif
230
231/* Needed for various definitions... */
232#if defined(__GNUC__) && !defined(_GNU_SOURCE)
233# define _GNU_SOURCE
234#endif
235
236#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
237# define _BSD_SOURCE
238#endif
239
240/*
241** For MinGW, check to see if we can include the header file containing its
242** version information, among other things.  Normally, this internal MinGW
243** header file would [only] be included automatically by other MinGW header
244** files; however, the contained version information is now required by this
245** header file to work around binary compatibility issues (see below) and
246** this is the only known way to reliably obtain it.  This entire #if block
247** would be completely unnecessary if there was any other way of detecting
248** MinGW via their preprocessor (e.g. if they customized their GCC to define
249** some MinGW-specific macros).  When compiling for MinGW, either the
250** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
251** defined; otherwise, detection of conditions specific to MinGW will be
252** disabled.
253*/
254#if defined(_HAVE_MINGW_H)
255# include "mingw.h"
256#elif defined(_HAVE__MINGW_H)
257# include "_mingw.h"
258#endif
259
260/*
261** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
262** define is required to maintain binary compatibility with the MSVC runtime
263** library in use (e.g. for Windows XP).
264*/
265#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
266    defined(_WIN32) && !defined(_WIN64) && \
267    defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
268    defined(__MSVCRT__)
269# define _USE_32BIT_TIME_T
270#endif
271
272/* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
273** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
274** MinGW.
275*/
276/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
277/************** Begin file sqlite3.h *****************************************/
278/*
279** 2001 September 15
280**
281** The author disclaims copyright to this source code.  In place of
282** a legal notice, here is a blessing:
283**
284**    May you do good and not evil.
285**    May you find forgiveness for yourself and forgive others.
286**    May you share freely, never taking more than you give.
287**
288*************************************************************************
289** This header file defines the interface that the SQLite library
290** presents to client programs.  If a C-function, structure, datatype,
291** or constant definition does not appear in this file, then it is
292** not a published API of SQLite, is subject to change without
293** notice, and should not be referenced by programs that use SQLite.
294**
295** Some of the definitions that are in this file are marked as
296** "experimental".  Experimental interfaces are normally new
297** features recently added to SQLite.  We do not anticipate changes
298** to experimental interfaces but reserve the right to make minor changes
299** if experience from use "in the wild" suggest such changes are prudent.
300**
301** The official C-language API documentation for SQLite is derived
302** from comments in this file.  This file is the authoritative source
303** on how SQLite interfaces are supposed to operate.
304**
305** The name of this file under configuration management is "sqlite.h.in".
306** The makefile makes some minor changes to this file (such as inserting
307** the version number) and changes its name to "sqlite3.h" as
308** part of the build process.
309*/
310#ifndef SQLITE3_H
311#define SQLITE3_H
312#include <stdarg.h>     /* Needed for the definition of va_list */
313
314/*
315** Make sure we can call this stuff from C++.
316*/
317#if 0
318extern "C" {
319#endif
320
321
322/*
323** Provide the ability to override linkage features of the interface.
324*/
325#ifndef SQLITE_EXTERN
326# define SQLITE_EXTERN extern
327#endif
328#ifndef SQLITE_API
329# define SQLITE_API
330#endif
331#ifndef SQLITE_CDECL
332# define SQLITE_CDECL
333#endif
334#ifndef SQLITE_APICALL
335# define SQLITE_APICALL
336#endif
337#ifndef SQLITE_STDCALL
338# define SQLITE_STDCALL SQLITE_APICALL
339#endif
340#ifndef SQLITE_CALLBACK
341# define SQLITE_CALLBACK
342#endif
343#ifndef SQLITE_SYSAPI
344# define SQLITE_SYSAPI
345#endif
346
347/*
348** These no-op macros are used in front of interfaces to mark those
349** interfaces as either deprecated or experimental.  New applications
350** should not use deprecated interfaces - they are supported for backwards
351** compatibility only.  Application writers should be aware that
352** experimental interfaces are subject to change in point releases.
353**
354** These macros used to resolve to various kinds of compiler magic that
355** would generate warning messages when they were used.  But that
356** compiler magic ended up generating such a flurry of bug reports
357** that we have taken it all out and gone back to using simple
358** noop macros.
359*/
360#define SQLITE_DEPRECATED
361#define SQLITE_EXPERIMENTAL
362
363/*
364** Ensure these symbols were not defined by some previous header file.
365*/
366#ifdef SQLITE_VERSION
367# undef SQLITE_VERSION
368#endif
369#ifdef SQLITE_VERSION_NUMBER
370# undef SQLITE_VERSION_NUMBER
371#endif
372
373/*
374** CAPI3REF: Compile-Time Library Version Numbers
375**
376** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
377** evaluates to a string literal that is the SQLite version in the
378** format "X.Y.Z" where X is the major version number (always 3 for
379** SQLite3) and Y is the minor version number and Z is the release number.)^
380** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
381** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
382** numbers used in [SQLITE_VERSION].)^
383** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
384** be larger than the release from which it is derived.  Either Y will
385** be held constant and Z will be incremented or else Y will be incremented
386** and Z will be reset to zero.
387**
388** Since [version 3.6.18] ([dateof:3.6.18]),
389** SQLite source code has been stored in the
390** <a href="http://www.fossil-scm.org/">Fossil configuration management
391** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
392** a string which identifies a particular check-in of SQLite
393** within its configuration management system.  ^The SQLITE_SOURCE_ID
394** string contains the date and time of the check-in (UTC) and a SHA1
395** or SHA3-256 hash of the entire source tree.
396**
397** See also: [sqlite3_libversion()],
398** [sqlite3_libversion_number()], [sqlite3_sourceid()],
399** [sqlite_version()] and [sqlite_source_id()].
400*/
401#define SQLITE_VERSION        "3.18.2"
402#define SQLITE_VERSION_NUMBER 3018002
403#define SQLITE_SOURCE_ID      "2017-06-17 09:59:36 036ebf729e4b21035d7f4f8e35a6f705e6bf99887889e2dc14ebf2242e7930dd"
404
405/*
406** CAPI3REF: Run-Time Library Version Numbers
407** KEYWORDS: sqlite3_version sqlite3_sourceid
408**
409** These interfaces provide the same information as the [SQLITE_VERSION],
410** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
411** but are associated with the library instead of the header file.  ^(Cautious
412** programmers might include assert() statements in their application to
413** verify that values returned by these interfaces match the macros in
414** the header, and thus ensure that the application is
415** compiled with matching library and header files.
416**
417** <blockquote><pre>
418** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
419** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
420** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
421** </pre></blockquote>)^
422**
423** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
424** macro.  ^The sqlite3_libversion() function returns a pointer to the
425** to the sqlite3_version[] string constant.  The sqlite3_libversion()
426** function is provided for use in DLLs since DLL users usually do not have
427** direct access to string constants within the DLL.  ^The
428** sqlite3_libversion_number() function returns an integer equal to
429** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
430** a pointer to a string constant whose value is the same as the
431** [SQLITE_SOURCE_ID] C preprocessor macro.
432**
433** See also: [sqlite_version()] and [sqlite_source_id()].
434*/
435SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
436SQLITE_API const char *sqlite3_libversion(void);
437SQLITE_API const char *sqlite3_sourceid(void);
438SQLITE_API int sqlite3_libversion_number(void);
439
440/*
441** CAPI3REF: Run-Time Library Compilation Options Diagnostics
442**
443** ^The sqlite3_compileoption_used() function returns 0 or 1
444** indicating whether the specified option was defined at
445** compile time.  ^The SQLITE_ prefix may be omitted from the
446** option name passed to sqlite3_compileoption_used().
447**
448** ^The sqlite3_compileoption_get() function allows iterating
449** over the list of options that were defined at compile time by
450** returning the N-th compile time option string.  ^If N is out of range,
451** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
452** prefix is omitted from any strings returned by
453** sqlite3_compileoption_get().
454**
455** ^Support for the diagnostic functions sqlite3_compileoption_used()
456** and sqlite3_compileoption_get() may be omitted by specifying the
457** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
458**
459** See also: SQL functions [sqlite_compileoption_used()] and
460** [sqlite_compileoption_get()] and the [compile_options pragma].
461*/
462#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
463SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
464SQLITE_API const char *sqlite3_compileoption_get(int N);
465#endif
466
467/*
468** CAPI3REF: Test To See If The Library Is Threadsafe
469**
470** ^The sqlite3_threadsafe() function returns zero if and only if
471** SQLite was compiled with mutexing code omitted due to the
472** [SQLITE_THREADSAFE] compile-time option being set to 0.
473**
474** SQLite can be compiled with or without mutexes.  When
475** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
476** are enabled and SQLite is threadsafe.  When the
477** [SQLITE_THREADSAFE] macro is 0,
478** the mutexes are omitted.  Without the mutexes, it is not safe
479** to use SQLite concurrently from more than one thread.
480**
481** Enabling mutexes incurs a measurable performance penalty.
482** So if speed is of utmost importance, it makes sense to disable
483** the mutexes.  But for maximum safety, mutexes should be enabled.
484** ^The default behavior is for mutexes to be enabled.
485**
486** This interface can be used by an application to make sure that the
487** version of SQLite that it is linking against was compiled with
488** the desired setting of the [SQLITE_THREADSAFE] macro.
489**
490** This interface only reports on the compile-time mutex setting
491** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
492** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
493** can be fully or partially disabled using a call to [sqlite3_config()]
494** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
495** or [SQLITE_CONFIG_SERIALIZED].  ^(The return value of the
496** sqlite3_threadsafe() function shows only the compile-time setting of
497** thread safety, not any run-time changes to that setting made by
498** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
499** is unchanged by calls to sqlite3_config().)^
500**
501** See the [threading mode] documentation for additional information.
502*/
503SQLITE_API int sqlite3_threadsafe(void);
504
505/*
506** CAPI3REF: Database Connection Handle
507** KEYWORDS: {database connection} {database connections}
508**
509** Each open SQLite database is represented by a pointer to an instance of
510** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
511** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
512** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
513** and [sqlite3_close_v2()] are its destructors.  There are many other
514** interfaces (such as
515** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
516** [sqlite3_busy_timeout()] to name but three) that are methods on an
517** sqlite3 object.
518*/
519typedef struct sqlite3 sqlite3;
520
521/*
522** CAPI3REF: 64-Bit Integer Types
523** KEYWORDS: sqlite_int64 sqlite_uint64
524**
525** Because there is no cross-platform way to specify 64-bit integer types
526** SQLite includes typedefs for 64-bit signed and unsigned integers.
527**
528** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
529** The sqlite_int64 and sqlite_uint64 types are supported for backwards
530** compatibility only.
531**
532** ^The sqlite3_int64 and sqlite_int64 types can store integer values
533** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
534** sqlite3_uint64 and sqlite_uint64 types can store integer values
535** between 0 and +18446744073709551615 inclusive.
536*/
537#ifdef SQLITE_INT64_TYPE
538  typedef SQLITE_INT64_TYPE sqlite_int64;
539# ifdef SQLITE_UINT64_TYPE
540    typedef SQLITE_UINT64_TYPE sqlite_uint64;
541# else
542    typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
543# endif
544#elif defined(_MSC_VER) || defined(__BORLANDC__)
545  typedef __int64 sqlite_int64;
546  typedef unsigned __int64 sqlite_uint64;
547#else
548  typedef long long int sqlite_int64;
549  typedef unsigned long long int sqlite_uint64;
550#endif
551typedef sqlite_int64 sqlite3_int64;
552typedef sqlite_uint64 sqlite3_uint64;
553
554/*
555** If compiling for a processor that lacks floating point support,
556** substitute integer for floating-point.
557*/
558#ifdef SQLITE_OMIT_FLOATING_POINT
559# define double sqlite3_int64
560#endif
561
562/*
563** CAPI3REF: Closing A Database Connection
564** DESTRUCTOR: sqlite3
565**
566** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
567** for the [sqlite3] object.
568** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
569** the [sqlite3] object is successfully destroyed and all associated
570** resources are deallocated.
571**
572** ^If the database connection is associated with unfinalized prepared
573** statements or unfinished sqlite3_backup objects then sqlite3_close()
574** will leave the database connection open and return [SQLITE_BUSY].
575** ^If sqlite3_close_v2() is called with unfinalized prepared statements
576** and/or unfinished sqlite3_backups, then the database connection becomes
577** an unusable "zombie" which will automatically be deallocated when the
578** last prepared statement is finalized or the last sqlite3_backup is
579** finished.  The sqlite3_close_v2() interface is intended for use with
580** host languages that are garbage collected, and where the order in which
581** destructors are called is arbitrary.
582**
583** Applications should [sqlite3_finalize | finalize] all [prepared statements],
584** [sqlite3_blob_close | close] all [BLOB handles], and
585** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
586** with the [sqlite3] object prior to attempting to close the object.  ^If
587** sqlite3_close_v2() is called on a [database connection] that still has
588** outstanding [prepared statements], [BLOB handles], and/or
589** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
590** of resources is deferred until all [prepared statements], [BLOB handles],
591** and [sqlite3_backup] objects are also destroyed.
592**
593** ^If an [sqlite3] object is destroyed while a transaction is open,
594** the transaction is automatically rolled back.
595**
596** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
597** must be either a NULL
598** pointer or an [sqlite3] object pointer obtained
599** from [sqlite3_open()], [sqlite3_open16()], or
600** [sqlite3_open_v2()], and not previously closed.
601** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
602** argument is a harmless no-op.
603*/
604SQLITE_API int sqlite3_close(sqlite3*);
605SQLITE_API int sqlite3_close_v2(sqlite3*);
606
607/*
608** The type for a callback function.
609** This is legacy and deprecated.  It is included for historical
610** compatibility and is not documented.
611*/
612typedef int (*sqlite3_callback)(void*,int,char**, char**);
613
614/*
615** CAPI3REF: One-Step Query Execution Interface
616** METHOD: sqlite3
617**
618** The sqlite3_exec() interface is a convenience wrapper around
619** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
620** that allows an application to run multiple statements of SQL
621** without having to use a lot of C code.
622**
623** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
624** semicolon-separate SQL statements passed into its 2nd argument,
625** in the context of the [database connection] passed in as its 1st
626** argument.  ^If the callback function of the 3rd argument to
627** sqlite3_exec() is not NULL, then it is invoked for each result row
628** coming out of the evaluated SQL statements.  ^The 4th argument to
629** sqlite3_exec() is relayed through to the 1st argument of each
630** callback invocation.  ^If the callback pointer to sqlite3_exec()
631** is NULL, then no callback is ever invoked and result rows are
632** ignored.
633**
634** ^If an error occurs while evaluating the SQL statements passed into
635** sqlite3_exec(), then execution of the current statement stops and
636** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
637** is not NULL then any error message is written into memory obtained
638** from [sqlite3_malloc()] and passed back through the 5th parameter.
639** To avoid memory leaks, the application should invoke [sqlite3_free()]
640** on error message strings returned through the 5th parameter of
641** sqlite3_exec() after the error message string is no longer needed.
642** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
643** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
644** NULL before returning.
645**
646** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
647** routine returns SQLITE_ABORT without invoking the callback again and
648** without running any subsequent SQL statements.
649**
650** ^The 2nd argument to the sqlite3_exec() callback function is the
651** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
652** callback is an array of pointers to strings obtained as if from
653** [sqlite3_column_text()], one for each column.  ^If an element of a
654** result row is NULL then the corresponding string pointer for the
655** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
656** sqlite3_exec() callback is an array of pointers to strings where each
657** entry represents the name of corresponding result column as obtained
658** from [sqlite3_column_name()].
659**
660** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
661** to an empty string, or a pointer that contains only whitespace and/or
662** SQL comments, then no SQL statements are evaluated and the database
663** is not changed.
664**
665** Restrictions:
666**
667** <ul>
668** <li> The application must ensure that the 1st parameter to sqlite3_exec()
669**      is a valid and open [database connection].
670** <li> The application must not close the [database connection] specified by
671**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
672** <li> The application must not modify the SQL statement text passed into
673**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
674** </ul>
675*/
676SQLITE_API int sqlite3_exec(
677  sqlite3*,                                  /* An open database */
678  const char *sql,                           /* SQL to be evaluated */
679  int (*callback)(void*,int,char**,char**),  /* Callback function */
680  void *,                                    /* 1st argument to callback */
681  char **errmsg                              /* Error msg written here */
682);
683
684/*
685** CAPI3REF: Result Codes
686** KEYWORDS: {result code definitions}
687**
688** Many SQLite functions return an integer result code from the set shown
689** here in order to indicate success or failure.
690**
691** New error codes may be added in future versions of SQLite.
692**
693** See also: [extended result code definitions]
694*/
695#define SQLITE_OK           0   /* Successful result */
696/* beginning-of-error-codes */
697#define SQLITE_ERROR        1   /* SQL error or missing database */
698#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
699#define SQLITE_PERM         3   /* Access permission denied */
700#define SQLITE_ABORT        4   /* Callback routine requested an abort */
701#define SQLITE_BUSY         5   /* The database file is locked */
702#define SQLITE_LOCKED       6   /* A table in the database is locked */
703#define SQLITE_NOMEM        7   /* A malloc() failed */
704#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
705#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
706#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
707#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
708#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
709#define SQLITE_FULL        13   /* Insertion failed because database is full */
710#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
711#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
712#define SQLITE_EMPTY       16   /* Database is empty */
713#define SQLITE_SCHEMA      17   /* The database schema changed */
714#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
715#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
716#define SQLITE_MISMATCH    20   /* Data type mismatch */
717#define SQLITE_MISUSE      21   /* Library used incorrectly */
718#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
719#define SQLITE_AUTH        23   /* Authorization denied */
720#define SQLITE_FORMAT      24   /* Auxiliary database format error */
721#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
722#define SQLITE_NOTADB      26   /* File opened that is not a database file */
723#define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
724#define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
725#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
726#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
727/* end-of-error-codes */
728
729/*
730** CAPI3REF: Extended Result Codes
731** KEYWORDS: {extended result code definitions}
732**
733** In its default configuration, SQLite API routines return one of 30 integer
734** [result codes].  However, experience has shown that many of
735** these result codes are too coarse-grained.  They do not provide as
736** much information about problems as programmers might like.  In an effort to
737** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
738** and later) include
739** support for additional result codes that provide more detailed information
740** about errors. These [extended result codes] are enabled or disabled
741** on a per database connection basis using the
742** [sqlite3_extended_result_codes()] API.  Or, the extended code for
743** the most recent error can be obtained using
744** [sqlite3_extended_errcode()].
745*/
746#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
747#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
748#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
749#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
750#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
751#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
752#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
753#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
754#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
755#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
756#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
757#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
758#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
759#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
760#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
761#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
762#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
763#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
764#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
765#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
766#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
767#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
768#define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
769#define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
770#define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
771#define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
772#define SQLITE_IOERR_VNODE             (SQLITE_IOERR | (27<<8))
773#define SQLITE_IOERR_AUTH              (SQLITE_IOERR | (28<<8))
774#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
775#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
776#define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
777#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
778#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
779#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
780#define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
781#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
782#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
783#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
784#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
785#define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
786#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
787#define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
788#define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
789#define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
790#define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
791#define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
792#define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
793#define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
794#define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
795#define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
796#define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
797#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
798#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
799#define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
800#define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
801#define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
802
803/*
804** CAPI3REF: Flags For File Open Operations
805**
806** These bit values are intended for use in the
807** 3rd parameter to the [sqlite3_open_v2()] interface and
808** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
809*/
810#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
811#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
812#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
813#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
814#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
815#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
816#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
817#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
818#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
819#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
820#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
821#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
822#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
823#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
824#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
825#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
826#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
827#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
828#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
829#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
830
831/* Reserved:                         0x00F00000 */
832
833/*
834** CAPI3REF: Device Characteristics
835**
836** The xDeviceCharacteristics method of the [sqlite3_io_methods]
837** object returns an integer which is a vector of these
838** bit values expressing I/O characteristics of the mass storage
839** device that holds the file that the [sqlite3_io_methods]
840** refers to.
841**
842** The SQLITE_IOCAP_ATOMIC property means that all writes of
843** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
844** mean that writes of blocks that are nnn bytes in size and
845** are aligned to an address which is an integer multiple of
846** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
847** that when data is appended to a file, the data is appended
848** first then the size of the file is extended, never the other
849** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
850** information is written to disk in the same order as calls
851** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
852** after reboot following a crash or power loss, the only bytes in a
853** file that were written at the application level might have changed
854** and that adjacent bytes, even bytes within the same sector are
855** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
856** flag indicates that a file cannot be deleted when open.  The
857** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
858** read-only media and cannot be changed even by processes with
859** elevated privileges.
860*/
861#define SQLITE_IOCAP_ATOMIC                 0x00000001
862#define SQLITE_IOCAP_ATOMIC512              0x00000002
863#define SQLITE_IOCAP_ATOMIC1K               0x00000004
864#define SQLITE_IOCAP_ATOMIC2K               0x00000008
865#define SQLITE_IOCAP_ATOMIC4K               0x00000010
866#define SQLITE_IOCAP_ATOMIC8K               0x00000020
867#define SQLITE_IOCAP_ATOMIC16K              0x00000040
868#define SQLITE_IOCAP_ATOMIC32K              0x00000080
869#define SQLITE_IOCAP_ATOMIC64K              0x00000100
870#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
871#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
872#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
873#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
874#define SQLITE_IOCAP_IMMUTABLE              0x00002000
875
876/*
877** CAPI3REF: File Locking Levels
878**
879** SQLite uses one of these integer values as the second
880** argument to calls it makes to the xLock() and xUnlock() methods
881** of an [sqlite3_io_methods] object.
882*/
883#define SQLITE_LOCK_NONE          0
884#define SQLITE_LOCK_SHARED        1
885#define SQLITE_LOCK_RESERVED      2
886#define SQLITE_LOCK_PENDING       3
887#define SQLITE_LOCK_EXCLUSIVE     4
888
889/*
890** CAPI3REF: Synchronization Type Flags
891**
892** When SQLite invokes the xSync() method of an
893** [sqlite3_io_methods] object it uses a combination of
894** these integer values as the second argument.
895**
896** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
897** sync operation only needs to flush data to mass storage.  Inode
898** information need not be flushed. If the lower four bits of the flag
899** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
900** If the lower four bits equal SQLITE_SYNC_FULL, that means
901** to use Mac OS X style fullsync instead of fsync().
902**
903** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
904** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
905** settings.  The [synchronous pragma] determines when calls to the
906** xSync VFS method occur and applies uniformly across all platforms.
907** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
908** energetic or rigorous or forceful the sync operations are and
909** only make a difference on Mac OSX for the default SQLite code.
910** (Third-party VFS implementations might also make the distinction
911** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
912** operating systems natively supported by SQLite, only Mac OSX
913** cares about the difference.)
914*/
915#define SQLITE_SYNC_NORMAL        0x00002
916#define SQLITE_SYNC_FULL          0x00003
917#define SQLITE_SYNC_DATAONLY      0x00010
918
919/*
920** CAPI3REF: OS Interface Open File Handle
921**
922** An [sqlite3_file] object represents an open file in the
923** [sqlite3_vfs | OS interface layer].  Individual OS interface
924** implementations will
925** want to subclass this object by appending additional fields
926** for their own use.  The pMethods entry is a pointer to an
927** [sqlite3_io_methods] object that defines methods for performing
928** I/O operations on the open file.
929*/
930typedef struct sqlite3_file sqlite3_file;
931struct sqlite3_file {
932  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
933};
934
935/*
936** CAPI3REF: OS Interface File Virtual Methods Object
937**
938** Every file opened by the [sqlite3_vfs.xOpen] method populates an
939** [sqlite3_file] object (or, more commonly, a subclass of the
940** [sqlite3_file] object) with a pointer to an instance of this object.
941** This object defines the methods used to perform various operations
942** against the open file represented by the [sqlite3_file] object.
943**
944** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
945** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
946** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
947** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
948** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
949** to NULL.
950**
951** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
952** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
953** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
954** flag may be ORed in to indicate that only the data of the file
955** and not its inode needs to be synced.
956**
957** The integer values to xLock() and xUnlock() are one of
958** <ul>
959** <li> [SQLITE_LOCK_NONE],
960** <li> [SQLITE_LOCK_SHARED],
961** <li> [SQLITE_LOCK_RESERVED],
962** <li> [SQLITE_LOCK_PENDING], or
963** <li> [SQLITE_LOCK_EXCLUSIVE].
964** </ul>
965** xLock() increases the lock. xUnlock() decreases the lock.
966** The xCheckReservedLock() method checks whether any database connection,
967** either in this process or in some other process, is holding a RESERVED,
968** PENDING, or EXCLUSIVE lock on the file.  It returns true
969** if such a lock exists and false otherwise.
970**
971** The xFileControl() method is a generic interface that allows custom
972** VFS implementations to directly control an open file using the
973** [sqlite3_file_control()] interface.  The second "op" argument is an
974** integer opcode.  The third argument is a generic pointer intended to
975** point to a structure that may contain arguments or space in which to
976** write return values.  Potential uses for xFileControl() might be
977** functions to enable blocking locks with timeouts, to change the
978** locking strategy (for example to use dot-file locks), to inquire
979** about the status of a lock, or to break stale locks.  The SQLite
980** core reserves all opcodes less than 100 for its own use.
981** A [file control opcodes | list of opcodes] less than 100 is available.
982** Applications that define a custom xFileControl method should use opcodes
983** greater than 100 to avoid conflicts.  VFS implementations should
984** return [SQLITE_NOTFOUND] for file control opcodes that they do not
985** recognize.
986**
987** The xSectorSize() method returns the sector size of the
988** device that underlies the file.  The sector size is the
989** minimum write that can be performed without disturbing
990** other bytes in the file.  The xDeviceCharacteristics()
991** method returns a bit vector describing behaviors of the
992** underlying device:
993**
994** <ul>
995** <li> [SQLITE_IOCAP_ATOMIC]
996** <li> [SQLITE_IOCAP_ATOMIC512]
997** <li> [SQLITE_IOCAP_ATOMIC1K]
998** <li> [SQLITE_IOCAP_ATOMIC2K]
999** <li> [SQLITE_IOCAP_ATOMIC4K]
1000** <li> [SQLITE_IOCAP_ATOMIC8K]
1001** <li> [SQLITE_IOCAP_ATOMIC16K]
1002** <li> [SQLITE_IOCAP_ATOMIC32K]
1003** <li> [SQLITE_IOCAP_ATOMIC64K]
1004** <li> [SQLITE_IOCAP_SAFE_APPEND]
1005** <li> [SQLITE_IOCAP_SEQUENTIAL]
1006** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
1007** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
1008** <li> [SQLITE_IOCAP_IMMUTABLE]
1009** </ul>
1010**
1011** The SQLITE_IOCAP_ATOMIC property means that all writes of
1012** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1013** mean that writes of blocks that are nnn bytes in size and
1014** are aligned to an address which is an integer multiple of
1015** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1016** that when data is appended to a file, the data is appended
1017** first then the size of the file is extended, never the other
1018** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1019** information is written to disk in the same order as calls
1020** to xWrite().
1021**
1022** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1023** in the unread portions of the buffer with zeros.  A VFS that
1024** fails to zero-fill short reads might seem to work.  However,
1025** failure to zero-fill short reads will eventually lead to
1026** database corruption.
1027*/
1028typedef struct sqlite3_io_methods sqlite3_io_methods;
1029struct sqlite3_io_methods {
1030  int iVersion;
1031  int (*xClose)(sqlite3_file*);
1032  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1033  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1034  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1035  int (*xSync)(sqlite3_file*, int flags);
1036  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1037  int (*xLock)(sqlite3_file*, int);
1038  int (*xUnlock)(sqlite3_file*, int);
1039  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1040  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1041  int (*xSectorSize)(sqlite3_file*);
1042  int (*xDeviceCharacteristics)(sqlite3_file*);
1043  /* Methods above are valid for version 1 */
1044  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1045  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1046  void (*xShmBarrier)(sqlite3_file*);
1047  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1048  /* Methods above are valid for version 2 */
1049  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1050  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1051  /* Methods above are valid for version 3 */
1052  /* Additional methods may be added in future releases */
1053};
1054
1055/*
1056** CAPI3REF: Standard File Control Opcodes
1057** KEYWORDS: {file control opcodes} {file control opcode}
1058**
1059** These integer constants are opcodes for the xFileControl method
1060** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1061** interface.
1062**
1063** <ul>
1064** <li>[[SQLITE_FCNTL_LOCKSTATE]]
1065** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1066** opcode causes the xFileControl method to write the current state of
1067** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1068** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1069** into an integer that the pArg argument points to. This capability
1070** is used during testing and is only available when the SQLITE_TEST
1071** compile-time option is used.
1072**
1073** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1074** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1075** layer a hint of how large the database file will grow to be during the
1076** current transaction.  This hint is not guaranteed to be accurate but it
1077** is often close.  The underlying VFS might choose to preallocate database
1078** file space based on this hint in order to help writes to the database
1079** file run faster.
1080**
1081** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1082** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1083** extends and truncates the database file in chunks of a size specified
1084** by the user. The fourth argument to [sqlite3_file_control()] should
1085** point to an integer (type int) containing the new chunk-size to use
1086** for the nominated database. Allocating database file space in large
1087** chunks (say 1MB at a time), may reduce file-system fragmentation and
1088** improve performance on some systems.
1089**
1090** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1091** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1092** to the [sqlite3_file] object associated with a particular database
1093** connection.  See also [SQLITE_FCNTL_JOURNAL_POINTER].
1094**
1095** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
1096** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
1097** to the [sqlite3_file] object associated with the journal file (either
1098** the [rollback journal] or the [write-ahead log]) for a particular database
1099** connection.  See also [SQLITE_FCNTL_FILE_POINTER].
1100**
1101** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1102** No longer in use.
1103**
1104** <li>[[SQLITE_FCNTL_SYNC]]
1105** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1106** sent to the VFS immediately before the xSync method is invoked on a
1107** database file descriptor. Or, if the xSync method is not invoked
1108** because the user has configured SQLite with
1109** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1110** of the xSync method. In most cases, the pointer argument passed with
1111** this file-control is NULL. However, if the database file is being synced
1112** as part of a multi-database commit, the argument points to a nul-terminated
1113** string containing the transactions master-journal file name. VFSes that
1114** do not need this signal should silently ignore this opcode. Applications
1115** should not call [sqlite3_file_control()] with this opcode as doing so may
1116** disrupt the operation of the specialized VFSes that do require it.
1117**
1118** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1119** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1120** and sent to the VFS after a transaction has been committed immediately
1121** but before the database is unlocked. VFSes that do not need this signal
1122** should silently ignore this opcode. Applications should not call
1123** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1124** operation of the specialized VFSes that do require it.
1125**
1126** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1127** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1128** retry counts and intervals for certain disk I/O operations for the
1129** windows [VFS] in order to provide robustness in the presence of
1130** anti-virus programs.  By default, the windows VFS will retry file read,
1131** file write, and file delete operations up to 10 times, with a delay
1132** of 25 milliseconds before the first retry and with the delay increasing
1133** by an additional 25 milliseconds with each subsequent retry.  This
1134** opcode allows these two values (10 retries and 25 milliseconds of delay)
1135** to be adjusted.  The values are changed for all database connections
1136** within the same process.  The argument is a pointer to an array of two
1137** integers where the first integer i the new retry count and the second
1138** integer is the delay.  If either integer is negative, then the setting
1139** is not changed but instead the prior value of that setting is written
1140** into the array entry, allowing the current retry settings to be
1141** interrogated.  The zDbName parameter is ignored.
1142**
1143** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1144** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1145** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
1146** write ahead log and shared memory files used for transaction control
1147** are automatically deleted when the latest connection to the database
1148** closes.  Setting persistent WAL mode causes those files to persist after
1149** close.  Persisting the files is useful when other processes that do not
1150** have write permission on the directory containing the database file want
1151** to read the database file, as the WAL and shared memory files must exist
1152** in order for the database to be readable.  The fourth parameter to
1153** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1154** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1155** WAL mode.  If the integer is -1, then it is overwritten with the current
1156** WAL persistence setting.
1157**
1158** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1159** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1160** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1161** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1162** xDeviceCharacteristics methods. The fourth parameter to
1163** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1164** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1165** mode.  If the integer is -1, then it is overwritten with the current
1166** zero-damage mode setting.
1167**
1168** <li>[[SQLITE_FCNTL_OVERWRITE]]
1169** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1170** a write transaction to indicate that, unless it is rolled back for some
1171** reason, the entire database file will be overwritten by the current
1172** transaction. This is used by VACUUM operations.
1173**
1174** <li>[[SQLITE_FCNTL_VFSNAME]]
1175** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1176** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1177** final bottom-level VFS are written into memory obtained from
1178** [sqlite3_malloc()] and the result is stored in the char* variable
1179** that the fourth parameter of [sqlite3_file_control()] points to.
1180** The caller is responsible for freeing the memory when done.  As with
1181** all file-control actions, there is no guarantee that this will actually
1182** do anything.  Callers should initialize the char* variable to a NULL
1183** pointer in case this file-control is not implemented.  This file-control
1184** is intended for diagnostic use only.
1185**
1186** <li>[[SQLITE_FCNTL_VFS_POINTER]]
1187** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1188** [VFSes] currently in use.  ^(The argument X in
1189** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
1190** of type "[sqlite3_vfs] **".  This opcodes will set *X
1191** to a pointer to the top-level VFS.)^
1192** ^When there are multiple VFS shims in the stack, this opcode finds the
1193** upper-most shim only.
1194**
1195** <li>[[SQLITE_FCNTL_PRAGMA]]
1196** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1197** file control is sent to the open [sqlite3_file] object corresponding
1198** to the database file to which the pragma statement refers. ^The argument
1199** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1200** pointers to strings (char**) in which the second element of the array
1201** is the name of the pragma and the third element is the argument to the
1202** pragma or NULL if the pragma has no argument.  ^The handler for an
1203** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1204** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1205** or the equivalent and that string will become the result of the pragma or
1206** the error message if the pragma fails. ^If the
1207** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1208** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1209** file control returns [SQLITE_OK], then the parser assumes that the
1210** VFS has handled the PRAGMA itself and the parser generates a no-op
1211** prepared statement if result string is NULL, or that returns a copy
1212** of the result string if the string is non-NULL.
1213** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1214** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1215** that the VFS encountered an error while handling the [PRAGMA] and the
1216** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1217** file control occurs at the beginning of pragma statement analysis and so
1218** it is able to override built-in [PRAGMA] statements.
1219**
1220** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1221** ^The [SQLITE_FCNTL_BUSYHANDLER]
1222** file-control may be invoked by SQLite on the database file handle
1223** shortly after it is opened in order to provide a custom VFS with access
1224** to the connections busy-handler callback. The argument is of type (void **)
1225** - an array of two (void *) values. The first (void *) actually points
1226** to a function of type (int (*)(void *)). In order to invoke the connections
1227** busy-handler, this function should be invoked with the second (void *) in
1228** the array as the only argument. If it returns non-zero, then the operation
1229** should be retried. If it returns zero, the custom VFS should abandon the
1230** current operation.
1231**
1232** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1233** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1234** to have SQLite generate a
1235** temporary filename using the same algorithm that is followed to generate
1236** temporary filenames for TEMP tables and other internal uses.  The
1237** argument should be a char** which will be filled with the filename
1238** written into memory obtained from [sqlite3_malloc()].  The caller should
1239** invoke [sqlite3_free()] on the result to avoid a memory leak.
1240**
1241** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1242** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1243** maximum number of bytes that will be used for memory-mapped I/O.
1244** The argument is a pointer to a value of type sqlite3_int64 that
1245** is an advisory maximum number of bytes in the file to memory map.  The
1246** pointer is overwritten with the old value.  The limit is not changed if
1247** the value originally pointed to is negative, and so the current limit
1248** can be queried by passing in a pointer to a negative number.  This
1249** file-control is used internally to implement [PRAGMA mmap_size].
1250**
1251** <li>[[SQLITE_FCNTL_TRACE]]
1252** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1253** to the VFS about what the higher layers of the SQLite stack are doing.
1254** This file control is used by some VFS activity tracing [shims].
1255** The argument is a zero-terminated string.  Higher layers in the
1256** SQLite stack may generate instances of this file control if
1257** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1258**
1259** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1260** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1261** pointer to an integer and it writes a boolean into that integer depending
1262** on whether or not the file has been renamed, moved, or deleted since it
1263** was first opened.
1264**
1265** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
1266** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
1267** underlying native file handle associated with a file handle.  This file
1268** control interprets its argument as a pointer to a native file handle and
1269** writes the resulting value there.
1270**
1271** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1272** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This
1273** opcode causes the xFileControl method to swap the file handle with the one
1274** pointed to by the pArg argument.  This capability is used during testing
1275** and only needs to be supported when SQLITE_TEST is defined.
1276**
1277** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1278** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1279** be advantageous to block on the next WAL lock if the lock is not immediately
1280** available.  The WAL subsystem issues this signal during rare
1281** circumstances in order to fix a problem with priority inversion.
1282** Applications should <em>not</em> use this file-control.
1283**
1284** <li>[[SQLITE_FCNTL_ZIPVFS]]
1285** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
1286** VFS should return SQLITE_NOTFOUND for this opcode.
1287**
1288** <li>[[SQLITE_FCNTL_RBU]]
1289** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
1290** the RBU extension only.  All other VFS should return SQLITE_NOTFOUND for
1291** this opcode.
1292** </ul>
1293*/
1294#define SQLITE_FCNTL_LOCKSTATE               1
1295#define SQLITE_FCNTL_GET_LOCKPROXYFILE       2
1296#define SQLITE_FCNTL_SET_LOCKPROXYFILE       3
1297#define SQLITE_FCNTL_LAST_ERRNO              4
1298#define SQLITE_FCNTL_SIZE_HINT               5
1299#define SQLITE_FCNTL_CHUNK_SIZE              6
1300#define SQLITE_FCNTL_FILE_POINTER            7
1301#define SQLITE_FCNTL_SYNC_OMITTED            8
1302#define SQLITE_FCNTL_WIN32_AV_RETRY          9
1303#define SQLITE_FCNTL_PERSIST_WAL            10
1304#define SQLITE_FCNTL_OVERWRITE              11
1305#define SQLITE_FCNTL_VFSNAME                12
1306#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1307#define SQLITE_FCNTL_PRAGMA                 14
1308#define SQLITE_FCNTL_BUSYHANDLER            15
1309#define SQLITE_FCNTL_TEMPFILENAME           16
1310#define SQLITE_FCNTL_MMAP_SIZE              18
1311#define SQLITE_FCNTL_TRACE                  19
1312#define SQLITE_FCNTL_HAS_MOVED              20
1313#define SQLITE_FCNTL_SYNC                   21
1314#define SQLITE_FCNTL_COMMIT_PHASETWO        22
1315#define SQLITE_FCNTL_WIN32_SET_HANDLE       23
1316#define SQLITE_FCNTL_WAL_BLOCK              24
1317#define SQLITE_FCNTL_ZIPVFS                 25
1318#define SQLITE_FCNTL_RBU                    26
1319#define SQLITE_FCNTL_VFS_POINTER            27
1320#define SQLITE_FCNTL_JOURNAL_POINTER        28
1321#define SQLITE_FCNTL_WIN32_GET_HANDLE       29
1322#define SQLITE_FCNTL_PDB                    30
1323
1324/* deprecated names */
1325#define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
1326#define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE
1327#define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO
1328
1329
1330/*
1331** CAPI3REF: Mutex Handle
1332**
1333** The mutex module within SQLite defines [sqlite3_mutex] to be an
1334** abstract type for a mutex object.  The SQLite core never looks
1335** at the internal representation of an [sqlite3_mutex].  It only
1336** deals with pointers to the [sqlite3_mutex] object.
1337**
1338** Mutexes are created using [sqlite3_mutex_alloc()].
1339*/
1340typedef struct sqlite3_mutex sqlite3_mutex;
1341
1342/*
1343** CAPI3REF: Loadable Extension Thunk
1344**
1345** A pointer to the opaque sqlite3_api_routines structure is passed as
1346** the third parameter to entry points of [loadable extensions].  This
1347** structure must be typedefed in order to work around compiler warnings
1348** on some platforms.
1349*/
1350typedef struct sqlite3_api_routines sqlite3_api_routines;
1351
1352/*
1353** CAPI3REF: OS Interface Object
1354**
1355** An instance of the sqlite3_vfs object defines the interface between
1356** the SQLite core and the underlying operating system.  The "vfs"
1357** in the name of the object stands for "virtual file system".  See
1358** the [VFS | VFS documentation] for further information.
1359**
1360** The value of the iVersion field is initially 1 but may be larger in
1361** future versions of SQLite.  Additional fields may be appended to this
1362** object when the iVersion value is increased.  Note that the structure
1363** of the sqlite3_vfs object changes in the transaction between
1364** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1365** modified.
1366**
1367** The szOsFile field is the size of the subclassed [sqlite3_file]
1368** structure used by this VFS.  mxPathname is the maximum length of
1369** a pathname in this VFS.
1370**
1371** Registered sqlite3_vfs objects are kept on a linked list formed by
1372** the pNext pointer.  The [sqlite3_vfs_register()]
1373** and [sqlite3_vfs_unregister()] interfaces manage this list
1374** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1375** searches the list.  Neither the application code nor the VFS
1376** implementation should use the pNext pointer.
1377**
1378** The pNext field is the only field in the sqlite3_vfs
1379** structure that SQLite will ever modify.  SQLite will only access
1380** or modify this field while holding a particular static mutex.
1381** The application should never modify anything within the sqlite3_vfs
1382** object once the object has been registered.
1383**
1384** The zName field holds the name of the VFS module.  The name must
1385** be unique across all VFS modules.
1386**
1387** [[sqlite3_vfs.xOpen]]
1388** ^SQLite guarantees that the zFilename parameter to xOpen
1389** is either a NULL pointer or string obtained
1390** from xFullPathname() with an optional suffix added.
1391** ^If a suffix is added to the zFilename parameter, it will
1392** consist of a single "-" character followed by no more than
1393** 11 alphanumeric and/or "-" characters.
1394** ^SQLite further guarantees that
1395** the string will be valid and unchanged until xClose() is
1396** called. Because of the previous sentence,
1397** the [sqlite3_file] can safely store a pointer to the
1398** filename if it needs to remember the filename for some reason.
1399** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1400** must invent its own temporary name for the file.  ^Whenever the
1401** xFilename parameter is NULL it will also be the case that the
1402** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1403**
1404** The flags argument to xOpen() includes all bits set in
1405** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1406** or [sqlite3_open16()] is used, then flags includes at least
1407** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1408** If xOpen() opens a file read-only then it sets *pOutFlags to
1409** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1410**
1411** ^(SQLite will also add one of the following flags to the xOpen()
1412** call, depending on the object being opened:
1413**
1414** <ul>
1415** <li>  [SQLITE_OPEN_MAIN_DB]
1416** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1417** <li>  [SQLITE_OPEN_TEMP_DB]
1418** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1419** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1420** <li>  [SQLITE_OPEN_SUBJOURNAL]
1421** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1422** <li>  [SQLITE_OPEN_WAL]
1423** </ul>)^
1424**
1425** The file I/O implementation can use the object type flags to
1426** change the way it deals with files.  For example, an application
1427** that does not care about crash recovery or rollback might make
1428** the open of a journal file a no-op.  Writes to this journal would
1429** also be no-ops, and any attempt to read the journal would return
1430** SQLITE_IOERR.  Or the implementation might recognize that a database
1431** file will be doing page-aligned sector reads and writes in a random
1432** order and set up its I/O subsystem accordingly.
1433**
1434** SQLite might also add one of the following flags to the xOpen method:
1435**
1436** <ul>
1437** <li> [SQLITE_OPEN_DELETEONCLOSE]
1438** <li> [SQLITE_OPEN_EXCLUSIVE]
1439** </ul>
1440**
1441** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1442** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1443** will be set for TEMP databases and their journals, transient
1444** databases, and subjournals.
1445**
1446** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1447** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1448** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1449** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1450** SQLITE_OPEN_CREATE, is used to indicate that file should always
1451** be created, and that it is an error if it already exists.
1452** It is <i>not</i> used to indicate the file should be opened
1453** for exclusive access.
1454**
1455** ^At least szOsFile bytes of memory are allocated by SQLite
1456** to hold the  [sqlite3_file] structure passed as the third
1457** argument to xOpen.  The xOpen method does not have to
1458** allocate the structure; it should just fill it in.  Note that
1459** the xOpen method must set the sqlite3_file.pMethods to either
1460** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1461** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1462** element will be valid after xOpen returns regardless of the success
1463** or failure of the xOpen call.
1464**
1465** [[sqlite3_vfs.xAccess]]
1466** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1467** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1468** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1469** to test whether a file is at least readable.   The file can be a
1470** directory.
1471**
1472** ^SQLite will always allocate at least mxPathname+1 bytes for the
1473** output buffer xFullPathname.  The exact size of the output buffer
1474** is also passed as a parameter to both  methods. If the output buffer
1475** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1476** handled as a fatal error by SQLite, vfs implementations should endeavor
1477** to prevent this by setting mxPathname to a sufficiently large value.
1478**
1479** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1480** interfaces are not strictly a part of the filesystem, but they are
1481** included in the VFS structure for completeness.
1482** The xRandomness() function attempts to return nBytes bytes
1483** of good-quality randomness into zOut.  The return value is
1484** the actual number of bytes of randomness obtained.
1485** The xSleep() method causes the calling thread to sleep for at
1486** least the number of microseconds given.  ^The xCurrentTime()
1487** method returns a Julian Day Number for the current date and time as
1488** a floating point value.
1489** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1490** Day Number multiplied by 86400000 (the number of milliseconds in
1491** a 24-hour day).
1492** ^SQLite will use the xCurrentTimeInt64() method to get the current
1493** date and time if that method is available (if iVersion is 2 or
1494** greater and the function pointer is not NULL) and will fall back
1495** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1496**
1497** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1498** are not used by the SQLite core.  These optional interfaces are provided
1499** by some VFSes to facilitate testing of the VFS code. By overriding
1500** system calls with functions under its control, a test program can
1501** simulate faults and error conditions that would otherwise be difficult
1502** or impossible to induce.  The set of system calls that can be overridden
1503** varies from one VFS to another, and from one version of the same VFS to the
1504** next.  Applications that use these interfaces must be prepared for any
1505** or all of these interfaces to be NULL or for their behavior to change
1506** from one release to the next.  Applications must not attempt to access
1507** any of these methods if the iVersion of the VFS is less than 3.
1508*/
1509typedef struct sqlite3_vfs sqlite3_vfs;
1510typedef void (*sqlite3_syscall_ptr)(void);
1511struct sqlite3_vfs {
1512  int iVersion;            /* Structure version number (currently 3) */
1513  int szOsFile;            /* Size of subclassed sqlite3_file */
1514  int mxPathname;          /* Maximum file pathname length */
1515  sqlite3_vfs *pNext;      /* Next registered VFS */
1516  const char *zName;       /* Name of this virtual file system */
1517  void *pAppData;          /* Pointer to application-specific data */
1518  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1519               int flags, int *pOutFlags);
1520  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1521  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1522  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1523  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1524  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1525  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1526  void (*xDlClose)(sqlite3_vfs*, void*);
1527  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1528  int (*xSleep)(sqlite3_vfs*, int microseconds);
1529  int (*xCurrentTime)(sqlite3_vfs*, double*);
1530  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1531  /*
1532  ** The methods above are in version 1 of the sqlite_vfs object
1533  ** definition.  Those that follow are added in version 2 or later
1534  */
1535  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1536  /*
1537  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1538  ** Those below are for version 3 and greater.
1539  */
1540  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1541  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1542  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1543  /*
1544  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1545  ** New fields may be appended in future versions.  The iVersion
1546  ** value will increment whenever this happens.
1547  */
1548};
1549
1550/*
1551** CAPI3REF: Flags for the xAccess VFS method
1552**
1553** These integer constants can be used as the third parameter to
1554** the xAccess method of an [sqlite3_vfs] object.  They determine
1555** what kind of permissions the xAccess method is looking for.
1556** With SQLITE_ACCESS_EXISTS, the xAccess method
1557** simply checks whether the file exists.
1558** With SQLITE_ACCESS_READWRITE, the xAccess method
1559** checks whether the named directory is both readable and writable
1560** (in other words, if files can be added, removed, and renamed within
1561** the directory).
1562** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1563** [temp_store_directory pragma], though this could change in a future
1564** release of SQLite.
1565** With SQLITE_ACCESS_READ, the xAccess method
1566** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1567** currently unused, though it might be used in a future release of
1568** SQLite.
1569*/
1570#define SQLITE_ACCESS_EXISTS    0
1571#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1572#define SQLITE_ACCESS_READ      2   /* Unused */
1573
1574/*
1575** CAPI3REF: Flags for the xShmLock VFS method
1576**
1577** These integer constants define the various locking operations
1578** allowed by the xShmLock method of [sqlite3_io_methods].  The
1579** following are the only legal combinations of flags to the
1580** xShmLock method:
1581**
1582** <ul>
1583** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1584** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1585** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1586** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1587** </ul>
1588**
1589** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1590** was given on the corresponding lock.
1591**
1592** The xShmLock method can transition between unlocked and SHARED or
1593** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1594** and EXCLUSIVE.
1595*/
1596#define SQLITE_SHM_UNLOCK       1
1597#define SQLITE_SHM_LOCK         2
1598#define SQLITE_SHM_SHARED       4
1599#define SQLITE_SHM_EXCLUSIVE    8
1600
1601/*
1602** CAPI3REF: Maximum xShmLock index
1603**
1604** The xShmLock method on [sqlite3_io_methods] may use values
1605** between 0 and this upper bound as its "offset" argument.
1606** The SQLite core will never attempt to acquire or release a
1607** lock outside of this range
1608*/
1609#define SQLITE_SHM_NLOCK        8
1610
1611
1612/*
1613** CAPI3REF: Initialize The SQLite Library
1614**
1615** ^The sqlite3_initialize() routine initializes the
1616** SQLite library.  ^The sqlite3_shutdown() routine
1617** deallocates any resources that were allocated by sqlite3_initialize().
1618** These routines are designed to aid in process initialization and
1619** shutdown on embedded systems.  Workstation applications using
1620** SQLite normally do not need to invoke either of these routines.
1621**
1622** A call to sqlite3_initialize() is an "effective" call if it is
1623** the first time sqlite3_initialize() is invoked during the lifetime of
1624** the process, or if it is the first time sqlite3_initialize() is invoked
1625** following a call to sqlite3_shutdown().  ^(Only an effective call
1626** of sqlite3_initialize() does any initialization.  All other calls
1627** are harmless no-ops.)^
1628**
1629** A call to sqlite3_shutdown() is an "effective" call if it is the first
1630** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1631** an effective call to sqlite3_shutdown() does any deinitialization.
1632** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1633**
1634** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1635** is not.  The sqlite3_shutdown() interface must only be called from a
1636** single thread.  All open [database connections] must be closed and all
1637** other SQLite resources must be deallocated prior to invoking
1638** sqlite3_shutdown().
1639**
1640** Among other things, ^sqlite3_initialize() will invoke
1641** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1642** will invoke sqlite3_os_end().
1643**
1644** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1645** ^If for some reason, sqlite3_initialize() is unable to initialize
1646** the library (perhaps it is unable to allocate a needed resource such
1647** as a mutex) it returns an [error code] other than [SQLITE_OK].
1648**
1649** ^The sqlite3_initialize() routine is called internally by many other
1650** SQLite interfaces so that an application usually does not need to
1651** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1652** calls sqlite3_initialize() so the SQLite library will be automatically
1653** initialized when [sqlite3_open()] is called if it has not be initialized
1654** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1655** compile-time option, then the automatic calls to sqlite3_initialize()
1656** are omitted and the application must call sqlite3_initialize() directly
1657** prior to using any other SQLite interface.  For maximum portability,
1658** it is recommended that applications always invoke sqlite3_initialize()
1659** directly prior to using any other SQLite interface.  Future releases
1660** of SQLite may require this.  In other words, the behavior exhibited
1661** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1662** default behavior in some future release of SQLite.
1663**
1664** The sqlite3_os_init() routine does operating-system specific
1665** initialization of the SQLite library.  The sqlite3_os_end()
1666** routine undoes the effect of sqlite3_os_init().  Typical tasks
1667** performed by these routines include allocation or deallocation
1668** of static resources, initialization of global variables,
1669** setting up a default [sqlite3_vfs] module, or setting up
1670** a default configuration using [sqlite3_config()].
1671**
1672** The application should never invoke either sqlite3_os_init()
1673** or sqlite3_os_end() directly.  The application should only invoke
1674** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1675** interface is called automatically by sqlite3_initialize() and
1676** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1677** implementations for sqlite3_os_init() and sqlite3_os_end()
1678** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1679** When [custom builds | built for other platforms]
1680** (using the [SQLITE_OS_OTHER=1] compile-time
1681** option) the application must supply a suitable implementation for
1682** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1683** implementation of sqlite3_os_init() or sqlite3_os_end()
1684** must return [SQLITE_OK] on success and some other [error code] upon
1685** failure.
1686*/
1687SQLITE_API int sqlite3_initialize(void);
1688SQLITE_API int sqlite3_shutdown(void);
1689SQLITE_API int sqlite3_os_init(void);
1690SQLITE_API int sqlite3_os_end(void);
1691
1692/*
1693** CAPI3REF: Configuring The SQLite Library
1694**
1695** The sqlite3_config() interface is used to make global configuration
1696** changes to SQLite in order to tune SQLite to the specific needs of
1697** the application.  The default configuration is recommended for most
1698** applications and so this routine is usually not necessary.  It is
1699** provided to support rare applications with unusual needs.
1700**
1701** <b>The sqlite3_config() interface is not threadsafe. The application
1702** must ensure that no other SQLite interfaces are invoked by other
1703** threads while sqlite3_config() is running.</b>
1704**
1705** The sqlite3_config() interface
1706** may only be invoked prior to library initialization using
1707** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1708** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1709** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1710** Note, however, that ^sqlite3_config() can be called as part of the
1711** implementation of an application-defined [sqlite3_os_init()].
1712**
1713** The first argument to sqlite3_config() is an integer
1714** [configuration option] that determines
1715** what property of SQLite is to be configured.  Subsequent arguments
1716** vary depending on the [configuration option]
1717** in the first argument.
1718**
1719** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1720** ^If the option is unknown or SQLite is unable to set the option
1721** then this routine returns a non-zero [error code].
1722*/
1723SQLITE_API int sqlite3_config(int, ...);
1724
1725/*
1726** CAPI3REF: Configure database connections
1727** METHOD: sqlite3
1728**
1729** The sqlite3_db_config() interface is used to make configuration
1730** changes to a [database connection].  The interface is similar to
1731** [sqlite3_config()] except that the changes apply to a single
1732** [database connection] (specified in the first argument).
1733**
1734** The second argument to sqlite3_db_config(D,V,...)  is the
1735** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1736** that indicates what aspect of the [database connection] is being configured.
1737** Subsequent arguments vary depending on the configuration verb.
1738**
1739** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1740** the call is considered successful.
1741*/
1742SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1743
1744/*
1745** CAPI3REF: Memory Allocation Routines
1746**
1747** An instance of this object defines the interface between SQLite
1748** and low-level memory allocation routines.
1749**
1750** This object is used in only one place in the SQLite interface.
1751** A pointer to an instance of this object is the argument to
1752** [sqlite3_config()] when the configuration option is
1753** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1754** By creating an instance of this object
1755** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1756** during configuration, an application can specify an alternative
1757** memory allocation subsystem for SQLite to use for all of its
1758** dynamic memory needs.
1759**
1760** Note that SQLite comes with several [built-in memory allocators]
1761** that are perfectly adequate for the overwhelming majority of applications
1762** and that this object is only useful to a tiny minority of applications
1763** with specialized memory allocation requirements.  This object is
1764** also used during testing of SQLite in order to specify an alternative
1765** memory allocator that simulates memory out-of-memory conditions in
1766** order to verify that SQLite recovers gracefully from such
1767** conditions.
1768**
1769** The xMalloc, xRealloc, and xFree methods must work like the
1770** malloc(), realloc() and free() functions from the standard C library.
1771** ^SQLite guarantees that the second argument to
1772** xRealloc is always a value returned by a prior call to xRoundup.
1773**
1774** xSize should return the allocated size of a memory allocation
1775** previously obtained from xMalloc or xRealloc.  The allocated size
1776** is always at least as big as the requested size but may be larger.
1777**
1778** The xRoundup method returns what would be the allocated size of
1779** a memory allocation given a particular requested size.  Most memory
1780** allocators round up memory allocations at least to the next multiple
1781** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1782** Every memory allocation request coming in through [sqlite3_malloc()]
1783** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1784** that causes the corresponding memory allocation to fail.
1785**
1786** The xInit method initializes the memory allocator.  For example,
1787** it might allocate any require mutexes or initialize internal data
1788** structures.  The xShutdown method is invoked (indirectly) by
1789** [sqlite3_shutdown()] and should deallocate any resources acquired
1790** by xInit.  The pAppData pointer is used as the only parameter to
1791** xInit and xShutdown.
1792**
1793** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1794** the xInit method, so the xInit method need not be threadsafe.  The
1795** xShutdown method is only called from [sqlite3_shutdown()] so it does
1796** not need to be threadsafe either.  For all other methods, SQLite
1797** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1798** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1799** it is by default) and so the methods are automatically serialized.
1800** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1801** methods must be threadsafe or else make their own arrangements for
1802** serialization.
1803**
1804** SQLite will never invoke xInit() more than once without an intervening
1805** call to xShutdown().
1806*/
1807typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1808struct sqlite3_mem_methods {
1809  void *(*xMalloc)(int);         /* Memory allocation function */
1810  void (*xFree)(void*);          /* Free a prior allocation */
1811  void *(*xRealloc)(void*,int);  /* Resize an allocation */
1812  int (*xSize)(void*);           /* Return the size of an allocation */
1813  int (*xRoundup)(int);          /* Round up request size to allocation size */
1814  int (*xInit)(void*);           /* Initialize the memory allocator */
1815  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1816  void *pAppData;                /* Argument to xInit() and xShutdown() */
1817};
1818
1819/*
1820** CAPI3REF: Configuration Options
1821** KEYWORDS: {configuration option}
1822**
1823** These constants are the available integer configuration options that
1824** can be passed as the first argument to the [sqlite3_config()] interface.
1825**
1826** New configuration options may be added in future releases of SQLite.
1827** Existing configuration options might be discontinued.  Applications
1828** should check the return code from [sqlite3_config()] to make sure that
1829** the call worked.  The [sqlite3_config()] interface will return a
1830** non-zero [error code] if a discontinued or unsupported configuration option
1831** is invoked.
1832**
1833** <dl>
1834** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1835** <dd>There are no arguments to this option.  ^This option sets the
1836** [threading mode] to Single-thread.  In other words, it disables
1837** all mutexing and puts SQLite into a mode where it can only be used
1838** by a single thread.   ^If SQLite is compiled with
1839** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1840** it is not possible to change the [threading mode] from its default
1841** value of Single-thread and so [sqlite3_config()] will return
1842** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1843** configuration option.</dd>
1844**
1845** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1846** <dd>There are no arguments to this option.  ^This option sets the
1847** [threading mode] to Multi-thread.  In other words, it disables
1848** mutexing on [database connection] and [prepared statement] objects.
1849** The application is responsible for serializing access to
1850** [database connections] and [prepared statements].  But other mutexes
1851** are enabled so that SQLite will be safe to use in a multi-threaded
1852** environment as long as no two threads attempt to use the same
1853** [database connection] at the same time.  ^If SQLite is compiled with
1854** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1855** it is not possible to set the Multi-thread [threading mode] and
1856** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1857** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1858**
1859** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1860** <dd>There are no arguments to this option.  ^This option sets the
1861** [threading mode] to Serialized. In other words, this option enables
1862** all mutexes including the recursive
1863** mutexes on [database connection] and [prepared statement] objects.
1864** In this mode (which is the default when SQLite is compiled with
1865** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1866** to [database connections] and [prepared statements] so that the
1867** application is free to use the same [database connection] or the
1868** same [prepared statement] in different threads at the same time.
1869** ^If SQLite is compiled with
1870** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1871** it is not possible to set the Serialized [threading mode] and
1872** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1873** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1874**
1875** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1876** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
1877** a pointer to an instance of the [sqlite3_mem_methods] structure.
1878** The argument specifies
1879** alternative low-level memory allocation routines to be used in place of
1880** the memory allocation routines built into SQLite.)^ ^SQLite makes
1881** its own private copy of the content of the [sqlite3_mem_methods] structure
1882** before the [sqlite3_config()] call returns.</dd>
1883**
1884** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1885** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
1886** is a pointer to an instance of the [sqlite3_mem_methods] structure.
1887** The [sqlite3_mem_methods]
1888** structure is filled with the currently defined memory allocation routines.)^
1889** This option can be used to overload the default memory allocation
1890** routines with a wrapper that simulations memory allocation failure or
1891** tracks memory usage, for example. </dd>
1892**
1893** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1894** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
1895** interpreted as a boolean, which enables or disables the collection of
1896** memory allocation statistics. ^(When memory allocation statistics are
1897** disabled, the following SQLite interfaces become non-operational:
1898**   <ul>
1899**   <li> [sqlite3_memory_used()]
1900**   <li> [sqlite3_memory_highwater()]
1901**   <li> [sqlite3_soft_heap_limit64()]
1902**   <li> [sqlite3_status64()]
1903**   </ul>)^
1904** ^Memory allocation statistics are enabled by default unless SQLite is
1905** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1906** allocation statistics are disabled by default.
1907** </dd>
1908**
1909** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1910** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
1911** that SQLite can use for scratch memory.  ^(There are three arguments
1912** to SQLITE_CONFIG_SCRATCH:  A pointer an 8-byte
1913** aligned memory buffer from which the scratch allocations will be
1914** drawn, the size of each scratch allocation (sz),
1915** and the maximum number of scratch allocations (N).)^
1916** The first argument must be a pointer to an 8-byte aligned buffer
1917** of at least sz*N bytes of memory.
1918** ^SQLite will not use more than one scratch buffers per thread.
1919** ^SQLite will never request a scratch buffer that is more than 6
1920** times the database page size.
1921** ^If SQLite needs needs additional
1922** scratch memory beyond what is provided by this configuration option, then
1923** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
1924** ^When the application provides any amount of scratch memory using
1925** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
1926** [sqlite3_malloc|heap allocations].
1927** This can help [Robson proof|prevent memory allocation failures] due to heap
1928** fragmentation in low-memory embedded systems.
1929** </dd>
1930**
1931** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1932** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
1933** that SQLite can use for the database page cache with the default page
1934** cache implementation.
1935** This configuration option is a no-op if an application-define page
1936** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
1937** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
1938** 8-byte aligned memory (pMem), the size of each page cache line (sz),
1939** and the number of cache lines (N).
1940** The sz argument should be the size of the largest database page
1941** (a power of two between 512 and 65536) plus some extra bytes for each
1942** page header.  ^The number of extra bytes needed by the page header
1943** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
1944** ^It is harmless, apart from the wasted memory,
1945** for the sz parameter to be larger than necessary.  The pMem
1946** argument must be either a NULL pointer or a pointer to an 8-byte
1947** aligned block of memory of at least sz*N bytes, otherwise
1948** subsequent behavior is undefined.
1949** ^When pMem is not NULL, SQLite will strive to use the memory provided
1950** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
1951** a page cache line is larger than sz bytes or if all of the pMem buffer
1952** is exhausted.
1953** ^If pMem is NULL and N is non-zero, then each database connection
1954** does an initial bulk allocation for page cache memory
1955** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
1956** of -1024*N bytes if N is negative, . ^If additional
1957** page cache memory is needed beyond what is provided by the initial
1958** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
1959** additional cache line. </dd>
1960**
1961** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1962** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
1963** that SQLite will use for all of its dynamic memory allocation needs
1964** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
1965** [SQLITE_CONFIG_PAGECACHE].
1966** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
1967** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
1968** [SQLITE_ERROR] if invoked otherwise.
1969** ^There are three arguments to SQLITE_CONFIG_HEAP:
1970** An 8-byte aligned pointer to the memory,
1971** the number of bytes in the memory buffer, and the minimum allocation size.
1972** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1973** to using its default memory allocator (the system malloc() implementation),
1974** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1975** memory pointer is not NULL then the alternative memory
1976** allocator is engaged to handle all of SQLites memory allocation needs.
1977** The first pointer (the memory pointer) must be aligned to an 8-byte
1978** boundary or subsequent behavior of SQLite will be undefined.
1979** The minimum allocation size is capped at 2**12. Reasonable values
1980** for the minimum allocation size are 2**5 through 2**8.</dd>
1981**
1982** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1983** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
1984** pointer to an instance of the [sqlite3_mutex_methods] structure.
1985** The argument specifies alternative low-level mutex routines to be used
1986** in place the mutex routines built into SQLite.)^  ^SQLite makes a copy of
1987** the content of the [sqlite3_mutex_methods] structure before the call to
1988** [sqlite3_config()] returns. ^If SQLite is compiled with
1989** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1990** the entire mutexing subsystem is omitted from the build and hence calls to
1991** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1992** return [SQLITE_ERROR].</dd>
1993**
1994** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1995** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
1996** is a pointer to an instance of the [sqlite3_mutex_methods] structure.  The
1997** [sqlite3_mutex_methods]
1998** structure is filled with the currently defined mutex routines.)^
1999** This option can be used to overload the default mutex allocation
2000** routines with a wrapper used to track mutex usage for performance
2001** profiling or testing, for example.   ^If SQLite is compiled with
2002** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2003** the entire mutexing subsystem is omitted from the build and hence calls to
2004** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2005** return [SQLITE_ERROR].</dd>
2006**
2007** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2008** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
2009** the default size of lookaside memory on each [database connection].
2010** The first argument is the
2011** size of each lookaside buffer slot and the second is the number of
2012** slots allocated to each database connection.)^  ^(SQLITE_CONFIG_LOOKASIDE
2013** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2014** option to [sqlite3_db_config()] can be used to change the lookaside
2015** configuration on individual connections.)^ </dd>
2016**
2017** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2018** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
2019** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies
2020** the interface to a custom page cache implementation.)^
2021** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
2022**
2023** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2024** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
2025** is a pointer to an [sqlite3_pcache_methods2] object.  SQLite copies of
2026** the current page cache implementation into that object.)^ </dd>
2027**
2028** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2029** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
2030** global [error log].
2031** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2032** function with a call signature of void(*)(void*,int,const char*),
2033** and a pointer to void. ^If the function pointer is not NULL, it is
2034** invoked by [sqlite3_log()] to process each logging event.  ^If the
2035** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2036** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2037** passed through as the first parameter to the application-defined logger
2038** function whenever that function is invoked.  ^The second parameter to
2039** the logger function is a copy of the first parameter to the corresponding
2040** [sqlite3_log()] call and is intended to be a [result code] or an
2041** [extended result code].  ^The third parameter passed to the logger is
2042** log message after formatting via [sqlite3_snprintf()].
2043** The SQLite logging interface is not reentrant; the logger function
2044** supplied by the application must not invoke any SQLite interface.
2045** In a multi-threaded application, the application-defined logger
2046** function must be threadsafe. </dd>
2047**
2048** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2049** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
2050** If non-zero, then URI handling is globally enabled. If the parameter is zero,
2051** then URI handling is globally disabled.)^ ^If URI handling is globally
2052** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
2053** [sqlite3_open16()] or
2054** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2055** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2056** connection is opened. ^If it is globally disabled, filenames are
2057** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2058** database connection is opened. ^(By default, URI handling is globally
2059** disabled. The default value may be changed by compiling with the
2060** [SQLITE_USE_URI] symbol defined.)^
2061**
2062** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2063** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
2064** argument which is interpreted as a boolean in order to enable or disable
2065** the use of covering indices for full table scans in the query optimizer.
2066** ^The default setting is determined
2067** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2068** if that compile-time option is omitted.
2069** The ability to disable the use of covering indices for full table scans
2070** is because some incorrectly coded legacy applications might malfunction
2071** when the optimization is enabled.  Providing the ability to
2072** disable the optimization allows the older, buggy application code to work
2073** without change even with newer versions of SQLite.
2074**
2075** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2076** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2077** <dd> These options are obsolete and should not be used by new code.
2078** They are retained for backwards compatibility but are now no-ops.
2079** </dd>
2080**
2081** [[SQLITE_CONFIG_SQLLOG]]
2082** <dt>SQLITE_CONFIG_SQLLOG
2083** <dd>This option is only available if sqlite is compiled with the
2084** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2085** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2086** The second should be of type (void*). The callback is invoked by the library
2087** in three separate circumstances, identified by the value passed as the
2088** fourth parameter. If the fourth parameter is 0, then the database connection
2089** passed as the second argument has just been opened. The third argument
2090** points to a buffer containing the name of the main database file. If the
2091** fourth parameter is 1, then the SQL statement that the third parameter
2092** points to has just been executed. Or, if the fourth parameter is 2, then
2093** the connection being passed as the second parameter is being closed. The
2094** third parameter is passed NULL In this case.  An example of using this
2095** configuration option can be seen in the "test_sqllog.c" source file in
2096** the canonical SQLite source tree.</dd>
2097**
2098** [[SQLITE_CONFIG_MMAP_SIZE]]
2099** <dt>SQLITE_CONFIG_MMAP_SIZE
2100** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2101** that are the default mmap size limit (the default setting for
2102** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2103** ^The default setting can be overridden by each database connection using
2104** either the [PRAGMA mmap_size] command, or by using the
2105** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
2106** will be silently truncated if necessary so that it does not exceed the
2107** compile-time maximum mmap size set by the
2108** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
2109** ^If either argument to this option is negative, then that argument is
2110** changed to its compile-time default.
2111**
2112** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
2113** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
2114** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
2115** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
2116** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
2117** that specifies the maximum size of the created heap.
2118**
2119** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
2120** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
2121** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
2122** is a pointer to an integer and writes into that integer the number of extra
2123** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
2124** The amount of extra space required can change depending on the compiler,
2125** target platform, and SQLite version.
2126**
2127** [[SQLITE_CONFIG_PMASZ]]
2128** <dt>SQLITE_CONFIG_PMASZ
2129** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
2130** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
2131** sorter to that integer.  The default minimum PMA Size is set by the
2132** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched
2133** to help with sort operations when multithreaded sorting
2134** is enabled (using the [PRAGMA threads] command) and the amount of content
2135** to be sorted exceeds the page size times the minimum of the
2136** [PRAGMA cache_size] setting and this value.
2137**
2138** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
2139** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
2140** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
2141** becomes the [statement journal] spill-to-disk threshold.
2142** [Statement journals] are held in memory until their size (in bytes)
2143** exceeds this threshold, at which point they are written to disk.
2144** Or if the threshold is -1, statement journals are always held
2145** exclusively in memory.
2146** Since many statement journals never become large, setting the spill
2147** threshold to a value such as 64KiB can greatly reduce the amount of
2148** I/O required to support statement rollback.
2149** The default value for this setting is controlled by the
2150** [SQLITE_STMTJRNL_SPILL] compile-time option.
2151** </dl>
2152*/
2153#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2154#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2155#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2156#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2157#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2158#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2159#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2160#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2161#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2162#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2163#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2164/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2165#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2166#define SQLITE_CONFIG_PCACHE       14  /* no-op */
2167#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2168#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2169#define SQLITE_CONFIG_URI          17  /* int */
2170#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2171#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2172#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
2173#define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
2174#define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
2175#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
2176#define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
2177#define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
2178#define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */
2179
2180/*
2181** CAPI3REF: Database Connection Configuration Options
2182**
2183** These constants are the available integer configuration options that
2184** can be passed as the second argument to the [sqlite3_db_config()] interface.
2185**
2186** New configuration options may be added in future releases of SQLite.
2187** Existing configuration options might be discontinued.  Applications
2188** should check the return code from [sqlite3_db_config()] to make sure that
2189** the call worked.  ^The [sqlite3_db_config()] interface will return a
2190** non-zero [error code] if a discontinued or unsupported configuration option
2191** is invoked.
2192**
2193** <dl>
2194** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2195** <dd> ^This option takes three additional arguments that determine the
2196** [lookaside memory allocator] configuration for the [database connection].
2197** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2198** pointer to a memory buffer to use for lookaside memory.
2199** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2200** may be NULL in which case SQLite will allocate the
2201** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2202** size of each lookaside buffer slot.  ^The third argument is the number of
2203** slots.  The size of the buffer in the first argument must be greater than
2204** or equal to the product of the second and third arguments.  The buffer
2205** must be aligned to an 8-byte boundary.  ^If the second argument to
2206** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2207** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2208** configuration for a database connection can only be changed when that
2209** connection is not currently using lookaside memory, or in other words
2210** when the "current value" returned by
2211** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2212** Any attempt to change the lookaside memory configuration when lookaside
2213** memory is in use leaves the configuration unchanged and returns
2214** [SQLITE_BUSY].)^</dd>
2215**
2216** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2217** <dd> ^This option is used to enable or disable the enforcement of
2218** [foreign key constraints].  There should be two additional arguments.
2219** The first argument is an integer which is 0 to disable FK enforcement,
2220** positive to enable FK enforcement or negative to leave FK enforcement
2221** unchanged.  The second parameter is a pointer to an integer into which
2222** is written 0 or 1 to indicate whether FK enforcement is off or on
2223** following this call.  The second parameter may be a NULL pointer, in
2224** which case the FK enforcement setting is not reported back. </dd>
2225**
2226** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2227** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2228** There should be two additional arguments.
2229** The first argument is an integer which is 0 to disable triggers,
2230** positive to enable triggers or negative to leave the setting unchanged.
2231** The second parameter is a pointer to an integer into which
2232** is written 0 or 1 to indicate whether triggers are disabled or enabled
2233** following this call.  The second parameter may be a NULL pointer, in
2234** which case the trigger setting is not reported back. </dd>
2235**
2236** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
2237** <dd> ^This option is used to enable or disable the two-argument
2238** version of the [fts3_tokenizer()] function which is part of the
2239** [FTS3] full-text search engine extension.
2240** There should be two additional arguments.
2241** The first argument is an integer which is 0 to disable fts3_tokenizer() or
2242** positive to enable fts3_tokenizer() or negative to leave the setting
2243** unchanged.
2244** The second parameter is a pointer to an integer into which
2245** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
2246** following this call.  The second parameter may be a NULL pointer, in
2247** which case the new setting is not reported back. </dd>
2248**
2249** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
2250** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
2251** interface independently of the [load_extension()] SQL function.
2252** The [sqlite3_enable_load_extension()] API enables or disables both the
2253** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
2254** There should be two additional arguments.
2255** When the first argument to this interface is 1, then only the C-API is
2256** enabled and the SQL function remains disabled.  If the first argument to
2257** this interface is 0, then both the C-API and the SQL function are disabled.
2258** If the first argument is -1, then no changes are made to state of either the
2259** C-API or the SQL function.
2260** The second parameter is a pointer to an integer into which
2261** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
2262** is disabled or enabled following this call.  The second parameter may
2263** be a NULL pointer, in which case the new setting is not reported back.
2264** </dd>
2265**
2266** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
2267** <dd> ^This option is used to change the name of the "main" database
2268** schema.  ^The sole argument is a pointer to a constant UTF8 string
2269** which will become the new schema name in place of "main".  ^SQLite
2270** does not make a copy of the new main schema name string, so the application
2271** must ensure that the argument passed into this DBCONFIG option is unchanged
2272** until after the database connection closes.
2273** </dd>
2274**
2275** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
2276** <dd> Usually, when a database in wal mode is closed or detached from a
2277** database handle, SQLite checks if this will mean that there are now no
2278** connections at all to the database. If so, it performs a checkpoint
2279** operation before closing the connection. This option may be used to
2280** override this behaviour. The first parameter passed to this operation
2281** is an integer - non-zero to disable checkpoints-on-close, or zero (the
2282** default) to enable them. The second parameter is a pointer to an integer
2283** into which is written 0 or 1 to indicate whether checkpoints-on-close
2284** have been disabled - 0 if they are not disabled, 1 if they are.
2285** </dd>
2286**
2287** </dl>
2288*/
2289#define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
2290#define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
2291#define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
2292#define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
2293#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
2294#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
2295#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */
2296
2297
2298/*
2299** CAPI3REF: Enable Or Disable Extended Result Codes
2300** METHOD: sqlite3
2301**
2302** ^The sqlite3_extended_result_codes() routine enables or disables the
2303** [extended result codes] feature of SQLite. ^The extended result
2304** codes are disabled by default for historical compatibility.
2305*/
2306SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2307
2308/*
2309** CAPI3REF: Last Insert Rowid
2310** METHOD: sqlite3
2311**
2312** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
2313** has a unique 64-bit signed
2314** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2315** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2316** names are not also used by explicitly declared columns. ^If
2317** the table has a column of type [INTEGER PRIMARY KEY] then that column
2318** is another alias for the rowid.
2319**
2320** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
2321** the most recent successful [INSERT] into a rowid table or [virtual table]
2322** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
2323** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
2324** on the database connection D, then sqlite3_last_insert_rowid(D) returns
2325** zero.
2326**
2327** As well as being set automatically as rows are inserted into database
2328** tables, the value returned by this function may be set explicitly by
2329** [sqlite3_set_last_insert_rowid()]
2330**
2331** Some virtual table implementations may INSERT rows into rowid tables as
2332** part of committing a transaction (e.g. to flush data accumulated in memory
2333** to disk). In this case subsequent calls to this function return the rowid
2334** associated with these internal INSERT operations, which leads to
2335** unintuitive results. Virtual table implementations that do write to rowid
2336** tables in this way can avoid this problem by restoring the original
2337** rowid value using [sqlite3_set_last_insert_rowid()] before returning
2338** control to the user.
2339**
2340** ^(If an [INSERT] occurs within a trigger then this routine will
2341** return the [rowid] of the inserted row as long as the trigger is
2342** running. Once the trigger program ends, the value returned
2343** by this routine reverts to what it was before the trigger was fired.)^
2344**
2345** ^An [INSERT] that fails due to a constraint violation is not a
2346** successful [INSERT] and does not change the value returned by this
2347** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2348** and INSERT OR ABORT make no changes to the return value of this
2349** routine when their insertion fails.  ^(When INSERT OR REPLACE
2350** encounters a constraint violation, it does not fail.  The
2351** INSERT continues to completion after deleting rows that caused
2352** the constraint problem so INSERT OR REPLACE will always change
2353** the return value of this interface.)^
2354**
2355** ^For the purposes of this routine, an [INSERT] is considered to
2356** be successful even if it is subsequently rolled back.
2357**
2358** This function is accessible to SQL statements via the
2359** [last_insert_rowid() SQL function].
2360**
2361** If a separate thread performs a new [INSERT] on the same
2362** database connection while the [sqlite3_last_insert_rowid()]
2363** function is running and thus changes the last insert [rowid],
2364** then the value returned by [sqlite3_last_insert_rowid()] is
2365** unpredictable and might not equal either the old or the new
2366** last insert [rowid].
2367*/
2368SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2369
2370/*
2371** CAPI3REF: Set the Last Insert Rowid value.
2372** METHOD: sqlite3
2373**
2374** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
2375** set the value returned by calling sqlite3_last_insert_rowid(D) to R
2376** without inserting a row into the database.
2377*/
2378SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
2379
2380/*
2381** CAPI3REF: Count The Number Of Rows Modified
2382** METHOD: sqlite3
2383**
2384** ^This function returns the number of rows modified, inserted or
2385** deleted by the most recently completed INSERT, UPDATE or DELETE
2386** statement on the database connection specified by the only parameter.
2387** ^Executing any other type of SQL statement does not modify the value
2388** returned by this function.
2389**
2390** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
2391** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
2392** [foreign key actions] or [REPLACE] constraint resolution are not counted.
2393**
2394** Changes to a view that are intercepted by
2395** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
2396** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
2397** DELETE statement run on a view is always zero. Only changes made to real
2398** tables are counted.
2399**
2400** Things are more complicated if the sqlite3_changes() function is
2401** executed while a trigger program is running. This may happen if the
2402** program uses the [changes() SQL function], or if some other callback
2403** function invokes sqlite3_changes() directly. Essentially:
2404**
2405** <ul>
2406**   <li> ^(Before entering a trigger program the value returned by
2407**        sqlite3_changes() function is saved. After the trigger program
2408**        has finished, the original value is restored.)^
2409**
2410**   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
2411**        statement sets the value returned by sqlite3_changes()
2412**        upon completion as normal. Of course, this value will not include
2413**        any changes performed by sub-triggers, as the sqlite3_changes()
2414**        value will be saved and restored after each sub-trigger has run.)^
2415** </ul>
2416**
2417** ^This means that if the changes() SQL function (or similar) is used
2418** by the first INSERT, UPDATE or DELETE statement within a trigger, it
2419** returns the value as set when the calling statement began executing.
2420** ^If it is used by the second or subsequent such statement within a trigger
2421** program, the value returned reflects the number of rows modified by the
2422** previous INSERT, UPDATE or DELETE statement within the same trigger.
2423**
2424** See also the [sqlite3_total_changes()] interface, the
2425** [count_changes pragma], and the [changes() SQL function].
2426**
2427** If a separate thread makes changes on the same database connection
2428** while [sqlite3_changes()] is running then the value returned
2429** is unpredictable and not meaningful.
2430*/
2431SQLITE_API int sqlite3_changes(sqlite3*);
2432
2433/*
2434** CAPI3REF: Total Number Of Rows Modified
2435** METHOD: sqlite3
2436**
2437** ^This function returns the total number of rows inserted, modified or
2438** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
2439** since the database connection was opened, including those executed as
2440** part of trigger programs. ^Executing any other type of SQL statement
2441** does not affect the value returned by sqlite3_total_changes().
2442**
2443** ^Changes made as part of [foreign key actions] are included in the
2444** count, but those made as part of REPLACE constraint resolution are
2445** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
2446** are not counted.
2447**
2448** See also the [sqlite3_changes()] interface, the
2449** [count_changes pragma], and the [total_changes() SQL function].
2450**
2451** If a separate thread makes changes on the same database connection
2452** while [sqlite3_total_changes()] is running then the value
2453** returned is unpredictable and not meaningful.
2454*/
2455SQLITE_API int sqlite3_total_changes(sqlite3*);
2456
2457/*
2458** CAPI3REF: Interrupt A Long-Running Query
2459** METHOD: sqlite3
2460**
2461** ^This function causes any pending database operation to abort and
2462** return at its earliest opportunity. This routine is typically
2463** called in response to a user action such as pressing "Cancel"
2464** or Ctrl-C where the user wants a long query operation to halt
2465** immediately.
2466**
2467** ^It is safe to call this routine from a thread different from the
2468** thread that is currently running the database operation.  But it
2469** is not safe to call this routine with a [database connection] that
2470** is closed or might close before sqlite3_interrupt() returns.
2471**
2472** ^If an SQL operation is very nearly finished at the time when
2473** sqlite3_interrupt() is called, then it might not have an opportunity
2474** to be interrupted and might continue to completion.
2475**
2476** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2477** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2478** that is inside an explicit transaction, then the entire transaction
2479** will be rolled back automatically.
2480**
2481** ^The sqlite3_interrupt(D) call is in effect until all currently running
2482** SQL statements on [database connection] D complete.  ^Any new SQL statements
2483** that are started after the sqlite3_interrupt() call and before the
2484** running statements reaches zero are interrupted as if they had been
2485** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2486** that are started after the running statement count reaches zero are
2487** not effected by the sqlite3_interrupt().
2488** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2489** SQL statements is a no-op and has no effect on SQL statements
2490** that are started after the sqlite3_interrupt() call returns.
2491**
2492** If the database connection closes while [sqlite3_interrupt()]
2493** is running then bad things will likely happen.
2494*/
2495SQLITE_API void sqlite3_interrupt(sqlite3*);
2496
2497/*
2498** CAPI3REF: Determine If An SQL Statement Is Complete
2499**
2500** These routines are useful during command-line input to determine if the
2501** currently entered text seems to form a complete SQL statement or
2502** if additional input is needed before sending the text into
2503** SQLite for parsing.  ^These routines return 1 if the input string
2504** appears to be a complete SQL statement.  ^A statement is judged to be
2505** complete if it ends with a semicolon token and is not a prefix of a
2506** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2507** string literals or quoted identifier names or comments are not
2508** independent tokens (they are part of the token in which they are
2509** embedded) and thus do not count as a statement terminator.  ^Whitespace
2510** and comments that follow the final semicolon are ignored.
2511**
2512** ^These routines return 0 if the statement is incomplete.  ^If a
2513** memory allocation fails, then SQLITE_NOMEM is returned.
2514**
2515** ^These routines do not parse the SQL statements thus
2516** will not detect syntactically incorrect SQL.
2517**
2518** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2519** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2520** automatically by sqlite3_complete16().  If that initialization fails,
2521** then the return value from sqlite3_complete16() will be non-zero
2522** regardless of whether or not the input SQL is complete.)^
2523**
2524** The input to [sqlite3_complete()] must be a zero-terminated
2525** UTF-8 string.
2526**
2527** The input to [sqlite3_complete16()] must be a zero-terminated
2528** UTF-16 string in native byte order.
2529*/
2530SQLITE_API int sqlite3_complete(const char *sql);
2531SQLITE_API int sqlite3_complete16(const void *sql);
2532
2533/*
2534** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2535** KEYWORDS: {busy-handler callback} {busy handler}
2536** METHOD: sqlite3
2537**
2538** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
2539** that might be invoked with argument P whenever
2540** an attempt is made to access a database table associated with
2541** [database connection] D when another thread
2542** or process has the table locked.
2543** The sqlite3_busy_handler() interface is used to implement
2544** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
2545**
2546** ^If the busy callback is NULL, then [SQLITE_BUSY]
2547** is returned immediately upon encountering the lock.  ^If the busy callback
2548** is not NULL, then the callback might be invoked with two arguments.
2549**
2550** ^The first argument to the busy handler is a copy of the void* pointer which
2551** is the third argument to sqlite3_busy_handler().  ^The second argument to
2552** the busy handler callback is the number of times that the busy handler has
2553** been invoked previously for the same locking event.  ^If the
2554** busy callback returns 0, then no additional attempts are made to
2555** access the database and [SQLITE_BUSY] is returned
2556** to the application.
2557** ^If the callback returns non-zero, then another attempt
2558** is made to access the database and the cycle repeats.
2559**
2560** The presence of a busy handler does not guarantee that it will be invoked
2561** when there is lock contention. ^If SQLite determines that invoking the busy
2562** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2563** to the application instead of invoking the
2564** busy handler.
2565** Consider a scenario where one process is holding a read lock that
2566** it is trying to promote to a reserved lock and
2567** a second process is holding a reserved lock that it is trying
2568** to promote to an exclusive lock.  The first process cannot proceed
2569** because it is blocked by the second and the second process cannot
2570** proceed because it is blocked by the first.  If both processes
2571** invoke the busy handlers, neither will make any progress.  Therefore,
2572** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2573** will induce the first process to release its read lock and allow
2574** the second process to proceed.
2575**
2576** ^The default busy callback is NULL.
2577**
2578** ^(There can only be a single busy handler defined for each
2579** [database connection].  Setting a new busy handler clears any
2580** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2581** or evaluating [PRAGMA busy_timeout=N] will change the
2582** busy handler and thus clear any previously set busy handler.
2583**
2584** The busy callback should not take any actions which modify the
2585** database connection that invoked the busy handler.  In other words,
2586** the busy handler is not reentrant.  Any such actions
2587** result in undefined behavior.
2588**
2589** A busy handler must not close the database connection
2590** or [prepared statement] that invoked the busy handler.
2591*/
2592SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
2593
2594/*
2595** CAPI3REF: Set A Busy Timeout
2596** METHOD: sqlite3
2597**
2598** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2599** for a specified amount of time when a table is locked.  ^The handler
2600** will sleep multiple times until at least "ms" milliseconds of sleeping
2601** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2602** the handler returns 0 which causes [sqlite3_step()] to return
2603** [SQLITE_BUSY].
2604**
2605** ^Calling this routine with an argument less than or equal to zero
2606** turns off all busy handlers.
2607**
2608** ^(There can only be a single busy handler for a particular
2609** [database connection] at any given moment.  If another busy handler
2610** was defined  (using [sqlite3_busy_handler()]) prior to calling
2611** this routine, that other busy handler is cleared.)^
2612**
2613** See also:  [PRAGMA busy_timeout]
2614*/
2615SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2616
2617/*
2618** CAPI3REF: Convenience Routines For Running Queries
2619** METHOD: sqlite3
2620**
2621** This is a legacy interface that is preserved for backwards compatibility.
2622** Use of this interface is not recommended.
2623**
2624** Definition: A <b>result table</b> is memory data structure created by the
2625** [sqlite3_get_table()] interface.  A result table records the
2626** complete query results from one or more queries.
2627**
2628** The table conceptually has a number of rows and columns.  But
2629** these numbers are not part of the result table itself.  These
2630** numbers are obtained separately.  Let N be the number of rows
2631** and M be the number of columns.
2632**
2633** A result table is an array of pointers to zero-terminated UTF-8 strings.
2634** There are (N+1)*M elements in the array.  The first M pointers point
2635** to zero-terminated strings that  contain the names of the columns.
2636** The remaining entries all point to query results.  NULL values result
2637** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2638** string representation as returned by [sqlite3_column_text()].
2639**
2640** A result table might consist of one or more memory allocations.
2641** It is not safe to pass a result table directly to [sqlite3_free()].
2642** A result table should be deallocated using [sqlite3_free_table()].
2643**
2644** ^(As an example of the result table format, suppose a query result
2645** is as follows:
2646**
2647** <blockquote><pre>
2648**        Name        | Age
2649**        -----------------------
2650**        Alice       | 43
2651**        Bob         | 28
2652**        Cindy       | 21
2653** </pre></blockquote>
2654**
2655** There are two column (M==2) and three rows (N==3).  Thus the
2656** result table has 8 entries.  Suppose the result table is stored
2657** in an array names azResult.  Then azResult holds this content:
2658**
2659** <blockquote><pre>
2660**        azResult&#91;0] = "Name";
2661**        azResult&#91;1] = "Age";
2662**        azResult&#91;2] = "Alice";
2663**        azResult&#91;3] = "43";
2664**        azResult&#91;4] = "Bob";
2665**        azResult&#91;5] = "28";
2666**        azResult&#91;6] = "Cindy";
2667**        azResult&#91;7] = "21";
2668** </pre></blockquote>)^
2669**
2670** ^The sqlite3_get_table() function evaluates one or more
2671** semicolon-separated SQL statements in the zero-terminated UTF-8
2672** string of its 2nd parameter and returns a result table to the
2673** pointer given in its 3rd parameter.
2674**
2675** After the application has finished with the result from sqlite3_get_table(),
2676** it must pass the result table pointer to sqlite3_free_table() in order to
2677** release the memory that was malloced.  Because of the way the
2678** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2679** function must not try to call [sqlite3_free()] directly.  Only
2680** [sqlite3_free_table()] is able to release the memory properly and safely.
2681**
2682** The sqlite3_get_table() interface is implemented as a wrapper around
2683** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2684** to any internal data structures of SQLite.  It uses only the public
2685** interface defined here.  As a consequence, errors that occur in the
2686** wrapper layer outside of the internal [sqlite3_exec()] call are not
2687** reflected in subsequent calls to [sqlite3_errcode()] or
2688** [sqlite3_errmsg()].
2689*/
2690SQLITE_API int sqlite3_get_table(
2691  sqlite3 *db,          /* An open database */
2692  const char *zSql,     /* SQL to be evaluated */
2693  char ***pazResult,    /* Results of the query */
2694  int *pnRow,           /* Number of result rows written here */
2695  int *pnColumn,        /* Number of result columns written here */
2696  char **pzErrmsg       /* Error msg written here */
2697);
2698SQLITE_API void sqlite3_free_table(char **result);
2699
2700/*
2701** CAPI3REF: Formatted String Printing Functions
2702**
2703** These routines are work-alikes of the "printf()" family of functions
2704** from the standard C library.
2705** These routines understand most of the common K&R formatting options,
2706** plus some additional non-standard formats, detailed below.
2707** Note that some of the more obscure formatting options from recent
2708** C-library standards are omitted from this implementation.
2709**
2710** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2711** results into memory obtained from [sqlite3_malloc()].
2712** The strings returned by these two routines should be
2713** released by [sqlite3_free()].  ^Both routines return a
2714** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2715** memory to hold the resulting string.
2716**
2717** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2718** the standard C library.  The result is written into the
2719** buffer supplied as the second parameter whose size is given by
2720** the first parameter. Note that the order of the
2721** first two parameters is reversed from snprintf().)^  This is an
2722** historical accident that cannot be fixed without breaking
2723** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2724** returns a pointer to its buffer instead of the number of
2725** characters actually written into the buffer.)^  We admit that
2726** the number of characters written would be a more useful return
2727** value but we cannot change the implementation of sqlite3_snprintf()
2728** now without breaking compatibility.
2729**
2730** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2731** guarantees that the buffer is always zero-terminated.  ^The first
2732** parameter "n" is the total size of the buffer, including space for
2733** the zero terminator.  So the longest string that can be completely
2734** written will be n-1 characters.
2735**
2736** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2737**
2738** These routines all implement some additional formatting
2739** options that are useful for constructing SQL statements.
2740** All of the usual printf() formatting options apply.  In addition, there
2741** is are "%q", "%Q", "%w" and "%z" options.
2742**
2743** ^(The %q option works like %s in that it substitutes a nul-terminated
2744** string from the argument list.  But %q also doubles every '\'' character.
2745** %q is designed for use inside a string literal.)^  By doubling each '\''
2746** character it escapes that character and allows it to be inserted into
2747** the string.
2748**
2749** For example, assume the string variable zText contains text as follows:
2750**
2751** <blockquote><pre>
2752**  char *zText = "It's a happy day!";
2753** </pre></blockquote>
2754**
2755** One can use this text in an SQL statement as follows:
2756**
2757** <blockquote><pre>
2758**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2759**  sqlite3_exec(db, zSQL, 0, 0, 0);
2760**  sqlite3_free(zSQL);
2761** </pre></blockquote>
2762**
2763** Because the %q format string is used, the '\'' character in zText
2764** is escaped and the SQL generated is as follows:
2765**
2766** <blockquote><pre>
2767**  INSERT INTO table1 VALUES('It''s a happy day!')
2768** </pre></blockquote>
2769**
2770** This is correct.  Had we used %s instead of %q, the generated SQL
2771** would have looked like this:
2772**
2773** <blockquote><pre>
2774**  INSERT INTO table1 VALUES('It's a happy day!');
2775** </pre></blockquote>
2776**
2777** This second example is an SQL syntax error.  As a general rule you should
2778** always use %q instead of %s when inserting text into a string literal.
2779**
2780** ^(The %Q option works like %q except it also adds single quotes around
2781** the outside of the total string.  Additionally, if the parameter in the
2782** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2783** single quotes).)^  So, for example, one could say:
2784**
2785** <blockquote><pre>
2786**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2787**  sqlite3_exec(db, zSQL, 0, 0, 0);
2788**  sqlite3_free(zSQL);
2789** </pre></blockquote>
2790**
2791** The code above will render a correct SQL statement in the zSQL
2792** variable even if the zText variable is a NULL pointer.
2793**
2794** ^(The "%w" formatting option is like "%q" except that it expects to
2795** be contained within double-quotes instead of single quotes, and it
2796** escapes the double-quote character instead of the single-quote
2797** character.)^  The "%w" formatting option is intended for safely inserting
2798** table and column names into a constructed SQL statement.
2799**
2800** ^(The "%z" formatting option works like "%s" but with the
2801** addition that after the string has been read and copied into
2802** the result, [sqlite3_free()] is called on the input string.)^
2803*/
2804SQLITE_API char *sqlite3_mprintf(const char*,...);
2805SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2806SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2807SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2808
2809/*
2810** CAPI3REF: Memory Allocation Subsystem
2811**
2812** The SQLite core uses these three routines for all of its own
2813** internal memory allocation needs. "Core" in the previous sentence
2814** does not include operating-system specific VFS implementation.  The
2815** Windows VFS uses native malloc() and free() for some operations.
2816**
2817** ^The sqlite3_malloc() routine returns a pointer to a block
2818** of memory at least N bytes in length, where N is the parameter.
2819** ^If sqlite3_malloc() is unable to obtain sufficient free
2820** memory, it returns a NULL pointer.  ^If the parameter N to
2821** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2822** a NULL pointer.
2823**
2824** ^The sqlite3_malloc64(N) routine works just like
2825** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
2826** of a signed 32-bit integer.
2827**
2828** ^Calling sqlite3_free() with a pointer previously returned
2829** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2830** that it might be reused.  ^The sqlite3_free() routine is
2831** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2832** to sqlite3_free() is harmless.  After being freed, memory
2833** should neither be read nor written.  Even reading previously freed
2834** memory might result in a segmentation fault or other severe error.
2835** Memory corruption, a segmentation fault, or other severe error
2836** might result if sqlite3_free() is called with a non-NULL pointer that
2837** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2838**
2839** ^The sqlite3_realloc(X,N) interface attempts to resize a
2840** prior memory allocation X to be at least N bytes.
2841** ^If the X parameter to sqlite3_realloc(X,N)
2842** is a NULL pointer then its behavior is identical to calling
2843** sqlite3_malloc(N).
2844** ^If the N parameter to sqlite3_realloc(X,N) is zero or
2845** negative then the behavior is exactly the same as calling
2846** sqlite3_free(X).
2847** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
2848** of at least N bytes in size or NULL if insufficient memory is available.
2849** ^If M is the size of the prior allocation, then min(N,M) bytes
2850** of the prior allocation are copied into the beginning of buffer returned
2851** by sqlite3_realloc(X,N) and the prior allocation is freed.
2852** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
2853** prior allocation is not freed.
2854**
2855** ^The sqlite3_realloc64(X,N) interfaces works the same as
2856** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
2857** of a 32-bit signed integer.
2858**
2859** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
2860** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
2861** sqlite3_msize(X) returns the size of that memory allocation in bytes.
2862** ^The value returned by sqlite3_msize(X) might be larger than the number
2863** of bytes requested when X was allocated.  ^If X is a NULL pointer then
2864** sqlite3_msize(X) returns zero.  If X points to something that is not
2865** the beginning of memory allocation, or if it points to a formerly
2866** valid memory allocation that has now been freed, then the behavior
2867** of sqlite3_msize(X) is undefined and possibly harmful.
2868**
2869** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
2870** sqlite3_malloc64(), and sqlite3_realloc64()
2871** is always aligned to at least an 8 byte boundary, or to a
2872** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2873** option is used.
2874**
2875** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2876** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2877** implementation of these routines to be omitted.  That capability
2878** is no longer provided.  Only built-in memory allocators can be used.
2879**
2880** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2881** the system malloc() and free() directly when converting
2882** filenames between the UTF-8 encoding used by SQLite
2883** and whatever filename encoding is used by the particular Windows
2884** installation.  Memory allocation errors were detected, but
2885** they were reported back as [SQLITE_CANTOPEN] or
2886** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2887**
2888** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2889** must be either NULL or else pointers obtained from a prior
2890** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2891** not yet been released.
2892**
2893** The application must not read or write any part of
2894** a block of memory after it has been released using
2895** [sqlite3_free()] or [sqlite3_realloc()].
2896*/
2897SQLITE_API void *sqlite3_malloc(int);
2898SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
2899SQLITE_API void *sqlite3_realloc(void*, int);
2900SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
2901SQLITE_API void sqlite3_free(void*);
2902SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
2903
2904/*
2905** CAPI3REF: Memory Allocator Statistics
2906**
2907** SQLite provides these two interfaces for reporting on the status
2908** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2909** routines, which form the built-in memory allocation subsystem.
2910**
2911** ^The [sqlite3_memory_used()] routine returns the number of bytes
2912** of memory currently outstanding (malloced but not freed).
2913** ^The [sqlite3_memory_highwater()] routine returns the maximum
2914** value of [sqlite3_memory_used()] since the high-water mark
2915** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2916** [sqlite3_memory_highwater()] include any overhead
2917** added by SQLite in its implementation of [sqlite3_malloc()],
2918** but not overhead added by the any underlying system library
2919** routines that [sqlite3_malloc()] may call.
2920**
2921** ^The memory high-water mark is reset to the current value of
2922** [sqlite3_memory_used()] if and only if the parameter to
2923** [sqlite3_memory_highwater()] is true.  ^The value returned
2924** by [sqlite3_memory_highwater(1)] is the high-water mark
2925** prior to the reset.
2926*/
2927SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2928SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2929
2930/*
2931** CAPI3REF: Pseudo-Random Number Generator
2932**
2933** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2934** select random [ROWID | ROWIDs] when inserting new records into a table that
2935** already uses the largest possible [ROWID].  The PRNG is also used for
2936** the build-in random() and randomblob() SQL functions.  This interface allows
2937** applications to access the same PRNG for other purposes.
2938**
2939** ^A call to this routine stores N bytes of randomness into buffer P.
2940** ^The P parameter can be a NULL pointer.
2941**
2942** ^If this routine has not been previously called or if the previous
2943** call had N less than one or a NULL pointer for P, then the PRNG is
2944** seeded using randomness obtained from the xRandomness method of
2945** the default [sqlite3_vfs] object.
2946** ^If the previous call to this routine had an N of 1 or more and a
2947** non-NULL P then the pseudo-randomness is generated
2948** internally and without recourse to the [sqlite3_vfs] xRandomness
2949** method.
2950*/
2951SQLITE_API void sqlite3_randomness(int N, void *P);
2952
2953/*
2954** CAPI3REF: Compile-Time Authorization Callbacks
2955** METHOD: sqlite3
2956**
2957** ^This routine registers an authorizer callback with a particular
2958** [database connection], supplied in the first argument.
2959** ^The authorizer callback is invoked as SQL statements are being compiled
2960** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2961** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2962** points during the compilation process, as logic is being created
2963** to perform various actions, the authorizer callback is invoked to
2964** see if those actions are allowed.  ^The authorizer callback should
2965** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2966** specific action but allow the SQL statement to continue to be
2967** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2968** rejected with an error.  ^If the authorizer callback returns
2969** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2970** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2971** the authorizer will fail with an error message.
2972**
2973** When the callback returns [SQLITE_OK], that means the operation
2974** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2975** [sqlite3_prepare_v2()] or equivalent call that triggered the
2976** authorizer will fail with an error message explaining that
2977** access is denied.
2978**
2979** ^The first parameter to the authorizer callback is a copy of the third
2980** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2981** to the callback is an integer [SQLITE_COPY | action code] that specifies
2982** the particular action to be authorized. ^The third through sixth parameters
2983** to the callback are zero-terminated strings that contain additional
2984** details about the action to be authorized.
2985**
2986** ^If the action code is [SQLITE_READ]
2987** and the callback returns [SQLITE_IGNORE] then the
2988** [prepared statement] statement is constructed to substitute
2989** a NULL value in place of the table column that would have
2990** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2991** return can be used to deny an untrusted user access to individual
2992** columns of a table.
2993** ^If the action code is [SQLITE_DELETE] and the callback returns
2994** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2995** [truncate optimization] is disabled and all rows are deleted individually.
2996**
2997** An authorizer is used when [sqlite3_prepare | preparing]
2998** SQL statements from an untrusted source, to ensure that the SQL statements
2999** do not try to access data they are not allowed to see, or that they do not
3000** try to execute malicious statements that damage the database.  For
3001** example, an application may allow a user to enter arbitrary
3002** SQL queries for evaluation by a database.  But the application does
3003** not want the user to be able to make arbitrary changes to the
3004** database.  An authorizer could then be put in place while the
3005** user-entered SQL is being [sqlite3_prepare | prepared] that
3006** disallows everything except [SELECT] statements.
3007**
3008** Applications that need to process SQL from untrusted sources
3009** might also consider lowering resource limits using [sqlite3_limit()]
3010** and limiting database size using the [max_page_count] [PRAGMA]
3011** in addition to using an authorizer.
3012**
3013** ^(Only a single authorizer can be in place on a database connection
3014** at a time.  Each call to sqlite3_set_authorizer overrides the
3015** previous call.)^  ^Disable the authorizer by installing a NULL callback.
3016** The authorizer is disabled by default.
3017**
3018** The authorizer callback must not do anything that will modify
3019** the database connection that invoked the authorizer callback.
3020** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3021** database connections for the meaning of "modify" in this paragraph.
3022**
3023** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
3024** statement might be re-prepared during [sqlite3_step()] due to a
3025** schema change.  Hence, the application should ensure that the
3026** correct authorizer callback remains in place during the [sqlite3_step()].
3027**
3028** ^Note that the authorizer callback is invoked only during
3029** [sqlite3_prepare()] or its variants.  Authorization is not
3030** performed during statement evaluation in [sqlite3_step()], unless
3031** as stated in the previous paragraph, sqlite3_step() invokes
3032** sqlite3_prepare_v2() to reprepare a statement after a schema change.
3033*/
3034SQLITE_API int sqlite3_set_authorizer(
3035  sqlite3*,
3036  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
3037  void *pUserData
3038);
3039
3040/*
3041** CAPI3REF: Authorizer Return Codes
3042**
3043** The [sqlite3_set_authorizer | authorizer callback function] must
3044** return either [SQLITE_OK] or one of these two constants in order
3045** to signal SQLite whether or not the action is permitted.  See the
3046** [sqlite3_set_authorizer | authorizer documentation] for additional
3047** information.
3048**
3049** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
3050** returned from the [sqlite3_vtab_on_conflict()] interface.
3051*/
3052#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
3053#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
3054
3055/*
3056** CAPI3REF: Authorizer Action Codes
3057**
3058** The [sqlite3_set_authorizer()] interface registers a callback function
3059** that is invoked to authorize certain SQL statement actions.  The
3060** second parameter to the callback is an integer code that specifies
3061** what action is being authorized.  These are the integer action codes that
3062** the authorizer callback may be passed.
3063**
3064** These action code values signify what kind of operation is to be
3065** authorized.  The 3rd and 4th parameters to the authorization
3066** callback function will be parameters or NULL depending on which of these
3067** codes is used as the second parameter.  ^(The 5th parameter to the
3068** authorizer callback is the name of the database ("main", "temp",
3069** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
3070** is the name of the inner-most trigger or view that is responsible for
3071** the access attempt or NULL if this access attempt is directly from
3072** top-level SQL code.
3073*/
3074/******************************************* 3rd ************ 4th ***********/
3075#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
3076#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
3077#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
3078#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
3079#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
3080#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
3081#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
3082#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
3083#define SQLITE_DELETE                9   /* Table Name      NULL            */
3084#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
3085#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
3086#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
3087#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
3088#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
3089#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
3090#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
3091#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
3092#define SQLITE_INSERT               18   /* Table Name      NULL            */
3093#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
3094#define SQLITE_READ                 20   /* Table Name      Column Name     */
3095#define SQLITE_SELECT               21   /* NULL            NULL            */
3096#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
3097#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
3098#define SQLITE_ATTACH               24   /* Filename        NULL            */
3099#define SQLITE_DETACH               25   /* Database Name   NULL            */
3100#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
3101#define SQLITE_REINDEX              27   /* Index Name      NULL            */
3102#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
3103#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
3104#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
3105#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
3106#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
3107#define SQLITE_COPY                  0   /* No longer used */
3108#define SQLITE_RECURSIVE            33   /* NULL            NULL            */
3109
3110/*
3111** CAPI3REF: Tracing And Profiling Functions
3112** METHOD: sqlite3
3113**
3114** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
3115** instead of the routines described here.
3116**
3117** These routines register callback functions that can be used for
3118** tracing and profiling the execution of SQL statements.
3119**
3120** ^The callback function registered by sqlite3_trace() is invoked at
3121** various times when an SQL statement is being run by [sqlite3_step()].
3122** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3123** SQL statement text as the statement first begins executing.
3124** ^(Additional sqlite3_trace() callbacks might occur
3125** as each triggered subprogram is entered.  The callbacks for triggers
3126** contain a UTF-8 SQL comment that identifies the trigger.)^
3127**
3128** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3129** the length of [bound parameter] expansion in the output of sqlite3_trace().
3130**
3131** ^The callback function registered by sqlite3_profile() is invoked
3132** as each SQL statement finishes.  ^The profile callback contains
3133** the original statement text and an estimate of wall-clock time
3134** of how long that statement took to run.  ^The profile callback
3135** time is in units of nanoseconds, however the current implementation
3136** is only capable of millisecond resolution so the six least significant
3137** digits in the time are meaningless.  Future versions of SQLite
3138** might provide greater resolution on the profiler callback.  The
3139** sqlite3_profile() function is considered experimental and is
3140** subject to change in future versions of SQLite.
3141*/
3142SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
3143   void(*xTrace)(void*,const char*), void*);
3144SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
3145   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3146
3147/*
3148** CAPI3REF: SQL Trace Event Codes
3149** KEYWORDS: SQLITE_TRACE
3150**
3151** These constants identify classes of events that can be monitored
3152** using the [sqlite3_trace_v2()] tracing logic.  The third argument
3153** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of
3154** the following constants.  ^The first argument to the trace callback
3155** is one of the following constants.
3156**
3157** New tracing constants may be added in future releases.
3158**
3159** ^A trace callback has four arguments: xCallback(T,C,P,X).
3160** ^The T argument is one of the integer type codes above.
3161** ^The C argument is a copy of the context pointer passed in as the
3162** fourth argument to [sqlite3_trace_v2()].
3163** The P and X arguments are pointers whose meanings depend on T.
3164**
3165** <dl>
3166** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
3167** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
3168** first begins running and possibly at other times during the
3169** execution of the prepared statement, such as at the start of each
3170** trigger subprogram. ^The P argument is a pointer to the
3171** [prepared statement]. ^The X argument is a pointer to a string which
3172** is the unexpanded SQL text of the prepared statement or an SQL comment
3173** that indicates the invocation of a trigger.  ^The callback can compute
3174** the same text that would have been returned by the legacy [sqlite3_trace()]
3175** interface by using the X argument when X begins with "--" and invoking
3176** [sqlite3_expanded_sql(P)] otherwise.
3177**
3178** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
3179** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
3180** information as is provided by the [sqlite3_profile()] callback.
3181** ^The P argument is a pointer to the [prepared statement] and the
3182** X argument points to a 64-bit integer which is the estimated of
3183** the number of nanosecond that the prepared statement took to run.
3184** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
3185**
3186** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
3187** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
3188** statement generates a single row of result.
3189** ^The P argument is a pointer to the [prepared statement] and the
3190** X argument is unused.
3191**
3192** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
3193** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
3194** connection closes.
3195** ^The P argument is a pointer to the [database connection] object
3196** and the X argument is unused.
3197** </dl>
3198*/
3199#define SQLITE_TRACE_STMT       0x01
3200#define SQLITE_TRACE_PROFILE    0x02
3201#define SQLITE_TRACE_ROW        0x04
3202#define SQLITE_TRACE_CLOSE      0x08
3203
3204/*
3205** CAPI3REF: SQL Trace Hook
3206** METHOD: sqlite3
3207**
3208** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
3209** function X against [database connection] D, using property mask M
3210** and context pointer P.  ^If the X callback is
3211** NULL or if the M mask is zero, then tracing is disabled.  The
3212** M argument should be the bitwise OR-ed combination of
3213** zero or more [SQLITE_TRACE] constants.
3214**
3215** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
3216** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
3217**
3218** ^The X callback is invoked whenever any of the events identified by
3219** mask M occur.  ^The integer return value from the callback is currently
3220** ignored, though this may change in future releases.  Callback
3221** implementations should return zero to ensure future compatibility.
3222**
3223** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
3224** ^The T argument is one of the [SQLITE_TRACE]
3225** constants to indicate why the callback was invoked.
3226** ^The C argument is a copy of the context pointer.
3227** The P and X arguments are pointers whose meanings depend on T.
3228**
3229** The sqlite3_trace_v2() interface is intended to replace the legacy
3230** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
3231** are deprecated.
3232*/
3233SQLITE_API int sqlite3_trace_v2(
3234  sqlite3*,
3235  unsigned uMask,
3236  int(*xCallback)(unsigned,void*,void*,void*),
3237  void *pCtx
3238);
3239
3240/*
3241** CAPI3REF: Query Progress Callbacks
3242** METHOD: sqlite3
3243**
3244** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3245** function X to be invoked periodically during long running calls to
3246** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
3247** database connection D.  An example use for this
3248** interface is to keep a GUI updated during a large query.
3249**
3250** ^The parameter P is passed through as the only parameter to the
3251** callback function X.  ^The parameter N is the approximate number of
3252** [virtual machine instructions] that are evaluated between successive
3253** invocations of the callback X.  ^If N is less than one then the progress
3254** handler is disabled.
3255**
3256** ^Only a single progress handler may be defined at one time per
3257** [database connection]; setting a new progress handler cancels the
3258** old one.  ^Setting parameter X to NULL disables the progress handler.
3259** ^The progress handler is also disabled by setting N to a value less
3260** than 1.
3261**
3262** ^If the progress callback returns non-zero, the operation is
3263** interrupted.  This feature can be used to implement a
3264** "Cancel" button on a GUI progress dialog box.
3265**
3266** The progress handler callback must not do anything that will modify
3267** the database connection that invoked the progress handler.
3268** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3269** database connections for the meaning of "modify" in this paragraph.
3270**
3271*/
3272SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3273
3274/*
3275** CAPI3REF: Opening A New Database Connection
3276** CONSTRUCTOR: sqlite3
3277**
3278** ^These routines open an SQLite database file as specified by the
3279** filename argument. ^The filename argument is interpreted as UTF-8 for
3280** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3281** order for sqlite3_open16(). ^(A [database connection] handle is usually
3282** returned in *ppDb, even if an error occurs.  The only exception is that
3283** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3284** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3285** object.)^ ^(If the database is opened (and/or created) successfully, then
3286** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
3287** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3288** an English language description of the error following a failure of any
3289** of the sqlite3_open() routines.
3290**
3291** ^The default encoding will be UTF-8 for databases created using
3292** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases
3293** created using sqlite3_open16() will be UTF-16 in the native byte order.
3294**
3295** Whether or not an error occurs when it is opened, resources
3296** associated with the [database connection] handle should be released by
3297** passing it to [sqlite3_close()] when it is no longer required.
3298**
3299** The sqlite3_open_v2() interface works like sqlite3_open()
3300** except that it accepts two additional parameters for additional control
3301** over the new database connection.  ^(The flags parameter to
3302** sqlite3_open_v2() can take one of
3303** the following three values, optionally combined with the
3304** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3305** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3306**
3307** <dl>
3308** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3309** <dd>The database is opened in read-only mode.  If the database does not
3310** already exist, an error is returned.</dd>)^
3311**
3312** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3313** <dd>The database is opened for reading and writing if possible, or reading
3314** only if the file is write protected by the operating system.  In either
3315** case the database must already exist, otherwise an error is returned.</dd>)^
3316**
3317** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3318** <dd>The database is opened for reading and writing, and is created if
3319** it does not already exist. This is the behavior that is always used for
3320** sqlite3_open() and sqlite3_open16().</dd>)^
3321** </dl>
3322**
3323** If the 3rd parameter to sqlite3_open_v2() is not one of the
3324** combinations shown above optionally combined with other
3325** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3326** then the behavior is undefined.
3327**
3328** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3329** opens in the multi-thread [threading mode] as long as the single-thread
3330** mode has not been set at compile-time or start-time.  ^If the
3331** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3332** in the serialized [threading mode] unless single-thread was
3333** previously selected at compile-time or start-time.
3334** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3335** eligible to use [shared cache mode], regardless of whether or not shared
3336** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
3337** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3338** participate in [shared cache mode] even if it is enabled.
3339**
3340** ^The fourth parameter to sqlite3_open_v2() is the name of the
3341** [sqlite3_vfs] object that defines the operating system interface that
3342** the new database connection should use.  ^If the fourth parameter is
3343** a NULL pointer then the default [sqlite3_vfs] object is used.
3344**
3345** ^If the filename is ":memory:", then a private, temporary in-memory database
3346** is created for the connection.  ^This in-memory database will vanish when
3347** the database connection is closed.  Future versions of SQLite might
3348** make use of additional special filenames that begin with the ":" character.
3349** It is recommended that when a database filename actually does begin with
3350** a ":" character you should prefix the filename with a pathname such as
3351** "./" to avoid ambiguity.
3352**
3353** ^If the filename is an empty string, then a private, temporary
3354** on-disk database will be created.  ^This private database will be
3355** automatically deleted as soon as the database connection is closed.
3356**
3357** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3358**
3359** ^If [URI filename] interpretation is enabled, and the filename argument
3360** begins with "file:", then the filename is interpreted as a URI. ^URI
3361** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3362** set in the fourth argument to sqlite3_open_v2(), or if it has
3363** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3364** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3365** As of SQLite version 3.7.7, URI filename interpretation is turned off
3366** by default, but future releases of SQLite might enable URI filename
3367** interpretation by default.  See "[URI filenames]" for additional
3368** information.
3369**
3370** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3371** authority, then it must be either an empty string or the string
3372** "localhost". ^If the authority is not an empty string or "localhost", an
3373** error is returned to the caller. ^The fragment component of a URI, if
3374** present, is ignored.
3375**
3376** ^SQLite uses the path component of the URI as the name of the disk file
3377** which contains the database. ^If the path begins with a '/' character,
3378** then it is interpreted as an absolute path. ^If the path does not begin
3379** with a '/' (meaning that the authority section is omitted from the URI)
3380** then the path is interpreted as a relative path.
3381** ^(On windows, the first component of an absolute path
3382** is a drive specification (e.g. "C:").)^
3383**
3384** [[core URI query parameters]]
3385** The query component of a URI may contain parameters that are interpreted
3386** either by SQLite itself, or by a [VFS | custom VFS implementation].
3387** SQLite and its built-in [VFSes] interpret the
3388** following query parameters:
3389**
3390** <ul>
3391**   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3392**     a VFS object that provides the operating system interface that should
3393**     be used to access the database file on disk. ^If this option is set to
3394**     an empty string the default VFS object is used. ^Specifying an unknown
3395**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3396**     present, then the VFS specified by the option takes precedence over
3397**     the value passed as the fourth parameter to sqlite3_open_v2().
3398**
3399**   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3400**     "rwc", or "memory". Attempting to set it to any other value is
3401**     an error)^.
3402**     ^If "ro" is specified, then the database is opened for read-only
3403**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3404**     third argument to sqlite3_open_v2(). ^If the mode option is set to
3405**     "rw", then the database is opened for read-write (but not create)
3406**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3407**     been set. ^Value "rwc" is equivalent to setting both
3408**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
3409**     set to "memory" then a pure [in-memory database] that never reads
3410**     or writes from disk is used. ^It is an error to specify a value for
3411**     the mode parameter that is less restrictive than that specified by
3412**     the flags passed in the third parameter to sqlite3_open_v2().
3413**
3414**   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3415**     "private". ^Setting it to "shared" is equivalent to setting the
3416**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3417**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3418**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3419**     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3420**     a URI filename, its value overrides any behavior requested by setting
3421**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3422**
3423**  <li> <b>psow</b>: ^The psow parameter indicates whether or not the
3424**     [powersafe overwrite] property does or does not apply to the
3425**     storage media on which the database file resides.
3426**
3427**  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
3428**     which if set disables file locking in rollback journal modes.  This
3429**     is useful for accessing a database on a filesystem that does not
3430**     support locking.  Caution:  Database corruption might result if two
3431**     or more processes write to the same database and any one of those
3432**     processes uses nolock=1.
3433**
3434**  <li> <b>immutable</b>: ^The immutable parameter is a boolean query
3435**     parameter that indicates that the database file is stored on
3436**     read-only media.  ^When immutable is set, SQLite assumes that the
3437**     database file cannot be changed, even by a process with higher
3438**     privilege, and so the database is opened read-only and all locking
3439**     and change detection is disabled.  Caution: Setting the immutable
3440**     property on a database file that does in fact change can result
3441**     in incorrect query results and/or [SQLITE_CORRUPT] errors.
3442**     See also: [SQLITE_IOCAP_IMMUTABLE].
3443**
3444** </ul>
3445**
3446** ^Specifying an unknown parameter in the query component of a URI is not an
3447** error.  Future versions of SQLite might understand additional query
3448** parameters.  See "[query parameters with special meaning to SQLite]" for
3449** additional information.
3450**
3451** [[URI filename examples]] <h3>URI filename examples</h3>
3452**
3453** <table border="1" align=center cellpadding=5>
3454** <tr><th> URI filenames <th> Results
3455** <tr><td> file:data.db <td>
3456**          Open the file "data.db" in the current directory.
3457** <tr><td> file:/home/fred/data.db<br>
3458**          file:///home/fred/data.db <br>
3459**          file://localhost/home/fred/data.db <br> <td>
3460**          Open the database file "/home/fred/data.db".
3461** <tr><td> file://darkstar/home/fred/data.db <td>
3462**          An error. "darkstar" is not a recognized authority.
3463** <tr><td style="white-space:nowrap">
3464**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3465**     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3466**          C:. Note that the %20 escaping in this example is not strictly
3467**          necessary - space characters can be used literally
3468**          in URI filenames.
3469** <tr><td> file:data.db?mode=ro&cache=private <td>
3470**          Open file "data.db" in the current directory for read-only access.
3471**          Regardless of whether or not shared-cache mode is enabled by
3472**          default, use a private cache.
3473** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
3474**          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
3475**          that uses dot-files in place of posix advisory locking.
3476** <tr><td> file:data.db?mode=readonly <td>
3477**          An error. "readonly" is not a valid option for the "mode" parameter.
3478** </table>
3479**
3480** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3481** query components of a URI. A hexadecimal escape sequence consists of a
3482** percent sign - "%" - followed by exactly two hexadecimal digits
3483** specifying an octet value. ^Before the path or query components of a
3484** URI filename are interpreted, they are encoded using UTF-8 and all
3485** hexadecimal escape sequences replaced by a single byte containing the
3486** corresponding octet. If this process generates an invalid UTF-8 encoding,
3487** the results are undefined.
3488**
3489** <b>Note to Windows users:</b>  The encoding used for the filename argument
3490** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3491** codepage is currently defined.  Filenames containing international
3492** characters must be converted to UTF-8 prior to passing them into
3493** sqlite3_open() or sqlite3_open_v2().
3494**
3495** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
3496** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
3497** features that require the use of temporary files may fail.
3498**
3499** See also: [sqlite3_temp_directory]
3500*/
3501SQLITE_API int sqlite3_open(
3502  const char *filename,   /* Database filename (UTF-8) */
3503  sqlite3 **ppDb          /* OUT: SQLite db handle */
3504);
3505SQLITE_API int sqlite3_open16(
3506  const void *filename,   /* Database filename (UTF-16) */
3507  sqlite3 **ppDb          /* OUT: SQLite db handle */
3508);
3509SQLITE_API int sqlite3_open_v2(
3510  const char *filename,   /* Database filename (UTF-8) */
3511  sqlite3 **ppDb,         /* OUT: SQLite db handle */
3512  int flags,              /* Flags */
3513  const char *zVfs        /* Name of VFS module to use */
3514);
3515
3516/*
3517** CAPI3REF: Obtain Values For URI Parameters
3518**
3519** These are utility routines, useful to VFS implementations, that check
3520** to see if a database file was a URI that contained a specific query
3521** parameter, and if so obtains the value of that query parameter.
3522**
3523** If F is the database filename pointer passed into the xOpen() method of
3524** a VFS implementation when the flags parameter to xOpen() has one or
3525** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3526** P is the name of the query parameter, then
3527** sqlite3_uri_parameter(F,P) returns the value of the P
3528** parameter if it exists or a NULL pointer if P does not appear as a
3529** query parameter on F.  If P is a query parameter of F
3530** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3531** a pointer to an empty string.
3532**
3533** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3534** parameter and returns true (1) or false (0) according to the value
3535** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3536** value of query parameter P is one of "yes", "true", or "on" in any
3537** case or if the value begins with a non-zero number.  The
3538** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3539** query parameter P is one of "no", "false", or "off" in any case or
3540** if the value begins with a numeric zero.  If P is not a query
3541** parameter on F or if the value of P is does not match any of the
3542** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3543**
3544** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3545** 64-bit signed integer and returns that integer, or D if P does not
3546** exist.  If the value of P is something other than an integer, then
3547** zero is returned.
3548**
3549** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3550** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3551** is not a database file pathname pointer that SQLite passed into the xOpen
3552** VFS method, then the behavior of this routine is undefined and probably
3553** undesirable.
3554*/
3555SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3556SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3557SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3558
3559
3560/*
3561** CAPI3REF: Error Codes And Messages
3562** METHOD: sqlite3
3563**
3564** ^If the most recent sqlite3_* API call associated with
3565** [database connection] D failed, then the sqlite3_errcode(D) interface
3566** returns the numeric [result code] or [extended result code] for that
3567** API call.
3568** If the most recent API call was successful,
3569** then the return value from sqlite3_errcode() is undefined.
3570** ^The sqlite3_extended_errcode()
3571** interface is the same except that it always returns the
3572** [extended result code] even when extended result codes are
3573** disabled.
3574**
3575** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3576** text that describes the error, as either UTF-8 or UTF-16 respectively.
3577** ^(Memory to hold the error message string is managed internally.
3578** The application does not need to worry about freeing the result.
3579** However, the error string might be overwritten or deallocated by
3580** subsequent calls to other SQLite interface functions.)^
3581**
3582** ^The sqlite3_errstr() interface returns the English-language text
3583** that describes the [result code], as UTF-8.
3584** ^(Memory to hold the error message string is managed internally
3585** and must not be freed by the application)^.
3586**
3587** When the serialized [threading mode] is in use, it might be the
3588** case that a second error occurs on a separate thread in between
3589** the time of the first error and the call to these interfaces.
3590** When that happens, the second error will be reported since these
3591** interfaces always report the most recent result.  To avoid
3592** this, each thread can obtain exclusive use of the [database connection] D
3593** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3594** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3595** all calls to the interfaces listed here are completed.
3596**
3597** If an interface fails with SQLITE_MISUSE, that means the interface
3598** was invoked incorrectly by the application.  In that case, the
3599** error code and message may or may not be set.
3600*/
3601SQLITE_API int sqlite3_errcode(sqlite3 *db);
3602SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3603SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3604SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3605SQLITE_API const char *sqlite3_errstr(int);
3606
3607/*
3608** CAPI3REF: Prepared Statement Object
3609** KEYWORDS: {prepared statement} {prepared statements}
3610**
3611** An instance of this object represents a single SQL statement that
3612** has been compiled into binary form and is ready to be evaluated.
3613**
3614** Think of each SQL statement as a separate computer program.  The
3615** original SQL text is source code.  A prepared statement object
3616** is the compiled object code.  All SQL must be converted into a
3617** prepared statement before it can be run.
3618**
3619** The life-cycle of a prepared statement object usually goes like this:
3620**
3621** <ol>
3622** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
3623** <li> Bind values to [parameters] using the sqlite3_bind_*()
3624**      interfaces.
3625** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3626** <li> Reset the prepared statement using [sqlite3_reset()] then go back
3627**      to step 2.  Do this zero or more times.
3628** <li> Destroy the object using [sqlite3_finalize()].
3629** </ol>
3630*/
3631typedef struct sqlite3_stmt sqlite3_stmt;
3632
3633/*
3634** CAPI3REF: Run-time Limits
3635** METHOD: sqlite3
3636**
3637** ^(This interface allows the size of various constructs to be limited
3638** on a connection by connection basis.  The first parameter is the
3639** [database connection] whose limit is to be set or queried.  The
3640** second parameter is one of the [limit categories] that define a
3641** class of constructs to be size limited.  The third parameter is the
3642** new limit for that construct.)^
3643**
3644** ^If the new limit is a negative number, the limit is unchanged.
3645** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3646** [limits | hard upper bound]
3647** set at compile-time by a C preprocessor macro called
3648** [limits | SQLITE_MAX_<i>NAME</i>].
3649** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3650** ^Attempts to increase a limit above its hard upper bound are
3651** silently truncated to the hard upper bound.
3652**
3653** ^Regardless of whether or not the limit was changed, the
3654** [sqlite3_limit()] interface returns the prior value of the limit.
3655** ^Hence, to find the current value of a limit without changing it,
3656** simply invoke this interface with the third parameter set to -1.
3657**
3658** Run-time limits are intended for use in applications that manage
3659** both their own internal database and also databases that are controlled
3660** by untrusted external sources.  An example application might be a
3661** web browser that has its own databases for storing history and
3662** separate databases controlled by JavaScript applications downloaded
3663** off the Internet.  The internal databases can be given the
3664** large, default limits.  Databases managed by external sources can
3665** be given much smaller limits designed to prevent a denial of service
3666** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3667** interface to further control untrusted SQL.  The size of the database
3668** created by an untrusted script can be contained using the
3669** [max_page_count] [PRAGMA].
3670**
3671** New run-time limit categories may be added in future releases.
3672*/
3673SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3674
3675/*
3676** CAPI3REF: Run-Time Limit Categories
3677** KEYWORDS: {limit category} {*limit categories}
3678**
3679** These constants define various performance limits
3680** that can be lowered at run-time using [sqlite3_limit()].
3681** The synopsis of the meanings of the various limits is shown below.
3682** Additional information is available at [limits | Limits in SQLite].
3683**
3684** <dl>
3685** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3686** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3687**
3688** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3689** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3690**
3691** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3692** <dd>The maximum number of columns in a table definition or in the
3693** result set of a [SELECT] or the maximum number of columns in an index
3694** or in an ORDER BY or GROUP BY clause.</dd>)^
3695**
3696** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3697** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3698**
3699** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3700** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3701**
3702** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3703** <dd>The maximum number of instructions in a virtual machine program
3704** used to implement an SQL statement.  If [sqlite3_prepare_v2()] or
3705** the equivalent tries to allocate space for more than this many opcodes
3706** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
3707**
3708** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3709** <dd>The maximum number of arguments on a function.</dd>)^
3710**
3711** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3712** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3713**
3714** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3715** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3716** <dd>The maximum length of the pattern argument to the [LIKE] or
3717** [GLOB] operators.</dd>)^
3718**
3719** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3720** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3721** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3722**
3723** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3724** <dd>The maximum depth of recursion for triggers.</dd>)^
3725**
3726** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
3727** <dd>The maximum number of auxiliary worker threads that a single
3728** [prepared statement] may start.</dd>)^
3729** </dl>
3730*/
3731#define SQLITE_LIMIT_LENGTH                    0
3732#define SQLITE_LIMIT_SQL_LENGTH                1
3733#define SQLITE_LIMIT_COLUMN                    2
3734#define SQLITE_LIMIT_EXPR_DEPTH                3
3735#define SQLITE_LIMIT_COMPOUND_SELECT           4
3736#define SQLITE_LIMIT_VDBE_OP                   5
3737#define SQLITE_LIMIT_FUNCTION_ARG              6
3738#define SQLITE_LIMIT_ATTACHED                  7
3739#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3740#define SQLITE_LIMIT_VARIABLE_NUMBER           9
3741#define SQLITE_LIMIT_TRIGGER_DEPTH            10
3742#define SQLITE_LIMIT_WORKER_THREADS           11
3743
3744
3745/*
3746** CAPI3REF: Compiling An SQL Statement
3747** KEYWORDS: {SQL statement compiler}
3748** METHOD: sqlite3
3749** CONSTRUCTOR: sqlite3_stmt
3750**
3751** To execute an SQL query, it must first be compiled into a byte-code
3752** program using one of these routines.
3753**
3754** The first argument, "db", is a [database connection] obtained from a
3755** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3756** [sqlite3_open16()].  The database connection must not have been closed.
3757**
3758** The second argument, "zSql", is the statement to be compiled, encoded
3759** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3760** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3761** use UTF-16.
3762**
3763** ^If the nByte argument is negative, then zSql is read up to the
3764** first zero terminator. ^If nByte is positive, then it is the
3765** number of bytes read from zSql.  ^If nByte is zero, then no prepared
3766** statement is generated.
3767** If the caller knows that the supplied string is nul-terminated, then
3768** there is a small performance advantage to passing an nByte parameter that
3769** is the number of bytes in the input string <i>including</i>
3770** the nul-terminator.
3771**
3772** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3773** past the end of the first SQL statement in zSql.  These routines only
3774** compile the first statement in zSql, so *pzTail is left pointing to
3775** what remains uncompiled.
3776**
3777** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3778** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3779** to NULL.  ^If the input text contains no SQL (if the input is an empty
3780** string or a comment) then *ppStmt is set to NULL.
3781** The calling procedure is responsible for deleting the compiled
3782** SQL statement using [sqlite3_finalize()] after it has finished with it.
3783** ppStmt may not be NULL.
3784**
3785** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3786** otherwise an [error code] is returned.
3787**
3788** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3789** recommended for all new programs. The two older interfaces are retained
3790** for backwards compatibility, but their use is discouraged.
3791** ^In the "v2" interfaces, the prepared statement
3792** that is returned (the [sqlite3_stmt] object) contains a copy of the
3793** original SQL text. This causes the [sqlite3_step()] interface to
3794** behave differently in three ways:
3795**
3796** <ol>
3797** <li>
3798** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3799** always used to do, [sqlite3_step()] will automatically recompile the SQL
3800** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3801** retries will occur before sqlite3_step() gives up and returns an error.
3802** </li>
3803**
3804** <li>
3805** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3806** [error codes] or [extended error codes].  ^The legacy behavior was that
3807** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3808** and the application would have to make a second call to [sqlite3_reset()]
3809** in order to find the underlying cause of the problem. With the "v2" prepare
3810** interfaces, the underlying reason for the error is returned immediately.
3811** </li>
3812**
3813** <li>
3814** ^If the specific value bound to [parameter | host parameter] in the
3815** WHERE clause might influence the choice of query plan for a statement,
3816** then the statement will be automatically recompiled, as if there had been
3817** a schema change, on the first  [sqlite3_step()] call following any change
3818** to the [sqlite3_bind_text | bindings] of that [parameter].
3819** ^The specific value of WHERE-clause [parameter] might influence the
3820** choice of query plan if the parameter is the left-hand side of a [LIKE]
3821** or [GLOB] operator or if the parameter is compared to an indexed column
3822** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3823** </li>
3824** </ol>
3825*/
3826SQLITE_API int sqlite3_prepare(
3827  sqlite3 *db,            /* Database handle */
3828  const char *zSql,       /* SQL statement, UTF-8 encoded */
3829  int nByte,              /* Maximum length of zSql in bytes. */
3830  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3831  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3832);
3833SQLITE_API int sqlite3_prepare_v2(
3834  sqlite3 *db,            /* Database handle */
3835  const char *zSql,       /* SQL statement, UTF-8 encoded */
3836  int nByte,              /* Maximum length of zSql in bytes. */
3837  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3838  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3839);
3840SQLITE_API int sqlite3_prepare16(
3841  sqlite3 *db,            /* Database handle */
3842  const void *zSql,       /* SQL statement, UTF-16 encoded */
3843  int nByte,              /* Maximum length of zSql in bytes. */
3844  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3845  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3846);
3847SQLITE_API int sqlite3_prepare16_v2(
3848  sqlite3 *db,            /* Database handle */
3849  const void *zSql,       /* SQL statement, UTF-16 encoded */
3850  int nByte,              /* Maximum length of zSql in bytes. */
3851  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3852  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3853);
3854
3855/*
3856** CAPI3REF: Retrieving Statement SQL
3857** METHOD: sqlite3_stmt
3858**
3859** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
3860** SQL text used to create [prepared statement] P if P was
3861** created by either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3862** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
3863** string containing the SQL text of prepared statement P with
3864** [bound parameters] expanded.
3865**
3866** ^(For example, if a prepared statement is created using the SQL
3867** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
3868** and parameter :xyz is unbound, then sqlite3_sql() will return
3869** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
3870** will return "SELECT 2345,NULL".)^
3871**
3872** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
3873** is available to hold the result, or if the result would exceed the
3874** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
3875**
3876** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
3877** bound parameter expansions.  ^The [SQLITE_OMIT_TRACE] compile-time
3878** option causes sqlite3_expanded_sql() to always return NULL.
3879**
3880** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
3881** automatically freed when the prepared statement is finalized.
3882** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
3883** is obtained from [sqlite3_malloc()] and must be free by the application
3884** by passing it to [sqlite3_free()].
3885*/
3886SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3887SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
3888
3889/*
3890** CAPI3REF: Determine If An SQL Statement Writes The Database
3891** METHOD: sqlite3_stmt
3892**
3893** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3894** and only if the [prepared statement] X makes no direct changes to
3895** the content of the database file.
3896**
3897** Note that [application-defined SQL functions] or
3898** [virtual tables] might change the database indirectly as a side effect.
3899** ^(For example, if an application defines a function "eval()" that
3900** calls [sqlite3_exec()], then the following SQL statement would
3901** change the database file through side-effects:
3902**
3903** <blockquote><pre>
3904**    SELECT eval('DELETE FROM t1') FROM t2;
3905** </pre></blockquote>
3906**
3907** But because the [SELECT] statement does not change the database file
3908** directly, sqlite3_stmt_readonly() would still return true.)^
3909**
3910** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3911** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3912** since the statements themselves do not actually modify the database but
3913** rather they control the timing of when other statements modify the
3914** database.  ^The [ATTACH] and [DETACH] statements also cause
3915** sqlite3_stmt_readonly() to return true since, while those statements
3916** change the configuration of a database connection, they do not make
3917** changes to the content of the database files on disk.
3918** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
3919** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
3920** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
3921** sqlite3_stmt_readonly() returns false for those commands.
3922*/
3923SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3924
3925/*
3926** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3927** METHOD: sqlite3_stmt
3928**
3929** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3930** [prepared statement] S has been stepped at least once using
3931** [sqlite3_step(S)] but has neither run to completion (returned
3932** [SQLITE_DONE] from [sqlite3_step(S)]) nor
3933** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3934** interface returns false if S is a NULL pointer.  If S is not a
3935** NULL pointer and is not a pointer to a valid [prepared statement]
3936** object, then the behavior is undefined and probably undesirable.
3937**
3938** This interface can be used in combination [sqlite3_next_stmt()]
3939** to locate all prepared statements associated with a database
3940** connection that are in need of being reset.  This can be used,
3941** for example, in diagnostic routines to search for prepared
3942** statements that are holding a transaction open.
3943*/
3944SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3945
3946/*
3947** CAPI3REF: Dynamically Typed Value Object
3948** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3949**
3950** SQLite uses the sqlite3_value object to represent all values
3951** that can be stored in a database table. SQLite uses dynamic typing
3952** for the values it stores.  ^Values stored in sqlite3_value objects
3953** can be integers, floating point values, strings, BLOBs, or NULL.
3954**
3955** An sqlite3_value object may be either "protected" or "unprotected".
3956** Some interfaces require a protected sqlite3_value.  Other interfaces
3957** will accept either a protected or an unprotected sqlite3_value.
3958** Every interface that accepts sqlite3_value arguments specifies
3959** whether or not it requires a protected sqlite3_value.  The
3960** [sqlite3_value_dup()] interface can be used to construct a new
3961** protected sqlite3_value from an unprotected sqlite3_value.
3962**
3963** The terms "protected" and "unprotected" refer to whether or not
3964** a mutex is held.  An internal mutex is held for a protected
3965** sqlite3_value object but no mutex is held for an unprotected
3966** sqlite3_value object.  If SQLite is compiled to be single-threaded
3967** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3968** or if SQLite is run in one of reduced mutex modes
3969** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3970** then there is no distinction between protected and unprotected
3971** sqlite3_value objects and they can be used interchangeably.  However,
3972** for maximum code portability it is recommended that applications
3973** still make the distinction between protected and unprotected
3974** sqlite3_value objects even when not strictly required.
3975**
3976** ^The sqlite3_value objects that are passed as parameters into the
3977** implementation of [application-defined SQL functions] are protected.
3978** ^The sqlite3_value object returned by
3979** [sqlite3_column_value()] is unprotected.
3980** Unprotected sqlite3_value objects may only be used with
3981** [sqlite3_result_value()] and [sqlite3_bind_value()].
3982** The [sqlite3_value_blob | sqlite3_value_type()] family of
3983** interfaces require protected sqlite3_value objects.
3984*/
3985typedef struct Mem sqlite3_value;
3986
3987/*
3988** CAPI3REF: SQL Function Context Object
3989**
3990** The context in which an SQL function executes is stored in an
3991** sqlite3_context object.  ^A pointer to an sqlite3_context object
3992** is always first parameter to [application-defined SQL functions].
3993** The application-defined SQL function implementation will pass this
3994** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3995** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3996** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3997** and/or [sqlite3_set_auxdata()].
3998*/
3999typedef struct sqlite3_context sqlite3_context;
4000
4001/*
4002** CAPI3REF: Binding Values To Prepared Statements
4003** KEYWORDS: {host parameter} {host parameters} {host parameter name}
4004** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
4005** METHOD: sqlite3_stmt
4006**
4007** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
4008** literals may be replaced by a [parameter] that matches one of following
4009** templates:
4010**
4011** <ul>
4012** <li>  ?
4013** <li>  ?NNN
4014** <li>  :VVV
4015** <li>  @VVV
4016** <li>  $VVV
4017** </ul>
4018**
4019** In the templates above, NNN represents an integer literal,
4020** and VVV represents an alphanumeric identifier.)^  ^The values of these
4021** parameters (also called "host parameter names" or "SQL parameters")
4022** can be set using the sqlite3_bind_*() routines defined here.
4023**
4024** ^The first argument to the sqlite3_bind_*() routines is always
4025** a pointer to the [sqlite3_stmt] object returned from
4026** [sqlite3_prepare_v2()] or its variants.
4027**
4028** ^The second argument is the index of the SQL parameter to be set.
4029** ^The leftmost SQL parameter has an index of 1.  ^When the same named
4030** SQL parameter is used more than once, second and subsequent
4031** occurrences have the same index as the first occurrence.
4032** ^The index for named parameters can be looked up using the
4033** [sqlite3_bind_parameter_index()] API if desired.  ^The index
4034** for "?NNN" parameters is the value of NNN.
4035** ^The NNN value must be between 1 and the [sqlite3_limit()]
4036** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
4037**
4038** ^The third argument is the value to bind to the parameter.
4039** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
4040** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
4041** is ignored and the end result is the same as sqlite3_bind_null().
4042**
4043** ^(In those routines that have a fourth argument, its value is the
4044** number of bytes in the parameter.  To be clear: the value is the
4045** number of <u>bytes</u> in the value, not the number of characters.)^
4046** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
4047** is negative, then the length of the string is
4048** the number of bytes up to the first zero terminator.
4049** If the fourth parameter to sqlite3_bind_blob() is negative, then
4050** the behavior is undefined.
4051** If a non-negative fourth parameter is provided to sqlite3_bind_text()
4052** or sqlite3_bind_text16() or sqlite3_bind_text64() then
4053** that parameter must be the byte offset
4054** where the NUL terminator would occur assuming the string were NUL
4055** terminated.  If any NUL characters occur at byte offsets less than
4056** the value of the fourth parameter then the resulting string value will
4057** contain embedded NULs.  The result of expressions involving strings
4058** with embedded NULs is undefined.
4059**
4060** ^The fifth argument to the BLOB and string binding interfaces
4061** is a destructor used to dispose of the BLOB or
4062** string after SQLite has finished with it.  ^The destructor is called
4063** to dispose of the BLOB or string even if the call to bind API fails.
4064** ^If the fifth argument is
4065** the special value [SQLITE_STATIC], then SQLite assumes that the
4066** information is in static, unmanaged space and does not need to be freed.
4067** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
4068** SQLite makes its own private copy of the data immediately, before
4069** the sqlite3_bind_*() routine returns.
4070**
4071** ^The sixth argument to sqlite3_bind_text64() must be one of
4072** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
4073** to specify the encoding of the text in the third parameter.  If
4074** the sixth argument to sqlite3_bind_text64() is not one of the
4075** allowed values shown above, or if the text encoding is different
4076** from the encoding specified by the sixth parameter, then the behavior
4077** is undefined.
4078**
4079** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
4080** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
4081** (just an integer to hold its size) while it is being processed.
4082** Zeroblobs are intended to serve as placeholders for BLOBs whose
4083** content is later written using
4084** [sqlite3_blob_open | incremental BLOB I/O] routines.
4085** ^A negative value for the zeroblob results in a zero-length BLOB.
4086**
4087** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
4088** for the [prepared statement] or with a prepared statement for which
4089** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
4090** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
4091** routine is passed a [prepared statement] that has been finalized, the
4092** result is undefined and probably harmful.
4093**
4094** ^Bindings are not cleared by the [sqlite3_reset()] routine.
4095** ^Unbound parameters are interpreted as NULL.
4096**
4097** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
4098** [error code] if anything goes wrong.
4099** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
4100** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
4101** [SQLITE_MAX_LENGTH].
4102** ^[SQLITE_RANGE] is returned if the parameter
4103** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
4104**
4105** See also: [sqlite3_bind_parameter_count()],
4106** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
4107*/
4108SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
4109SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
4110                        void(*)(void*));
4111SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
4112SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
4113SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
4114SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
4115SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
4116SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
4117SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
4118                         void(*)(void*), unsigned char encoding);
4119SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
4120SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
4121SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
4122
4123/*
4124** CAPI3REF: Number Of SQL Parameters
4125** METHOD: sqlite3_stmt
4126**
4127** ^This routine can be used to find the number of [SQL parameters]
4128** in a [prepared statement].  SQL parameters are tokens of the
4129** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
4130** placeholders for values that are [sqlite3_bind_blob | bound]
4131** to the parameters at a later time.
4132**
4133** ^(This routine actually returns the index of the largest (rightmost)
4134** parameter. For all forms except ?NNN, this will correspond to the
4135** number of unique parameters.  If parameters of the ?NNN form are used,
4136** there may be gaps in the list.)^
4137**
4138** See also: [sqlite3_bind_blob|sqlite3_bind()],
4139** [sqlite3_bind_parameter_name()], and
4140** [sqlite3_bind_parameter_index()].
4141*/
4142SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
4143
4144/*
4145** CAPI3REF: Name Of A Host Parameter
4146** METHOD: sqlite3_stmt
4147**
4148** ^The sqlite3_bind_parameter_name(P,N) interface returns
4149** the name of the N-th [SQL parameter] in the [prepared statement] P.
4150** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
4151** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
4152** respectively.
4153** In other words, the initial ":" or "$" or "@" or "?"
4154** is included as part of the name.)^
4155** ^Parameters of the form "?" without a following integer have no name
4156** and are referred to as "nameless" or "anonymous parameters".
4157**
4158** ^The first host parameter has an index of 1, not 0.
4159**
4160** ^If the value N is out of range or if the N-th parameter is
4161** nameless, then NULL is returned.  ^The returned string is
4162** always in UTF-8 encoding even if the named parameter was
4163** originally specified as UTF-16 in [sqlite3_prepare16()] or
4164** [sqlite3_prepare16_v2()].
4165**
4166** See also: [sqlite3_bind_blob|sqlite3_bind()],
4167** [sqlite3_bind_parameter_count()], and
4168** [sqlite3_bind_parameter_index()].
4169*/
4170SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
4171
4172/*
4173** CAPI3REF: Index Of A Parameter With A Given Name
4174** METHOD: sqlite3_stmt
4175**
4176** ^Return the index of an SQL parameter given its name.  ^The
4177** index value returned is suitable for use as the second
4178** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
4179** is returned if no matching parameter is found.  ^The parameter
4180** name must be given in UTF-8 even if the original statement
4181** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
4182**
4183** See also: [sqlite3_bind_blob|sqlite3_bind()],
4184** [sqlite3_bind_parameter_count()], and
4185** [sqlite3_bind_parameter_name()].
4186*/
4187SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
4188
4189/*
4190** CAPI3REF: Reset All Bindings On A Prepared Statement
4191** METHOD: sqlite3_stmt
4192**
4193** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
4194** the [sqlite3_bind_blob | bindings] on a [prepared statement].
4195** ^Use this routine to reset all host parameters to NULL.
4196*/
4197SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
4198
4199/*
4200** CAPI3REF: Number Of Columns In A Result Set
4201** METHOD: sqlite3_stmt
4202**
4203** ^Return the number of columns in the result set returned by the
4204** [prepared statement]. ^If this routine returns 0, that means the
4205** [prepared statement] returns no data (for example an [UPDATE]).
4206** ^However, just because this routine returns a positive number does not
4207** mean that one or more rows of data will be returned.  ^A SELECT statement
4208** will always have a positive sqlite3_column_count() but depending on the
4209** WHERE clause constraints and the table content, it might return no rows.
4210**
4211** See also: [sqlite3_data_count()]
4212*/
4213SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
4214
4215/*
4216** CAPI3REF: Column Names In A Result Set
4217** METHOD: sqlite3_stmt
4218**
4219** ^These routines return the name assigned to a particular column
4220** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
4221** interface returns a pointer to a zero-terminated UTF-8 string
4222** and sqlite3_column_name16() returns a pointer to a zero-terminated
4223** UTF-16 string.  ^The first parameter is the [prepared statement]
4224** that implements the [SELECT] statement. ^The second parameter is the
4225** column number.  ^The leftmost column is number 0.
4226**
4227** ^The returned string pointer is valid until either the [prepared statement]
4228** is destroyed by [sqlite3_finalize()] or until the statement is automatically
4229** reprepared by the first call to [sqlite3_step()] for a particular run
4230** or until the next call to
4231** sqlite3_column_name() or sqlite3_column_name16() on the same column.
4232**
4233** ^If sqlite3_malloc() fails during the processing of either routine
4234** (for example during a conversion from UTF-8 to UTF-16) then a
4235** NULL pointer is returned.
4236**
4237** ^The name of a result column is the value of the "AS" clause for
4238** that column, if there is an AS clause.  If there is no AS clause
4239** then the name of the column is unspecified and may change from
4240** one release of SQLite to the next.
4241*/
4242SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
4243SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
4244
4245/*
4246** CAPI3REF: Source Of Data In A Query Result
4247** METHOD: sqlite3_stmt
4248**
4249** ^These routines provide a means to determine the database, table, and
4250** table column that is the origin of a particular result column in
4251** [SELECT] statement.
4252** ^The name of the database or table or column can be returned as
4253** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
4254** the database name, the _table_ routines return the table name, and
4255** the origin_ routines return the column name.
4256** ^The returned string is valid until the [prepared statement] is destroyed
4257** using [sqlite3_finalize()] or until the statement is automatically
4258** reprepared by the first call to [sqlite3_step()] for a particular run
4259** or until the same information is requested
4260** again in a different encoding.
4261**
4262** ^The names returned are the original un-aliased names of the
4263** database, table, and column.
4264**
4265** ^The first argument to these interfaces is a [prepared statement].
4266** ^These functions return information about the Nth result column returned by
4267** the statement, where N is the second function argument.
4268** ^The left-most column is column 0 for these routines.
4269**
4270** ^If the Nth column returned by the statement is an expression or
4271** subquery and is not a column value, then all of these functions return
4272** NULL.  ^These routine might also return NULL if a memory allocation error
4273** occurs.  ^Otherwise, they return the name of the attached database, table,
4274** or column that query result column was extracted from.
4275**
4276** ^As with all other SQLite APIs, those whose names end with "16" return
4277** UTF-16 encoded strings and the other functions return UTF-8.
4278**
4279** ^These APIs are only available if the library was compiled with the
4280** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
4281**
4282** If two or more threads call one or more of these routines against the same
4283** prepared statement and column at the same time then the results are
4284** undefined.
4285**
4286** If two or more threads call one or more
4287** [sqlite3_column_database_name | column metadata interfaces]
4288** for the same [prepared statement] and result column
4289** at the same time then the results are undefined.
4290*/
4291SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
4292SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
4293SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
4294SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
4295SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
4296SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
4297
4298/*
4299** CAPI3REF: Declared Datatype Of A Query Result
4300** METHOD: sqlite3_stmt
4301**
4302** ^(The first parameter is a [prepared statement].
4303** If this statement is a [SELECT] statement and the Nth column of the
4304** returned result set of that [SELECT] is a table column (not an
4305** expression or subquery) then the declared type of the table
4306** column is returned.)^  ^If the Nth column of the result set is an
4307** expression or subquery, then a NULL pointer is returned.
4308** ^The returned string is always UTF-8 encoded.
4309**
4310** ^(For example, given the database schema:
4311**
4312** CREATE TABLE t1(c1 VARIANT);
4313**
4314** and the following statement to be compiled:
4315**
4316** SELECT c1 + 1, c1 FROM t1;
4317**
4318** this routine would return the string "VARIANT" for the second result
4319** column (i==1), and a NULL pointer for the first result column (i==0).)^
4320**
4321** ^SQLite uses dynamic run-time typing.  ^So just because a column
4322** is declared to contain a particular type does not mean that the
4323** data stored in that column is of the declared type.  SQLite is
4324** strongly typed, but the typing is dynamic not static.  ^Type
4325** is associated with individual values, not with the containers
4326** used to hold those values.
4327*/
4328SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
4329SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
4330
4331/*
4332** CAPI3REF: Evaluate An SQL Statement
4333** METHOD: sqlite3_stmt
4334**
4335** After a [prepared statement] has been prepared using either
4336** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4337** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4338** must be called one or more times to evaluate the statement.
4339**
4340** The details of the behavior of the sqlite3_step() interface depend
4341** on whether the statement was prepared using the newer "v2" interface
4342** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4343** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
4344** new "v2" interface is recommended for new applications but the legacy
4345** interface will continue to be supported.
4346**
4347** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4348** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4349** ^With the "v2" interface, any of the other [result codes] or
4350** [extended result codes] might be returned as well.
4351**
4352** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4353** database locks it needs to do its job.  ^If the statement is a [COMMIT]
4354** or occurs outside of an explicit transaction, then you can retry the
4355** statement.  If the statement is not a [COMMIT] and occurs within an
4356** explicit transaction then you should rollback the transaction before
4357** continuing.
4358**
4359** ^[SQLITE_DONE] means that the statement has finished executing
4360** successfully.  sqlite3_step() should not be called again on this virtual
4361** machine without first calling [sqlite3_reset()] to reset the virtual
4362** machine back to its initial state.
4363**
4364** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4365** is returned each time a new row of data is ready for processing by the
4366** caller. The values may be accessed using the [column access functions].
4367** sqlite3_step() is called again to retrieve the next row of data.
4368**
4369** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4370** violation) has occurred.  sqlite3_step() should not be called again on
4371** the VM. More information may be found by calling [sqlite3_errmsg()].
4372** ^With the legacy interface, a more specific error code (for example,
4373** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4374** can be obtained by calling [sqlite3_reset()] on the
4375** [prepared statement].  ^In the "v2" interface,
4376** the more specific error code is returned directly by sqlite3_step().
4377**
4378** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4379** Perhaps it was called on a [prepared statement] that has
4380** already been [sqlite3_finalize | finalized] or on one that had
4381** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
4382** be the case that the same database connection is being used by two or
4383** more threads at the same moment in time.
4384**
4385** For all versions of SQLite up to and including 3.6.23.1, a call to
4386** [sqlite3_reset()] was required after sqlite3_step() returned anything
4387** other than [SQLITE_ROW] before any subsequent invocation of
4388** sqlite3_step().  Failure to reset the prepared statement using
4389** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4390** sqlite3_step().  But after [version 3.6.23.1] ([dateof:3.6.23.1],
4391** sqlite3_step() began
4392** calling [sqlite3_reset()] automatically in this circumstance rather
4393** than returning [SQLITE_MISUSE].  This is not considered a compatibility
4394** break because any application that ever receives an SQLITE_MISUSE error
4395** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
4396** can be used to restore the legacy behavior.
4397**
4398** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4399** API always returns a generic error code, [SQLITE_ERROR], following any
4400** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4401** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4402** specific [error codes] that better describes the error.
4403** We admit that this is a goofy design.  The problem has been fixed
4404** with the "v2" interface.  If you prepare all of your SQL statements
4405** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4406** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4407** then the more specific [error codes] are returned directly
4408** by sqlite3_step().  The use of the "v2" interface is recommended.
4409*/
4410SQLITE_API int sqlite3_step(sqlite3_stmt*);
4411
4412/*
4413** CAPI3REF: Number of columns in a result set
4414** METHOD: sqlite3_stmt
4415**
4416** ^The sqlite3_data_count(P) interface returns the number of columns in the
4417** current row of the result set of [prepared statement] P.
4418** ^If prepared statement P does not have results ready to return
4419** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4420** interfaces) then sqlite3_data_count(P) returns 0.
4421** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4422** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4423** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
4424** will return non-zero if previous call to [sqlite3_step](P) returned
4425** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4426** where it always returns zero since each step of that multi-step
4427** pragma returns 0 columns of data.
4428**
4429** See also: [sqlite3_column_count()]
4430*/
4431SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4432
4433/*
4434** CAPI3REF: Fundamental Datatypes
4435** KEYWORDS: SQLITE_TEXT
4436**
4437** ^(Every value in SQLite has one of five fundamental datatypes:
4438**
4439** <ul>
4440** <li> 64-bit signed integer
4441** <li> 64-bit IEEE floating point number
4442** <li> string
4443** <li> BLOB
4444** <li> NULL
4445** </ul>)^
4446**
4447** These constants are codes for each of those types.
4448**
4449** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4450** for a completely different meaning.  Software that links against both
4451** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4452** SQLITE_TEXT.
4453*/
4454#define SQLITE_INTEGER  1
4455#define SQLITE_FLOAT    2
4456#define SQLITE_BLOB     4
4457#define SQLITE_NULL     5
4458#ifdef SQLITE_TEXT
4459# undef SQLITE_TEXT
4460#else
4461# define SQLITE_TEXT     3
4462#endif
4463#define SQLITE3_TEXT     3
4464
4465/*
4466** CAPI3REF: Result Values From A Query
4467** KEYWORDS: {column access functions}
4468** METHOD: sqlite3_stmt
4469**
4470** ^These routines return information about a single column of the current
4471** result row of a query.  ^In every case the first argument is a pointer
4472** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4473** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4474** and the second argument is the index of the column for which information
4475** should be returned. ^The leftmost column of the result set has the index 0.
4476** ^The number of columns in the result can be determined using
4477** [sqlite3_column_count()].
4478**
4479** If the SQL statement does not currently point to a valid row, or if the
4480** column index is out of range, the result is undefined.
4481** These routines may only be called when the most recent call to
4482** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4483** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4484** If any of these routines are called after [sqlite3_reset()] or
4485** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4486** something other than [SQLITE_ROW], the results are undefined.
4487** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4488** are called from a different thread while any of these routines
4489** are pending, then the results are undefined.
4490**
4491** ^The sqlite3_column_type() routine returns the
4492** [SQLITE_INTEGER | datatype code] for the initial data type
4493** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
4494** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4495** returned by sqlite3_column_type() is only meaningful if no type
4496** conversions have occurred as described below.  After a type conversion,
4497** the value returned by sqlite3_column_type() is undefined.  Future
4498** versions of SQLite may change the behavior of sqlite3_column_type()
4499** following a type conversion.
4500**
4501** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4502** routine returns the number of bytes in that BLOB or string.
4503** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4504** the string to UTF-8 and then returns the number of bytes.
4505** ^If the result is a numeric value then sqlite3_column_bytes() uses
4506** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4507** the number of bytes in that string.
4508** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4509**
4510** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4511** routine returns the number of bytes in that BLOB or string.
4512** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4513** the string to UTF-16 and then returns the number of bytes.
4514** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4515** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4516** the number of bytes in that string.
4517** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4518**
4519** ^The values returned by [sqlite3_column_bytes()] and
4520** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4521** of the string.  ^For clarity: the values returned by
4522** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4523** bytes in the string, not the number of characters.
4524**
4525** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4526** even empty strings, are always zero-terminated.  ^The return
4527** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4528**
4529** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
4530** [unprotected sqlite3_value] object.  In a multithreaded environment,
4531** an unprotected sqlite3_value object may only be used safely with
4532** [sqlite3_bind_value()] and [sqlite3_result_value()].
4533** If the [unprotected sqlite3_value] object returned by
4534** [sqlite3_column_value()] is used in any other way, including calls
4535** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4536** or [sqlite3_value_bytes()], the behavior is not threadsafe.
4537**
4538** These routines attempt to convert the value where appropriate.  ^For
4539** example, if the internal representation is FLOAT and a text result
4540** is requested, [sqlite3_snprintf()] is used internally to perform the
4541** conversion automatically.  ^(The following table details the conversions
4542** that are applied:
4543**
4544** <blockquote>
4545** <table border="1">
4546** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4547**
4548** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4549** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4550** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
4551** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
4552** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4553** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4554** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4555** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
4556** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4557** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
4558** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
4559** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
4560** <tr><td>  TEXT    <td>   BLOB    <td> No change
4561** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
4562** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
4563** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4564** </table>
4565** </blockquote>)^
4566**
4567** Note that when type conversions occur, pointers returned by prior
4568** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4569** sqlite3_column_text16() may be invalidated.
4570** Type conversions and pointer invalidations might occur
4571** in the following cases:
4572**
4573** <ul>
4574** <li> The initial content is a BLOB and sqlite3_column_text() or
4575**      sqlite3_column_text16() is called.  A zero-terminator might
4576**      need to be added to the string.</li>
4577** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4578**      sqlite3_column_text16() is called.  The content must be converted
4579**      to UTF-16.</li>
4580** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4581**      sqlite3_column_text() is called.  The content must be converted
4582**      to UTF-8.</li>
4583** </ul>
4584**
4585** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4586** not invalidate a prior pointer, though of course the content of the buffer
4587** that the prior pointer references will have been modified.  Other kinds
4588** of conversion are done in place when it is possible, but sometimes they
4589** are not possible and in those cases prior pointers are invalidated.
4590**
4591** The safest policy is to invoke these routines
4592** in one of the following ways:
4593**
4594** <ul>
4595**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4596**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4597**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4598** </ul>
4599**
4600** In other words, you should call sqlite3_column_text(),
4601** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4602** into the desired format, then invoke sqlite3_column_bytes() or
4603** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4604** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4605** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4606** with calls to sqlite3_column_bytes().
4607**
4608** ^The pointers returned are valid until a type conversion occurs as
4609** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4610** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4611** and BLOBs is freed automatically.  Do <em>not</em> pass the pointers returned
4612** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4613** [sqlite3_free()].
4614**
4615** ^(If a memory allocation error occurs during the evaluation of any
4616** of these routines, a default value is returned.  The default value
4617** is either the integer 0, the floating point number 0.0, or a NULL
4618** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4619** [SQLITE_NOMEM].)^
4620*/
4621SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4622SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4623SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4624SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4625SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4626SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4627SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4628SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4629SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4630SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4631
4632/*
4633** CAPI3REF: Destroy A Prepared Statement Object
4634** DESTRUCTOR: sqlite3_stmt
4635**
4636** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4637** ^If the most recent evaluation of the statement encountered no errors
4638** or if the statement is never been evaluated, then sqlite3_finalize() returns
4639** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4640** sqlite3_finalize(S) returns the appropriate [error code] or
4641** [extended error code].
4642**
4643** ^The sqlite3_finalize(S) routine can be called at any point during
4644** the life cycle of [prepared statement] S:
4645** before statement S is ever evaluated, after
4646** one or more calls to [sqlite3_reset()], or after any call
4647** to [sqlite3_step()] regardless of whether or not the statement has
4648** completed execution.
4649**
4650** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4651**
4652** The application must finalize every [prepared statement] in order to avoid
4653** resource leaks.  It is a grievous error for the application to try to use
4654** a prepared statement after it has been finalized.  Any use of a prepared
4655** statement after it has been finalized can result in undefined and
4656** undesirable behavior such as segfaults and heap corruption.
4657*/
4658SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4659
4660/*
4661** CAPI3REF: Reset A Prepared Statement Object
4662** METHOD: sqlite3_stmt
4663**
4664** The sqlite3_reset() function is called to reset a [prepared statement]
4665** object back to its initial state, ready to be re-executed.
4666** ^Any SQL statement variables that had values bound to them using
4667** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4668** Use [sqlite3_clear_bindings()] to reset the bindings.
4669**
4670** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4671** back to the beginning of its program.
4672**
4673** ^If the most recent call to [sqlite3_step(S)] for the
4674** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4675** or if [sqlite3_step(S)] has never before been called on S,
4676** then [sqlite3_reset(S)] returns [SQLITE_OK].
4677**
4678** ^If the most recent call to [sqlite3_step(S)] for the
4679** [prepared statement] S indicated an error, then
4680** [sqlite3_reset(S)] returns an appropriate [error code].
4681**
4682** ^The [sqlite3_reset(S)] interface does not change the values
4683** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4684*/
4685SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4686
4687/*
4688** CAPI3REF: Create Or Redefine SQL Functions
4689** KEYWORDS: {function creation routines}
4690** KEYWORDS: {application-defined SQL function}
4691** KEYWORDS: {application-defined SQL functions}
4692** METHOD: sqlite3
4693**
4694** ^These functions (collectively known as "function creation routines")
4695** are used to add SQL functions or aggregates or to redefine the behavior
4696** of existing SQL functions or aggregates.  The only differences between
4697** these routines are the text encoding expected for
4698** the second parameter (the name of the function being created)
4699** and the presence or absence of a destructor callback for
4700** the application data pointer.
4701**
4702** ^The first parameter is the [database connection] to which the SQL
4703** function is to be added.  ^If an application uses more than one database
4704** connection then application-defined SQL functions must be added
4705** to each database connection separately.
4706**
4707** ^The second parameter is the name of the SQL function to be created or
4708** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4709** representation, exclusive of the zero-terminator.  ^Note that the name
4710** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4711** ^Any attempt to create a function with a longer name
4712** will result in [SQLITE_MISUSE] being returned.
4713**
4714** ^The third parameter (nArg)
4715** is the number of arguments that the SQL function or
4716** aggregate takes. ^If this parameter is -1, then the SQL function or
4717** aggregate may take any number of arguments between 0 and the limit
4718** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4719** parameter is less than -1 or greater than 127 then the behavior is
4720** undefined.
4721**
4722** ^The fourth parameter, eTextRep, specifies what
4723** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4724** its parameters.  The application should set this parameter to
4725** [SQLITE_UTF16LE] if the function implementation invokes
4726** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
4727** implementation invokes [sqlite3_value_text16be()] on an input, or
4728** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
4729** otherwise.  ^The same SQL function may be registered multiple times using
4730** different preferred text encodings, with different implementations for
4731** each encoding.
4732** ^When multiple implementations of the same function are available, SQLite
4733** will pick the one that involves the least amount of data conversion.
4734**
4735** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
4736** to signal that the function will always return the same result given
4737** the same inputs within a single SQL statement.  Most SQL functions are
4738** deterministic.  The built-in [random()] SQL function is an example of a
4739** function that is not deterministic.  The SQLite query planner is able to
4740** perform additional optimizations on deterministic functions, so use
4741** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
4742**
4743** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4744** function can gain access to this pointer using [sqlite3_user_data()].)^
4745**
4746** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4747** pointers to C-language functions that implement the SQL function or
4748** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4749** callback only; NULL pointers must be passed as the xStep and xFinal
4750** parameters. ^An aggregate SQL function requires an implementation of xStep
4751** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4752** SQL function or aggregate, pass NULL pointers for all three function
4753** callbacks.
4754**
4755** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4756** then it is destructor for the application data pointer.
4757** The destructor is invoked when the function is deleted, either by being
4758** overloaded or when the database connection closes.)^
4759** ^The destructor is also invoked if the call to
4760** sqlite3_create_function_v2() fails.
4761** ^When the destructor callback of the tenth parameter is invoked, it
4762** is passed a single argument which is a copy of the application data
4763** pointer which was the fifth parameter to sqlite3_create_function_v2().
4764**
4765** ^It is permitted to register multiple implementations of the same
4766** functions with the same name but with either differing numbers of
4767** arguments or differing preferred text encodings.  ^SQLite will use
4768** the implementation that most closely matches the way in which the
4769** SQL function is used.  ^A function implementation with a non-negative
4770** nArg parameter is a better match than a function implementation with
4771** a negative nArg.  ^A function where the preferred text encoding
4772** matches the database encoding is a better
4773** match than a function where the encoding is different.
4774** ^A function where the encoding difference is between UTF16le and UTF16be
4775** is a closer match than a function where the encoding difference is
4776** between UTF8 and UTF16.
4777**
4778** ^Built-in functions may be overloaded by new application-defined functions.
4779**
4780** ^An application-defined function is permitted to call other
4781** SQLite interfaces.  However, such calls must not
4782** close the database connection nor finalize or reset the prepared
4783** statement in which the function is running.
4784*/
4785SQLITE_API int sqlite3_create_function(
4786  sqlite3 *db,
4787  const char *zFunctionName,
4788  int nArg,
4789  int eTextRep,
4790  void *pApp,
4791  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4792  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4793  void (*xFinal)(sqlite3_context*)
4794);
4795SQLITE_API int sqlite3_create_function16(
4796  sqlite3 *db,
4797  const void *zFunctionName,
4798  int nArg,
4799  int eTextRep,
4800  void *pApp,
4801  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4802  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4803  void (*xFinal)(sqlite3_context*)
4804);
4805SQLITE_API int sqlite3_create_function_v2(
4806  sqlite3 *db,
4807  const char *zFunctionName,
4808  int nArg,
4809  int eTextRep,
4810  void *pApp,
4811  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4812  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4813  void (*xFinal)(sqlite3_context*),
4814  void(*xDestroy)(void*)
4815);
4816
4817/*
4818** CAPI3REF: Text Encodings
4819**
4820** These constant define integer codes that represent the various
4821** text encodings supported by SQLite.
4822*/
4823#define SQLITE_UTF8           1    /* IMP: R-37514-35566 */
4824#define SQLITE_UTF16LE        2    /* IMP: R-03371-37637 */
4825#define SQLITE_UTF16BE        3    /* IMP: R-51971-34154 */
4826#define SQLITE_UTF16          4    /* Use native byte order */
4827#define SQLITE_ANY            5    /* Deprecated */
4828#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4829
4830/*
4831** CAPI3REF: Function Flags
4832**
4833** These constants may be ORed together with the
4834** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
4835** to [sqlite3_create_function()], [sqlite3_create_function16()], or
4836** [sqlite3_create_function_v2()].
4837*/
4838#define SQLITE_DETERMINISTIC    0x800
4839
4840/*
4841** CAPI3REF: Deprecated Functions
4842** DEPRECATED
4843**
4844** These functions are [deprecated].  In order to maintain
4845** backwards compatibility with older code, these functions continue
4846** to be supported.  However, new applications should avoid
4847** the use of these functions.  To encourage programmers to avoid
4848** these functions, we will not explain what they do.
4849*/
4850#ifndef SQLITE_OMIT_DEPRECATED
4851SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4852SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4853SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4854SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4855SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4856SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4857                      void*,sqlite3_int64);
4858#endif
4859
4860/*
4861** CAPI3REF: Obtaining SQL Values
4862** METHOD: sqlite3_value
4863**
4864** The C-language implementation of SQL functions and aggregates uses
4865** this set of interface routines to access the parameter values on
4866** the function or aggregate.
4867**
4868** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4869** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4870** define callbacks that implement the SQL functions and aggregates.
4871** The 3rd parameter to these callbacks is an array of pointers to
4872** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4873** each parameter to the SQL function.  These routines are used to
4874** extract values from the [sqlite3_value] objects.
4875**
4876** These routines work only with [protected sqlite3_value] objects.
4877** Any attempt to use these routines on an [unprotected sqlite3_value]
4878** object results in undefined behavior.
4879**
4880** ^These routines work just like the corresponding [column access functions]
4881** except that these routines take a single [protected sqlite3_value] object
4882** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4883**
4884** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4885** in the native byte-order of the host machine.  ^The
4886** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4887** extract UTF-16 strings as big-endian and little-endian respectively.
4888**
4889** ^(The sqlite3_value_numeric_type() interface attempts to apply
4890** numeric affinity to the value.  This means that an attempt is
4891** made to convert the value to an integer or floating point.  If
4892** such a conversion is possible without loss of information (in other
4893** words, if the value is a string that looks like a number)
4894** then the conversion is performed.  Otherwise no conversion occurs.
4895** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4896**
4897** Please pay particular attention to the fact that the pointer returned
4898** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4899** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4900** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4901** or [sqlite3_value_text16()].
4902**
4903** These routines must be called from the same thread as
4904** the SQL function that supplied the [sqlite3_value*] parameters.
4905*/
4906SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4907SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4908SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4909SQLITE_API double sqlite3_value_double(sqlite3_value*);
4910SQLITE_API int sqlite3_value_int(sqlite3_value*);
4911SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4912SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4913SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4914SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4915SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4916SQLITE_API int sqlite3_value_type(sqlite3_value*);
4917SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4918
4919/*
4920** CAPI3REF: Finding The Subtype Of SQL Values
4921** METHOD: sqlite3_value
4922**
4923** The sqlite3_value_subtype(V) function returns the subtype for
4924** an [application-defined SQL function] argument V.  The subtype
4925** information can be used to pass a limited amount of context from
4926** one SQL function to another.  Use the [sqlite3_result_subtype()]
4927** routine to set the subtype for the return value of an SQL function.
4928**
4929** SQLite makes no use of subtype itself.  It merely passes the subtype
4930** from the result of one [application-defined SQL function] into the
4931** input of another.
4932*/
4933SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
4934
4935/*
4936** CAPI3REF: Copy And Free SQL Values
4937** METHOD: sqlite3_value
4938**
4939** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
4940** object D and returns a pointer to that copy.  ^The [sqlite3_value] returned
4941** is a [protected sqlite3_value] object even if the input is not.
4942** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
4943** memory allocation fails.
4944**
4945** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
4946** previously obtained from [sqlite3_value_dup()].  ^If V is a NULL pointer
4947** then sqlite3_value_free(V) is a harmless no-op.
4948*/
4949SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
4950SQLITE_API void sqlite3_value_free(sqlite3_value*);
4951
4952/*
4953** CAPI3REF: Obtain Aggregate Function Context
4954** METHOD: sqlite3_context
4955**
4956** Implementations of aggregate SQL functions use this
4957** routine to allocate memory for storing their state.
4958**
4959** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4960** for a particular aggregate function, SQLite
4961** allocates N of memory, zeroes out that memory, and returns a pointer
4962** to the new memory. ^On second and subsequent calls to
4963** sqlite3_aggregate_context() for the same aggregate function instance,
4964** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4965** called once for each invocation of the xStep callback and then one
4966** last time when the xFinal callback is invoked.  ^(When no rows match
4967** an aggregate query, the xStep() callback of the aggregate function
4968** implementation is never called and xFinal() is called exactly once.
4969** In those cases, sqlite3_aggregate_context() might be called for the
4970** first time from within xFinal().)^
4971**
4972** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4973** when first called if N is less than or equal to zero or if a memory
4974** allocate error occurs.
4975**
4976** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4977** determined by the N parameter on first successful call.  Changing the
4978** value of N in subsequent call to sqlite3_aggregate_context() within
4979** the same aggregate function instance will not resize the memory
4980** allocation.)^  Within the xFinal callback, it is customary to set
4981** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4982** pointless memory allocations occur.
4983**
4984** ^SQLite automatically frees the memory allocated by
4985** sqlite3_aggregate_context() when the aggregate query concludes.
4986**
4987** The first parameter must be a copy of the
4988** [sqlite3_context | SQL function context] that is the first parameter
4989** to the xStep or xFinal callback routine that implements the aggregate
4990** function.
4991**
4992** This routine must be called from the same thread in which
4993** the aggregate SQL function is running.
4994*/
4995SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4996
4997/*
4998** CAPI3REF: User Data For Functions
4999** METHOD: sqlite3_context
5000**
5001** ^The sqlite3_user_data() interface returns a copy of
5002** the pointer that was the pUserData parameter (the 5th parameter)
5003** of the [sqlite3_create_function()]
5004** and [sqlite3_create_function16()] routines that originally
5005** registered the application defined function.
5006**
5007** This routine must be called from the same thread in which
5008** the application-defined function is running.
5009*/
5010SQLITE_API void *sqlite3_user_data(sqlite3_context*);
5011
5012/*
5013** CAPI3REF: Database Connection For Functions
5014** METHOD: sqlite3_context
5015**
5016** ^The sqlite3_context_db_handle() interface returns a copy of
5017** the pointer to the [database connection] (the 1st parameter)
5018** of the [sqlite3_create_function()]
5019** and [sqlite3_create_function16()] routines that originally
5020** registered the application defined function.
5021*/
5022SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
5023
5024/*
5025** CAPI3REF: Function Auxiliary Data
5026** METHOD: sqlite3_context
5027**
5028** These functions may be used by (non-aggregate) SQL functions to
5029** associate metadata with argument values. If the same value is passed to
5030** multiple invocations of the same SQL function during query execution, under
5031** some circumstances the associated metadata may be preserved.  An example
5032** of where this might be useful is in a regular-expression matching
5033** function. The compiled version of the regular expression can be stored as
5034** metadata associated with the pattern string.
5035** Then as long as the pattern string remains the same,
5036** the compiled regular expression can be reused on multiple
5037** invocations of the same function.
5038**
5039** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
5040** associated by the sqlite3_set_auxdata() function with the Nth argument
5041** value to the application-defined function. ^If there is no metadata
5042** associated with the function argument, this sqlite3_get_auxdata() interface
5043** returns a NULL pointer.
5044**
5045** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
5046** argument of the application-defined function.  ^Subsequent
5047** calls to sqlite3_get_auxdata(C,N) return P from the most recent
5048** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
5049** NULL if the metadata has been discarded.
5050** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
5051** SQLite will invoke the destructor function X with parameter P exactly
5052** once, when the metadata is discarded.
5053** SQLite is free to discard the metadata at any time, including: <ul>
5054** <li> ^(when the corresponding function parameter changes)^, or
5055** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
5056**      SQL statement)^, or
5057** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
5058**       parameter)^, or
5059** <li> ^(during the original sqlite3_set_auxdata() call when a memory
5060**      allocation error occurs.)^ </ul>
5061**
5062** Note the last bullet in particular.  The destructor X in
5063** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
5064** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
5065** should be called near the end of the function implementation and the
5066** function implementation should not make any use of P after
5067** sqlite3_set_auxdata() has been called.
5068**
5069** ^(In practice, metadata is preserved between function calls for
5070** function parameters that are compile-time constants, including literal
5071** values and [parameters] and expressions composed from the same.)^
5072**
5073** These routines must be called from the same thread in which
5074** the SQL function is running.
5075*/
5076SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
5077SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
5078
5079
5080/*
5081** CAPI3REF: Constants Defining Special Destructor Behavior
5082**
5083** These are special values for the destructor that is passed in as the
5084** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
5085** argument is SQLITE_STATIC, it means that the content pointer is constant
5086** and will never change.  It does not need to be destroyed.  ^The
5087** SQLITE_TRANSIENT value means that the content will likely change in
5088** the near future and that SQLite should make its own private copy of
5089** the content before returning.
5090**
5091** The typedef is necessary to work around problems in certain
5092** C++ compilers.
5093*/
5094typedef void (*sqlite3_destructor_type)(void*);
5095#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
5096#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
5097
5098/*
5099** CAPI3REF: Setting The Result Of An SQL Function
5100** METHOD: sqlite3_context
5101**
5102** These routines are used by the xFunc or xFinal callbacks that
5103** implement SQL functions and aggregates.  See
5104** [sqlite3_create_function()] and [sqlite3_create_function16()]
5105** for additional information.
5106**
5107** These functions work very much like the [parameter binding] family of
5108** functions used to bind values to host parameters in prepared statements.
5109** Refer to the [SQL parameter] documentation for additional information.
5110**
5111** ^The sqlite3_result_blob() interface sets the result from
5112** an application-defined function to be the BLOB whose content is pointed
5113** to by the second parameter and which is N bytes long where N is the
5114** third parameter.
5115**
5116** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
5117** interfaces set the result of the application-defined function to be
5118** a BLOB containing all zero bytes and N bytes in size.
5119**
5120** ^The sqlite3_result_double() interface sets the result from
5121** an application-defined function to be a floating point value specified
5122** by its 2nd argument.
5123**
5124** ^The sqlite3_result_error() and sqlite3_result_error16() functions
5125** cause the implemented SQL function to throw an exception.
5126** ^SQLite uses the string pointed to by the
5127** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
5128** as the text of an error message.  ^SQLite interprets the error
5129** message string from sqlite3_result_error() as UTF-8. ^SQLite
5130** interprets the string from sqlite3_result_error16() as UTF-16 in native
5131** byte order.  ^If the third parameter to sqlite3_result_error()
5132** or sqlite3_result_error16() is negative then SQLite takes as the error
5133** message all text up through the first zero character.
5134** ^If the third parameter to sqlite3_result_error() or
5135** sqlite3_result_error16() is non-negative then SQLite takes that many
5136** bytes (not characters) from the 2nd parameter as the error message.
5137** ^The sqlite3_result_error() and sqlite3_result_error16()
5138** routines make a private copy of the error message text before
5139** they return.  Hence, the calling function can deallocate or
5140** modify the text after they return without harm.
5141** ^The sqlite3_result_error_code() function changes the error code
5142** returned by SQLite as a result of an error in a function.  ^By default,
5143** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
5144** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
5145**
5146** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
5147** error indicating that a string or BLOB is too long to represent.
5148**
5149** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
5150** error indicating that a memory allocation failed.
5151**
5152** ^The sqlite3_result_int() interface sets the return value
5153** of the application-defined function to be the 32-bit signed integer
5154** value given in the 2nd argument.
5155** ^The sqlite3_result_int64() interface sets the return value
5156** of the application-defined function to be the 64-bit signed integer
5157** value given in the 2nd argument.
5158**
5159** ^The sqlite3_result_null() interface sets the return value
5160** of the application-defined function to be NULL.
5161**
5162** ^The sqlite3_result_text(), sqlite3_result_text16(),
5163** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
5164** set the return value of the application-defined function to be
5165** a text string which is represented as UTF-8, UTF-16 native byte order,
5166** UTF-16 little endian, or UTF-16 big endian, respectively.
5167** ^The sqlite3_result_text64() interface sets the return value of an
5168** application-defined function to be a text string in an encoding
5169** specified by the fifth (and last) parameter, which must be one
5170** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
5171** ^SQLite takes the text result from the application from
5172** the 2nd parameter of the sqlite3_result_text* interfaces.
5173** ^If the 3rd parameter to the sqlite3_result_text* interfaces
5174** is negative, then SQLite takes result text from the 2nd parameter
5175** through the first zero character.
5176** ^If the 3rd parameter to the sqlite3_result_text* interfaces
5177** is non-negative, then as many bytes (not characters) of the text
5178** pointed to by the 2nd parameter are taken as the application-defined
5179** function result.  If the 3rd parameter is non-negative, then it
5180** must be the byte offset into the string where the NUL terminator would
5181** appear if the string where NUL terminated.  If any NUL characters occur
5182** in the string at a byte offset that is less than the value of the 3rd
5183** parameter, then the resulting string will contain embedded NULs and the
5184** result of expressions operating on strings with embedded NULs is undefined.
5185** ^If the 4th parameter to the sqlite3_result_text* interfaces
5186** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
5187** function as the destructor on the text or BLOB result when it has
5188** finished using that result.
5189** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
5190** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
5191** assumes that the text or BLOB result is in constant space and does not
5192** copy the content of the parameter nor call a destructor on the content
5193** when it has finished using that result.
5194** ^If the 4th parameter to the sqlite3_result_text* interfaces
5195** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
5196** then SQLite makes a copy of the result into space obtained from
5197** from [sqlite3_malloc()] before it returns.
5198**
5199** ^The sqlite3_result_value() interface sets the result of
5200** the application-defined function to be a copy of the
5201** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
5202** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
5203** so that the [sqlite3_value] specified in the parameter may change or
5204** be deallocated after sqlite3_result_value() returns without harm.
5205** ^A [protected sqlite3_value] object may always be used where an
5206** [unprotected sqlite3_value] object is required, so either
5207** kind of [sqlite3_value] object can be used with this interface.
5208**
5209** If these routines are called from within the different thread
5210** than the one containing the application-defined function that received
5211** the [sqlite3_context] pointer, the results are undefined.
5212*/
5213SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
5214SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
5215                           sqlite3_uint64,void(*)(void*));
5216SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
5217SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
5218SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
5219SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
5220SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
5221SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
5222SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
5223SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
5224SQLITE_API void sqlite3_result_null(sqlite3_context*);
5225SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
5226SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
5227                           void(*)(void*), unsigned char encoding);
5228SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
5229SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
5230SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
5231SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
5232SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
5233SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
5234
5235
5236/*
5237** CAPI3REF: Setting The Subtype Of An SQL Function
5238** METHOD: sqlite3_context
5239**
5240** The sqlite3_result_subtype(C,T) function causes the subtype of
5241** the result from the [application-defined SQL function] with
5242** [sqlite3_context] C to be the value T.  Only the lower 8 bits
5243** of the subtype T are preserved in current versions of SQLite;
5244** higher order bits are discarded.
5245** The number of subtype bytes preserved by SQLite might increase
5246** in future releases of SQLite.
5247*/
5248SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
5249
5250/*
5251** CAPI3REF: Define New Collating Sequences
5252** METHOD: sqlite3
5253**
5254** ^These functions add, remove, or modify a [collation] associated
5255** with the [database connection] specified as the first argument.
5256**
5257** ^The name of the collation is a UTF-8 string
5258** for sqlite3_create_collation() and sqlite3_create_collation_v2()
5259** and a UTF-16 string in native byte order for sqlite3_create_collation16().
5260** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
5261** considered to be the same name.
5262**
5263** ^(The third argument (eTextRep) must be one of the constants:
5264** <ul>
5265** <li> [SQLITE_UTF8],
5266** <li> [SQLITE_UTF16LE],
5267** <li> [SQLITE_UTF16BE],
5268** <li> [SQLITE_UTF16], or
5269** <li> [SQLITE_UTF16_ALIGNED].
5270** </ul>)^
5271** ^The eTextRep argument determines the encoding of strings passed
5272** to the collating function callback, xCallback.
5273** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
5274** force strings to be UTF16 with native byte order.
5275** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
5276** on an even byte address.
5277**
5278** ^The fourth argument, pArg, is an application data pointer that is passed
5279** through as the first argument to the collating function callback.
5280**
5281** ^The fifth argument, xCallback, is a pointer to the collating function.
5282** ^Multiple collating functions can be registered using the same name but
5283** with different eTextRep parameters and SQLite will use whichever
5284** function requires the least amount of data transformation.
5285** ^If the xCallback argument is NULL then the collating function is
5286** deleted.  ^When all collating functions having the same name are deleted,
5287** that collation is no longer usable.
5288**
5289** ^The collating function callback is invoked with a copy of the pArg
5290** application data pointer and with two strings in the encoding specified
5291** by the eTextRep argument.  The collating function must return an
5292** integer that is negative, zero, or positive
5293** if the first string is less than, equal to, or greater than the second,
5294** respectively.  A collating function must always return the same answer
5295** given the same inputs.  If two or more collating functions are registered
5296** to the same collation name (using different eTextRep values) then all
5297** must give an equivalent answer when invoked with equivalent strings.
5298** The collating function must obey the following properties for all
5299** strings A, B, and C:
5300**
5301** <ol>
5302** <li> If A==B then B==A.
5303** <li> If A==B and B==C then A==C.
5304** <li> If A&lt;B THEN B&gt;A.
5305** <li> If A&lt;B and B&lt;C then A&lt;C.
5306** </ol>
5307**
5308** If a collating function fails any of the above constraints and that
5309** collating function is  registered and used, then the behavior of SQLite
5310** is undefined.
5311**
5312** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
5313** with the addition that the xDestroy callback is invoked on pArg when
5314** the collating function is deleted.
5315** ^Collating functions are deleted when they are overridden by later
5316** calls to the collation creation functions or when the
5317** [database connection] is closed using [sqlite3_close()].
5318**
5319** ^The xDestroy callback is <u>not</u> called if the
5320** sqlite3_create_collation_v2() function fails.  Applications that invoke
5321** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
5322** check the return code and dispose of the application data pointer
5323** themselves rather than expecting SQLite to deal with it for them.
5324** This is different from every other SQLite interface.  The inconsistency
5325** is unfortunate but cannot be changed without breaking backwards
5326** compatibility.
5327**
5328** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
5329*/
5330SQLITE_API int sqlite3_create_collation(
5331  sqlite3*,
5332  const char *zName,
5333  int eTextRep,
5334  void *pArg,
5335  int(*xCompare)(void*,int,const void*,int,const void*)
5336);
5337SQLITE_API int sqlite3_create_collation_v2(
5338  sqlite3*,
5339  const char *zName,
5340  int eTextRep,
5341  void *pArg,
5342  int(*xCompare)(void*,int,const void*,int,const void*),
5343  void(*xDestroy)(void*)
5344);
5345SQLITE_API int sqlite3_create_collation16(
5346  sqlite3*,
5347  const void *zName,
5348  int eTextRep,
5349  void *pArg,
5350  int(*xCompare)(void*,int,const void*,int,const void*)
5351);
5352
5353/*
5354** CAPI3REF: Collation Needed Callbacks
5355** METHOD: sqlite3
5356**
5357** ^To avoid having to register all collation sequences before a database
5358** can be used, a single callback function may be registered with the
5359** [database connection] to be invoked whenever an undefined collation
5360** sequence is required.
5361**
5362** ^If the function is registered using the sqlite3_collation_needed() API,
5363** then it is passed the names of undefined collation sequences as strings
5364** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
5365** the names are passed as UTF-16 in machine native byte order.
5366** ^A call to either function replaces the existing collation-needed callback.
5367**
5368** ^(When the callback is invoked, the first argument passed is a copy
5369** of the second argument to sqlite3_collation_needed() or
5370** sqlite3_collation_needed16().  The second argument is the database
5371** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5372** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5373** sequence function required.  The fourth parameter is the name of the
5374** required collation sequence.)^
5375**
5376** The callback function should register the desired collation using
5377** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5378** [sqlite3_create_collation_v2()].
5379*/
5380SQLITE_API int sqlite3_collation_needed(
5381  sqlite3*,
5382  void*,
5383  void(*)(void*,sqlite3*,int eTextRep,const char*)
5384);
5385SQLITE_API int sqlite3_collation_needed16(
5386  sqlite3*,
5387  void*,
5388  void(*)(void*,sqlite3*,int eTextRep,const void*)
5389);
5390
5391#ifdef SQLITE_HAS_CODEC
5392/*
5393** Specify the key for an encrypted database.  This routine should be
5394** called right after sqlite3_open().
5395**
5396** The code to implement this API is not available in the public release
5397** of SQLite.
5398*/
5399SQLITE_API int sqlite3_key(
5400  sqlite3 *db,                   /* Database to be rekeyed */
5401  const void *pKey, int nKey     /* The key */
5402);
5403SQLITE_API int sqlite3_key_v2(
5404  sqlite3 *db,                   /* Database to be rekeyed */
5405  const char *zDbName,           /* Name of the database */
5406  const void *pKey, int nKey     /* The key */
5407);
5408
5409/*
5410** Change the key on an open database.  If the current database is not
5411** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
5412** database is decrypted.
5413**
5414** The code to implement this API is not available in the public release
5415** of SQLite.
5416*/
5417SQLITE_API int sqlite3_rekey(
5418  sqlite3 *db,                   /* Database to be rekeyed */
5419  const void *pKey, int nKey     /* The new key */
5420);
5421SQLITE_API int sqlite3_rekey_v2(
5422  sqlite3 *db,                   /* Database to be rekeyed */
5423  const char *zDbName,           /* Name of the database */
5424  const void *pKey, int nKey     /* The new key */
5425);
5426
5427/*
5428** Specify the activation key for a SEE database.  Unless
5429** activated, none of the SEE routines will work.
5430*/
5431SQLITE_API void sqlite3_activate_see(
5432  const char *zPassPhrase        /* Activation phrase */
5433);
5434#endif
5435
5436#ifdef SQLITE_ENABLE_CEROD
5437/*
5438** Specify the activation key for a CEROD database.  Unless
5439** activated, none of the CEROD routines will work.
5440*/
5441SQLITE_API void sqlite3_activate_cerod(
5442  const char *zPassPhrase        /* Activation phrase */
5443);
5444#endif
5445
5446/*
5447** CAPI3REF: Suspend Execution For A Short Time
5448**
5449** The sqlite3_sleep() function causes the current thread to suspend execution
5450** for at least a number of milliseconds specified in its parameter.
5451**
5452** If the operating system does not support sleep requests with
5453** millisecond time resolution, then the time will be rounded up to
5454** the nearest second. The number of milliseconds of sleep actually
5455** requested from the operating system is returned.
5456**
5457** ^SQLite implements this interface by calling the xSleep()
5458** method of the default [sqlite3_vfs] object.  If the xSleep() method
5459** of the default VFS is not implemented correctly, or not implemented at
5460** all, then the behavior of sqlite3_sleep() may deviate from the description
5461** in the previous paragraphs.
5462*/
5463SQLITE_API int sqlite3_sleep(int);
5464
5465/*
5466** CAPI3REF: Name Of The Folder Holding Temporary Files
5467**
5468** ^(If this global variable is made to point to a string which is
5469** the name of a folder (a.k.a. directory), then all temporary files
5470** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5471** will be placed in that directory.)^  ^If this variable
5472** is a NULL pointer, then SQLite performs a search for an appropriate
5473** temporary file directory.
5474**
5475** Applications are strongly discouraged from using this global variable.
5476** It is required to set a temporary folder on Windows Runtime (WinRT).
5477** But for all other platforms, it is highly recommended that applications
5478** neither read nor write this variable.  This global variable is a relic
5479** that exists for backwards compatibility of legacy applications and should
5480** be avoided in new projects.
5481**
5482** It is not safe to read or modify this variable in more than one
5483** thread at a time.  It is not safe to read or modify this variable
5484** if a [database connection] is being used at the same time in a separate
5485** thread.
5486** It is intended that this variable be set once
5487** as part of process initialization and before any SQLite interface
5488** routines have been called and that this variable remain unchanged
5489** thereafter.
5490**
5491** ^The [temp_store_directory pragma] may modify this variable and cause
5492** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5493** the [temp_store_directory pragma] always assumes that any string
5494** that this variable points to is held in memory obtained from
5495** [sqlite3_malloc] and the pragma may attempt to free that memory
5496** using [sqlite3_free].
5497** Hence, if this variable is modified directly, either it should be
5498** made NULL or made to point to memory obtained from [sqlite3_malloc]
5499** or else the use of the [temp_store_directory pragma] should be avoided.
5500** Except when requested by the [temp_store_directory pragma], SQLite
5501** does not free the memory that sqlite3_temp_directory points to.  If
5502** the application wants that memory to be freed, it must do
5503** so itself, taking care to only do so after all [database connection]
5504** objects have been destroyed.
5505**
5506** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
5507** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
5508** features that require the use of temporary files may fail.  Here is an
5509** example of how to do this using C++ with the Windows Runtime:
5510**
5511** <blockquote><pre>
5512** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5513** &nbsp;     TemporaryFolder->Path->Data();
5514** char zPathBuf&#91;MAX_PATH + 1&#93;;
5515** memset(zPathBuf, 0, sizeof(zPathBuf));
5516** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5517** &nbsp;     NULL, NULL);
5518** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5519** </pre></blockquote>
5520*/
5521SQLITE_API char *sqlite3_temp_directory;
5522
5523/*
5524** CAPI3REF: Name Of The Folder Holding Database Files
5525**
5526** ^(If this global variable is made to point to a string which is
5527** the name of a folder (a.k.a. directory), then all database files
5528** specified with a relative pathname and created or accessed by
5529** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5530** to be relative to that directory.)^ ^If this variable is a NULL
5531** pointer, then SQLite assumes that all database files specified
5532** with a relative pathname are relative to the current directory
5533** for the process.  Only the windows VFS makes use of this global
5534** variable; it is ignored by the unix VFS.
5535**
5536** Changing the value of this variable while a database connection is
5537** open can result in a corrupt database.
5538**
5539** It is not safe to read or modify this variable in more than one
5540** thread at a time.  It is not safe to read or modify this variable
5541** if a [database connection] is being used at the same time in a separate
5542** thread.
5543** It is intended that this variable be set once
5544** as part of process initialization and before any SQLite interface
5545** routines have been called and that this variable remain unchanged
5546** thereafter.
5547**
5548** ^The [data_store_directory pragma] may modify this variable and cause
5549** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5550** the [data_store_directory pragma] always assumes that any string
5551** that this variable points to is held in memory obtained from
5552** [sqlite3_malloc] and the pragma may attempt to free that memory
5553** using [sqlite3_free].
5554** Hence, if this variable is modified directly, either it should be
5555** made NULL or made to point to memory obtained from [sqlite3_malloc]
5556** or else the use of the [data_store_directory pragma] should be avoided.
5557*/
5558SQLITE_API char *sqlite3_data_directory;
5559
5560/*
5561** CAPI3REF: Test For Auto-Commit Mode
5562** KEYWORDS: {autocommit mode}
5563** METHOD: sqlite3
5564**
5565** ^The sqlite3_get_autocommit() interface returns non-zero or
5566** zero if the given database connection is or is not in autocommit mode,
5567** respectively.  ^Autocommit mode is on by default.
5568** ^Autocommit mode is disabled by a [BEGIN] statement.
5569** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5570**
5571** If certain kinds of errors occur on a statement within a multi-statement
5572** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5573** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5574** transaction might be rolled back automatically.  The only way to
5575** find out whether SQLite automatically rolled back the transaction after
5576** an error is to use this function.
5577**
5578** If another thread changes the autocommit status of the database
5579** connection while this routine is running, then the return value
5580** is undefined.
5581*/
5582SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5583
5584/*
5585** CAPI3REF: Find The Database Handle Of A Prepared Statement
5586** METHOD: sqlite3_stmt
5587**
5588** ^The sqlite3_db_handle interface returns the [database connection] handle
5589** to which a [prepared statement] belongs.  ^The [database connection]
5590** returned by sqlite3_db_handle is the same [database connection]
5591** that was the first argument
5592** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5593** create the statement in the first place.
5594*/
5595SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5596
5597/*
5598** CAPI3REF: Return The Filename For A Database Connection
5599** METHOD: sqlite3
5600**
5601** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5602** associated with database N of connection D.  ^The main database file
5603** has the name "main".  If there is no attached database N on the database
5604** connection D, or if database N is a temporary or in-memory database, then
5605** a NULL pointer is returned.
5606**
5607** ^The filename returned by this function is the output of the
5608** xFullPathname method of the [VFS].  ^In other words, the filename
5609** will be an absolute pathname, even if the filename used
5610** to open the database originally was a URI or relative pathname.
5611*/
5612SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5613
5614/*
5615** CAPI3REF: Determine if a database is read-only
5616** METHOD: sqlite3
5617**
5618** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5619** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5620** the name of a database on connection D.
5621*/
5622SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5623
5624/*
5625** CAPI3REF: Find the next prepared statement
5626** METHOD: sqlite3
5627**
5628** ^This interface returns a pointer to the next [prepared statement] after
5629** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5630** then this interface returns a pointer to the first prepared statement
5631** associated with the database connection pDb.  ^If no prepared statement
5632** satisfies the conditions of this routine, it returns NULL.
5633**
5634** The [database connection] pointer D in a call to
5635** [sqlite3_next_stmt(D,S)] must refer to an open database
5636** connection and in particular must not be a NULL pointer.
5637*/
5638SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5639
5640/*
5641** CAPI3REF: Commit And Rollback Notification Callbacks
5642** METHOD: sqlite3
5643**
5644** ^The sqlite3_commit_hook() interface registers a callback
5645** function to be invoked whenever a transaction is [COMMIT | committed].
5646** ^Any callback set by a previous call to sqlite3_commit_hook()
5647** for the same database connection is overridden.
5648** ^The sqlite3_rollback_hook() interface registers a callback
5649** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5650** ^Any callback set by a previous call to sqlite3_rollback_hook()
5651** for the same database connection is overridden.
5652** ^The pArg argument is passed through to the callback.
5653** ^If the callback on a commit hook function returns non-zero,
5654** then the commit is converted into a rollback.
5655**
5656** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5657** return the P argument from the previous call of the same function
5658** on the same [database connection] D, or NULL for
5659** the first call for each function on D.
5660**
5661** The commit and rollback hook callbacks are not reentrant.
5662** The callback implementation must not do anything that will modify
5663** the database connection that invoked the callback.  Any actions
5664** to modify the database connection must be deferred until after the
5665** completion of the [sqlite3_step()] call that triggered the commit
5666** or rollback hook in the first place.
5667** Note that running any other SQL statements, including SELECT statements,
5668** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5669** the database connections for the meaning of "modify" in this paragraph.
5670**
5671** ^Registering a NULL function disables the callback.
5672**
5673** ^When the commit hook callback routine returns zero, the [COMMIT]
5674** operation is allowed to continue normally.  ^If the commit hook
5675** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5676** ^The rollback hook is invoked on a rollback that results from a commit
5677** hook returning non-zero, just as it would be with any other rollback.
5678**
5679** ^For the purposes of this API, a transaction is said to have been
5680** rolled back if an explicit "ROLLBACK" statement is executed, or
5681** an error or constraint causes an implicit rollback to occur.
5682** ^The rollback callback is not invoked if a transaction is
5683** automatically rolled back because the database connection is closed.
5684**
5685** See also the [sqlite3_update_hook()] interface.
5686*/
5687SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5688SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5689
5690/*
5691** CAPI3REF: Data Change Notification Callbacks
5692** METHOD: sqlite3
5693**
5694** ^The sqlite3_update_hook() interface registers a callback function
5695** with the [database connection] identified by the first argument
5696** to be invoked whenever a row is updated, inserted or deleted in
5697** a [rowid table].
5698** ^Any callback set by a previous call to this function
5699** for the same database connection is overridden.
5700**
5701** ^The second argument is a pointer to the function to invoke when a
5702** row is updated, inserted or deleted in a rowid table.
5703** ^The first argument to the callback is a copy of the third argument
5704** to sqlite3_update_hook().
5705** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5706** or [SQLITE_UPDATE], depending on the operation that caused the callback
5707** to be invoked.
5708** ^The third and fourth arguments to the callback contain pointers to the
5709** database and table name containing the affected row.
5710** ^The final callback parameter is the [rowid] of the row.
5711** ^In the case of an update, this is the [rowid] after the update takes place.
5712**
5713** ^(The update hook is not invoked when internal system tables are
5714** modified (i.e. sqlite_master and sqlite_sequence).)^
5715** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
5716**
5717** ^In the current implementation, the update hook
5718** is not invoked when conflicting rows are deleted because of an
5719** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5720** invoked when rows are deleted using the [truncate optimization].
5721** The exceptions defined in this paragraph might change in a future
5722** release of SQLite.
5723**
5724** The update hook implementation must not do anything that will modify
5725** the database connection that invoked the update hook.  Any actions
5726** to modify the database connection must be deferred until after the
5727** completion of the [sqlite3_step()] call that triggered the update hook.
5728** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5729** database connections for the meaning of "modify" in this paragraph.
5730**
5731** ^The sqlite3_update_hook(D,C,P) function
5732** returns the P argument from the previous call
5733** on the same [database connection] D, or NULL for
5734** the first call on D.
5735**
5736** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
5737** and [sqlite3_preupdate_hook()] interfaces.
5738*/
5739SQLITE_API void *sqlite3_update_hook(
5740  sqlite3*,
5741  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5742  void*
5743);
5744
5745/*
5746** CAPI3REF: Enable Or Disable Shared Pager Cache
5747**
5748** ^(This routine enables or disables the sharing of the database cache
5749** and schema data structures between [database connection | connections]
5750** to the same database. Sharing is enabled if the argument is true
5751** and disabled if the argument is false.)^
5752**
5753** ^Cache sharing is enabled and disabled for an entire process.
5754** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
5755** In prior versions of SQLite,
5756** sharing was enabled or disabled for each thread separately.
5757**
5758** ^(The cache sharing mode set by this interface effects all subsequent
5759** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5760** Existing database connections continue use the sharing mode
5761** that was in effect at the time they were opened.)^
5762**
5763** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5764** successfully.  An [error code] is returned otherwise.)^
5765**
5766** ^Shared cache is disabled by default. But this might change in
5767** future releases of SQLite.  Applications that care about shared
5768** cache setting should set it explicitly.
5769**
5770** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
5771** and will always return SQLITE_MISUSE. On those systems,
5772** shared cache mode should be enabled per-database connection via
5773** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
5774**
5775** This interface is threadsafe on processors where writing a
5776** 32-bit integer is atomic.
5777**
5778** See Also:  [SQLite Shared-Cache Mode]
5779*/
5780SQLITE_API int sqlite3_enable_shared_cache(int);
5781
5782/*
5783** CAPI3REF: Attempt To Free Heap Memory
5784**
5785** ^The sqlite3_release_memory() interface attempts to free N bytes
5786** of heap memory by deallocating non-essential memory allocations
5787** held by the database library.   Memory used to cache database
5788** pages to improve performance is an example of non-essential memory.
5789** ^sqlite3_release_memory() returns the number of bytes actually freed,
5790** which might be more or less than the amount requested.
5791** ^The sqlite3_release_memory() routine is a no-op returning zero
5792** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5793**
5794** See also: [sqlite3_db_release_memory()]
5795*/
5796SQLITE_API int sqlite3_release_memory(int);
5797
5798/*
5799** CAPI3REF: Free Memory Used By A Database Connection
5800** METHOD: sqlite3
5801**
5802** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5803** memory as possible from database connection D. Unlike the
5804** [sqlite3_release_memory()] interface, this interface is in effect even
5805** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5806** omitted.
5807**
5808** See also: [sqlite3_release_memory()]
5809*/
5810SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5811
5812/*
5813** CAPI3REF: Impose A Limit On Heap Size
5814**
5815** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5816** soft limit on the amount of heap memory that may be allocated by SQLite.
5817** ^SQLite strives to keep heap memory utilization below the soft heap
5818** limit by reducing the number of pages held in the page cache
5819** as heap memory usages approaches the limit.
5820** ^The soft heap limit is "soft" because even though SQLite strives to stay
5821** below the limit, it will exceed the limit rather than generate
5822** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
5823** is advisory only.
5824**
5825** ^The return value from sqlite3_soft_heap_limit64() is the size of
5826** the soft heap limit prior to the call, or negative in the case of an
5827** error.  ^If the argument N is negative
5828** then no change is made to the soft heap limit.  Hence, the current
5829** size of the soft heap limit can be determined by invoking
5830** sqlite3_soft_heap_limit64() with a negative argument.
5831**
5832** ^If the argument N is zero then the soft heap limit is disabled.
5833**
5834** ^(The soft heap limit is not enforced in the current implementation
5835** if one or more of following conditions are true:
5836**
5837** <ul>
5838** <li> The soft heap limit is set to zero.
5839** <li> Memory accounting is disabled using a combination of the
5840**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5841**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5842** <li> An alternative page cache implementation is specified using
5843**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5844** <li> The page cache allocates from its own memory pool supplied
5845**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5846**      from the heap.
5847** </ul>)^
5848**
5849** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]),
5850** the soft heap limit is enforced
5851** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5852** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5853** the soft heap limit is enforced on every memory allocation.  Without
5854** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5855** when memory is allocated by the page cache.  Testing suggests that because
5856** the page cache is the predominate memory user in SQLite, most
5857** applications will achieve adequate soft heap limit enforcement without
5858** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5859**
5860** The circumstances under which SQLite will enforce the soft heap limit may
5861** changes in future releases of SQLite.
5862*/
5863SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5864
5865/*
5866** CAPI3REF: Deprecated Soft Heap Limit Interface
5867** DEPRECATED
5868**
5869** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5870** interface.  This routine is provided for historical compatibility
5871** only.  All new applications should use the
5872** [sqlite3_soft_heap_limit64()] interface rather than this one.
5873*/
5874SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5875
5876
5877/*
5878** CAPI3REF: Extract Metadata About A Column Of A Table
5879** METHOD: sqlite3
5880**
5881** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
5882** information about column C of table T in database D
5883** on [database connection] X.)^  ^The sqlite3_table_column_metadata()
5884** interface returns SQLITE_OK and fills in the non-NULL pointers in
5885** the final five arguments with appropriate values if the specified
5886** column exists.  ^The sqlite3_table_column_metadata() interface returns
5887** SQLITE_ERROR and if the specified column does not exist.
5888** ^If the column-name parameter to sqlite3_table_column_metadata() is a
5889** NULL pointer, then this routine simply checks for the existence of the
5890** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
5891** does not.
5892**
5893** ^The column is identified by the second, third and fourth parameters to
5894** this function. ^(The second parameter is either the name of the database
5895** (i.e. "main", "temp", or an attached database) containing the specified
5896** table or NULL.)^ ^If it is NULL, then all attached databases are searched
5897** for the table using the same algorithm used by the database engine to
5898** resolve unqualified table references.
5899**
5900** ^The third and fourth parameters to this function are the table and column
5901** name of the desired column, respectively.
5902**
5903** ^Metadata is returned by writing to the memory locations passed as the 5th
5904** and subsequent parameters to this function. ^Any of these arguments may be
5905** NULL, in which case the corresponding element of metadata is omitted.
5906**
5907** ^(<blockquote>
5908** <table border="1">
5909** <tr><th> Parameter <th> Output<br>Type <th>  Description
5910**
5911** <tr><td> 5th <td> const char* <td> Data type
5912** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5913** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5914** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5915** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5916** </table>
5917** </blockquote>)^
5918**
5919** ^The memory pointed to by the character pointers returned for the
5920** declaration type and collation sequence is valid until the next
5921** call to any SQLite API function.
5922**
5923** ^If the specified table is actually a view, an [error code] is returned.
5924**
5925** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
5926** is not a [WITHOUT ROWID] table and an
5927** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5928** parameters are set for the explicitly declared column. ^(If there is no
5929** [INTEGER PRIMARY KEY] column, then the outputs
5930** for the [rowid] are set as follows:
5931**
5932** <pre>
5933**     data type: "INTEGER"
5934**     collation sequence: "BINARY"
5935**     not null: 0
5936**     primary key: 1
5937**     auto increment: 0
5938** </pre>)^
5939**
5940** ^This function causes all database schemas to be read from disk and
5941** parsed, if that has not already been done, and returns an error if
5942** any errors are encountered while loading the schema.
5943*/
5944SQLITE_API int sqlite3_table_column_metadata(
5945  sqlite3 *db,                /* Connection handle */
5946  const char *zDbName,        /* Database name or NULL */
5947  const char *zTableName,     /* Table name */
5948  const char *zColumnName,    /* Column name */
5949  char const **pzDataType,    /* OUTPUT: Declared data type */
5950  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5951  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5952  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5953  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5954);
5955
5956/*
5957** CAPI3REF: Load An Extension
5958** METHOD: sqlite3
5959**
5960** ^This interface loads an SQLite extension library from the named file.
5961**
5962** ^The sqlite3_load_extension() interface attempts to load an
5963** [SQLite extension] library contained in the file zFile.  If
5964** the file cannot be loaded directly, attempts are made to load
5965** with various operating-system specific extensions added.
5966** So for example, if "samplelib" cannot be loaded, then names like
5967** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5968** be tried also.
5969**
5970** ^The entry point is zProc.
5971** ^(zProc may be 0, in which case SQLite will try to come up with an
5972** entry point name on its own.  It first tries "sqlite3_extension_init".
5973** If that does not work, it constructs a name "sqlite3_X_init" where the
5974** X is consists of the lower-case equivalent of all ASCII alphabetic
5975** characters in the filename from the last "/" to the first following
5976** "." and omitting any initial "lib".)^
5977** ^The sqlite3_load_extension() interface returns
5978** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5979** ^If an error occurs and pzErrMsg is not 0, then the
5980** [sqlite3_load_extension()] interface shall attempt to
5981** fill *pzErrMsg with error message text stored in memory
5982** obtained from [sqlite3_malloc()]. The calling function
5983** should free this memory by calling [sqlite3_free()].
5984**
5985** ^Extension loading must be enabled using
5986** [sqlite3_enable_load_extension()] or
5987** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
5988** prior to calling this API,
5989** otherwise an error will be returned.
5990**
5991** <b>Security warning:</b> It is recommended that the
5992** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
5993** interface.  The use of the [sqlite3_enable_load_extension()] interface
5994** should be avoided.  This will keep the SQL function [load_extension()]
5995** disabled and prevent SQL injections from giving attackers
5996** access to extension loading capabilities.
5997**
5998** See also the [load_extension() SQL function].
5999*/
6000SQLITE_API int sqlite3_load_extension(
6001  sqlite3 *db,          /* Load the extension into this database connection */
6002  const char *zFile,    /* Name of the shared library containing extension */
6003  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
6004  char **pzErrMsg       /* Put error message here if not 0 */
6005);
6006
6007/*
6008** CAPI3REF: Enable Or Disable Extension Loading
6009** METHOD: sqlite3
6010**
6011** ^So as not to open security holes in older applications that are
6012** unprepared to deal with [extension loading], and as a means of disabling
6013** [extension loading] while evaluating user-entered SQL, the following API
6014** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
6015**
6016** ^Extension loading is off by default.
6017** ^Call the sqlite3_enable_load_extension() routine with onoff==1
6018** to turn extension loading on and call it with onoff==0 to turn
6019** it back off again.
6020**
6021** ^This interface enables or disables both the C-API
6022** [sqlite3_load_extension()] and the SQL function [load_extension()].
6023** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
6024** to enable or disable only the C-API.)^
6025**
6026** <b>Security warning:</b> It is recommended that extension loading
6027** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
6028** rather than this interface, so the [load_extension()] SQL function
6029** remains disabled. This will prevent SQL injections from giving attackers
6030** access to extension loading capabilities.
6031*/
6032SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
6033
6034/*
6035** CAPI3REF: Automatically Load Statically Linked Extensions
6036**
6037** ^This interface causes the xEntryPoint() function to be invoked for
6038** each new [database connection] that is created.  The idea here is that
6039** xEntryPoint() is the entry point for a statically linked [SQLite extension]
6040** that is to be automatically loaded into all new database connections.
6041**
6042** ^(Even though the function prototype shows that xEntryPoint() takes
6043** no arguments and returns void, SQLite invokes xEntryPoint() with three
6044** arguments and expects an integer result as if the signature of the
6045** entry point where as follows:
6046**
6047** <blockquote><pre>
6048** &nbsp;  int xEntryPoint(
6049** &nbsp;    sqlite3 *db,
6050** &nbsp;    const char **pzErrMsg,
6051** &nbsp;    const struct sqlite3_api_routines *pThunk
6052** &nbsp;  );
6053** </pre></blockquote>)^
6054**
6055** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
6056** point to an appropriate error message (obtained from [sqlite3_mprintf()])
6057** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
6058** is NULL before calling the xEntryPoint().  ^SQLite will invoke
6059** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
6060** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
6061** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
6062**
6063** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
6064** on the list of automatic extensions is a harmless no-op. ^No entry point
6065** will be called more than once for each database connection that is opened.
6066**
6067** See also: [sqlite3_reset_auto_extension()]
6068** and [sqlite3_cancel_auto_extension()]
6069*/
6070SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
6071
6072/*
6073** CAPI3REF: Cancel Automatic Extension Loading
6074**
6075** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
6076** initialization routine X that was registered using a prior call to
6077** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
6078** routine returns 1 if initialization routine X was successfully
6079** unregistered and it returns 0 if X was not on the list of initialization
6080** routines.
6081*/
6082SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
6083
6084/*
6085** CAPI3REF: Reset Automatic Extension Loading
6086**
6087** ^This interface disables all automatic extensions previously
6088** registered using [sqlite3_auto_extension()].
6089*/
6090SQLITE_API void sqlite3_reset_auto_extension(void);
6091
6092/*
6093** The interface to the virtual-table mechanism is currently considered
6094** to be experimental.  The interface might change in incompatible ways.
6095** If this is a problem for you, do not use the interface at this time.
6096**
6097** When the virtual-table mechanism stabilizes, we will declare the
6098** interface fixed, support it indefinitely, and remove this comment.
6099*/
6100
6101/*
6102** Structures used by the virtual table interface
6103*/
6104typedef struct sqlite3_vtab sqlite3_vtab;
6105typedef struct sqlite3_index_info sqlite3_index_info;
6106typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
6107typedef struct sqlite3_module sqlite3_module;
6108
6109/*
6110** CAPI3REF: Virtual Table Object
6111** KEYWORDS: sqlite3_module {virtual table module}
6112**
6113** This structure, sometimes called a "virtual table module",
6114** defines the implementation of a [virtual tables].
6115** This structure consists mostly of methods for the module.
6116**
6117** ^A virtual table module is created by filling in a persistent
6118** instance of this structure and passing a pointer to that instance
6119** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
6120** ^The registration remains valid until it is replaced by a different
6121** module or until the [database connection] closes.  The content
6122** of this structure must not change while it is registered with
6123** any database connection.
6124*/
6125struct sqlite3_module {
6126  int iVersion;
6127  int (*xCreate)(sqlite3*, void *pAux,
6128               int argc, const char *const*argv,
6129               sqlite3_vtab **ppVTab, char**);
6130  int (*xConnect)(sqlite3*, void *pAux,
6131               int argc, const char *const*argv,
6132               sqlite3_vtab **ppVTab, char**);
6133  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
6134  int (*xDisconnect)(sqlite3_vtab *pVTab);
6135  int (*xDestroy)(sqlite3_vtab *pVTab);
6136  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
6137  int (*xClose)(sqlite3_vtab_cursor*);
6138  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
6139                int argc, sqlite3_value **argv);
6140  int (*xNext)(sqlite3_vtab_cursor*);
6141  int (*xEof)(sqlite3_vtab_cursor*);
6142  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
6143  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
6144  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
6145  int (*xBegin)(sqlite3_vtab *pVTab);
6146  int (*xSync)(sqlite3_vtab *pVTab);
6147  int (*xCommit)(sqlite3_vtab *pVTab);
6148  int (*xRollback)(sqlite3_vtab *pVTab);
6149  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
6150                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
6151                       void **ppArg);
6152  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
6153  /* The methods above are in version 1 of the sqlite_module object. Those
6154  ** below are for version 2 and greater. */
6155  int (*xSavepoint)(sqlite3_vtab *pVTab, int);
6156  int (*xRelease)(sqlite3_vtab *pVTab, int);
6157  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
6158};
6159
6160/*
6161** CAPI3REF: Virtual Table Indexing Information
6162** KEYWORDS: sqlite3_index_info
6163**
6164** The sqlite3_index_info structure and its substructures is used as part
6165** of the [virtual table] interface to
6166** pass information into and receive the reply from the [xBestIndex]
6167** method of a [virtual table module].  The fields under **Inputs** are the
6168** inputs to xBestIndex and are read-only.  xBestIndex inserts its
6169** results into the **Outputs** fields.
6170**
6171** ^(The aConstraint[] array records WHERE clause constraints of the form:
6172**
6173** <blockquote>column OP expr</blockquote>
6174**
6175** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
6176** stored in aConstraint[].op using one of the
6177** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
6178** ^(The index of the column is stored in
6179** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
6180** expr on the right-hand side can be evaluated (and thus the constraint
6181** is usable) and false if it cannot.)^
6182**
6183** ^The optimizer automatically inverts terms of the form "expr OP column"
6184** and makes other simplifications to the WHERE clause in an attempt to
6185** get as many WHERE clause terms into the form shown above as possible.
6186** ^The aConstraint[] array only reports WHERE clause terms that are
6187** relevant to the particular virtual table being queried.
6188**
6189** ^Information about the ORDER BY clause is stored in aOrderBy[].
6190** ^Each term of aOrderBy records a column of the ORDER BY clause.
6191**
6192** The colUsed field indicates which columns of the virtual table may be
6193** required by the current scan. Virtual table columns are numbered from
6194** zero in the order in which they appear within the CREATE TABLE statement
6195** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
6196** the corresponding bit is set within the colUsed mask if the column may be
6197** required by SQLite. If the table has at least 64 columns and any column
6198** to the right of the first 63 is required, then bit 63 of colUsed is also
6199** set. In other words, column iCol may be required if the expression
6200** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
6201** non-zero.
6202**
6203** The [xBestIndex] method must fill aConstraintUsage[] with information
6204** about what parameters to pass to xFilter.  ^If argvIndex>0 then
6205** the right-hand side of the corresponding aConstraint[] is evaluated
6206** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
6207** is true, then the constraint is assumed to be fully handled by the
6208** virtual table and is not checked again by SQLite.)^
6209**
6210** ^The idxNum and idxPtr values are recorded and passed into the
6211** [xFilter] method.
6212** ^[sqlite3_free()] is used to free idxPtr if and only if
6213** needToFreeIdxPtr is true.
6214**
6215** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
6216** the correct order to satisfy the ORDER BY clause so that no separate
6217** sorting step is required.
6218**
6219** ^The estimatedCost value is an estimate of the cost of a particular
6220** strategy. A cost of N indicates that the cost of the strategy is similar
6221** to a linear scan of an SQLite table with N rows. A cost of log(N)
6222** indicates that the expense of the operation is similar to that of a
6223** binary search on a unique indexed field of an SQLite table with N rows.
6224**
6225** ^The estimatedRows value is an estimate of the number of rows that
6226** will be returned by the strategy.
6227**
6228** The xBestIndex method may optionally populate the idxFlags field with a
6229** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
6230** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
6231** assumes that the strategy may visit at most one row.
6232**
6233** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
6234** SQLite also assumes that if a call to the xUpdate() method is made as
6235** part of the same statement to delete or update a virtual table row and the
6236** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
6237** any database changes. In other words, if the xUpdate() returns
6238** SQLITE_CONSTRAINT, the database contents must be exactly as they were
6239** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
6240** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
6241** the xUpdate method are automatically rolled back by SQLite.
6242**
6243** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
6244** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
6245** If a virtual table extension is
6246** used with an SQLite version earlier than 3.8.2, the results of attempting
6247** to read or write the estimatedRows field are undefined (but are likely
6248** to included crashing the application). The estimatedRows field should
6249** therefore only be used if [sqlite3_libversion_number()] returns a
6250** value greater than or equal to 3008002. Similarly, the idxFlags field
6251** was added for [version 3.9.0] ([dateof:3.9.0]).
6252** It may therefore only be used if
6253** sqlite3_libversion_number() returns a value greater than or equal to
6254** 3009000.
6255*/
6256struct sqlite3_index_info {
6257  /* Inputs */
6258  int nConstraint;           /* Number of entries in aConstraint */
6259  struct sqlite3_index_constraint {
6260     int iColumn;              /* Column constrained.  -1 for ROWID */
6261     unsigned char op;         /* Constraint operator */
6262     unsigned char usable;     /* True if this constraint is usable */
6263     int iTermOffset;          /* Used internally - xBestIndex should ignore */
6264  } *aConstraint;            /* Table of WHERE clause constraints */
6265  int nOrderBy;              /* Number of terms in the ORDER BY clause */
6266  struct sqlite3_index_orderby {
6267     int iColumn;              /* Column number */
6268     unsigned char desc;       /* True for DESC.  False for ASC. */
6269  } *aOrderBy;               /* The ORDER BY clause */
6270  /* Outputs */
6271  struct sqlite3_index_constraint_usage {
6272    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
6273    unsigned char omit;      /* Do not code a test for this constraint */
6274  } *aConstraintUsage;
6275  int idxNum;                /* Number used to identify the index */
6276  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
6277  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
6278  int orderByConsumed;       /* True if output is already ordered */
6279  double estimatedCost;           /* Estimated cost of using this index */
6280  /* Fields below are only available in SQLite 3.8.2 and later */
6281  sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
6282  /* Fields below are only available in SQLite 3.9.0 and later */
6283  int idxFlags;              /* Mask of SQLITE_INDEX_SCAN_* flags */
6284  /* Fields below are only available in SQLite 3.10.0 and later */
6285  sqlite3_uint64 colUsed;    /* Input: Mask of columns used by statement */
6286};
6287
6288/*
6289** CAPI3REF: Virtual Table Scan Flags
6290*/
6291#define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */
6292
6293/*
6294** CAPI3REF: Virtual Table Constraint Operator Codes
6295**
6296** These macros defined the allowed values for the
6297** [sqlite3_index_info].aConstraint[].op field.  Each value represents
6298** an operator that is part of a constraint term in the wHERE clause of
6299** a query that uses a [virtual table].
6300*/
6301#define SQLITE_INDEX_CONSTRAINT_EQ      2
6302#define SQLITE_INDEX_CONSTRAINT_GT      4
6303#define SQLITE_INDEX_CONSTRAINT_LE      8
6304#define SQLITE_INDEX_CONSTRAINT_LT     16
6305#define SQLITE_INDEX_CONSTRAINT_GE     32
6306#define SQLITE_INDEX_CONSTRAINT_MATCH  64
6307#define SQLITE_INDEX_CONSTRAINT_LIKE   65
6308#define SQLITE_INDEX_CONSTRAINT_GLOB   66
6309#define SQLITE_INDEX_CONSTRAINT_REGEXP 67
6310
6311/*
6312** CAPI3REF: Register A Virtual Table Implementation
6313** METHOD: sqlite3
6314**
6315** ^These routines are used to register a new [virtual table module] name.
6316** ^Module names must be registered before
6317** creating a new [virtual table] using the module and before using a
6318** preexisting [virtual table] for the module.
6319**
6320** ^The module name is registered on the [database connection] specified
6321** by the first parameter.  ^The name of the module is given by the
6322** second parameter.  ^The third parameter is a pointer to
6323** the implementation of the [virtual table module].   ^The fourth
6324** parameter is an arbitrary client data pointer that is passed through
6325** into the [xCreate] and [xConnect] methods of the virtual table module
6326** when a new virtual table is be being created or reinitialized.
6327**
6328** ^The sqlite3_create_module_v2() interface has a fifth parameter which
6329** is a pointer to a destructor for the pClientData.  ^SQLite will
6330** invoke the destructor function (if it is not NULL) when SQLite
6331** no longer needs the pClientData pointer.  ^The destructor will also
6332** be invoked if the call to sqlite3_create_module_v2() fails.
6333** ^The sqlite3_create_module()
6334** interface is equivalent to sqlite3_create_module_v2() with a NULL
6335** destructor.
6336*/
6337SQLITE_API int sqlite3_create_module(
6338  sqlite3 *db,               /* SQLite connection to register module with */
6339  const char *zName,         /* Name of the module */
6340  const sqlite3_module *p,   /* Methods for the module */
6341  void *pClientData          /* Client data for xCreate/xConnect */
6342);
6343SQLITE_API int sqlite3_create_module_v2(
6344  sqlite3 *db,               /* SQLite connection to register module with */
6345  const char *zName,         /* Name of the module */
6346  const sqlite3_module *p,   /* Methods for the module */
6347  void *pClientData,         /* Client data for xCreate/xConnect */
6348  void(*xDestroy)(void*)     /* Module destructor function */
6349);
6350
6351/*
6352** CAPI3REF: Virtual Table Instance Object
6353** KEYWORDS: sqlite3_vtab
6354**
6355** Every [virtual table module] implementation uses a subclass
6356** of this object to describe a particular instance
6357** of the [virtual table].  Each subclass will
6358** be tailored to the specific needs of the module implementation.
6359** The purpose of this superclass is to define certain fields that are
6360** common to all module implementations.
6361**
6362** ^Virtual tables methods can set an error message by assigning a
6363** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
6364** take care that any prior string is freed by a call to [sqlite3_free()]
6365** prior to assigning a new string to zErrMsg.  ^After the error message
6366** is delivered up to the client application, the string will be automatically
6367** freed by sqlite3_free() and the zErrMsg field will be zeroed.
6368*/
6369struct sqlite3_vtab {
6370  const sqlite3_module *pModule;  /* The module for this virtual table */
6371  int nRef;                       /* Number of open cursors */
6372  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
6373  /* Virtual table implementations will typically add additional fields */
6374};
6375
6376/*
6377** CAPI3REF: Virtual Table Cursor Object
6378** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
6379**
6380** Every [virtual table module] implementation uses a subclass of the
6381** following structure to describe cursors that point into the
6382** [virtual table] and are used
6383** to loop through the virtual table.  Cursors are created using the
6384** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
6385** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
6386** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
6387** of the module.  Each module implementation will define
6388** the content of a cursor structure to suit its own needs.
6389**
6390** This superclass exists in order to define fields of the cursor that
6391** are common to all implementations.
6392*/
6393struct sqlite3_vtab_cursor {
6394  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
6395  /* Virtual table implementations will typically add additional fields */
6396};
6397
6398/*
6399** CAPI3REF: Declare The Schema Of A Virtual Table
6400**
6401** ^The [xCreate] and [xConnect] methods of a
6402** [virtual table module] call this interface
6403** to declare the format (the names and datatypes of the columns) of
6404** the virtual tables they implement.
6405*/
6406SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
6407
6408/*
6409** CAPI3REF: Overload A Function For A Virtual Table
6410** METHOD: sqlite3
6411**
6412** ^(Virtual tables can provide alternative implementations of functions
6413** using the [xFindFunction] method of the [virtual table module].
6414** But global versions of those functions
6415** must exist in order to be overloaded.)^
6416**
6417** ^(This API makes sure a global version of a function with a particular
6418** name and number of parameters exists.  If no such function exists
6419** before this API is called, a new function is created.)^  ^The implementation
6420** of the new function always causes an exception to be thrown.  So
6421** the new function is not good for anything by itself.  Its only
6422** purpose is to be a placeholder function that can be overloaded
6423** by a [virtual table].
6424*/
6425SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
6426
6427/*
6428** The interface to the virtual-table mechanism defined above (back up
6429** to a comment remarkably similar to this one) is currently considered
6430** to be experimental.  The interface might change in incompatible ways.
6431** If this is a problem for you, do not use the interface at this time.
6432**
6433** When the virtual-table mechanism stabilizes, we will declare the
6434** interface fixed, support it indefinitely, and remove this comment.
6435*/
6436
6437/*
6438** CAPI3REF: A Handle To An Open BLOB
6439** KEYWORDS: {BLOB handle} {BLOB handles}
6440**
6441** An instance of this object represents an open BLOB on which
6442** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
6443** ^Objects of this type are created by [sqlite3_blob_open()]
6444** and destroyed by [sqlite3_blob_close()].
6445** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
6446** can be used to read or write small subsections of the BLOB.
6447** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
6448*/
6449typedef struct sqlite3_blob sqlite3_blob;
6450
6451/*
6452** CAPI3REF: Open A BLOB For Incremental I/O
6453** METHOD: sqlite3
6454** CONSTRUCTOR: sqlite3_blob
6455**
6456** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
6457** in row iRow, column zColumn, table zTable in database zDb;
6458** in other words, the same BLOB that would be selected by:
6459**
6460** <pre>
6461**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
6462** </pre>)^
6463**
6464** ^(Parameter zDb is not the filename that contains the database, but
6465** rather the symbolic name of the database. For attached databases, this is
6466** the name that appears after the AS keyword in the [ATTACH] statement.
6467** For the main database file, the database name is "main". For TEMP
6468** tables, the database name is "temp".)^
6469**
6470** ^If the flags parameter is non-zero, then the BLOB is opened for read
6471** and write access. ^If the flags parameter is zero, the BLOB is opened for
6472** read-only access.
6473**
6474** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
6475** in *ppBlob. Otherwise an [error code] is returned and, unless the error
6476** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
6477** the API is not misused, it is always safe to call [sqlite3_blob_close()]
6478** on *ppBlob after this function it returns.
6479**
6480** This function fails with SQLITE_ERROR if any of the following are true:
6481** <ul>
6482**   <li> ^(Database zDb does not exist)^,
6483**   <li> ^(Table zTable does not exist within database zDb)^,
6484**   <li> ^(Table zTable is a WITHOUT ROWID table)^,
6485**   <li> ^(Column zColumn does not exist)^,
6486**   <li> ^(Row iRow is not present in the table)^,
6487**   <li> ^(The specified column of row iRow contains a value that is not
6488**         a TEXT or BLOB value)^,
6489**   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
6490**         constraint and the blob is being opened for read/write access)^,
6491**   <li> ^([foreign key constraints | Foreign key constraints] are enabled,
6492**         column zColumn is part of a [child key] definition and the blob is
6493**         being opened for read/write access)^.
6494** </ul>
6495**
6496** ^Unless it returns SQLITE_MISUSE, this function sets the
6497** [database connection] error code and message accessible via
6498** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6499**
6500** A BLOB referenced by sqlite3_blob_open() may be read using the
6501** [sqlite3_blob_read()] interface and modified by using
6502** [sqlite3_blob_write()].  The [BLOB handle] can be moved to a
6503** different row of the same table using the [sqlite3_blob_reopen()]
6504** interface.  However, the column, table, or database of a [BLOB handle]
6505** cannot be changed after the [BLOB handle] is opened.
6506**
6507** ^(If the row that a BLOB handle points to is modified by an
6508** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6509** then the BLOB handle is marked as "expired".
6510** This is true if any column of the row is changed, even a column
6511** other than the one the BLOB handle is open on.)^
6512** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6513** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
6514** ^(Changes written into a BLOB prior to the BLOB expiring are not
6515** rolled back by the expiration of the BLOB.  Such changes will eventually
6516** commit if the transaction continues to completion.)^
6517**
6518** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
6519** the opened blob.  ^The size of a blob may not be changed by this
6520** interface.  Use the [UPDATE] SQL command to change the size of a
6521** blob.
6522**
6523** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
6524** and the built-in [zeroblob] SQL function may be used to create a
6525** zero-filled blob to read or write using the incremental-blob interface.
6526**
6527** To avoid a resource leak, every open [BLOB handle] should eventually
6528** be released by a call to [sqlite3_blob_close()].
6529**
6530** See also: [sqlite3_blob_close()],
6531** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
6532** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
6533*/
6534SQLITE_API int sqlite3_blob_open(
6535  sqlite3*,
6536  const char *zDb,
6537  const char *zTable,
6538  const char *zColumn,
6539  sqlite3_int64 iRow,
6540  int flags,
6541  sqlite3_blob **ppBlob
6542);
6543
6544/*
6545** CAPI3REF: Move a BLOB Handle to a New Row
6546** METHOD: sqlite3_blob
6547**
6548** ^This function is used to move an existing [BLOB handle] so that it points
6549** to a different row of the same database table. ^The new row is identified
6550** by the rowid value passed as the second argument. Only the row can be
6551** changed. ^The database, table and column on which the blob handle is open
6552** remain the same. Moving an existing [BLOB handle] to a new row is
6553** faster than closing the existing handle and opening a new one.
6554**
6555** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6556** it must exist and there must be either a blob or text value stored in
6557** the nominated column.)^ ^If the new row is not present in the table, or if
6558** it does not contain a blob or text value, or if another error occurs, an
6559** SQLite error code is returned and the blob handle is considered aborted.
6560** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6561** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6562** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6563** always returns zero.
6564**
6565** ^This function sets the database handle error code and message.
6566*/
6567SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
6568
6569/*
6570** CAPI3REF: Close A BLOB Handle
6571** DESTRUCTOR: sqlite3_blob
6572**
6573** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
6574** unconditionally.  Even if this routine returns an error code, the
6575** handle is still closed.)^
6576**
6577** ^If the blob handle being closed was opened for read-write access, and if
6578** the database is in auto-commit mode and there are no other open read-write
6579** blob handles or active write statements, the current transaction is
6580** committed. ^If an error occurs while committing the transaction, an error
6581** code is returned and the transaction rolled back.
6582**
6583** Calling this function with an argument that is not a NULL pointer or an
6584** open blob handle results in undefined behaviour. ^Calling this routine
6585** with a null pointer (such as would be returned by a failed call to
6586** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
6587** is passed a valid open blob handle, the values returned by the
6588** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
6589*/
6590SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
6591
6592/*
6593** CAPI3REF: Return The Size Of An Open BLOB
6594** METHOD: sqlite3_blob
6595**
6596** ^Returns the size in bytes of the BLOB accessible via the
6597** successfully opened [BLOB handle] in its only argument.  ^The
6598** incremental blob I/O routines can only read or overwriting existing
6599** blob content; they cannot change the size of a blob.
6600**
6601** This routine only works on a [BLOB handle] which has been created
6602** by a prior successful call to [sqlite3_blob_open()] and which has not
6603** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6604** to this routine results in undefined and probably undesirable behavior.
6605*/
6606SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
6607
6608/*
6609** CAPI3REF: Read Data From A BLOB Incrementally
6610** METHOD: sqlite3_blob
6611**
6612** ^(This function is used to read data from an open [BLOB handle] into a
6613** caller-supplied buffer. N bytes of data are copied into buffer Z
6614** from the open BLOB, starting at offset iOffset.)^
6615**
6616** ^If offset iOffset is less than N bytes from the end of the BLOB,
6617** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
6618** less than zero, [SQLITE_ERROR] is returned and no data is read.
6619** ^The size of the blob (and hence the maximum value of N+iOffset)
6620** can be determined using the [sqlite3_blob_bytes()] interface.
6621**
6622** ^An attempt to read from an expired [BLOB handle] fails with an
6623** error code of [SQLITE_ABORT].
6624**
6625** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6626** Otherwise, an [error code] or an [extended error code] is returned.)^
6627**
6628** This routine only works on a [BLOB handle] which has been created
6629** by a prior successful call to [sqlite3_blob_open()] and which has not
6630** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6631** to this routine results in undefined and probably undesirable behavior.
6632**
6633** See also: [sqlite3_blob_write()].
6634*/
6635SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6636
6637/*
6638** CAPI3REF: Write Data Into A BLOB Incrementally
6639** METHOD: sqlite3_blob
6640**
6641** ^(This function is used to write data into an open [BLOB handle] from a
6642** caller-supplied buffer. N bytes of data are copied from the buffer Z
6643** into the open BLOB, starting at offset iOffset.)^
6644**
6645** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6646** Otherwise, an  [error code] or an [extended error code] is returned.)^
6647** ^Unless SQLITE_MISUSE is returned, this function sets the
6648** [database connection] error code and message accessible via
6649** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6650**
6651** ^If the [BLOB handle] passed as the first argument was not opened for
6652** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6653** this function returns [SQLITE_READONLY].
6654**
6655** This function may only modify the contents of the BLOB; it is
6656** not possible to increase the size of a BLOB using this API.
6657** ^If offset iOffset is less than N bytes from the end of the BLOB,
6658** [SQLITE_ERROR] is returned and no data is written. The size of the
6659** BLOB (and hence the maximum value of N+iOffset) can be determined
6660** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
6661** than zero [SQLITE_ERROR] is returned and no data is written.
6662**
6663** ^An attempt to write to an expired [BLOB handle] fails with an
6664** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
6665** before the [BLOB handle] expired are not rolled back by the
6666** expiration of the handle, though of course those changes might
6667** have been overwritten by the statement that expired the BLOB handle
6668** or by other independent statements.
6669**
6670** This routine only works on a [BLOB handle] which has been created
6671** by a prior successful call to [sqlite3_blob_open()] and which has not
6672** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6673** to this routine results in undefined and probably undesirable behavior.
6674**
6675** See also: [sqlite3_blob_read()].
6676*/
6677SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6678
6679/*
6680** CAPI3REF: Virtual File System Objects
6681**
6682** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6683** that SQLite uses to interact
6684** with the underlying operating system.  Most SQLite builds come with a
6685** single default VFS that is appropriate for the host computer.
6686** New VFSes can be registered and existing VFSes can be unregistered.
6687** The following interfaces are provided.
6688**
6689** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6690** ^Names are case sensitive.
6691** ^Names are zero-terminated UTF-8 strings.
6692** ^If there is no match, a NULL pointer is returned.
6693** ^If zVfsName is NULL then the default VFS is returned.
6694**
6695** ^New VFSes are registered with sqlite3_vfs_register().
6696** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6697** ^The same VFS can be registered multiple times without injury.
6698** ^To make an existing VFS into the default VFS, register it again
6699** with the makeDflt flag set.  If two different VFSes with the
6700** same name are registered, the behavior is undefined.  If a
6701** VFS is registered with a name that is NULL or an empty string,
6702** then the behavior is undefined.
6703**
6704** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6705** ^(If the default VFS is unregistered, another VFS is chosen as
6706** the default.  The choice for the new VFS is arbitrary.)^
6707*/
6708SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6709SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6710SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6711
6712/*
6713** CAPI3REF: Mutexes
6714**
6715** The SQLite core uses these routines for thread
6716** synchronization. Though they are intended for internal
6717** use by SQLite, code that links against SQLite is
6718** permitted to use any of these routines.
6719**
6720** The SQLite source code contains multiple implementations
6721** of these mutex routines.  An appropriate implementation
6722** is selected automatically at compile-time.  The following
6723** implementations are available in the SQLite core:
6724**
6725** <ul>
6726** <li>   SQLITE_MUTEX_PTHREADS
6727** <li>   SQLITE_MUTEX_W32
6728** <li>   SQLITE_MUTEX_NOOP
6729** </ul>
6730**
6731** The SQLITE_MUTEX_NOOP implementation is a set of routines
6732** that does no real locking and is appropriate for use in
6733** a single-threaded application.  The SQLITE_MUTEX_PTHREADS and
6734** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6735** and Windows.
6736**
6737** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6738** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6739** implementation is included with the library. In this case the
6740** application must supply a custom mutex implementation using the
6741** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6742** before calling sqlite3_initialize() or any other public sqlite3_
6743** function that calls sqlite3_initialize().
6744**
6745** ^The sqlite3_mutex_alloc() routine allocates a new
6746** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
6747** routine returns NULL if it is unable to allocate the requested
6748** mutex.  The argument to sqlite3_mutex_alloc() must one of these
6749** integer constants:
6750**
6751** <ul>
6752** <li>  SQLITE_MUTEX_FAST
6753** <li>  SQLITE_MUTEX_RECURSIVE
6754** <li>  SQLITE_MUTEX_STATIC_MASTER
6755** <li>  SQLITE_MUTEX_STATIC_MEM
6756** <li>  SQLITE_MUTEX_STATIC_OPEN
6757** <li>  SQLITE_MUTEX_STATIC_PRNG
6758** <li>  SQLITE_MUTEX_STATIC_LRU
6759** <li>  SQLITE_MUTEX_STATIC_PMEM
6760** <li>  SQLITE_MUTEX_STATIC_APP1
6761** <li>  SQLITE_MUTEX_STATIC_APP2
6762** <li>  SQLITE_MUTEX_STATIC_APP3
6763** <li>  SQLITE_MUTEX_STATIC_VFS1
6764** <li>  SQLITE_MUTEX_STATIC_VFS2
6765** <li>  SQLITE_MUTEX_STATIC_VFS3
6766** </ul>
6767**
6768** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6769** cause sqlite3_mutex_alloc() to create
6770** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6771** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6772** The mutex implementation does not need to make a distinction
6773** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6774** not want to.  SQLite will only request a recursive mutex in
6775** cases where it really needs one.  If a faster non-recursive mutex
6776** implementation is available on the host platform, the mutex subsystem
6777** might return such a mutex in response to SQLITE_MUTEX_FAST.
6778**
6779** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6780** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6781** a pointer to a static preexisting mutex.  ^Nine static mutexes are
6782** used by the current version of SQLite.  Future versions of SQLite
6783** may add additional static mutexes.  Static mutexes are for internal
6784** use by SQLite only.  Applications that use SQLite mutexes should
6785** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6786** SQLITE_MUTEX_RECURSIVE.
6787**
6788** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6789** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6790** returns a different mutex on every call.  ^For the static
6791** mutex types, the same mutex is returned on every call that has
6792** the same type number.
6793**
6794** ^The sqlite3_mutex_free() routine deallocates a previously
6795** allocated dynamic mutex.  Attempting to deallocate a static
6796** mutex results in undefined behavior.
6797**
6798** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6799** to enter a mutex.  ^If another thread is already within the mutex,
6800** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6801** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6802** upon successful entry.  ^(Mutexes created using
6803** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6804** In such cases, the
6805** mutex must be exited an equal number of times before another thread
6806** can enter.)^  If the same thread tries to enter any mutex other
6807** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
6808**
6809** ^(Some systems (for example, Windows 95) do not support the operation
6810** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6811** will always return SQLITE_BUSY. The SQLite core only ever uses
6812** sqlite3_mutex_try() as an optimization so this is acceptable
6813** behavior.)^
6814**
6815** ^The sqlite3_mutex_leave() routine exits a mutex that was
6816** previously entered by the same thread.   The behavior
6817** is undefined if the mutex is not currently entered by the
6818** calling thread or is not currently allocated.
6819**
6820** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6821** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6822** behave as no-ops.
6823**
6824** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6825*/
6826SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6827SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6828SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6829SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6830SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6831
6832/*
6833** CAPI3REF: Mutex Methods Object
6834**
6835** An instance of this structure defines the low-level routines
6836** used to allocate and use mutexes.
6837**
6838** Usually, the default mutex implementations provided by SQLite are
6839** sufficient, however the application has the option of substituting a custom
6840** implementation for specialized deployments or systems for which SQLite
6841** does not provide a suitable implementation. In this case, the application
6842** creates and populates an instance of this structure to pass
6843** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6844** Additionally, an instance of this structure can be used as an
6845** output variable when querying the system for the current mutex
6846** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6847**
6848** ^The xMutexInit method defined by this structure is invoked as
6849** part of system initialization by the sqlite3_initialize() function.
6850** ^The xMutexInit routine is called by SQLite exactly once for each
6851** effective call to [sqlite3_initialize()].
6852**
6853** ^The xMutexEnd method defined by this structure is invoked as
6854** part of system shutdown by the sqlite3_shutdown() function. The
6855** implementation of this method is expected to release all outstanding
6856** resources obtained by the mutex methods implementation, especially
6857** those obtained by the xMutexInit method.  ^The xMutexEnd()
6858** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6859**
6860** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6861** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6862** xMutexNotheld) implement the following interfaces (respectively):
6863**
6864** <ul>
6865**   <li>  [sqlite3_mutex_alloc()] </li>
6866**   <li>  [sqlite3_mutex_free()] </li>
6867**   <li>  [sqlite3_mutex_enter()] </li>
6868**   <li>  [sqlite3_mutex_try()] </li>
6869**   <li>  [sqlite3_mutex_leave()] </li>
6870**   <li>  [sqlite3_mutex_held()] </li>
6871**   <li>  [sqlite3_mutex_notheld()] </li>
6872** </ul>)^
6873**
6874** The only difference is that the public sqlite3_XXX functions enumerated
6875** above silently ignore any invocations that pass a NULL pointer instead
6876** of a valid mutex handle. The implementations of the methods defined
6877** by this structure are not required to handle this case, the results
6878** of passing a NULL pointer instead of a valid mutex handle are undefined
6879** (i.e. it is acceptable to provide an implementation that segfaults if
6880** it is passed a NULL pointer).
6881**
6882** The xMutexInit() method must be threadsafe.  It must be harmless to
6883** invoke xMutexInit() multiple times within the same process and without
6884** intervening calls to xMutexEnd().  Second and subsequent calls to
6885** xMutexInit() must be no-ops.
6886**
6887** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6888** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory
6889** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6890** memory allocation for a fast or recursive mutex.
6891**
6892** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6893** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6894** If xMutexInit fails in any way, it is expected to clean up after itself
6895** prior to returning.
6896*/
6897typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6898struct sqlite3_mutex_methods {
6899  int (*xMutexInit)(void);
6900  int (*xMutexEnd)(void);
6901  sqlite3_mutex *(*xMutexAlloc)(int);
6902  void (*xMutexFree)(sqlite3_mutex *);
6903  void (*xMutexEnter)(sqlite3_mutex *);
6904  int (*xMutexTry)(sqlite3_mutex *);
6905  void (*xMutexLeave)(sqlite3_mutex *);
6906  int (*xMutexHeld)(sqlite3_mutex *);
6907  int (*xMutexNotheld)(sqlite3_mutex *);
6908};
6909
6910/*
6911** CAPI3REF: Mutex Verification Routines
6912**
6913** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6914** are intended for use inside assert() statements.  The SQLite core
6915** never uses these routines except inside an assert() and applications
6916** are advised to follow the lead of the core.  The SQLite core only
6917** provides implementations for these routines when it is compiled
6918** with the SQLITE_DEBUG flag.  External mutex implementations
6919** are only required to provide these routines if SQLITE_DEBUG is
6920** defined and if NDEBUG is not defined.
6921**
6922** These routines should return true if the mutex in their argument
6923** is held or not held, respectively, by the calling thread.
6924**
6925** The implementation is not required to provide versions of these
6926** routines that actually work. If the implementation does not provide working
6927** versions of these routines, it should at least provide stubs that always
6928** return true so that one does not get spurious assertion failures.
6929**
6930** If the argument to sqlite3_mutex_held() is a NULL pointer then
6931** the routine should return 1.   This seems counter-intuitive since
6932** clearly the mutex cannot be held if it does not exist.  But
6933** the reason the mutex does not exist is because the build is not
6934** using mutexes.  And we do not want the assert() containing the
6935** call to sqlite3_mutex_held() to fail, so a non-zero return is
6936** the appropriate thing to do.  The sqlite3_mutex_notheld()
6937** interface should also return 1 when given a NULL pointer.
6938*/
6939#ifndef NDEBUG
6940SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6941SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6942#endif
6943
6944/*
6945** CAPI3REF: Mutex Types
6946**
6947** The [sqlite3_mutex_alloc()] interface takes a single argument
6948** which is one of these integer constants.
6949**
6950** The set of static mutexes may change from one SQLite release to the
6951** next.  Applications that override the built-in mutex logic must be
6952** prepared to accommodate additional static mutexes.
6953*/
6954#define SQLITE_MUTEX_FAST             0
6955#define SQLITE_MUTEX_RECURSIVE        1
6956#define SQLITE_MUTEX_STATIC_MASTER    2
6957#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6958#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6959#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6960#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_randomness() */
6961#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6962#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6963#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6964#define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */
6965#define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */
6966#define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */
6967#define SQLITE_MUTEX_STATIC_VFS1     11  /* For use by built-in VFS */
6968#define SQLITE_MUTEX_STATIC_VFS2     12  /* For use by extension VFS */
6969#define SQLITE_MUTEX_STATIC_VFS3     13  /* For use by application VFS */
6970
6971/*
6972** CAPI3REF: Retrieve the mutex for a database connection
6973** METHOD: sqlite3
6974**
6975** ^This interface returns a pointer the [sqlite3_mutex] object that
6976** serializes access to the [database connection] given in the argument
6977** when the [threading mode] is Serialized.
6978** ^If the [threading mode] is Single-thread or Multi-thread then this
6979** routine returns a NULL pointer.
6980*/
6981SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6982
6983/*
6984** CAPI3REF: Low-Level Control Of Database Files
6985** METHOD: sqlite3
6986**
6987** ^The [sqlite3_file_control()] interface makes a direct call to the
6988** xFileControl method for the [sqlite3_io_methods] object associated
6989** with a particular database identified by the second argument. ^The
6990** name of the database is "main" for the main database or "temp" for the
6991** TEMP database, or the name that appears after the AS keyword for
6992** databases that are added using the [ATTACH] SQL command.
6993** ^A NULL pointer can be used in place of "main" to refer to the
6994** main database file.
6995** ^The third and fourth parameters to this routine
6996** are passed directly through to the second and third parameters of
6997** the xFileControl method.  ^The return value of the xFileControl
6998** method becomes the return value of this routine.
6999**
7000** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
7001** a pointer to the underlying [sqlite3_file] object to be written into
7002** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
7003** case is a short-circuit path which does not actually invoke the
7004** underlying sqlite3_io_methods.xFileControl method.
7005**
7006** ^If the second parameter (zDbName) does not match the name of any
7007** open database file, then SQLITE_ERROR is returned.  ^This error
7008** code is not remembered and will not be recalled by [sqlite3_errcode()]
7009** or [sqlite3_errmsg()].  The underlying xFileControl method might
7010** also return SQLITE_ERROR.  There is no way to distinguish between
7011** an incorrect zDbName and an SQLITE_ERROR return from the underlying
7012** xFileControl method.
7013**
7014** See also: [SQLITE_FCNTL_LOCKSTATE]
7015*/
7016SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
7017
7018/*
7019** CAPI3REF: Testing Interface
7020**
7021** ^The sqlite3_test_control() interface is used to read out internal
7022** state of SQLite and to inject faults into SQLite for testing
7023** purposes.  ^The first parameter is an operation code that determines
7024** the number, meaning, and operation of all subsequent parameters.
7025**
7026** This interface is not for use by applications.  It exists solely
7027** for verifying the correct operation of the SQLite library.  Depending
7028** on how the SQLite library is compiled, this interface might not exist.
7029**
7030** The details of the operation codes, their meanings, the parameters
7031** they take, and what they do are all subject to change without notice.
7032** Unlike most of the SQLite API, this function is not guaranteed to
7033** operate consistently from one release to the next.
7034*/
7035SQLITE_API int sqlite3_test_control(int op, ...);
7036
7037/*
7038** CAPI3REF: Testing Interface Operation Codes
7039**
7040** These constants are the valid operation code parameters used
7041** as the first argument to [sqlite3_test_control()].
7042**
7043** These parameters and their meanings are subject to change
7044** without notice.  These values are for testing purposes only.
7045** Applications should not use any of these parameters or the
7046** [sqlite3_test_control()] interface.
7047*/
7048#define SQLITE_TESTCTRL_FIRST                    5
7049#define SQLITE_TESTCTRL_PRNG_SAVE                5
7050#define SQLITE_TESTCTRL_PRNG_RESTORE             6
7051#define SQLITE_TESTCTRL_PRNG_RESET               7
7052#define SQLITE_TESTCTRL_BITVEC_TEST              8
7053#define SQLITE_TESTCTRL_FAULT_INSTALL            9
7054#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
7055#define SQLITE_TESTCTRL_PENDING_BYTE            11
7056#define SQLITE_TESTCTRL_ASSERT                  12
7057#define SQLITE_TESTCTRL_ALWAYS                  13
7058#define SQLITE_TESTCTRL_RESERVE                 14
7059#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
7060#define SQLITE_TESTCTRL_ISKEYWORD               16
7061#define SQLITE_TESTCTRL_SCRATCHMALLOC           17
7062#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
7063#define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */
7064#define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD    19
7065#define SQLITE_TESTCTRL_NEVER_CORRUPT           20
7066#define SQLITE_TESTCTRL_VDBE_COVERAGE           21
7067#define SQLITE_TESTCTRL_BYTEORDER               22
7068#define SQLITE_TESTCTRL_ISINIT                  23
7069#define SQLITE_TESTCTRL_SORTER_MMAP             24
7070#define SQLITE_TESTCTRL_IMPOSTER                25
7071#define SQLITE_TESTCTRL_LAST                    25
7072
7073/*
7074** CAPI3REF: SQLite Runtime Status
7075**
7076** ^These interfaces are used to retrieve runtime status information
7077** about the performance of SQLite, and optionally to reset various
7078** highwater marks.  ^The first argument is an integer code for
7079** the specific parameter to measure.  ^(Recognized integer codes
7080** are of the form [status parameters | SQLITE_STATUS_...].)^
7081** ^The current value of the parameter is returned into *pCurrent.
7082** ^The highest recorded value is returned in *pHighwater.  ^If the
7083** resetFlag is true, then the highest record value is reset after
7084** *pHighwater is written.  ^(Some parameters do not record the highest
7085** value.  For those parameters
7086** nothing is written into *pHighwater and the resetFlag is ignored.)^
7087** ^(Other parameters record only the highwater mark and not the current
7088** value.  For these latter parameters nothing is written into *pCurrent.)^
7089**
7090** ^The sqlite3_status() and sqlite3_status64() routines return
7091** SQLITE_OK on success and a non-zero [error code] on failure.
7092**
7093** If either the current value or the highwater mark is too large to
7094** be represented by a 32-bit integer, then the values returned by
7095** sqlite3_status() are undefined.
7096**
7097** See also: [sqlite3_db_status()]
7098*/
7099SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
7100SQLITE_API int sqlite3_status64(
7101  int op,
7102  sqlite3_int64 *pCurrent,
7103  sqlite3_int64 *pHighwater,
7104  int resetFlag
7105);
7106
7107
7108/*
7109** CAPI3REF: Status Parameters
7110** KEYWORDS: {status parameters}
7111**
7112** These integer constants designate various run-time status parameters
7113** that can be returned by [sqlite3_status()].
7114**
7115** <dl>
7116** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
7117** <dd>This parameter is the current amount of memory checked out
7118** using [sqlite3_malloc()], either directly or indirectly.  The
7119** figure includes calls made to [sqlite3_malloc()] by the application
7120** and internal memory usage by the SQLite library.  Scratch memory
7121** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
7122** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
7123** this parameter.  The amount returned is the sum of the allocation
7124** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
7125**
7126** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
7127** <dd>This parameter records the largest memory allocation request
7128** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
7129** internal equivalents).  Only the value returned in the
7130** *pHighwater parameter to [sqlite3_status()] is of interest.
7131** The value written into the *pCurrent parameter is undefined.</dd>)^
7132**
7133** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
7134** <dd>This parameter records the number of separate memory allocations
7135** currently checked out.</dd>)^
7136**
7137** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
7138** <dd>This parameter returns the number of pages used out of the
7139** [pagecache memory allocator] that was configured using
7140** [SQLITE_CONFIG_PAGECACHE].  The
7141** value returned is in pages, not in bytes.</dd>)^
7142**
7143** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
7144** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
7145** <dd>This parameter returns the number of bytes of page cache
7146** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
7147** buffer and where forced to overflow to [sqlite3_malloc()].  The
7148** returned value includes allocations that overflowed because they
7149** where too large (they were larger than the "sz" parameter to
7150** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
7151** no space was left in the page cache.</dd>)^
7152**
7153** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
7154** <dd>This parameter records the largest memory allocation request
7155** handed to [pagecache memory allocator].  Only the value returned in the
7156** *pHighwater parameter to [sqlite3_status()] is of interest.
7157** The value written into the *pCurrent parameter is undefined.</dd>)^
7158**
7159** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
7160** <dd>This parameter returns the number of allocations used out of the
7161** [scratch memory allocator] configured using
7162** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
7163** in bytes.  Since a single thread may only have one scratch allocation
7164** outstanding at time, this parameter also reports the number of threads
7165** using scratch memory at the same time.</dd>)^
7166**
7167** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
7168** <dd>This parameter returns the number of bytes of scratch memory
7169** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
7170** buffer and where forced to overflow to [sqlite3_malloc()].  The values
7171** returned include overflows because the requested allocation was too
7172** larger (that is, because the requested allocation was larger than the
7173** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
7174** slots were available.
7175** </dd>)^
7176**
7177** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
7178** <dd>This parameter records the largest memory allocation request
7179** handed to [scratch memory allocator].  Only the value returned in the
7180** *pHighwater parameter to [sqlite3_status()] is of interest.
7181** The value written into the *pCurrent parameter is undefined.</dd>)^
7182**
7183** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
7184** <dd>The *pHighwater parameter records the deepest parser stack.
7185** The *pCurrent value is undefined.  The *pHighwater value is only
7186** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
7187** </dl>
7188**
7189** New status parameters may be added from time to time.
7190*/
7191#define SQLITE_STATUS_MEMORY_USED          0
7192#define SQLITE_STATUS_PAGECACHE_USED       1
7193#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
7194#define SQLITE_STATUS_SCRATCH_USED         3
7195#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
7196#define SQLITE_STATUS_MALLOC_SIZE          5
7197#define SQLITE_STATUS_PARSER_STACK         6
7198#define SQLITE_STATUS_PAGECACHE_SIZE       7
7199#define SQLITE_STATUS_SCRATCH_SIZE         8
7200#define SQLITE_STATUS_MALLOC_COUNT         9
7201
7202/*
7203** CAPI3REF: Database Connection Status
7204** METHOD: sqlite3
7205**
7206** ^This interface is used to retrieve runtime status information
7207** about a single [database connection].  ^The first argument is the
7208** database connection object to be interrogated.  ^The second argument
7209** is an integer constant, taken from the set of
7210** [SQLITE_DBSTATUS options], that
7211** determines the parameter to interrogate.  The set of
7212** [SQLITE_DBSTATUS options] is likely
7213** to grow in future releases of SQLite.
7214**
7215** ^The current value of the requested parameter is written into *pCur
7216** and the highest instantaneous value is written into *pHiwtr.  ^If
7217** the resetFlg is true, then the highest instantaneous value is
7218** reset back down to the current value.
7219**
7220** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
7221** non-zero [error code] on failure.
7222**
7223** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
7224*/
7225SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
7226
7227/*
7228** CAPI3REF: Status Parameters for database connections
7229** KEYWORDS: {SQLITE_DBSTATUS options}
7230**
7231** These constants are the available integer "verbs" that can be passed as
7232** the second argument to the [sqlite3_db_status()] interface.
7233**
7234** New verbs may be added in future releases of SQLite. Existing verbs
7235** might be discontinued. Applications should check the return code from
7236** [sqlite3_db_status()] to make sure that the call worked.
7237** The [sqlite3_db_status()] interface will return a non-zero error code
7238** if a discontinued or unsupported verb is invoked.
7239**
7240** <dl>
7241** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
7242** <dd>This parameter returns the number of lookaside memory slots currently
7243** checked out.</dd>)^
7244**
7245** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
7246** <dd>This parameter returns the number malloc attempts that were
7247** satisfied using lookaside memory. Only the high-water value is meaningful;
7248** the current value is always zero.)^
7249**
7250** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
7251** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
7252** <dd>This parameter returns the number malloc attempts that might have
7253** been satisfied using lookaside memory but failed due to the amount of
7254** memory requested being larger than the lookaside slot size.
7255** Only the high-water value is meaningful;
7256** the current value is always zero.)^
7257**
7258** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
7259** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
7260** <dd>This parameter returns the number malloc attempts that might have
7261** been satisfied using lookaside memory but failed due to all lookaside
7262** memory already being in use.
7263** Only the high-water value is meaningful;
7264** the current value is always zero.)^
7265**
7266** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
7267** <dd>This parameter returns the approximate number of bytes of heap
7268** memory used by all pager caches associated with the database connection.)^
7269** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
7270**
7271** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
7272** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
7273** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
7274** pager cache is shared between two or more connections the bytes of heap
7275** memory used by that pager cache is divided evenly between the attached
7276** connections.)^  In other words, if none of the pager caches associated
7277** with the database connection are shared, this request returns the same
7278** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
7279** shared, the value returned by this call will be smaller than that returned
7280** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
7281** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
7282**
7283** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
7284** <dd>This parameter returns the approximate number of bytes of heap
7285** memory used to store the schema for all databases associated
7286** with the connection - main, temp, and any [ATTACH]-ed databases.)^
7287** ^The full amount of memory used by the schemas is reported, even if the
7288** schema memory is shared with other database connections due to
7289** [shared cache mode] being enabled.
7290** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
7291**
7292** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
7293** <dd>This parameter returns the approximate number of bytes of heap
7294** and lookaside memory used by all prepared statements associated with
7295** the database connection.)^
7296** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
7297** </dd>
7298**
7299** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
7300** <dd>This parameter returns the number of pager cache hits that have
7301** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
7302** is always 0.
7303** </dd>
7304**
7305** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
7306** <dd>This parameter returns the number of pager cache misses that have
7307** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
7308** is always 0.
7309** </dd>
7310**
7311** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
7312** <dd>This parameter returns the number of dirty cache entries that have
7313** been written to disk. Specifically, the number of pages written to the
7314** wal file in wal mode databases, or the number of pages written to the
7315** database file in rollback mode databases. Any pages written as part of
7316** transaction rollback or database recovery operations are not included.
7317** If an IO or other error occurs while writing a page to disk, the effect
7318** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
7319** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
7320** </dd>
7321**
7322** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
7323** <dd>This parameter returns zero for the current value if and only if
7324** all foreign key constraints (deferred or immediate) have been
7325** resolved.)^  ^The highwater mark is always 0.
7326** </dd>
7327** </dl>
7328*/
7329#define SQLITE_DBSTATUS_LOOKASIDE_USED       0
7330#define SQLITE_DBSTATUS_CACHE_USED           1
7331#define SQLITE_DBSTATUS_SCHEMA_USED          2
7332#define SQLITE_DBSTATUS_STMT_USED            3
7333#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
7334#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
7335#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
7336#define SQLITE_DBSTATUS_CACHE_HIT            7
7337#define SQLITE_DBSTATUS_CACHE_MISS           8
7338#define SQLITE_DBSTATUS_CACHE_WRITE          9
7339#define SQLITE_DBSTATUS_DEFERRED_FKS        10
7340#define SQLITE_DBSTATUS_CACHE_USED_SHARED   11
7341#define SQLITE_DBSTATUS_MAX                 11   /* Largest defined DBSTATUS */
7342
7343
7344/*
7345** CAPI3REF: Prepared Statement Status
7346** METHOD: sqlite3_stmt
7347**
7348** ^(Each prepared statement maintains various
7349** [SQLITE_STMTSTATUS counters] that measure the number
7350** of times it has performed specific operations.)^  These counters can
7351** be used to monitor the performance characteristics of the prepared
7352** statements.  For example, if the number of table steps greatly exceeds
7353** the number of table searches or result rows, that would tend to indicate
7354** that the prepared statement is using a full table scan rather than
7355** an index.
7356**
7357** ^(This interface is used to retrieve and reset counter values from
7358** a [prepared statement].  The first argument is the prepared statement
7359** object to be interrogated.  The second argument
7360** is an integer code for a specific [SQLITE_STMTSTATUS counter]
7361** to be interrogated.)^
7362** ^The current value of the requested counter is returned.
7363** ^If the resetFlg is true, then the counter is reset to zero after this
7364** interface call returns.
7365**
7366** See also: [sqlite3_status()] and [sqlite3_db_status()].
7367*/
7368SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
7369
7370/*
7371** CAPI3REF: Status Parameters for prepared statements
7372** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
7373**
7374** These preprocessor macros define integer codes that name counter
7375** values associated with the [sqlite3_stmt_status()] interface.
7376** The meanings of the various counters are as follows:
7377**
7378** <dl>
7379** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
7380** <dd>^This is the number of times that SQLite has stepped forward in
7381** a table as part of a full table scan.  Large numbers for this counter
7382** may indicate opportunities for performance improvement through
7383** careful use of indices.</dd>
7384**
7385** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
7386** <dd>^This is the number of sort operations that have occurred.
7387** A non-zero value in this counter may indicate an opportunity to
7388** improvement performance through careful use of indices.</dd>
7389**
7390** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
7391** <dd>^This is the number of rows inserted into transient indices that
7392** were created automatically in order to help joins run faster.
7393** A non-zero value in this counter may indicate an opportunity to
7394** improvement performance by adding permanent indices that do not
7395** need to be reinitialized each time the statement is run.</dd>
7396**
7397** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
7398** <dd>^This is the number of virtual machine operations executed
7399** by the prepared statement if that number is less than or equal
7400** to 2147483647.  The number of virtual machine operations can be
7401** used as a proxy for the total work done by the prepared statement.
7402** If the number of virtual machine operations exceeds 2147483647
7403** then the value returned by this statement status code is undefined.
7404** </dd>
7405** </dl>
7406*/
7407#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
7408#define SQLITE_STMTSTATUS_SORT              2
7409#define SQLITE_STMTSTATUS_AUTOINDEX         3
7410#define SQLITE_STMTSTATUS_VM_STEP           4
7411
7412/*
7413** CAPI3REF: Custom Page Cache Object
7414**
7415** The sqlite3_pcache type is opaque.  It is implemented by
7416** the pluggable module.  The SQLite core has no knowledge of
7417** its size or internal structure and never deals with the
7418** sqlite3_pcache object except by holding and passing pointers
7419** to the object.
7420**
7421** See [sqlite3_pcache_methods2] for additional information.
7422*/
7423typedef struct sqlite3_pcache sqlite3_pcache;
7424
7425/*
7426** CAPI3REF: Custom Page Cache Object
7427**
7428** The sqlite3_pcache_page object represents a single page in the
7429** page cache.  The page cache will allocate instances of this
7430** object.  Various methods of the page cache use pointers to instances
7431** of this object as parameters or as their return value.
7432**
7433** See [sqlite3_pcache_methods2] for additional information.
7434*/
7435typedef struct sqlite3_pcache_page sqlite3_pcache_page;
7436struct sqlite3_pcache_page {
7437  void *pBuf;        /* The content of the page */
7438  void *pExtra;      /* Extra information associated with the page */
7439};
7440
7441/*
7442** CAPI3REF: Application Defined Page Cache.
7443** KEYWORDS: {page cache}
7444**
7445** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
7446** register an alternative page cache implementation by passing in an
7447** instance of the sqlite3_pcache_methods2 structure.)^
7448** In many applications, most of the heap memory allocated by
7449** SQLite is used for the page cache.
7450** By implementing a
7451** custom page cache using this API, an application can better control
7452** the amount of memory consumed by SQLite, the way in which
7453** that memory is allocated and released, and the policies used to
7454** determine exactly which parts of a database file are cached and for
7455** how long.
7456**
7457** The alternative page cache mechanism is an
7458** extreme measure that is only needed by the most demanding applications.
7459** The built-in page cache is recommended for most uses.
7460**
7461** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
7462** internal buffer by SQLite within the call to [sqlite3_config].  Hence
7463** the application may discard the parameter after the call to
7464** [sqlite3_config()] returns.)^
7465**
7466** [[the xInit() page cache method]]
7467** ^(The xInit() method is called once for each effective
7468** call to [sqlite3_initialize()])^
7469** (usually only once during the lifetime of the process). ^(The xInit()
7470** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
7471** The intent of the xInit() method is to set up global data structures
7472** required by the custom page cache implementation.
7473** ^(If the xInit() method is NULL, then the
7474** built-in default page cache is used instead of the application defined
7475** page cache.)^
7476**
7477** [[the xShutdown() page cache method]]
7478** ^The xShutdown() method is called by [sqlite3_shutdown()].
7479** It can be used to clean up
7480** any outstanding resources before process shutdown, if required.
7481** ^The xShutdown() method may be NULL.
7482**
7483** ^SQLite automatically serializes calls to the xInit method,
7484** so the xInit method need not be threadsafe.  ^The
7485** xShutdown method is only called from [sqlite3_shutdown()] so it does
7486** not need to be threadsafe either.  All other methods must be threadsafe
7487** in multithreaded applications.
7488**
7489** ^SQLite will never invoke xInit() more than once without an intervening
7490** call to xShutdown().
7491**
7492** [[the xCreate() page cache methods]]
7493** ^SQLite invokes the xCreate() method to construct a new cache instance.
7494** SQLite will typically create one cache instance for each open database file,
7495** though this is not guaranteed. ^The
7496** first parameter, szPage, is the size in bytes of the pages that must
7497** be allocated by the cache.  ^szPage will always a power of two.  ^The
7498** second parameter szExtra is a number of bytes of extra storage
7499** associated with each page cache entry.  ^The szExtra parameter will
7500** a number less than 250.  SQLite will use the
7501** extra szExtra bytes on each page to store metadata about the underlying
7502** database page on disk.  The value passed into szExtra depends
7503** on the SQLite version, the target platform, and how SQLite was compiled.
7504** ^The third argument to xCreate(), bPurgeable, is true if the cache being
7505** created will be used to cache database pages of a file stored on disk, or
7506** false if it is used for an in-memory database. The cache implementation
7507** does not have to do anything special based with the value of bPurgeable;
7508** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
7509** never invoke xUnpin() except to deliberately delete a page.
7510** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
7511** false will always have the "discard" flag set to true.
7512** ^Hence, a cache created with bPurgeable false will
7513** never contain any unpinned pages.
7514**
7515** [[the xCachesize() page cache method]]
7516** ^(The xCachesize() method may be called at any time by SQLite to set the
7517** suggested maximum cache-size (number of pages stored by) the cache
7518** instance passed as the first argument. This is the value configured using
7519** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
7520** parameter, the implementation is not required to do anything with this
7521** value; it is advisory only.
7522**
7523** [[the xPagecount() page cache methods]]
7524** The xPagecount() method must return the number of pages currently
7525** stored in the cache, both pinned and unpinned.
7526**
7527** [[the xFetch() page cache methods]]
7528** The xFetch() method locates a page in the cache and returns a pointer to
7529** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
7530** The pBuf element of the returned sqlite3_pcache_page object will be a
7531** pointer to a buffer of szPage bytes used to store the content of a
7532** single database page.  The pExtra element of sqlite3_pcache_page will be
7533** a pointer to the szExtra bytes of extra storage that SQLite has requested
7534** for each entry in the page cache.
7535**
7536** The page to be fetched is determined by the key. ^The minimum key value
7537** is 1.  After it has been retrieved using xFetch, the page is considered
7538** to be "pinned".
7539**
7540** If the requested page is already in the page cache, then the page cache
7541** implementation must return a pointer to the page buffer with its content
7542** intact.  If the requested page is not already in the cache, then the
7543** cache implementation should use the value of the createFlag
7544** parameter to help it determined what action to take:
7545**
7546** <table border=1 width=85% align=center>
7547** <tr><th> createFlag <th> Behavior when page is not already in cache
7548** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
7549** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
7550**                 Otherwise return NULL.
7551** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
7552**                 NULL if allocating a new page is effectively impossible.
7553** </table>
7554**
7555** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
7556** will only use a createFlag of 2 after a prior call with a createFlag of 1
7557** failed.)^  In between the to xFetch() calls, SQLite may
7558** attempt to unpin one or more cache pages by spilling the content of
7559** pinned pages to disk and synching the operating system disk cache.
7560**
7561** [[the xUnpin() page cache method]]
7562** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
7563** as its second argument.  If the third parameter, discard, is non-zero,
7564** then the page must be evicted from the cache.
7565** ^If the discard parameter is
7566** zero, then the page may be discarded or retained at the discretion of
7567** page cache implementation. ^The page cache implementation
7568** may choose to evict unpinned pages at any time.
7569**
7570** The cache must not perform any reference counting. A single
7571** call to xUnpin() unpins the page regardless of the number of prior calls
7572** to xFetch().
7573**
7574** [[the xRekey() page cache methods]]
7575** The xRekey() method is used to change the key value associated with the
7576** page passed as the second argument. If the cache
7577** previously contains an entry associated with newKey, it must be
7578** discarded. ^Any prior cache entry associated with newKey is guaranteed not
7579** to be pinned.
7580**
7581** When SQLite calls the xTruncate() method, the cache must discard all
7582** existing cache entries with page numbers (keys) greater than or equal
7583** to the value of the iLimit parameter passed to xTruncate(). If any
7584** of these pages are pinned, they are implicitly unpinned, meaning that
7585** they can be safely discarded.
7586**
7587** [[the xDestroy() page cache method]]
7588** ^The xDestroy() method is used to delete a cache allocated by xCreate().
7589** All resources associated with the specified cache should be freed. ^After
7590** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7591** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7592** functions.
7593**
7594** [[the xShrink() page cache method]]
7595** ^SQLite invokes the xShrink() method when it wants the page cache to
7596** free up as much of heap memory as possible.  The page cache implementation
7597** is not obligated to free any memory, but well-behaved implementations should
7598** do their best.
7599*/
7600typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
7601struct sqlite3_pcache_methods2 {
7602  int iVersion;
7603  void *pArg;
7604  int (*xInit)(void*);
7605  void (*xShutdown)(void*);
7606  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7607  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7608  int (*xPagecount)(sqlite3_pcache*);
7609  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7610  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7611  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
7612      unsigned oldKey, unsigned newKey);
7613  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7614  void (*xDestroy)(sqlite3_pcache*);
7615  void (*xShrink)(sqlite3_pcache*);
7616};
7617
7618/*
7619** This is the obsolete pcache_methods object that has now been replaced
7620** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
7621** retained in the header file for backwards compatibility only.
7622*/
7623typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7624struct sqlite3_pcache_methods {
7625  void *pArg;
7626  int (*xInit)(void*);
7627  void (*xShutdown)(void*);
7628  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7629  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7630  int (*xPagecount)(sqlite3_pcache*);
7631  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7632  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7633  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7634  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7635  void (*xDestroy)(sqlite3_pcache*);
7636};
7637
7638
7639/*
7640** CAPI3REF: Online Backup Object
7641**
7642** The sqlite3_backup object records state information about an ongoing
7643** online backup operation.  ^The sqlite3_backup object is created by
7644** a call to [sqlite3_backup_init()] and is destroyed by a call to
7645** [sqlite3_backup_finish()].
7646**
7647** See Also: [Using the SQLite Online Backup API]
7648*/
7649typedef struct sqlite3_backup sqlite3_backup;
7650
7651/*
7652** CAPI3REF: Online Backup API.
7653**
7654** The backup API copies the content of one database into another.
7655** It is useful either for creating backups of databases or
7656** for copying in-memory databases to or from persistent files.
7657**
7658** See Also: [Using the SQLite Online Backup API]
7659**
7660** ^SQLite holds a write transaction open on the destination database file
7661** for the duration of the backup operation.
7662** ^The source database is read-locked only while it is being read;
7663** it is not locked continuously for the entire backup operation.
7664** ^Thus, the backup may be performed on a live source database without
7665** preventing other database connections from
7666** reading or writing to the source database while the backup is underway.
7667**
7668** ^(To perform a backup operation:
7669**   <ol>
7670**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
7671**         backup,
7672**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
7673**         the data between the two databases, and finally
7674**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
7675**         associated with the backup operation.
7676**   </ol>)^
7677** There should be exactly one call to sqlite3_backup_finish() for each
7678** successful call to sqlite3_backup_init().
7679**
7680** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7681**
7682** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
7683** [database connection] associated with the destination database
7684** and the database name, respectively.
7685** ^The database name is "main" for the main database, "temp" for the
7686** temporary database, or the name specified after the AS keyword in
7687** an [ATTACH] statement for an attached database.
7688** ^The S and M arguments passed to
7689** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7690** and database name of the source database, respectively.
7691** ^The source and destination [database connections] (parameters S and D)
7692** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7693** an error.
7694**
7695** ^A call to sqlite3_backup_init() will fail, returning NULL, if
7696** there is already a read or read-write transaction open on the
7697** destination database.
7698**
7699** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7700** returned and an error code and error message are stored in the
7701** destination [database connection] D.
7702** ^The error code and message for the failed call to sqlite3_backup_init()
7703** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7704** [sqlite3_errmsg16()] functions.
7705** ^A successful call to sqlite3_backup_init() returns a pointer to an
7706** [sqlite3_backup] object.
7707** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7708** sqlite3_backup_finish() functions to perform the specified backup
7709** operation.
7710**
7711** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7712**
7713** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
7714** the source and destination databases specified by [sqlite3_backup] object B.
7715** ^If N is negative, all remaining source pages are copied.
7716** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7717** are still more pages to be copied, then the function returns [SQLITE_OK].
7718** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7719** from source to destination, then it returns [SQLITE_DONE].
7720** ^If an error occurs while running sqlite3_backup_step(B,N),
7721** then an [error code] is returned. ^As well as [SQLITE_OK] and
7722** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7723** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7724** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7725**
7726** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7727** <ol>
7728** <li> the destination database was opened read-only, or
7729** <li> the destination database is using write-ahead-log journaling
7730** and the destination and source page sizes differ, or
7731** <li> the destination database is an in-memory database and the
7732** destination and source page sizes differ.
7733** </ol>)^
7734**
7735** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7736** the [sqlite3_busy_handler | busy-handler function]
7737** is invoked (if one is specified). ^If the
7738** busy-handler returns non-zero before the lock is available, then
7739** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7740** sqlite3_backup_step() can be retried later. ^If the source
7741** [database connection]
7742** is being used to write to the source database when sqlite3_backup_step()
7743** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7744** case the call to sqlite3_backup_step() can be retried later on. ^(If
7745** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7746** [SQLITE_READONLY] is returned, then
7747** there is no point in retrying the call to sqlite3_backup_step(). These
7748** errors are considered fatal.)^  The application must accept
7749** that the backup operation has failed and pass the backup operation handle
7750** to the sqlite3_backup_finish() to release associated resources.
7751**
7752** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7753** on the destination file. ^The exclusive lock is not released until either
7754** sqlite3_backup_finish() is called or the backup operation is complete
7755** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
7756** sqlite3_backup_step() obtains a [shared lock] on the source database that
7757** lasts for the duration of the sqlite3_backup_step() call.
7758** ^Because the source database is not locked between calls to
7759** sqlite3_backup_step(), the source database may be modified mid-way
7760** through the backup process.  ^If the source database is modified by an
7761** external process or via a database connection other than the one being
7762** used by the backup operation, then the backup will be automatically
7763** restarted by the next call to sqlite3_backup_step(). ^If the source
7764** database is modified by the using the same database connection as is used
7765** by the backup operation, then the backup database is automatically
7766** updated at the same time.
7767**
7768** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7769**
7770** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7771** application wishes to abandon the backup operation, the application
7772** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7773** ^The sqlite3_backup_finish() interfaces releases all
7774** resources associated with the [sqlite3_backup] object.
7775** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7776** active write-transaction on the destination database is rolled back.
7777** The [sqlite3_backup] object is invalid
7778** and may not be used following a call to sqlite3_backup_finish().
7779**
7780** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7781** sqlite3_backup_step() errors occurred, regardless or whether or not
7782** sqlite3_backup_step() completed.
7783** ^If an out-of-memory condition or IO error occurred during any prior
7784** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7785** sqlite3_backup_finish() returns the corresponding [error code].
7786**
7787** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7788** is not a permanent error and does not affect the return value of
7789** sqlite3_backup_finish().
7790**
7791** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
7792** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7793**
7794** ^The sqlite3_backup_remaining() routine returns the number of pages still
7795** to be backed up at the conclusion of the most recent sqlite3_backup_step().
7796** ^The sqlite3_backup_pagecount() routine returns the total number of pages
7797** in the source database at the conclusion of the most recent
7798** sqlite3_backup_step().
7799** ^(The values returned by these functions are only updated by
7800** sqlite3_backup_step(). If the source database is modified in a way that
7801** changes the size of the source database or the number of pages remaining,
7802** those changes are not reflected in the output of sqlite3_backup_pagecount()
7803** and sqlite3_backup_remaining() until after the next
7804** sqlite3_backup_step().)^
7805**
7806** <b>Concurrent Usage of Database Handles</b>
7807**
7808** ^The source [database connection] may be used by the application for other
7809** purposes while a backup operation is underway or being initialized.
7810** ^If SQLite is compiled and configured to support threadsafe database
7811** connections, then the source database connection may be used concurrently
7812** from within other threads.
7813**
7814** However, the application must guarantee that the destination
7815** [database connection] is not passed to any other API (by any thread) after
7816** sqlite3_backup_init() is called and before the corresponding call to
7817** sqlite3_backup_finish().  SQLite does not currently check to see
7818** if the application incorrectly accesses the destination [database connection]
7819** and so no error code is reported, but the operations may malfunction
7820** nevertheless.  Use of the destination database connection while a
7821** backup is in progress might also also cause a mutex deadlock.
7822**
7823** If running in [shared cache mode], the application must
7824** guarantee that the shared cache used by the destination database
7825** is not accessed while the backup is running. In practice this means
7826** that the application must guarantee that the disk file being
7827** backed up to is not accessed by any connection within the process,
7828** not just the specific connection that was passed to sqlite3_backup_init().
7829**
7830** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7831** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7832** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7833** APIs are not strictly speaking threadsafe. If they are invoked at the
7834** same time as another thread is invoking sqlite3_backup_step() it is
7835** possible that they return invalid values.
7836*/
7837SQLITE_API sqlite3_backup *sqlite3_backup_init(
7838  sqlite3 *pDest,                        /* Destination database handle */
7839  const char *zDestName,                 /* Destination database name */
7840  sqlite3 *pSource,                      /* Source database handle */
7841  const char *zSourceName                /* Source database name */
7842);
7843SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7844SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7845SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7846SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7847
7848/*
7849** CAPI3REF: Unlock Notification
7850** METHOD: sqlite3
7851**
7852** ^When running in shared-cache mode, a database operation may fail with
7853** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7854** individual tables within the shared-cache cannot be obtained. See
7855** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7856** ^This API may be used to register a callback that SQLite will invoke
7857** when the connection currently holding the required lock relinquishes it.
7858** ^This API is only available if the library was compiled with the
7859** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7860**
7861** See Also: [Using the SQLite Unlock Notification Feature].
7862**
7863** ^Shared-cache locks are released when a database connection concludes
7864** its current transaction, either by committing it or rolling it back.
7865**
7866** ^When a connection (known as the blocked connection) fails to obtain a
7867** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7868** identity of the database connection (the blocking connection) that
7869** has locked the required resource is stored internally. ^After an
7870** application receives an SQLITE_LOCKED error, it may call the
7871** sqlite3_unlock_notify() method with the blocked connection handle as
7872** the first argument to register for a callback that will be invoked
7873** when the blocking connections current transaction is concluded. ^The
7874** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7875** call that concludes the blocking connections transaction.
7876**
7877** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7878** there is a chance that the blocking connection will have already
7879** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7880** If this happens, then the specified callback is invoked immediately,
7881** from within the call to sqlite3_unlock_notify().)^
7882**
7883** ^If the blocked connection is attempting to obtain a write-lock on a
7884** shared-cache table, and more than one other connection currently holds
7885** a read-lock on the same table, then SQLite arbitrarily selects one of
7886** the other connections to use as the blocking connection.
7887**
7888** ^(There may be at most one unlock-notify callback registered by a
7889** blocked connection. If sqlite3_unlock_notify() is called when the
7890** blocked connection already has a registered unlock-notify callback,
7891** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7892** called with a NULL pointer as its second argument, then any existing
7893** unlock-notify callback is canceled. ^The blocked connections
7894** unlock-notify callback may also be canceled by closing the blocked
7895** connection using [sqlite3_close()].
7896**
7897** The unlock-notify callback is not reentrant. If an application invokes
7898** any sqlite3_xxx API functions from within an unlock-notify callback, a
7899** crash or deadlock may be the result.
7900**
7901** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7902** returns SQLITE_OK.
7903**
7904** <b>Callback Invocation Details</b>
7905**
7906** When an unlock-notify callback is registered, the application provides a
7907** single void* pointer that is passed to the callback when it is invoked.
7908** However, the signature of the callback function allows SQLite to pass
7909** it an array of void* context pointers. The first argument passed to
7910** an unlock-notify callback is a pointer to an array of void* pointers,
7911** and the second is the number of entries in the array.
7912**
7913** When a blocking connections transaction is concluded, there may be
7914** more than one blocked connection that has registered for an unlock-notify
7915** callback. ^If two or more such blocked connections have specified the
7916** same callback function, then instead of invoking the callback function
7917** multiple times, it is invoked once with the set of void* context pointers
7918** specified by the blocked connections bundled together into an array.
7919** This gives the application an opportunity to prioritize any actions
7920** related to the set of unblocked database connections.
7921**
7922** <b>Deadlock Detection</b>
7923**
7924** Assuming that after registering for an unlock-notify callback a
7925** database waits for the callback to be issued before taking any further
7926** action (a reasonable assumption), then using this API may cause the
7927** application to deadlock. For example, if connection X is waiting for
7928** connection Y's transaction to be concluded, and similarly connection
7929** Y is waiting on connection X's transaction, then neither connection
7930** will proceed and the system may remain deadlocked indefinitely.
7931**
7932** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7933** detection. ^If a given call to sqlite3_unlock_notify() would put the
7934** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7935** unlock-notify callback is registered. The system is said to be in
7936** a deadlocked state if connection A has registered for an unlock-notify
7937** callback on the conclusion of connection B's transaction, and connection
7938** B has itself registered for an unlock-notify callback when connection
7939** A's transaction is concluded. ^Indirect deadlock is also detected, so
7940** the system is also considered to be deadlocked if connection B has
7941** registered for an unlock-notify callback on the conclusion of connection
7942** C's transaction, where connection C is waiting on connection A. ^Any
7943** number of levels of indirection are allowed.
7944**
7945** <b>The "DROP TABLE" Exception</b>
7946**
7947** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7948** always appropriate to call sqlite3_unlock_notify(). There is however,
7949** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7950** SQLite checks if there are any currently executing SELECT statements
7951** that belong to the same connection. If there are, SQLITE_LOCKED is
7952** returned. In this case there is no "blocking connection", so invoking
7953** sqlite3_unlock_notify() results in the unlock-notify callback being
7954** invoked immediately. If the application then re-attempts the "DROP TABLE"
7955** or "DROP INDEX" query, an infinite loop might be the result.
7956**
7957** One way around this problem is to check the extended error code returned
7958** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7959** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7960** the special "DROP TABLE/INDEX" case, the extended error code is just
7961** SQLITE_LOCKED.)^
7962*/
7963SQLITE_API int sqlite3_unlock_notify(
7964  sqlite3 *pBlocked,                          /* Waiting connection */
7965  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7966  void *pNotifyArg                            /* Argument to pass to xNotify */
7967);
7968
7969
7970/*
7971** CAPI3REF: String Comparison
7972**
7973** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7974** and extensions to compare the contents of two buffers containing UTF-8
7975** strings in a case-independent fashion, using the same definition of "case
7976** independence" that SQLite uses internally when comparing identifiers.
7977*/
7978SQLITE_API int sqlite3_stricmp(const char *, const char *);
7979SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7980
7981/*
7982** CAPI3REF: String Globbing
7983*
7984** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
7985** string X matches the [GLOB] pattern P.
7986** ^The definition of [GLOB] pattern matching used in
7987** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7988** SQL dialect understood by SQLite.  ^The [sqlite3_strglob(P,X)] function
7989** is case sensitive.
7990**
7991** Note that this routine returns zero on a match and non-zero if the strings
7992** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7993**
7994** See also: [sqlite3_strlike()].
7995*/
7996SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
7997
7998/*
7999** CAPI3REF: String LIKE Matching
8000*
8001** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
8002** string X matches the [LIKE] pattern P with escape character E.
8003** ^The definition of [LIKE] pattern matching used in
8004** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
8005** operator in the SQL dialect understood by SQLite.  ^For "X LIKE P" without
8006** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
8007** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
8008** insensitive - equivalent upper and lower case ASCII characters match
8009** one another.
8010**
8011** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
8012** only ASCII characters are case folded.
8013**
8014** Note that this routine returns zero on a match and non-zero if the strings
8015** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
8016**
8017** See also: [sqlite3_strglob()].
8018*/
8019SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
8020
8021/*
8022** CAPI3REF: Error Logging Interface
8023**
8024** ^The [sqlite3_log()] interface writes a message into the [error log]
8025** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
8026** ^If logging is enabled, the zFormat string and subsequent arguments are
8027** used with [sqlite3_snprintf()] to generate the final output string.
8028**
8029** The sqlite3_log() interface is intended for use by extensions such as
8030** virtual tables, collating functions, and SQL functions.  While there is
8031** nothing to prevent an application from calling sqlite3_log(), doing so
8032** is considered bad form.
8033**
8034** The zFormat string must not be NULL.
8035**
8036** To avoid deadlocks and other threading problems, the sqlite3_log() routine
8037** will not use dynamically allocated memory.  The log message is stored in
8038** a fixed-length buffer on the stack.  If the log message is longer than
8039** a few hundred characters, it will be truncated to the length of the
8040** buffer.
8041*/
8042SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
8043
8044/*
8045** CAPI3REF: Write-Ahead Log Commit Hook
8046** METHOD: sqlite3
8047**
8048** ^The [sqlite3_wal_hook()] function is used to register a callback that
8049** is invoked each time data is committed to a database in wal mode.
8050**
8051** ^(The callback is invoked by SQLite after the commit has taken place and
8052** the associated write-lock on the database released)^, so the implementation
8053** may read, write or [checkpoint] the database as required.
8054**
8055** ^The first parameter passed to the callback function when it is invoked
8056** is a copy of the third parameter passed to sqlite3_wal_hook() when
8057** registering the callback. ^The second is a copy of the database handle.
8058** ^The third parameter is the name of the database that was written to -
8059** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
8060** is the number of pages currently in the write-ahead log file,
8061** including those that were just committed.
8062**
8063** The callback function should normally return [SQLITE_OK].  ^If an error
8064** code is returned, that error will propagate back up through the
8065** SQLite code base to cause the statement that provoked the callback
8066** to report an error, though the commit will have still occurred. If the
8067** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
8068** that does not correspond to any valid SQLite error code, the results
8069** are undefined.
8070**
8071** A single database handle may have at most a single write-ahead log callback
8072** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
8073** previously registered write-ahead log callback. ^Note that the
8074** [sqlite3_wal_autocheckpoint()] interface and the
8075** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
8076** overwrite any prior [sqlite3_wal_hook()] settings.
8077*/
8078SQLITE_API void *sqlite3_wal_hook(
8079  sqlite3*,
8080  int(*)(void *,sqlite3*,const char*,int),
8081  void*
8082);
8083
8084/*
8085** CAPI3REF: Configure an auto-checkpoint
8086** METHOD: sqlite3
8087**
8088** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
8089** [sqlite3_wal_hook()] that causes any database on [database connection] D
8090** to automatically [checkpoint]
8091** after committing a transaction if there are N or
8092** more frames in the [write-ahead log] file.  ^Passing zero or
8093** a negative value as the nFrame parameter disables automatic
8094** checkpoints entirely.
8095**
8096** ^The callback registered by this function replaces any existing callback
8097** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
8098** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
8099** configured by this function.
8100**
8101** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
8102** from SQL.
8103**
8104** ^Checkpoints initiated by this mechanism are
8105** [sqlite3_wal_checkpoint_v2|PASSIVE].
8106**
8107** ^Every new [database connection] defaults to having the auto-checkpoint
8108** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
8109** pages.  The use of this interface
8110** is only necessary if the default setting is found to be suboptimal
8111** for a particular application.
8112*/
8113SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
8114
8115/*
8116** CAPI3REF: Checkpoint a database
8117** METHOD: sqlite3
8118**
8119** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
8120** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
8121**
8122** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
8123** [write-ahead log] for database X on [database connection] D to be
8124** transferred into the database file and for the write-ahead log to
8125** be reset.  See the [checkpointing] documentation for addition
8126** information.
8127**
8128** This interface used to be the only way to cause a checkpoint to
8129** occur.  But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
8130** interface was added.  This interface is retained for backwards
8131** compatibility and as a convenience for applications that need to manually
8132** start a callback but which do not need the full power (and corresponding
8133** complication) of [sqlite3_wal_checkpoint_v2()].
8134*/
8135SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
8136
8137/*
8138** CAPI3REF: Checkpoint a database
8139** METHOD: sqlite3
8140**
8141** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
8142** operation on database X of [database connection] D in mode M.  Status
8143** information is written back into integers pointed to by L and C.)^
8144** ^(The M parameter must be a valid [checkpoint mode]:)^
8145**
8146** <dl>
8147** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
8148**   ^Checkpoint as many frames as possible without waiting for any database
8149**   readers or writers to finish, then sync the database file if all frames
8150**   in the log were checkpointed. ^The [busy-handler callback]
8151**   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
8152**   ^On the other hand, passive mode might leave the checkpoint unfinished
8153**   if there are concurrent readers or writers.
8154**
8155** <dt>SQLITE_CHECKPOINT_FULL<dd>
8156**   ^This mode blocks (it invokes the
8157**   [sqlite3_busy_handler|busy-handler callback]) until there is no
8158**   database writer and all readers are reading from the most recent database
8159**   snapshot. ^It then checkpoints all frames in the log file and syncs the
8160**   database file. ^This mode blocks new database writers while it is pending,
8161**   but new database readers are allowed to continue unimpeded.
8162**
8163** <dt>SQLITE_CHECKPOINT_RESTART<dd>
8164**   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
8165**   that after checkpointing the log file it blocks (calls the
8166**   [busy-handler callback])
8167**   until all readers are reading from the database file only. ^This ensures
8168**   that the next writer will restart the log file from the beginning.
8169**   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
8170**   database writer attempts while it is pending, but does not impede readers.
8171**
8172** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
8173**   ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
8174**   addition that it also truncates the log file to zero bytes just prior
8175**   to a successful return.
8176** </dl>
8177**
8178** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
8179** the log file or to -1 if the checkpoint could not run because
8180** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
8181** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
8182** log file (including any that were already checkpointed before the function
8183** was called) or to -1 if the checkpoint could not run due to an error or
8184** because the database is not in WAL mode. ^Note that upon successful
8185** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
8186** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
8187**
8188** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
8189** any other process is running a checkpoint operation at the same time, the
8190** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
8191** busy-handler configured, it will not be invoked in this case.
8192**
8193** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
8194** exclusive "writer" lock on the database file. ^If the writer lock cannot be
8195** obtained immediately, and a busy-handler is configured, it is invoked and
8196** the writer lock retried until either the busy-handler returns 0 or the lock
8197** is successfully obtained. ^The busy-handler is also invoked while waiting for
8198** database readers as described above. ^If the busy-handler returns 0 before
8199** the writer lock is obtained or while waiting for database readers, the
8200** checkpoint operation proceeds from that point in the same way as
8201** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
8202** without blocking any further. ^SQLITE_BUSY is returned in this case.
8203**
8204** ^If parameter zDb is NULL or points to a zero length string, then the
8205** specified operation is attempted on all WAL databases [attached] to
8206** [database connection] db.  In this case the
8207** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
8208** an SQLITE_BUSY error is encountered when processing one or more of the
8209** attached WAL databases, the operation is still attempted on any remaining
8210** attached databases and SQLITE_BUSY is returned at the end. ^If any other
8211** error occurs while processing an attached database, processing is abandoned
8212** and the error code is returned to the caller immediately. ^If no error
8213** (SQLITE_BUSY or otherwise) is encountered while processing the attached
8214** databases, SQLITE_OK is returned.
8215**
8216** ^If database zDb is the name of an attached database that is not in WAL
8217** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
8218** zDb is not NULL (or a zero length string) and is not the name of any
8219** attached database, SQLITE_ERROR is returned to the caller.
8220**
8221** ^Unless it returns SQLITE_MISUSE,
8222** the sqlite3_wal_checkpoint_v2() interface
8223** sets the error information that is queried by
8224** [sqlite3_errcode()] and [sqlite3_errmsg()].
8225**
8226** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
8227** from SQL.
8228*/
8229SQLITE_API int sqlite3_wal_checkpoint_v2(
8230  sqlite3 *db,                    /* Database handle */
8231  const char *zDb,                /* Name of attached database (or NULL) */
8232  int eMode,                      /* SQLITE_CHECKPOINT_* value */
8233  int *pnLog,                     /* OUT: Size of WAL log in frames */
8234  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
8235);
8236
8237/*
8238** CAPI3REF: Checkpoint Mode Values
8239** KEYWORDS: {checkpoint mode}
8240**
8241** These constants define all valid values for the "checkpoint mode" passed
8242** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
8243** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
8244** meaning of each of these checkpoint modes.
8245*/
8246#define SQLITE_CHECKPOINT_PASSIVE  0  /* Do as much as possible w/o blocking */
8247#define SQLITE_CHECKPOINT_FULL     1  /* Wait for writers, then checkpoint */
8248#define SQLITE_CHECKPOINT_RESTART  2  /* Like FULL but wait for for readers */
8249#define SQLITE_CHECKPOINT_TRUNCATE 3  /* Like RESTART but also truncate WAL */
8250
8251/*
8252** CAPI3REF: Virtual Table Interface Configuration
8253**
8254** This function may be called by either the [xConnect] or [xCreate] method
8255** of a [virtual table] implementation to configure
8256** various facets of the virtual table interface.
8257**
8258** If this interface is invoked outside the context of an xConnect or
8259** xCreate virtual table method then the behavior is undefined.
8260**
8261** At present, there is only one option that may be configured using
8262** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
8263** may be added in the future.
8264*/
8265SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
8266
8267/*
8268** CAPI3REF: Virtual Table Configuration Options
8269**
8270** These macros define the various options to the
8271** [sqlite3_vtab_config()] interface that [virtual table] implementations
8272** can use to customize and optimize their behavior.
8273**
8274** <dl>
8275** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
8276** <dd>Calls of the form
8277** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
8278** where X is an integer.  If X is zero, then the [virtual table] whose
8279** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
8280** support constraints.  In this configuration (which is the default) if
8281** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
8282** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
8283** specified as part of the users SQL statement, regardless of the actual
8284** ON CONFLICT mode specified.
8285**
8286** If X is non-zero, then the virtual table implementation guarantees
8287** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
8288** any modifications to internal or persistent data structures have been made.
8289** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
8290** is able to roll back a statement or database transaction, and abandon
8291** or continue processing the current SQL statement as appropriate.
8292** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
8293** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
8294** had been ABORT.
8295**
8296** Virtual table implementations that are required to handle OR REPLACE
8297** must do so within the [xUpdate] method. If a call to the
8298** [sqlite3_vtab_on_conflict()] function indicates that the current ON
8299** CONFLICT policy is REPLACE, the virtual table implementation should
8300** silently replace the appropriate rows within the xUpdate callback and
8301** return SQLITE_OK. Or, if this is not possible, it may return
8302** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
8303** constraint handling.
8304** </dl>
8305*/
8306#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
8307
8308/*
8309** CAPI3REF: Determine The Virtual Table Conflict Policy
8310**
8311** This function may only be called from within a call to the [xUpdate] method
8312** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
8313** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
8314** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
8315** of the SQL statement that triggered the call to the [xUpdate] method of the
8316** [virtual table].
8317*/
8318SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
8319
8320/*
8321** CAPI3REF: Conflict resolution modes
8322** KEYWORDS: {conflict resolution mode}
8323**
8324** These constants are returned by [sqlite3_vtab_on_conflict()] to
8325** inform a [virtual table] implementation what the [ON CONFLICT] mode
8326** is for the SQL statement being evaluated.
8327**
8328** Note that the [SQLITE_IGNORE] constant is also used as a potential
8329** return value from the [sqlite3_set_authorizer()] callback and that
8330** [SQLITE_ABORT] is also a [result code].
8331*/
8332#define SQLITE_ROLLBACK 1
8333/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
8334#define SQLITE_FAIL     3
8335/* #define SQLITE_ABORT 4  // Also an error code */
8336#define SQLITE_REPLACE  5
8337
8338/*
8339** CAPI3REF: Prepared Statement Scan Status Opcodes
8340** KEYWORDS: {scanstatus options}
8341**
8342** The following constants can be used for the T parameter to the
8343** [sqlite3_stmt_scanstatus(S,X,T,V)] interface.  Each constant designates a
8344** different metric for sqlite3_stmt_scanstatus() to return.
8345**
8346** When the value returned to V is a string, space to hold that string is
8347** managed by the prepared statement S and will be automatically freed when
8348** S is finalized.
8349**
8350** <dl>
8351** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
8352** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
8353** set to the total number of times that the X-th loop has run.</dd>
8354**
8355** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
8356** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
8357** to the total number of rows examined by all iterations of the X-th loop.</dd>
8358**
8359** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
8360** <dd>^The "double" variable pointed to by the T parameter will be set to the
8361** query planner's estimate for the average number of rows output from each
8362** iteration of the X-th loop.  If the query planner's estimates was accurate,
8363** then this value will approximate the quotient NVISIT/NLOOP and the
8364** product of this value for all prior loops with the same SELECTID will
8365** be the NLOOP value for the current loop.
8366**
8367** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
8368** <dd>^The "const char *" variable pointed to by the T parameter will be set
8369** to a zero-terminated UTF-8 string containing the name of the index or table
8370** used for the X-th loop.
8371**
8372** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
8373** <dd>^The "const char *" variable pointed to by the T parameter will be set
8374** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
8375** description for the X-th loop.
8376**
8377** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
8378** <dd>^The "int" variable pointed to by the T parameter will be set to the
8379** "select-id" for the X-th loop.  The select-id identifies which query or
8380** subquery the loop is part of.  The main query has a select-id of zero.
8381** The select-id is the same value as is output in the first column
8382** of an [EXPLAIN QUERY PLAN] query.
8383** </dl>
8384*/
8385#define SQLITE_SCANSTAT_NLOOP    0
8386#define SQLITE_SCANSTAT_NVISIT   1
8387#define SQLITE_SCANSTAT_EST      2
8388#define SQLITE_SCANSTAT_NAME     3
8389#define SQLITE_SCANSTAT_EXPLAIN  4
8390#define SQLITE_SCANSTAT_SELECTID 5
8391
8392/*
8393** CAPI3REF: Prepared Statement Scan Status
8394** METHOD: sqlite3_stmt
8395**
8396** This interface returns information about the predicted and measured
8397** performance for pStmt.  Advanced applications can use this
8398** interface to compare the predicted and the measured performance and
8399** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
8400**
8401** Since this interface is expected to be rarely used, it is only
8402** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
8403** compile-time option.
8404**
8405** The "iScanStatusOp" parameter determines which status information to return.
8406** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
8407** of this interface is undefined.
8408** ^The requested measurement is written into a variable pointed to by
8409** the "pOut" parameter.
8410** Parameter "idx" identifies the specific loop to retrieve statistics for.
8411** Loops are numbered starting from zero. ^If idx is out of range - less than
8412** zero or greater than or equal to the total number of loops used to implement
8413** the statement - a non-zero value is returned and the variable that pOut
8414** points to is unchanged.
8415**
8416** ^Statistics might not be available for all loops in all statements. ^In cases
8417** where there exist loops with no available statistics, this function behaves
8418** as if the loop did not exist - it returns non-zero and leave the variable
8419** that pOut points to unchanged.
8420**
8421** See also: [sqlite3_stmt_scanstatus_reset()]
8422*/
8423SQLITE_API int sqlite3_stmt_scanstatus(
8424  sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */
8425  int idx,                  /* Index of loop to report on */
8426  int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */
8427  void *pOut                /* Result written here */
8428);
8429
8430/*
8431** CAPI3REF: Zero Scan-Status Counters
8432** METHOD: sqlite3_stmt
8433**
8434** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
8435**
8436** This API is only available if the library is built with pre-processor
8437** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
8438*/
8439SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
8440
8441/*
8442** CAPI3REF: Flush caches to disk mid-transaction
8443**
8444** ^If a write-transaction is open on [database connection] D when the
8445** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
8446** pages in the pager-cache that are not currently in use are written out
8447** to disk. A dirty page may be in use if a database cursor created by an
8448** active SQL statement is reading from it, or if it is page 1 of a database
8449** file (page 1 is always "in use").  ^The [sqlite3_db_cacheflush(D)]
8450** interface flushes caches for all schemas - "main", "temp", and
8451** any [attached] databases.
8452**
8453** ^If this function needs to obtain extra database locks before dirty pages
8454** can be flushed to disk, it does so. ^If those locks cannot be obtained
8455** immediately and there is a busy-handler callback configured, it is invoked
8456** in the usual manner. ^If the required lock still cannot be obtained, then
8457** the database is skipped and an attempt made to flush any dirty pages
8458** belonging to the next (if any) database. ^If any databases are skipped
8459** because locks cannot be obtained, but no other error occurs, this
8460** function returns SQLITE_BUSY.
8461**
8462** ^If any other error occurs while flushing dirty pages to disk (for
8463** example an IO error or out-of-memory condition), then processing is
8464** abandoned and an SQLite [error code] is returned to the caller immediately.
8465**
8466** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
8467**
8468** ^This function does not set the database handle error code or message
8469** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
8470*/
8471SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
8472
8473/*
8474** CAPI3REF: The pre-update hook.
8475**
8476** ^These interfaces are only available if SQLite is compiled using the
8477** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
8478**
8479** ^The [sqlite3_preupdate_hook()] interface registers a callback function
8480** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
8481** on a database table.
8482** ^At most one preupdate hook may be registered at a time on a single
8483** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
8484** the previous setting.
8485** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
8486** with a NULL pointer as the second parameter.
8487** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
8488** the first parameter to callbacks.
8489**
8490** ^The preupdate hook only fires for changes to real database tables; the
8491** preupdate hook is not invoked for changes to [virtual tables] or to
8492** system tables like sqlite_master or sqlite_stat1.
8493**
8494** ^The second parameter to the preupdate callback is a pointer to
8495** the [database connection] that registered the preupdate hook.
8496** ^The third parameter to the preupdate callback is one of the constants
8497** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
8498** kind of update operation that is about to occur.
8499** ^(The fourth parameter to the preupdate callback is the name of the
8500** database within the database connection that is being modified.  This
8501** will be "main" for the main database or "temp" for TEMP tables or
8502** the name given after the AS keyword in the [ATTACH] statement for attached
8503** databases.)^
8504** ^The fifth parameter to the preupdate callback is the name of the
8505** table that is being modified.
8506**
8507** For an UPDATE or DELETE operation on a [rowid table], the sixth
8508** parameter passed to the preupdate callback is the initial [rowid] of the
8509** row being modified or deleted. For an INSERT operation on a rowid table,
8510** or any operation on a WITHOUT ROWID table, the value of the sixth
8511** parameter is undefined. For an INSERT or UPDATE on a rowid table the
8512** seventh parameter is the final rowid value of the row being inserted
8513** or updated. The value of the seventh parameter passed to the callback
8514** function is not defined for operations on WITHOUT ROWID tables, or for
8515** INSERT operations on rowid tables.
8516**
8517** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
8518** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
8519** provide additional information about a preupdate event. These routines
8520** may only be called from within a preupdate callback.  Invoking any of
8521** these routines from outside of a preupdate callback or with a
8522** [database connection] pointer that is different from the one supplied
8523** to the preupdate callback results in undefined and probably undesirable
8524** behavior.
8525**
8526** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
8527** in the row that is being inserted, updated, or deleted.
8528**
8529** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
8530** a [protected sqlite3_value] that contains the value of the Nth column of
8531** the table row before it is updated.  The N parameter must be between 0
8532** and one less than the number of columns or the behavior will be
8533** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
8534** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
8535** behavior is undefined.  The [sqlite3_value] that P points to
8536** will be destroyed when the preupdate callback returns.
8537**
8538** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
8539** a [protected sqlite3_value] that contains the value of the Nth column of
8540** the table row after it is updated.  The N parameter must be between 0
8541** and one less than the number of columns or the behavior will be
8542** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
8543** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
8544** behavior is undefined.  The [sqlite3_value] that P points to
8545** will be destroyed when the preupdate callback returns.
8546**
8547** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
8548** callback was invoked as a result of a direct insert, update, or delete
8549** operation; or 1 for inserts, updates, or deletes invoked by top-level
8550** triggers; or 2 for changes resulting from triggers called by top-level
8551** triggers; and so forth.
8552**
8553** See also:  [sqlite3_update_hook()]
8554*/
8555#if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
8556SQLITE_API void *sqlite3_preupdate_hook(
8557  sqlite3 *db,
8558  void(*xPreUpdate)(
8559    void *pCtx,                   /* Copy of third arg to preupdate_hook() */
8560    sqlite3 *db,                  /* Database handle */
8561    int op,                       /* SQLITE_UPDATE, DELETE or INSERT */
8562    char const *zDb,              /* Database name */
8563    char const *zName,            /* Table name */
8564    sqlite3_int64 iKey1,          /* Rowid of row about to be deleted/updated */
8565    sqlite3_int64 iKey2           /* New rowid value (for a rowid UPDATE) */
8566  ),
8567  void*
8568);
8569SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
8570SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
8571SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
8572SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
8573#endif
8574
8575/*
8576** CAPI3REF: Low-level system error code
8577**
8578** ^Attempt to return the underlying operating system error code or error
8579** number that caused the most recent I/O error or failure to open a file.
8580** The return value is OS-dependent.  For example, on unix systems, after
8581** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
8582** called to get back the underlying "errno" that caused the problem, such
8583** as ENOSPC, EAUTH, EISDIR, and so forth.
8584*/
8585SQLITE_API int sqlite3_system_errno(sqlite3*);
8586
8587/*
8588** CAPI3REF: Database Snapshot
8589** KEYWORDS: {snapshot} {sqlite3_snapshot}
8590** EXPERIMENTAL
8591**
8592** An instance of the snapshot object records the state of a [WAL mode]
8593** database for some specific point in history.
8594**
8595** In [WAL mode], multiple [database connections] that are open on the
8596** same database file can each be reading a different historical version
8597** of the database file.  When a [database connection] begins a read
8598** transaction, that connection sees an unchanging copy of the database
8599** as it existed for the point in time when the transaction first started.
8600** Subsequent changes to the database from other connections are not seen
8601** by the reader until a new read transaction is started.
8602**
8603** The sqlite3_snapshot object records state information about an historical
8604** version of the database file so that it is possible to later open a new read
8605** transaction that sees that historical version of the database rather than
8606** the most recent version.
8607**
8608** The constructor for this object is [sqlite3_snapshot_get()].  The
8609** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
8610** to an historical snapshot (if possible).  The destructor for
8611** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
8612*/
8613typedef struct sqlite3_snapshot {
8614  unsigned char hidden[48];
8615} sqlite3_snapshot;
8616
8617/*
8618** CAPI3REF: Record A Database Snapshot
8619** EXPERIMENTAL
8620**
8621** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
8622** new [sqlite3_snapshot] object that records the current state of
8623** schema S in database connection D.  ^On success, the
8624** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
8625** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
8626** If there is not already a read-transaction open on schema S when
8627** this function is called, one is opened automatically.
8628**
8629** The following must be true for this function to succeed. If any of
8630** the following statements are false when sqlite3_snapshot_get() is
8631** called, SQLITE_ERROR is returned. The final value of *P is undefined
8632** in this case.
8633**
8634** <ul>
8635**   <li> The database handle must be in [autocommit mode].
8636**
8637**   <li> Schema S of [database connection] D must be a [WAL mode] database.
8638**
8639**   <li> There must not be a write transaction open on schema S of database
8640**        connection D.
8641**
8642**   <li> One or more transactions must have been written to the current wal
8643**        file since it was created on disk (by any connection). This means
8644**        that a snapshot cannot be taken on a wal mode database with no wal
8645**        file immediately after it is first opened. At least one transaction
8646**        must be written to it first.
8647** </ul>
8648**
8649** This function may also return SQLITE_NOMEM.  If it is called with the
8650** database handle in autocommit mode but fails for some other reason,
8651** whether or not a read transaction is opened on schema S is undefined.
8652**
8653** The [sqlite3_snapshot] object returned from a successful call to
8654** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
8655** to avoid a memory leak.
8656**
8657** The [sqlite3_snapshot_get()] interface is only available when the
8658** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8659*/
8660SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
8661  sqlite3 *db,
8662  const char *zSchema,
8663  sqlite3_snapshot **ppSnapshot
8664);
8665
8666/*
8667** CAPI3REF: Start a read transaction on an historical snapshot
8668** EXPERIMENTAL
8669**
8670** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
8671** read transaction for schema S of
8672** [database connection] D such that the read transaction
8673** refers to historical [snapshot] P, rather than the most
8674** recent change to the database.
8675** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
8676** or an appropriate [error code] if it fails.
8677**
8678** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
8679** the first operation following the [BEGIN] that takes the schema S
8680** out of [autocommit mode].
8681** ^In other words, schema S must not currently be in
8682** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
8683** database connection D must be out of [autocommit mode].
8684** ^A [snapshot] will fail to open if it has been overwritten by a
8685** [checkpoint].
8686** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
8687** database connection D does not know that the database file for
8688** schema S is in [WAL mode].  A database connection might not know
8689** that the database file is in [WAL mode] if there has been no prior
8690** I/O on that database connection, or if the database entered [WAL mode]
8691** after the most recent I/O on the database connection.)^
8692** (Hint: Run "[PRAGMA application_id]" against a newly opened
8693** database connection in order to make it ready to use snapshots.)
8694**
8695** The [sqlite3_snapshot_open()] interface is only available when the
8696** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8697*/
8698SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
8699  sqlite3 *db,
8700  const char *zSchema,
8701  sqlite3_snapshot *pSnapshot
8702);
8703
8704/*
8705** CAPI3REF: Destroy a snapshot
8706** EXPERIMENTAL
8707**
8708** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
8709** The application must eventually free every [sqlite3_snapshot] object
8710** using this routine to avoid a memory leak.
8711**
8712** The [sqlite3_snapshot_free()] interface is only available when the
8713** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8714*/
8715SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
8716
8717/*
8718** CAPI3REF: Compare the ages of two snapshot handles.
8719** EXPERIMENTAL
8720**
8721** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
8722** of two valid snapshot handles.
8723**
8724** If the two snapshot handles are not associated with the same database
8725** file, the result of the comparison is undefined.
8726**
8727** Additionally, the result of the comparison is only valid if both of the
8728** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
8729** last time the wal file was deleted. The wal file is deleted when the
8730** database is changed back to rollback mode or when the number of database
8731** clients drops to zero. If either snapshot handle was obtained before the
8732** wal file was last deleted, the value returned by this function
8733** is undefined.
8734**
8735** Otherwise, this API returns a negative value if P1 refers to an older
8736** snapshot than P2, zero if the two handles refer to the same database
8737** snapshot, and a positive value if P1 is a newer snapshot than P2.
8738*/
8739SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
8740  sqlite3_snapshot *p1,
8741  sqlite3_snapshot *p2
8742);
8743
8744/*
8745** CAPI3REF: Recover snapshots from a wal file
8746** EXPERIMENTAL
8747**
8748** If all connections disconnect from a database file but do not perform
8749** a checkpoint, the existing wal file is opened along with the database
8750** file the next time the database is opened. At this point it is only
8751** possible to successfully call sqlite3_snapshot_open() to open the most
8752** recent snapshot of the database (the one at the head of the wal file),
8753** even though the wal file may contain other valid snapshots for which
8754** clients have sqlite3_snapshot handles.
8755**
8756** This function attempts to scan the wal file associated with database zDb
8757** of database handle db and make all valid snapshots available to
8758** sqlite3_snapshot_open(). It is an error if there is already a read
8759** transaction open on the database, or if the database is not a wal mode
8760** database.
8761**
8762** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
8763*/
8764SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
8765
8766/*
8767** Undo the hack that converts floating point types to integer for
8768** builds on processors without floating point support.
8769*/
8770#ifdef SQLITE_OMIT_FLOATING_POINT
8771# undef double
8772#endif
8773
8774#if 0
8775}  /* End of the 'extern "C"' block */
8776#endif
8777#endif /* SQLITE3_H */
8778
8779/******** Begin file sqlite3rtree.h *********/
8780/*
8781** 2010 August 30
8782**
8783** The author disclaims copyright to this source code.  In place of
8784** a legal notice, here is a blessing:
8785**
8786**    May you do good and not evil.
8787**    May you find forgiveness for yourself and forgive others.
8788**    May you share freely, never taking more than you give.
8789**
8790*************************************************************************
8791*/
8792
8793#ifndef _SQLITE3RTREE_H_
8794#define _SQLITE3RTREE_H_
8795
8796
8797#if 0
8798extern "C" {
8799#endif
8800
8801typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
8802typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
8803
8804/* The double-precision datatype used by RTree depends on the
8805** SQLITE_RTREE_INT_ONLY compile-time option.
8806*/
8807#ifdef SQLITE_RTREE_INT_ONLY
8808  typedef sqlite3_int64 sqlite3_rtree_dbl;
8809#else
8810  typedef double sqlite3_rtree_dbl;
8811#endif
8812
8813/*
8814** Register a geometry callback named zGeom that can be used as part of an
8815** R-Tree geometry query as follows:
8816**
8817**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
8818*/
8819SQLITE_API int sqlite3_rtree_geometry_callback(
8820  sqlite3 *db,
8821  const char *zGeom,
8822  int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
8823  void *pContext
8824);
8825
8826
8827/*
8828** A pointer to a structure of the following type is passed as the first
8829** argument to callbacks registered using rtree_geometry_callback().
8830*/
8831struct sqlite3_rtree_geometry {
8832  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
8833  int nParam;                     /* Size of array aParam[] */
8834  sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */
8835  void *pUser;                    /* Callback implementation user data */
8836  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
8837};
8838
8839/*
8840** Register a 2nd-generation geometry callback named zScore that can be
8841** used as part of an R-Tree geometry query as follows:
8842**
8843**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
8844*/
8845SQLITE_API int sqlite3_rtree_query_callback(
8846  sqlite3 *db,
8847  const char *zQueryFunc,
8848  int (*xQueryFunc)(sqlite3_rtree_query_info*),
8849  void *pContext,
8850  void (*xDestructor)(void*)
8851);
8852
8853
8854/*
8855** A pointer to a structure of the following type is passed as the
8856** argument to scored geometry callback registered using
8857** sqlite3_rtree_query_callback().
8858**
8859** Note that the first 5 fields of this structure are identical to
8860** sqlite3_rtree_geometry.  This structure is a subclass of
8861** sqlite3_rtree_geometry.
8862*/
8863struct sqlite3_rtree_query_info {
8864  void *pContext;                   /* pContext from when function registered */
8865  int nParam;                       /* Number of function parameters */
8866  sqlite3_rtree_dbl *aParam;        /* value of function parameters */
8867  void *pUser;                      /* callback can use this, if desired */
8868  void (*xDelUser)(void*);          /* function to free pUser */
8869  sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
8870  unsigned int *anQueue;            /* Number of pending entries in the queue */
8871  int nCoord;                       /* Number of coordinates */
8872  int iLevel;                       /* Level of current node or entry */
8873  int mxLevel;                      /* The largest iLevel value in the tree */
8874  sqlite3_int64 iRowid;             /* Rowid for current entry */
8875  sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
8876  int eParentWithin;                /* Visibility of parent node */
8877  int eWithin;                      /* OUT: Visiblity */
8878  sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
8879  /* The following fields are only available in 3.8.11 and later */
8880  sqlite3_value **apSqlParam;       /* Original SQL values of parameters */
8881};
8882
8883/*
8884** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
8885*/
8886#define NOT_WITHIN       0   /* Object completely outside of query region */
8887#define PARTLY_WITHIN    1   /* Object partially overlaps query region */
8888#define FULLY_WITHIN     2   /* Object fully contained within query region */
8889
8890
8891#if 0
8892}  /* end of the 'extern "C"' block */
8893#endif
8894
8895#endif  /* ifndef _SQLITE3RTREE_H_ */
8896
8897/******** End of sqlite3rtree.h *********/
8898/******** Begin file sqlite3session.h *********/
8899
8900#if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
8901#define __SQLITESESSION_H_ 1
8902
8903/*
8904** Make sure we can call this stuff from C++.
8905*/
8906#if 0
8907extern "C" {
8908#endif
8909
8910
8911/*
8912** CAPI3REF: Session Object Handle
8913*/
8914typedef struct sqlite3_session sqlite3_session;
8915
8916/*
8917** CAPI3REF: Changeset Iterator Handle
8918*/
8919typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
8920
8921/*
8922** CAPI3REF: Create A New Session Object
8923**
8924** Create a new session object attached to database handle db. If successful,
8925** a pointer to the new object is written to *ppSession and SQLITE_OK is
8926** returned. If an error occurs, *ppSession is set to NULL and an SQLite
8927** error code (e.g. SQLITE_NOMEM) is returned.
8928**
8929** It is possible to create multiple session objects attached to a single
8930** database handle.
8931**
8932** Session objects created using this function should be deleted using the
8933** [sqlite3session_delete()] function before the database handle that they
8934** are attached to is itself closed. If the database handle is closed before
8935** the session object is deleted, then the results of calling any session
8936** module function, including [sqlite3session_delete()] on the session object
8937** are undefined.
8938**
8939** Because the session module uses the [sqlite3_preupdate_hook()] API, it
8940** is not possible for an application to register a pre-update hook on a
8941** database handle that has one or more session objects attached. Nor is
8942** it possible to create a session object attached to a database handle for
8943** which a pre-update hook is already defined. The results of attempting
8944** either of these things are undefined.
8945**
8946** The session object will be used to create changesets for tables in
8947** database zDb, where zDb is either "main", or "temp", or the name of an
8948** attached database. It is not an error if database zDb is not attached
8949** to the database when the session object is created.
8950*/
8951SQLITE_API int sqlite3session_create(
8952  sqlite3 *db,                    /* Database handle */
8953  const char *zDb,                /* Name of db (e.g. "main") */
8954  sqlite3_session **ppSession     /* OUT: New session object */
8955);
8956
8957/*
8958** CAPI3REF: Delete A Session Object
8959**
8960** Delete a session object previously allocated using
8961** [sqlite3session_create()]. Once a session object has been deleted, the
8962** results of attempting to use pSession with any other session module
8963** function are undefined.
8964**
8965** Session objects must be deleted before the database handle to which they
8966** are attached is closed. Refer to the documentation for
8967** [sqlite3session_create()] for details.
8968*/
8969SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
8970
8971
8972/*
8973** CAPI3REF: Enable Or Disable A Session Object
8974**
8975** Enable or disable the recording of changes by a session object. When
8976** enabled, a session object records changes made to the database. When
8977** disabled - it does not. A newly created session object is enabled.
8978** Refer to the documentation for [sqlite3session_changeset()] for further
8979** details regarding how enabling and disabling a session object affects
8980** the eventual changesets.
8981**
8982** Passing zero to this function disables the session. Passing a value
8983** greater than zero enables it. Passing a value less than zero is a
8984** no-op, and may be used to query the current state of the session.
8985**
8986** The return value indicates the final state of the session object: 0 if
8987** the session is disabled, or 1 if it is enabled.
8988*/
8989SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
8990
8991/*
8992** CAPI3REF: Set Or Clear the Indirect Change Flag
8993**
8994** Each change recorded by a session object is marked as either direct or
8995** indirect. A change is marked as indirect if either:
8996**
8997** <ul>
8998**   <li> The session object "indirect" flag is set when the change is
8999**        made, or
9000**   <li> The change is made by an SQL trigger or foreign key action
9001**        instead of directly as a result of a users SQL statement.
9002** </ul>
9003**
9004** If a single row is affected by more than one operation within a session,
9005** then the change is considered indirect if all operations meet the criteria
9006** for an indirect change above, or direct otherwise.
9007**
9008** This function is used to set, clear or query the session object indirect
9009** flag.  If the second argument passed to this function is zero, then the
9010** indirect flag is cleared. If it is greater than zero, the indirect flag
9011** is set. Passing a value less than zero does not modify the current value
9012** of the indirect flag, and may be used to query the current state of the
9013** indirect flag for the specified session object.
9014**
9015** The return value indicates the final state of the indirect flag: 0 if
9016** it is clear, or 1 if it is set.
9017*/
9018SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
9019
9020/*
9021** CAPI3REF: Attach A Table To A Session Object
9022**
9023** If argument zTab is not NULL, then it is the name of a table to attach
9024** to the session object passed as the first argument. All subsequent changes
9025** made to the table while the session object is enabled will be recorded. See
9026** documentation for [sqlite3session_changeset()] for further details.
9027**
9028** Or, if argument zTab is NULL, then changes are recorded for all tables
9029** in the database. If additional tables are added to the database (by
9030** executing "CREATE TABLE" statements) after this call is made, changes for
9031** the new tables are also recorded.
9032**
9033** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
9034** defined as part of their CREATE TABLE statement. It does not matter if the
9035** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
9036** KEY may consist of a single column, or may be a composite key.
9037**
9038** It is not an error if the named table does not exist in the database. Nor
9039** is it an error if the named table does not have a PRIMARY KEY. However,
9040** no changes will be recorded in either of these scenarios.
9041**
9042** Changes are not recorded for individual rows that have NULL values stored
9043** in one or more of their PRIMARY KEY columns.
9044**
9045** SQLITE_OK is returned if the call completes without error. Or, if an error
9046** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
9047*/
9048SQLITE_API int sqlite3session_attach(
9049  sqlite3_session *pSession,      /* Session object */
9050  const char *zTab                /* Table name */
9051);
9052
9053/*
9054** CAPI3REF: Set a table filter on a Session Object.
9055**
9056** The second argument (xFilter) is the "filter callback". For changes to rows
9057** in tables that are not attached to the Session object, the filter is called
9058** to determine whether changes to the table's rows should be tracked or not.
9059** If xFilter returns 0, changes is not tracked. Note that once a table is
9060** attached, xFilter will not be called again.
9061*/
9062SQLITE_API void sqlite3session_table_filter(
9063  sqlite3_session *pSession,      /* Session object */
9064  int(*xFilter)(
9065    void *pCtx,                   /* Copy of third arg to _filter_table() */
9066    const char *zTab              /* Table name */
9067  ),
9068  void *pCtx                      /* First argument passed to xFilter */
9069);
9070
9071/*
9072** CAPI3REF: Generate A Changeset From A Session Object
9073**
9074** Obtain a changeset containing changes to the tables attached to the
9075** session object passed as the first argument. If successful,
9076** set *ppChangeset to point to a buffer containing the changeset
9077** and *pnChangeset to the size of the changeset in bytes before returning
9078** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
9079** zero and return an SQLite error code.
9080**
9081** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
9082** each representing a change to a single row of an attached table. An INSERT
9083** change contains the values of each field of a new database row. A DELETE
9084** contains the original values of each field of a deleted database row. An
9085** UPDATE change contains the original values of each field of an updated
9086** database row along with the updated values for each updated non-primary-key
9087** column. It is not possible for an UPDATE change to represent a change that
9088** modifies the values of primary key columns. If such a change is made, it
9089** is represented in a changeset as a DELETE followed by an INSERT.
9090**
9091** Changes are not recorded for rows that have NULL values stored in one or
9092** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
9093** no corresponding change is present in the changesets returned by this
9094** function. If an existing row with one or more NULL values stored in
9095** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
9096** only an INSERT is appears in the changeset. Similarly, if an existing row
9097** with non-NULL PRIMARY KEY values is updated so that one or more of its
9098** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
9099** DELETE change only.
9100**
9101** The contents of a changeset may be traversed using an iterator created
9102** using the [sqlite3changeset_start()] API. A changeset may be applied to
9103** a database with a compatible schema using the [sqlite3changeset_apply()]
9104** API.
9105**
9106** Within a changeset generated by this function, all changes related to a
9107** single table are grouped together. In other words, when iterating through
9108** a changeset or when applying a changeset to a database, all changes related
9109** to a single table are processed before moving on to the next table. Tables
9110** are sorted in the same order in which they were attached (or auto-attached)
9111** to the sqlite3_session object. The order in which the changes related to
9112** a single table are stored is undefined.
9113**
9114** Following a successful call to this function, it is the responsibility of
9115** the caller to eventually free the buffer that *ppChangeset points to using
9116** [sqlite3_free()].
9117**
9118** <h3>Changeset Generation</h3>
9119**
9120** Once a table has been attached to a session object, the session object
9121** records the primary key values of all new rows inserted into the table.
9122** It also records the original primary key and other column values of any
9123** deleted or updated rows. For each unique primary key value, data is only
9124** recorded once - the first time a row with said primary key is inserted,
9125** updated or deleted in the lifetime of the session.
9126**
9127** There is one exception to the previous paragraph: when a row is inserted,
9128** updated or deleted, if one or more of its primary key columns contain a
9129** NULL value, no record of the change is made.
9130**
9131** The session object therefore accumulates two types of records - those
9132** that consist of primary key values only (created when the user inserts
9133** a new record) and those that consist of the primary key values and the
9134** original values of other table columns (created when the users deletes
9135** or updates a record).
9136**
9137** When this function is called, the requested changeset is created using
9138** both the accumulated records and the current contents of the database
9139** file. Specifically:
9140**
9141** <ul>
9142**   <li> For each record generated by an insert, the database is queried
9143**        for a row with a matching primary key. If one is found, an INSERT
9144**        change is added to the changeset. If no such row is found, no change
9145**        is added to the changeset.
9146**
9147**   <li> For each record generated by an update or delete, the database is
9148**        queried for a row with a matching primary key. If such a row is
9149**        found and one or more of the non-primary key fields have been
9150**        modified from their original values, an UPDATE change is added to
9151**        the changeset. Or, if no such row is found in the table, a DELETE
9152**        change is added to the changeset. If there is a row with a matching
9153**        primary key in the database, but all fields contain their original
9154**        values, no change is added to the changeset.
9155** </ul>
9156**
9157** This means, amongst other things, that if a row is inserted and then later
9158** deleted while a session object is active, neither the insert nor the delete
9159** will be present in the changeset. Or if a row is deleted and then later a
9160** row with the same primary key values inserted while a session object is
9161** active, the resulting changeset will contain an UPDATE change instead of
9162** a DELETE and an INSERT.
9163**
9164** When a session object is disabled (see the [sqlite3session_enable()] API),
9165** it does not accumulate records when rows are inserted, updated or deleted.
9166** This may appear to have some counter-intuitive effects if a single row
9167** is written to more than once during a session. For example, if a row
9168** is inserted while a session object is enabled, then later deleted while
9169** the same session object is disabled, no INSERT record will appear in the
9170** changeset, even though the delete took place while the session was disabled.
9171** Or, if one field of a row is updated while a session is disabled, and
9172** another field of the same row is updated while the session is enabled, the
9173** resulting changeset will contain an UPDATE change that updates both fields.
9174*/
9175SQLITE_API int sqlite3session_changeset(
9176  sqlite3_session *pSession,      /* Session object */
9177  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
9178  void **ppChangeset              /* OUT: Buffer containing changeset */
9179);
9180
9181/*
9182** CAPI3REF: Load The Difference Between Tables Into A Session
9183**
9184** If it is not already attached to the session object passed as the first
9185** argument, this function attaches table zTbl in the same manner as the
9186** [sqlite3session_attach()] function. If zTbl does not exist, or if it
9187** does not have a primary key, this function is a no-op (but does not return
9188** an error).
9189**
9190** Argument zFromDb must be the name of a database ("main", "temp" etc.)
9191** attached to the same database handle as the session object that contains
9192** a table compatible with the table attached to the session by this function.
9193** A table is considered compatible if it:
9194**
9195** <ul>
9196**   <li> Has the same name,
9197**   <li> Has the same set of columns declared in the same order, and
9198**   <li> Has the same PRIMARY KEY definition.
9199** </ul>
9200**
9201** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
9202** are compatible but do not have any PRIMARY KEY columns, it is not an error
9203** but no changes are added to the session object. As with other session
9204** APIs, tables without PRIMARY KEYs are simply ignored.
9205**
9206** This function adds a set of changes to the session object that could be
9207** used to update the table in database zFrom (call this the "from-table")
9208** so that its content is the same as the table attached to the session
9209** object (call this the "to-table"). Specifically:
9210**
9211** <ul>
9212**   <li> For each row (primary key) that exists in the to-table but not in
9213**     the from-table, an INSERT record is added to the session object.
9214**
9215**   <li> For each row (primary key) that exists in the to-table but not in
9216**     the from-table, a DELETE record is added to the session object.
9217**
9218**   <li> For each row (primary key) that exists in both tables, but features
9219**     different non-PK values in each, an UPDATE record is added to the
9220**     session.
9221** </ul>
9222**
9223** To clarify, if this function is called and then a changeset constructed
9224** using [sqlite3session_changeset()], then after applying that changeset to
9225** database zFrom the contents of the two compatible tables would be
9226** identical.
9227**
9228** It an error if database zFrom does not exist or does not contain the
9229** required compatible table.
9230**
9231** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
9232** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
9233** may be set to point to a buffer containing an English language error
9234** message. It is the responsibility of the caller to free this buffer using
9235** sqlite3_free().
9236*/
9237SQLITE_API int sqlite3session_diff(
9238  sqlite3_session *pSession,
9239  const char *zFromDb,
9240  const char *zTbl,
9241  char **pzErrMsg
9242);
9243
9244
9245/*
9246** CAPI3REF: Generate A Patchset From A Session Object
9247**
9248** The differences between a patchset and a changeset are that:
9249**
9250** <ul>
9251**   <li> DELETE records consist of the primary key fields only. The
9252**        original values of other fields are omitted.
9253**   <li> The original values of any modified fields are omitted from
9254**        UPDATE records.
9255** </ul>
9256**
9257** A patchset blob may be used with up to date versions of all
9258** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
9259** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
9260** attempting to use a patchset blob with old versions of the
9261** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
9262**
9263** Because the non-primary key "old.*" fields are omitted, no
9264** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
9265** is passed to the sqlite3changeset_apply() API. Other conflict types work
9266** in the same way as for changesets.
9267**
9268** Changes within a patchset are ordered in the same way as for changesets
9269** generated by the sqlite3session_changeset() function (i.e. all changes for
9270** a single table are grouped together, tables appear in the order in which
9271** they were attached to the session object).
9272*/
9273SQLITE_API int sqlite3session_patchset(
9274  sqlite3_session *pSession,      /* Session object */
9275  int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
9276  void **ppPatchset               /* OUT: Buffer containing changeset */
9277);
9278
9279/*
9280** CAPI3REF: Test if a changeset has recorded any changes.
9281**
9282** Return non-zero if no changes to attached tables have been recorded by
9283** the session object passed as the first argument. Otherwise, if one or
9284** more changes have been recorded, return zero.
9285**
9286** Even if this function returns zero, it is possible that calling
9287** [sqlite3session_changeset()] on the session handle may still return a
9288** changeset that contains no changes. This can happen when a row in
9289** an attached table is modified and then later on the original values
9290** are restored. However, if this function returns non-zero, then it is
9291** guaranteed that a call to sqlite3session_changeset() will return a
9292** changeset containing zero changes.
9293*/
9294SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
9295
9296/*
9297** CAPI3REF: Create An Iterator To Traverse A Changeset
9298**
9299** Create an iterator used to iterate through the contents of a changeset.
9300** If successful, *pp is set to point to the iterator handle and SQLITE_OK
9301** is returned. Otherwise, if an error occurs, *pp is set to zero and an
9302** SQLite error code is returned.
9303**
9304** The following functions can be used to advance and query a changeset
9305** iterator created by this function:
9306**
9307** <ul>
9308**   <li> [sqlite3changeset_next()]
9309**   <li> [sqlite3changeset_op()]
9310**   <li> [sqlite3changeset_new()]
9311**   <li> [sqlite3changeset_old()]
9312** </ul>
9313**
9314** It is the responsibility of the caller to eventually destroy the iterator
9315** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
9316** changeset (pChangeset) must remain valid until after the iterator is
9317** destroyed.
9318**
9319** Assuming the changeset blob was created by one of the
9320** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
9321** [sqlite3changeset_invert()] functions, all changes within the changeset
9322** that apply to a single table are grouped together. This means that when
9323** an application iterates through a changeset using an iterator created by
9324** this function, all changes that relate to a single table are visited
9325** consecutively. There is no chance that the iterator will visit a change
9326** the applies to table X, then one for table Y, and then later on visit
9327** another change for table X.
9328*/
9329SQLITE_API int sqlite3changeset_start(
9330  sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */
9331  int nChangeset,                 /* Size of changeset blob in bytes */
9332  void *pChangeset                /* Pointer to blob containing changeset */
9333);
9334
9335
9336/*
9337** CAPI3REF: Advance A Changeset Iterator
9338**
9339** This function may only be used with iterators created by function
9340** [sqlite3changeset_start()]. If it is called on an iterator passed to
9341** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
9342** is returned and the call has no effect.
9343**
9344** Immediately after an iterator is created by sqlite3changeset_start(), it
9345** does not point to any change in the changeset. Assuming the changeset
9346** is not empty, the first call to this function advances the iterator to
9347** point to the first change in the changeset. Each subsequent call advances
9348** the iterator to point to the next change in the changeset (if any). If
9349** no error occurs and the iterator points to a valid change after a call
9350** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
9351** Otherwise, if all changes in the changeset have already been visited,
9352** SQLITE_DONE is returned.
9353**
9354** If an error occurs, an SQLite error code is returned. Possible error
9355** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
9356** SQLITE_NOMEM.
9357*/
9358SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
9359
9360/*
9361** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
9362**
9363** The pIter argument passed to this function may either be an iterator
9364** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9365** created by [sqlite3changeset_start()]. In the latter case, the most recent
9366** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
9367** is not the case, this function returns [SQLITE_MISUSE].
9368**
9369** If argument pzTab is not NULL, then *pzTab is set to point to a
9370** nul-terminated utf-8 encoded string containing the name of the table
9371** affected by the current change. The buffer remains valid until either
9372** sqlite3changeset_next() is called on the iterator or until the
9373** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
9374** set to the number of columns in the table affected by the change. If
9375** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
9376** is an indirect change, or false (0) otherwise. See the documentation for
9377** [sqlite3session_indirect()] for a description of direct and indirect
9378** changes. Finally, if pOp is not NULL, then *pOp is set to one of
9379** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
9380** type of change that the iterator currently points to.
9381**
9382** If no error occurs, SQLITE_OK is returned. If an error does occur, an
9383** SQLite error code is returned. The values of the output variables may not
9384** be trusted in this case.
9385*/
9386SQLITE_API int sqlite3changeset_op(
9387  sqlite3_changeset_iter *pIter,  /* Iterator object */
9388  const char **pzTab,             /* OUT: Pointer to table name */
9389  int *pnCol,                     /* OUT: Number of columns in table */
9390  int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
9391  int *pbIndirect                 /* OUT: True for an 'indirect' change */
9392);
9393
9394/*
9395** CAPI3REF: Obtain The Primary Key Definition Of A Table
9396**
9397** For each modified table, a changeset includes the following:
9398**
9399** <ul>
9400**   <li> The number of columns in the table, and
9401**   <li> Which of those columns make up the tables PRIMARY KEY.
9402** </ul>
9403**
9404** This function is used to find which columns comprise the PRIMARY KEY of
9405** the table modified by the change that iterator pIter currently points to.
9406** If successful, *pabPK is set to point to an array of nCol entries, where
9407** nCol is the number of columns in the table. Elements of *pabPK are set to
9408** 0x01 if the corresponding column is part of the tables primary key, or
9409** 0x00 if it is not.
9410**
9411** If argument pnCol is not NULL, then *pnCol is set to the number of columns
9412** in the table.
9413**
9414** If this function is called when the iterator does not point to a valid
9415** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
9416** SQLITE_OK is returned and the output variables populated as described
9417** above.
9418*/
9419SQLITE_API int sqlite3changeset_pk(
9420  sqlite3_changeset_iter *pIter,  /* Iterator object */
9421  unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
9422  int *pnCol                      /* OUT: Number of entries in output array */
9423);
9424
9425/*
9426** CAPI3REF: Obtain old.* Values From A Changeset Iterator
9427**
9428** The pIter argument passed to this function may either be an iterator
9429** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9430** created by [sqlite3changeset_start()]. In the latter case, the most recent
9431** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9432** Furthermore, it may only be called if the type of change that the iterator
9433** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
9434** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9435**
9436** Argument iVal must be greater than or equal to 0, and less than the number
9437** of columns in the table affected by the current change. Otherwise,
9438** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9439**
9440** If successful, this function sets *ppValue to point to a protected
9441** sqlite3_value object containing the iVal'th value from the vector of
9442** original row values stored as part of the UPDATE or DELETE change and
9443** returns SQLITE_OK. The name of the function comes from the fact that this
9444** is similar to the "old.*" columns available to update or delete triggers.
9445**
9446** If some other error occurs (e.g. an OOM condition), an SQLite error code
9447** is returned and *ppValue is set to NULL.
9448*/
9449SQLITE_API int sqlite3changeset_old(
9450  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
9451  int iVal,                       /* Column number */
9452  sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
9453);
9454
9455/*
9456** CAPI3REF: Obtain new.* Values From A Changeset Iterator
9457**
9458** The pIter argument passed to this function may either be an iterator
9459** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9460** created by [sqlite3changeset_start()]. In the latter case, the most recent
9461** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9462** Furthermore, it may only be called if the type of change that the iterator
9463** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
9464** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9465**
9466** Argument iVal must be greater than or equal to 0, and less than the number
9467** of columns in the table affected by the current change. Otherwise,
9468** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9469**
9470** If successful, this function sets *ppValue to point to a protected
9471** sqlite3_value object containing the iVal'th value from the vector of
9472** new row values stored as part of the UPDATE or INSERT change and
9473** returns SQLITE_OK. If the change is an UPDATE and does not include
9474** a new value for the requested column, *ppValue is set to NULL and
9475** SQLITE_OK returned. The name of the function comes from the fact that
9476** this is similar to the "new.*" columns available to update or delete
9477** triggers.
9478**
9479** If some other error occurs (e.g. an OOM condition), an SQLite error code
9480** is returned and *ppValue is set to NULL.
9481*/
9482SQLITE_API int sqlite3changeset_new(
9483  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
9484  int iVal,                       /* Column number */
9485  sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
9486);
9487
9488/*
9489** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
9490**
9491** This function should only be used with iterator objects passed to a
9492** conflict-handler callback by [sqlite3changeset_apply()] with either
9493** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
9494** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
9495** is set to NULL.
9496**
9497** Argument iVal must be greater than or equal to 0, and less than the number
9498** of columns in the table affected by the current change. Otherwise,
9499** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9500**
9501** If successful, this function sets *ppValue to point to a protected
9502** sqlite3_value object containing the iVal'th value from the
9503** "conflicting row" associated with the current conflict-handler callback
9504** and returns SQLITE_OK.
9505**
9506** If some other error occurs (e.g. an OOM condition), an SQLite error code
9507** is returned and *ppValue is set to NULL.
9508*/
9509SQLITE_API int sqlite3changeset_conflict(
9510  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
9511  int iVal,                       /* Column number */
9512  sqlite3_value **ppValue         /* OUT: Value from conflicting row */
9513);
9514
9515/*
9516** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
9517**
9518** This function may only be called with an iterator passed to an
9519** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
9520** it sets the output variable to the total number of known foreign key
9521** violations in the destination database and returns SQLITE_OK.
9522**
9523** In all other cases this function returns SQLITE_MISUSE.
9524*/
9525SQLITE_API int sqlite3changeset_fk_conflicts(
9526  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
9527  int *pnOut                      /* OUT: Number of FK violations */
9528);
9529
9530
9531/*
9532** CAPI3REF: Finalize A Changeset Iterator
9533**
9534** This function is used to finalize an iterator allocated with
9535** [sqlite3changeset_start()].
9536**
9537** This function should only be called on iterators created using the
9538** [sqlite3changeset_start()] function. If an application calls this
9539** function with an iterator passed to a conflict-handler by
9540** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
9541** call has no effect.
9542**
9543** If an error was encountered within a call to an sqlite3changeset_xxx()
9544** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
9545** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
9546** to that error is returned by this function. Otherwise, SQLITE_OK is
9547** returned. This is to allow the following pattern (pseudo-code):
9548**
9549**   sqlite3changeset_start();
9550**   while( SQLITE_ROW==sqlite3changeset_next() ){
9551**     // Do something with change.
9552**   }
9553**   rc = sqlite3changeset_finalize();
9554**   if( rc!=SQLITE_OK ){
9555**     // An error has occurred
9556**   }
9557*/
9558SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
9559
9560/*
9561** CAPI3REF: Invert A Changeset
9562**
9563** This function is used to "invert" a changeset object. Applying an inverted
9564** changeset to a database reverses the effects of applying the uninverted
9565** changeset. Specifically:
9566**
9567** <ul>
9568**   <li> Each DELETE change is changed to an INSERT, and
9569**   <li> Each INSERT change is changed to a DELETE, and
9570**   <li> For each UPDATE change, the old.* and new.* values are exchanged.
9571** </ul>
9572**
9573** This function does not change the order in which changes appear within
9574** the changeset. It merely reverses the sense of each individual change.
9575**
9576** If successful, a pointer to a buffer containing the inverted changeset
9577** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
9578** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
9579** zeroed and an SQLite error code returned.
9580**
9581** It is the responsibility of the caller to eventually call sqlite3_free()
9582** on the *ppOut pointer to free the buffer allocation following a successful
9583** call to this function.
9584**
9585** WARNING/TODO: This function currently assumes that the input is a valid
9586** changeset. If it is not, the results are undefined.
9587*/
9588SQLITE_API int sqlite3changeset_invert(
9589  int nIn, const void *pIn,       /* Input changeset */
9590  int *pnOut, void **ppOut        /* OUT: Inverse of input */
9591);
9592
9593/*
9594** CAPI3REF: Concatenate Two Changeset Objects
9595**
9596** This function is used to concatenate two changesets, A and B, into a
9597** single changeset. The result is a changeset equivalent to applying
9598** changeset A followed by changeset B.
9599**
9600** This function combines the two input changesets using an
9601** sqlite3_changegroup object. Calling it produces similar results as the
9602** following code fragment:
9603**
9604**   sqlite3_changegroup *pGrp;
9605**   rc = sqlite3_changegroup_new(&pGrp);
9606**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
9607**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
9608**   if( rc==SQLITE_OK ){
9609**     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
9610**   }else{
9611**     *ppOut = 0;
9612**     *pnOut = 0;
9613**   }
9614**
9615** Refer to the sqlite3_changegroup documentation below for details.
9616*/
9617SQLITE_API int sqlite3changeset_concat(
9618  int nA,                         /* Number of bytes in buffer pA */
9619  void *pA,                       /* Pointer to buffer containing changeset A */
9620  int nB,                         /* Number of bytes in buffer pB */
9621  void *pB,                       /* Pointer to buffer containing changeset B */
9622  int *pnOut,                     /* OUT: Number of bytes in output changeset */
9623  void **ppOut                    /* OUT: Buffer containing output changeset */
9624);
9625
9626
9627/*
9628** CAPI3REF: Changegroup Handle
9629*/
9630typedef struct sqlite3_changegroup sqlite3_changegroup;
9631
9632/*
9633** CAPI3REF: Create A New Changegroup Object
9634**
9635** An sqlite3_changegroup object is used to combine two or more changesets
9636** (or patchsets) into a single changeset (or patchset). A single changegroup
9637** object may combine changesets or patchsets, but not both. The output is
9638** always in the same format as the input.
9639**
9640** If successful, this function returns SQLITE_OK and populates (*pp) with
9641** a pointer to a new sqlite3_changegroup object before returning. The caller
9642** should eventually free the returned object using a call to
9643** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
9644** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
9645**
9646** The usual usage pattern for an sqlite3_changegroup object is as follows:
9647**
9648** <ul>
9649**   <li> It is created using a call to sqlite3changegroup_new().
9650**
9651**   <li> Zero or more changesets (or patchsets) are added to the object
9652**        by calling sqlite3changegroup_add().
9653**
9654**   <li> The result of combining all input changesets together is obtained
9655**        by the application via a call to sqlite3changegroup_output().
9656**
9657**   <li> The object is deleted using a call to sqlite3changegroup_delete().
9658** </ul>
9659**
9660** Any number of calls to add() and output() may be made between the calls to
9661** new() and delete(), and in any order.
9662**
9663** As well as the regular sqlite3changegroup_add() and
9664** sqlite3changegroup_output() functions, also available are the streaming
9665** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
9666*/
9667int sqlite3changegroup_new(sqlite3_changegroup **pp);
9668
9669/*
9670** CAPI3REF: Add A Changeset To A Changegroup
9671**
9672** Add all changes within the changeset (or patchset) in buffer pData (size
9673** nData bytes) to the changegroup.
9674**
9675** If the buffer contains a patchset, then all prior calls to this function
9676** on the same changegroup object must also have specified patchsets. Or, if
9677** the buffer contains a changeset, so must have the earlier calls to this
9678** function. Otherwise, SQLITE_ERROR is returned and no changes are added
9679** to the changegroup.
9680**
9681** Rows within the changeset and changegroup are identified by the values in
9682** their PRIMARY KEY columns. A change in the changeset is considered to
9683** apply to the same row as a change already present in the changegroup if
9684** the two rows have the same primary key.
9685**
9686** Changes to rows that do not already appear in the changegroup are
9687** simply copied into it. Or, if both the new changeset and the changegroup
9688** contain changes that apply to a single row, the final contents of the
9689** changegroup depends on the type of each change, as follows:
9690**
9691** <table border=1 style="margin-left:8ex;margin-right:8ex">
9692**   <tr><th style="white-space:pre">Existing Change  </th>
9693**       <th style="white-space:pre">New Change       </th>
9694**       <th>Output Change
9695**   <tr><td>INSERT <td>INSERT <td>
9696**       The new change is ignored. This case does not occur if the new
9697**       changeset was recorded immediately after the changesets already
9698**       added to the changegroup.
9699**   <tr><td>INSERT <td>UPDATE <td>
9700**       The INSERT change remains in the changegroup. The values in the
9701**       INSERT change are modified as if the row was inserted by the
9702**       existing change and then updated according to the new change.
9703**   <tr><td>INSERT <td>DELETE <td>
9704**       The existing INSERT is removed from the changegroup. The DELETE is
9705**       not added.
9706**   <tr><td>UPDATE <td>INSERT <td>
9707**       The new change is ignored. This case does not occur if the new
9708**       changeset was recorded immediately after the changesets already
9709**       added to the changegroup.
9710**   <tr><td>UPDATE <td>UPDATE <td>
9711**       The existing UPDATE remains within the changegroup. It is amended
9712**       so that the accompanying values are as if the row was updated once
9713**       by the existing change and then again by the new change.
9714**   <tr><td>UPDATE <td>DELETE <td>
9715**       The existing UPDATE is replaced by the new DELETE within the
9716**       changegroup.
9717**   <tr><td>DELETE <td>INSERT <td>
9718**       If one or more of the column values in the row inserted by the
9719**       new change differ from those in the row deleted by the existing
9720**       change, the existing DELETE is replaced by an UPDATE within the
9721**       changegroup. Otherwise, if the inserted row is exactly the same
9722**       as the deleted row, the existing DELETE is simply discarded.
9723**   <tr><td>DELETE <td>UPDATE <td>
9724**       The new change is ignored. This case does not occur if the new
9725**       changeset was recorded immediately after the changesets already
9726**       added to the changegroup.
9727**   <tr><td>DELETE <td>DELETE <td>
9728**       The new change is ignored. This case does not occur if the new
9729**       changeset was recorded immediately after the changesets already
9730**       added to the changegroup.
9731** </table>
9732**
9733** If the new changeset contains changes to a table that is already present
9734** in the changegroup, then the number of columns and the position of the
9735** primary key columns for the table must be consistent. If this is not the
9736** case, this function fails with SQLITE_SCHEMA. If the input changeset
9737** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
9738** returned. Or, if an out-of-memory condition occurs during processing, this
9739** function returns SQLITE_NOMEM. In all cases, if an error occurs the
9740** final contents of the changegroup is undefined.
9741**
9742** If no error occurs, SQLITE_OK is returned.
9743*/
9744int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
9745
9746/*
9747** CAPI3REF: Obtain A Composite Changeset From A Changegroup
9748**
9749** Obtain a buffer containing a changeset (or patchset) representing the
9750** current contents of the changegroup. If the inputs to the changegroup
9751** were themselves changesets, the output is a changeset. Or, if the
9752** inputs were patchsets, the output is also a patchset.
9753**
9754** As with the output of the sqlite3session_changeset() and
9755** sqlite3session_patchset() functions, all changes related to a single
9756** table are grouped together in the output of this function. Tables appear
9757** in the same order as for the very first changeset added to the changegroup.
9758** If the second or subsequent changesets added to the changegroup contain
9759** changes for tables that do not appear in the first changeset, they are
9760** appended onto the end of the output changeset, again in the order in
9761** which they are first encountered.
9762**
9763** If an error occurs, an SQLite error code is returned and the output
9764** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
9765** is returned and the output variables are set to the size of and a
9766** pointer to the output buffer, respectively. In this case it is the
9767** responsibility of the caller to eventually free the buffer using a
9768** call to sqlite3_free().
9769*/
9770int sqlite3changegroup_output(
9771  sqlite3_changegroup*,
9772  int *pnData,                    /* OUT: Size of output buffer in bytes */
9773  void **ppData                   /* OUT: Pointer to output buffer */
9774);
9775
9776/*
9777** CAPI3REF: Delete A Changegroup Object
9778*/
9779void sqlite3changegroup_delete(sqlite3_changegroup*);
9780
9781/*
9782** CAPI3REF: Apply A Changeset To A Database
9783**
9784** Apply a changeset to a database. This function attempts to update the
9785** "main" database attached to handle db with the changes found in the
9786** changeset passed via the second and third arguments.
9787**
9788** The fourth argument (xFilter) passed to this function is the "filter
9789** callback". If it is not NULL, then for each table affected by at least one
9790** change in the changeset, the filter callback is invoked with
9791** the table name as the second argument, and a copy of the context pointer
9792** passed as the sixth argument to this function as the first. If the "filter
9793** callback" returns zero, then no attempt is made to apply any changes to
9794** the table. Otherwise, if the return value is non-zero or the xFilter
9795** argument to this function is NULL, all changes related to the table are
9796** attempted.
9797**
9798** For each table that is not excluded by the filter callback, this function
9799** tests that the target database contains a compatible table. A table is
9800** considered compatible if all of the following are true:
9801**
9802** <ul>
9803**   <li> The table has the same name as the name recorded in the
9804**        changeset, and
9805**   <li> The table has at least as many columns as recorded in the
9806**        changeset, and
9807**   <li> The table has primary key columns in the same position as
9808**        recorded in the changeset.
9809** </ul>
9810**
9811** If there is no compatible table, it is not an error, but none of the
9812** changes associated with the table are applied. A warning message is issued
9813** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
9814** one such warning is issued for each table in the changeset.
9815**
9816** For each change for which there is a compatible table, an attempt is made
9817** to modify the table contents according to the UPDATE, INSERT or DELETE
9818** change. If a change cannot be applied cleanly, the conflict handler
9819** function passed as the fifth argument to sqlite3changeset_apply() may be
9820** invoked. A description of exactly when the conflict handler is invoked for
9821** each type of change is below.
9822**
9823** Unlike the xFilter argument, xConflict may not be passed NULL. The results
9824** of passing anything other than a valid function pointer as the xConflict
9825** argument are undefined.
9826**
9827** Each time the conflict handler function is invoked, it must return one
9828** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
9829** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
9830** if the second argument passed to the conflict handler is either
9831** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
9832** returns an illegal value, any changes already made are rolled back and
9833** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
9834** actions are taken by sqlite3changeset_apply() depending on the value
9835** returned by each invocation of the conflict-handler function. Refer to
9836** the documentation for the three
9837** [SQLITE_CHANGESET_OMIT|available return values] for details.
9838**
9839** <dl>
9840** <dt>DELETE Changes<dd>
9841**   For each DELETE change, this function checks if the target database
9842**   contains a row with the same primary key value (or values) as the
9843**   original row values stored in the changeset. If it does, and the values
9844**   stored in all non-primary key columns also match the values stored in
9845**   the changeset the row is deleted from the target database.
9846**
9847**   If a row with matching primary key values is found, but one or more of
9848**   the non-primary key fields contains a value different from the original
9849**   row value stored in the changeset, the conflict-handler function is
9850**   invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
9851**   database table has more columns than are recorded in the changeset,
9852**   only the values of those non-primary key fields are compared against
9853**   the current database contents - any trailing database table columns
9854**   are ignored.
9855**
9856**   If no row with matching primary key values is found in the database,
9857**   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9858**   passed as the second argument.
9859**
9860**   If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
9861**   (which can only happen if a foreign key constraint is violated), the
9862**   conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
9863**   passed as the second argument. This includes the case where the DELETE
9864**   operation is attempted because an earlier call to the conflict handler
9865**   function returned [SQLITE_CHANGESET_REPLACE].
9866**
9867** <dt>INSERT Changes<dd>
9868**   For each INSERT change, an attempt is made to insert the new row into
9869**   the database. If the changeset row contains fewer fields than the
9870**   database table, the trailing fields are populated with their default
9871**   values.
9872**
9873**   If the attempt to insert the row fails because the database already
9874**   contains a row with the same primary key values, the conflict handler
9875**   function is invoked with the second argument set to
9876**   [SQLITE_CHANGESET_CONFLICT].
9877**
9878**   If the attempt to insert the row fails because of some other constraint
9879**   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
9880**   invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
9881**   This includes the case where the INSERT operation is re-attempted because
9882**   an earlier call to the conflict handler function returned
9883**   [SQLITE_CHANGESET_REPLACE].
9884**
9885** <dt>UPDATE Changes<dd>
9886**   For each UPDATE change, this function checks if the target database
9887**   contains a row with the same primary key value (or values) as the
9888**   original row values stored in the changeset. If it does, and the values
9889**   stored in all modified non-primary key columns also match the values
9890**   stored in the changeset the row is updated within the target database.
9891**
9892**   If a row with matching primary key values is found, but one or more of
9893**   the modified non-primary key fields contains a value different from an
9894**   original row value stored in the changeset, the conflict-handler function
9895**   is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
9896**   UPDATE changes only contain values for non-primary key fields that are
9897**   to be modified, only those fields need to match the original values to
9898**   avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
9899**
9900**   If no row with matching primary key values is found in the database,
9901**   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9902**   passed as the second argument.
9903**
9904**   If the UPDATE operation is attempted, but SQLite returns
9905**   SQLITE_CONSTRAINT, the conflict-handler function is invoked with
9906**   [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
9907**   This includes the case where the UPDATE operation is attempted after
9908**   an earlier call to the conflict handler function returned
9909**   [SQLITE_CHANGESET_REPLACE].
9910** </dl>
9911**
9912** It is safe to execute SQL statements, including those that write to the
9913** table that the callback related to, from within the xConflict callback.
9914** This can be used to further customize the applications conflict
9915** resolution strategy.
9916**
9917** All changes made by this function are enclosed in a savepoint transaction.
9918** If any other error (aside from a constraint failure when attempting to
9919** write to the target database) occurs, then the savepoint transaction is
9920** rolled back, restoring the target database to its original state, and an
9921** SQLite error code returned.
9922*/
9923SQLITE_API int sqlite3changeset_apply(
9924  sqlite3 *db,                    /* Apply change to "main" db of this handle */
9925  int nChangeset,                 /* Size of changeset in bytes */
9926  void *pChangeset,               /* Changeset blob */
9927  int(*xFilter)(
9928    void *pCtx,                   /* Copy of sixth arg to _apply() */
9929    const char *zTab              /* Table name */
9930  ),
9931  int(*xConflict)(
9932    void *pCtx,                   /* Copy of sixth arg to _apply() */
9933    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
9934    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
9935  ),
9936  void *pCtx                      /* First argument passed to xConflict */
9937);
9938
9939/*
9940** CAPI3REF: Constants Passed To The Conflict Handler
9941**
9942** Values that may be passed as the second argument to a conflict-handler.
9943**
9944** <dl>
9945** <dt>SQLITE_CHANGESET_DATA<dd>
9946**   The conflict handler is invoked with CHANGESET_DATA as the second argument
9947**   when processing a DELETE or UPDATE change if a row with the required
9948**   PRIMARY KEY fields is present in the database, but one or more other
9949**   (non primary-key) fields modified by the update do not contain the
9950**   expected "before" values.
9951**
9952**   The conflicting row, in this case, is the database row with the matching
9953**   primary key.
9954**
9955** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
9956**   The conflict handler is invoked with CHANGESET_NOTFOUND as the second
9957**   argument when processing a DELETE or UPDATE change if a row with the
9958**   required PRIMARY KEY fields is not present in the database.
9959**
9960**   There is no conflicting row in this case. The results of invoking the
9961**   sqlite3changeset_conflict() API are undefined.
9962**
9963** <dt>SQLITE_CHANGESET_CONFLICT<dd>
9964**   CHANGESET_CONFLICT is passed as the second argument to the conflict
9965**   handler while processing an INSERT change if the operation would result
9966**   in duplicate primary key values.
9967**
9968**   The conflicting row in this case is the database row with the matching
9969**   primary key.
9970**
9971** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
9972**   If foreign key handling is enabled, and applying a changeset leaves the
9973**   database in a state containing foreign key violations, the conflict
9974**   handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
9975**   exactly once before the changeset is committed. If the conflict handler
9976**   returns CHANGESET_OMIT, the changes, including those that caused the
9977**   foreign key constraint violation, are committed. Or, if it returns
9978**   CHANGESET_ABORT, the changeset is rolled back.
9979**
9980**   No current or conflicting row information is provided. The only function
9981**   it is possible to call on the supplied sqlite3_changeset_iter handle
9982**   is sqlite3changeset_fk_conflicts().
9983**
9984** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
9985**   If any other constraint violation occurs while applying a change (i.e.
9986**   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
9987**   invoked with CHANGESET_CONSTRAINT as the second argument.
9988**
9989**   There is no conflicting row in this case. The results of invoking the
9990**   sqlite3changeset_conflict() API are undefined.
9991**
9992** </dl>
9993*/
9994#define SQLITE_CHANGESET_DATA        1
9995#define SQLITE_CHANGESET_NOTFOUND    2
9996#define SQLITE_CHANGESET_CONFLICT    3
9997#define SQLITE_CHANGESET_CONSTRAINT  4
9998#define SQLITE_CHANGESET_FOREIGN_KEY 5
9999
10000/*
10001** CAPI3REF: Constants Returned By The Conflict Handler
10002**
10003** A conflict handler callback must return one of the following three values.
10004**
10005** <dl>
10006** <dt>SQLITE_CHANGESET_OMIT<dd>
10007**   If a conflict handler returns this value no special action is taken. The
10008**   change that caused the conflict is not applied. The session module
10009**   continues to the next change in the changeset.
10010**
10011** <dt>SQLITE_CHANGESET_REPLACE<dd>
10012**   This value may only be returned if the second argument to the conflict
10013**   handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
10014**   is not the case, any changes applied so far are rolled back and the
10015**   call to sqlite3changeset_apply() returns SQLITE_MISUSE.
10016**
10017**   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
10018**   handler, then the conflicting row is either updated or deleted, depending
10019**   on the type of change.
10020**
10021**   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
10022**   handler, then the conflicting row is removed from the database and a
10023**   second attempt to apply the change is made. If this second attempt fails,
10024**   the original row is restored to the database before continuing.
10025**
10026** <dt>SQLITE_CHANGESET_ABORT<dd>
10027**   If this value is returned, any changes applied so far are rolled back
10028**   and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
10029** </dl>
10030*/
10031#define SQLITE_CHANGESET_OMIT       0
10032#define SQLITE_CHANGESET_REPLACE    1
10033#define SQLITE_CHANGESET_ABORT      2
10034
10035/*
10036** CAPI3REF: Streaming Versions of API functions.
10037**
10038** The six streaming API xxx_strm() functions serve similar purposes to the
10039** corresponding non-streaming API functions:
10040**
10041** <table border=1 style="margin-left:8ex;margin-right:8ex">
10042**   <tr><th>Streaming function<th>Non-streaming equivalent</th>
10043**   <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply]
10044**   <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat]
10045**   <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert]
10046**   <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start]
10047**   <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset]
10048**   <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset]
10049** </table>
10050**
10051** Non-streaming functions that accept changesets (or patchsets) as input
10052** require that the entire changeset be stored in a single buffer in memory.
10053** Similarly, those that return a changeset or patchset do so by returning
10054** a pointer to a single large buffer allocated using sqlite3_malloc().
10055** Normally this is convenient. However, if an application running in a
10056** low-memory environment is required to handle very large changesets, the
10057** large contiguous memory allocations required can become onerous.
10058**
10059** In order to avoid this problem, instead of a single large buffer, input
10060** is passed to a streaming API functions by way of a callback function that
10061** the sessions module invokes to incrementally request input data as it is
10062** required. In all cases, a pair of API function parameters such as
10063**
10064**  <pre>
10065**  &nbsp;     int nChangeset,
10066**  &nbsp;     void *pChangeset,
10067**  </pre>
10068**
10069** Is replaced by:
10070**
10071**  <pre>
10072**  &nbsp;     int (*xInput)(void *pIn, void *pData, int *pnData),
10073**  &nbsp;     void *pIn,
10074**  </pre>
10075**
10076** Each time the xInput callback is invoked by the sessions module, the first
10077** argument passed is a copy of the supplied pIn context pointer. The second
10078** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
10079** error occurs the xInput method should copy up to (*pnData) bytes of data
10080** into the buffer and set (*pnData) to the actual number of bytes copied
10081** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
10082** should be set to zero to indicate this. Or, if an error occurs, an SQLite
10083** error code should be returned. In all cases, if an xInput callback returns
10084** an error, all processing is abandoned and the streaming API function
10085** returns a copy of the error code to the caller.
10086**
10087** In the case of sqlite3changeset_start_strm(), the xInput callback may be
10088** invoked by the sessions module at any point during the lifetime of the
10089** iterator. If such an xInput callback returns an error, the iterator enters
10090** an error state, whereby all subsequent calls to iterator functions
10091** immediately fail with the same error code as returned by xInput.
10092**
10093** Similarly, streaming API functions that return changesets (or patchsets)
10094** return them in chunks by way of a callback function instead of via a
10095** pointer to a single large buffer. In this case, a pair of parameters such
10096** as:
10097**
10098**  <pre>
10099**  &nbsp;     int *pnChangeset,
10100**  &nbsp;     void **ppChangeset,
10101**  </pre>
10102**
10103** Is replaced by:
10104**
10105**  <pre>
10106**  &nbsp;     int (*xOutput)(void *pOut, const void *pData, int nData),
10107**  &nbsp;     void *pOut
10108**  </pre>
10109**
10110** The xOutput callback is invoked zero or more times to return data to
10111** the application. The first parameter passed to each call is a copy of the
10112** pOut pointer supplied by the application. The second parameter, pData,
10113** points to a buffer nData bytes in size containing the chunk of output
10114** data being returned. If the xOutput callback successfully processes the
10115** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
10116** it should return some other SQLite error code. In this case processing
10117** is immediately abandoned and the streaming API function returns a copy
10118** of the xOutput error code to the application.
10119**
10120** The sessions module never invokes an xOutput callback with the third
10121** parameter set to a value less than or equal to zero. Other than this,
10122** no guarantees are made as to the size of the chunks of data returned.
10123*/
10124SQLITE_API int sqlite3changeset_apply_strm(
10125  sqlite3 *db,                    /* Apply change to "main" db of this handle */
10126  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
10127  void *pIn,                                          /* First arg for xInput */
10128  int(*xFilter)(
10129    void *pCtx,                   /* Copy of sixth arg to _apply() */
10130    const char *zTab              /* Table name */
10131  ),
10132  int(*xConflict)(
10133    void *pCtx,                   /* Copy of sixth arg to _apply() */
10134    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
10135    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
10136  ),
10137  void *pCtx                      /* First argument passed to xConflict */
10138);
10139SQLITE_API int sqlite3changeset_concat_strm(
10140  int (*xInputA)(void *pIn, void *pData, int *pnData),
10141  void *pInA,
10142  int (*xInputB)(void *pIn, void *pData, int *pnData),
10143  void *pInB,
10144  int (*xOutput)(void *pOut, const void *pData, int nData),
10145  void *pOut
10146);
10147SQLITE_API int sqlite3changeset_invert_strm(
10148  int (*xInput)(void *pIn, void *pData, int *pnData),
10149  void *pIn,
10150  int (*xOutput)(void *pOut, const void *pData, int nData),
10151  void *pOut
10152);
10153SQLITE_API int sqlite3changeset_start_strm(
10154  sqlite3_changeset_iter **pp,
10155  int (*xInput)(void *pIn, void *pData, int *pnData),
10156  void *pIn
10157);
10158SQLITE_API int sqlite3session_changeset_strm(
10159  sqlite3_session *pSession,
10160  int (*xOutput)(void *pOut, const void *pData, int nData),
10161  void *pOut
10162);
10163SQLITE_API int sqlite3session_patchset_strm(
10164  sqlite3_session *pSession,
10165  int (*xOutput)(void *pOut, const void *pData, int nData),
10166  void *pOut
10167);
10168int sqlite3changegroup_add_strm(sqlite3_changegroup*,
10169    int (*xInput)(void *pIn, void *pData, int *pnData),
10170    void *pIn
10171);
10172int sqlite3changegroup_output_strm(sqlite3_changegroup*,
10173    int (*xOutput)(void *pOut, const void *pData, int nData),
10174    void *pOut
10175);
10176
10177
10178/*
10179** Make sure we can call this stuff from C++.
10180*/
10181#if 0
10182}
10183#endif
10184
10185#endif  /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
10186
10187/******** End of sqlite3session.h *********/
10188/******** Begin file fts5.h *********/
10189/*
10190** 2014 May 31
10191**
10192** The author disclaims copyright to this source code.  In place of
10193** a legal notice, here is a blessing:
10194**
10195**    May you do good and not evil.
10196**    May you find forgiveness for yourself and forgive others.
10197**    May you share freely, never taking more than you give.
10198**
10199******************************************************************************
10200**
10201** Interfaces to extend FTS5. Using the interfaces defined in this file,
10202** FTS5 may be extended with:
10203**
10204**     * custom tokenizers, and
10205**     * custom auxiliary functions.
10206*/
10207
10208
10209#ifndef _FTS5_H
10210#define _FTS5_H
10211
10212
10213#if 0
10214extern "C" {
10215#endif
10216
10217/*************************************************************************
10218** CUSTOM AUXILIARY FUNCTIONS
10219**
10220** Virtual table implementations may overload SQL functions by implementing
10221** the sqlite3_module.xFindFunction() method.
10222*/
10223
10224typedef struct Fts5ExtensionApi Fts5ExtensionApi;
10225typedef struct Fts5Context Fts5Context;
10226typedef struct Fts5PhraseIter Fts5PhraseIter;
10227
10228typedef void (*fts5_extension_function)(
10229  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
10230  Fts5Context *pFts,              /* First arg to pass to pApi functions */
10231  sqlite3_context *pCtx,          /* Context for returning result/error */
10232  int nVal,                       /* Number of values in apVal[] array */
10233  sqlite3_value **apVal           /* Array of trailing arguments */
10234);
10235
10236struct Fts5PhraseIter {
10237  const unsigned char *a;
10238  const unsigned char *b;
10239};
10240
10241/*
10242** EXTENSION API FUNCTIONS
10243**
10244** xUserData(pFts):
10245**   Return a copy of the context pointer the extension function was
10246**   registered with.
10247**
10248** xColumnTotalSize(pFts, iCol, pnToken):
10249**   If parameter iCol is less than zero, set output variable *pnToken
10250**   to the total number of tokens in the FTS5 table. Or, if iCol is
10251**   non-negative but less than the number of columns in the table, return
10252**   the total number of tokens in column iCol, considering all rows in
10253**   the FTS5 table.
10254**
10255**   If parameter iCol is greater than or equal to the number of columns
10256**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
10257**   an OOM condition or IO error), an appropriate SQLite error code is
10258**   returned.
10259**
10260** xColumnCount(pFts):
10261**   Return the number of columns in the table.
10262**
10263** xColumnSize(pFts, iCol, pnToken):
10264**   If parameter iCol is less than zero, set output variable *pnToken
10265**   to the total number of tokens in the current row. Or, if iCol is
10266**   non-negative but less than the number of columns in the table, set
10267**   *pnToken to the number of tokens in column iCol of the current row.
10268**
10269**   If parameter iCol is greater than or equal to the number of columns
10270**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
10271**   an OOM condition or IO error), an appropriate SQLite error code is
10272**   returned.
10273**
10274**   This function may be quite inefficient if used with an FTS5 table
10275**   created with the "columnsize=0" option.
10276**
10277** xColumnText:
10278**   This function attempts to retrieve the text of column iCol of the
10279**   current document. If successful, (*pz) is set to point to a buffer
10280**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
10281**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
10282**   if an error occurs, an SQLite error code is returned and the final values
10283**   of (*pz) and (*pn) are undefined.
10284**
10285** xPhraseCount:
10286**   Returns the number of phrases in the current query expression.
10287**
10288** xPhraseSize:
10289**   Returns the number of tokens in phrase iPhrase of the query. Phrases
10290**   are numbered starting from zero.
10291**
10292** xInstCount:
10293**   Set *pnInst to the total number of occurrences of all phrases within
10294**   the query within the current row. Return SQLITE_OK if successful, or
10295**   an error code (i.e. SQLITE_NOMEM) if an error occurs.
10296**
10297**   This API can be quite slow if used with an FTS5 table created with the
10298**   "detail=none" or "detail=column" option. If the FTS5 table is created
10299**   with either "detail=none" or "detail=column" and "content=" option
10300**   (i.e. if it is a contentless table), then this API always returns 0.
10301**
10302** xInst:
10303**   Query for the details of phrase match iIdx within the current row.
10304**   Phrase matches are numbered starting from zero, so the iIdx argument
10305**   should be greater than or equal to zero and smaller than the value
10306**   output by xInstCount().
10307**
10308**   Usually, output parameter *piPhrase is set to the phrase number, *piCol
10309**   to the column in which it occurs and *piOff the token offset of the
10310**   first token of the phrase. The exception is if the table was created
10311**   with the offsets=0 option specified. In this case *piOff is always
10312**   set to -1.
10313**
10314**   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
10315**   if an error occurs.
10316**
10317**   This API can be quite slow if used with an FTS5 table created with the
10318**   "detail=none" or "detail=column" option.
10319**
10320** xRowid:
10321**   Returns the rowid of the current row.
10322**
10323** xTokenize:
10324**   Tokenize text using the tokenizer belonging to the FTS5 table.
10325**
10326** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
10327**   This API function is used to query the FTS table for phrase iPhrase
10328**   of the current query. Specifically, a query equivalent to:
10329**
10330**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
10331**
10332**   with $p set to a phrase equivalent to the phrase iPhrase of the
10333**   current query is executed. Any column filter that applies to
10334**   phrase iPhrase of the current query is included in $p. For each
10335**   row visited, the callback function passed as the fourth argument
10336**   is invoked. The context and API objects passed to the callback
10337**   function may be used to access the properties of each matched row.
10338**   Invoking Api.xUserData() returns a copy of the pointer passed as
10339**   the third argument to pUserData.
10340**
10341**   If the callback function returns any value other than SQLITE_OK, the
10342**   query is abandoned and the xQueryPhrase function returns immediately.
10343**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
10344**   Otherwise, the error code is propagated upwards.
10345**
10346**   If the query runs to completion without incident, SQLITE_OK is returned.
10347**   Or, if some error occurs before the query completes or is aborted by
10348**   the callback, an SQLite error code is returned.
10349**
10350**
10351** xSetAuxdata(pFts5, pAux, xDelete)
10352**
10353**   Save the pointer passed as the second argument as the extension functions
10354**   "auxiliary data". The pointer may then be retrieved by the current or any
10355**   future invocation of the same fts5 extension function made as part of
10356**   of the same MATCH query using the xGetAuxdata() API.
10357**
10358**   Each extension function is allocated a single auxiliary data slot for
10359**   each FTS query (MATCH expression). If the extension function is invoked
10360**   more than once for a single FTS query, then all invocations share a
10361**   single auxiliary data context.
10362**
10363**   If there is already an auxiliary data pointer when this function is
10364**   invoked, then it is replaced by the new pointer. If an xDelete callback
10365**   was specified along with the original pointer, it is invoked at this
10366**   point.
10367**
10368**   The xDelete callback, if one is specified, is also invoked on the
10369**   auxiliary data pointer after the FTS5 query has finished.
10370**
10371**   If an error (e.g. an OOM condition) occurs within this function, an
10372**   the auxiliary data is set to NULL and an error code returned. If the
10373**   xDelete parameter was not NULL, it is invoked on the auxiliary data
10374**   pointer before returning.
10375**
10376**
10377** xGetAuxdata(pFts5, bClear)
10378**
10379**   Returns the current auxiliary data pointer for the fts5 extension
10380**   function. See the xSetAuxdata() method for details.
10381**
10382**   If the bClear argument is non-zero, then the auxiliary data is cleared
10383**   (set to NULL) before this function returns. In this case the xDelete,
10384**   if any, is not invoked.
10385**
10386**
10387** xRowCount(pFts5, pnRow)
10388**
10389**   This function is used to retrieve the total number of rows in the table.
10390**   In other words, the same value that would be returned by:
10391**
10392**        SELECT count(*) FROM ftstable;
10393**
10394** xPhraseFirst()
10395**   This function is used, along with type Fts5PhraseIter and the xPhraseNext
10396**   method, to iterate through all instances of a single query phrase within
10397**   the current row. This is the same information as is accessible via the
10398**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
10399**   to use, this API may be faster under some circumstances. To iterate
10400**   through instances of phrase iPhrase, use the following code:
10401**
10402**       Fts5PhraseIter iter;
10403**       int iCol, iOff;
10404**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
10405**           iCol>=0;
10406**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
10407**       ){
10408**         // An instance of phrase iPhrase at offset iOff of column iCol
10409**       }
10410**
10411**   The Fts5PhraseIter structure is defined above. Applications should not
10412**   modify this structure directly - it should only be used as shown above
10413**   with the xPhraseFirst() and xPhraseNext() API methods (and by
10414**   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
10415**
10416**   This API can be quite slow if used with an FTS5 table created with the
10417**   "detail=none" or "detail=column" option. If the FTS5 table is created
10418**   with either "detail=none" or "detail=column" and "content=" option
10419**   (i.e. if it is a contentless table), then this API always iterates
10420**   through an empty set (all calls to xPhraseFirst() set iCol to -1).
10421**
10422** xPhraseNext()
10423**   See xPhraseFirst above.
10424**
10425** xPhraseFirstColumn()
10426**   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
10427**   and xPhraseNext() APIs described above. The difference is that instead
10428**   of iterating through all instances of a phrase in the current row, these
10429**   APIs are used to iterate through the set of columns in the current row
10430**   that contain one or more instances of a specified phrase. For example:
10431**
10432**       Fts5PhraseIter iter;
10433**       int iCol;
10434**       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
10435**           iCol>=0;
10436**           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
10437**       ){
10438**         // Column iCol contains at least one instance of phrase iPhrase
10439**       }
10440**
10441**   This API can be quite slow if used with an FTS5 table created with the
10442**   "detail=none" option. If the FTS5 table is created with either
10443**   "detail=none" "content=" option (i.e. if it is a contentless table),
10444**   then this API always iterates through an empty set (all calls to
10445**   xPhraseFirstColumn() set iCol to -1).
10446**
10447**   The information accessed using this API and its companion
10448**   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
10449**   (or xInst/xInstCount). The chief advantage of this API is that it is
10450**   significantly more efficient than those alternatives when used with
10451**   "detail=column" tables.
10452**
10453** xPhraseNextColumn()
10454**   See xPhraseFirstColumn above.
10455*/
10456struct Fts5ExtensionApi {
10457  int iVersion;                   /* Currently always set to 3 */
10458
10459  void *(*xUserData)(Fts5Context*);
10460
10461  int (*xColumnCount)(Fts5Context*);
10462  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
10463  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
10464
10465  int (*xTokenize)(Fts5Context*,
10466    const char *pText, int nText, /* Text to tokenize */
10467    void *pCtx,                   /* Context passed to xToken() */
10468    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
10469  );
10470
10471  int (*xPhraseCount)(Fts5Context*);
10472  int (*xPhraseSize)(Fts5Context*, int iPhrase);
10473
10474  int (*xInstCount)(Fts5Context*, int *pnInst);
10475  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
10476
10477  sqlite3_int64 (*xRowid)(Fts5Context*);
10478  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
10479  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
10480
10481  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
10482    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
10483  );
10484  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
10485  void *(*xGetAuxdata)(Fts5Context*, int bClear);
10486
10487  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
10488  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
10489
10490  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
10491  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
10492};
10493
10494/*
10495** CUSTOM AUXILIARY FUNCTIONS
10496*************************************************************************/
10497
10498/*************************************************************************
10499** CUSTOM TOKENIZERS
10500**
10501** Applications may also register custom tokenizer types. A tokenizer
10502** is registered by providing fts5 with a populated instance of the
10503** following structure. All structure methods must be defined, setting
10504** any member of the fts5_tokenizer struct to NULL leads to undefined
10505** behaviour. The structure methods are expected to function as follows:
10506**
10507** xCreate:
10508**   This function is used to allocate and initialize a tokenizer instance.
10509**   A tokenizer instance is required to actually tokenize text.
10510**
10511**   The first argument passed to this function is a copy of the (void*)
10512**   pointer provided by the application when the fts5_tokenizer object
10513**   was registered with FTS5 (the third argument to xCreateTokenizer()).
10514**   The second and third arguments are an array of nul-terminated strings
10515**   containing the tokenizer arguments, if any, specified following the
10516**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
10517**   to create the FTS5 table.
10518**
10519**   The final argument is an output variable. If successful, (*ppOut)
10520**   should be set to point to the new tokenizer handle and SQLITE_OK
10521**   returned. If an error occurs, some value other than SQLITE_OK should
10522**   be returned. In this case, fts5 assumes that the final value of *ppOut
10523**   is undefined.
10524**
10525** xDelete:
10526**   This function is invoked to delete a tokenizer handle previously
10527**   allocated using xCreate(). Fts5 guarantees that this function will
10528**   be invoked exactly once for each successful call to xCreate().
10529**
10530** xTokenize:
10531**   This function is expected to tokenize the nText byte string indicated
10532**   by argument pText. pText may or may not be nul-terminated. The first
10533**   argument passed to this function is a pointer to an Fts5Tokenizer object
10534**   returned by an earlier call to xCreate().
10535**
10536**   The second argument indicates the reason that FTS5 is requesting
10537**   tokenization of the supplied text. This is always one of the following
10538**   four values:
10539**
10540**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
10541**            or removed from the FTS table. The tokenizer is being invoked to
10542**            determine the set of tokens to add to (or delete from) the
10543**            FTS index.
10544**
10545**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
10546**            against the FTS index. The tokenizer is being called to tokenize
10547**            a bareword or quoted string specified as part of the query.
10548**
10549**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
10550**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
10551**            followed by a "*" character, indicating that the last token
10552**            returned by the tokenizer will be treated as a token prefix.
10553**
10554**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
10555**            satisfy an fts5_api.xTokenize() request made by an auxiliary
10556**            function. Or an fts5_api.xColumnSize() request made by the same
10557**            on a columnsize=0 database.
10558**   </ul>
10559**
10560**   For each token in the input string, the supplied callback xToken() must
10561**   be invoked. The first argument to it should be a copy of the pointer
10562**   passed as the second argument to xTokenize(). The third and fourth
10563**   arguments are a pointer to a buffer containing the token text, and the
10564**   size of the token in bytes. The 4th and 5th arguments are the byte offsets
10565**   of the first byte of and first byte immediately following the text from
10566**   which the token is derived within the input.
10567**
10568**   The second argument passed to the xToken() callback ("tflags") should
10569**   normally be set to 0. The exception is if the tokenizer supports
10570**   synonyms. In this case see the discussion below for details.
10571**
10572**   FTS5 assumes the xToken() callback is invoked for each token in the
10573**   order that they occur within the input text.
10574**
10575**   If an xToken() callback returns any value other than SQLITE_OK, then
10576**   the tokenization should be abandoned and the xTokenize() method should
10577**   immediately return a copy of the xToken() return value. Or, if the
10578**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
10579**   if an error occurs with the xTokenize() implementation itself, it
10580**   may abandon the tokenization and return any error code other than
10581**   SQLITE_OK or SQLITE_DONE.
10582**
10583** SYNONYM SUPPORT
10584**
10585**   Custom tokenizers may also support synonyms. Consider a case in which a
10586**   user wishes to query for a phrase such as "first place". Using the
10587**   built-in tokenizers, the FTS5 query 'first + place' will match instances
10588**   of "first place" within the document set, but not alternative forms
10589**   such as "1st place". In some applications, it would be better to match
10590**   all instances of "first place" or "1st place" regardless of which form
10591**   the user specified in the MATCH query text.
10592**
10593**   There are several ways to approach this in FTS5:
10594**
10595**   <ol><li> By mapping all synonyms to a single token. In this case, the
10596**            In the above example, this means that the tokenizer returns the
10597**            same token for inputs "first" and "1st". Say that token is in
10598**            fact "first", so that when the user inserts the document "I won
10599**            1st place" entries are added to the index for tokens "i", "won",
10600**            "first" and "place". If the user then queries for '1st + place',
10601**            the tokenizer substitutes "first" for "1st" and the query works
10602**            as expected.
10603**
10604**       <li> By adding multiple synonyms for a single term to the FTS index.
10605**            In this case, when tokenizing query text, the tokenizer may
10606**            provide multiple synonyms for a single term within the document.
10607**            FTS5 then queries the index for each synonym individually. For
10608**            example, faced with the query:
10609**
10610**   <codeblock>
10611**     ... MATCH 'first place'</codeblock>
10612**
10613**            the tokenizer offers both "1st" and "first" as synonyms for the
10614**            first token in the MATCH query and FTS5 effectively runs a query
10615**            similar to:
10616**
10617**   <codeblock>
10618**     ... MATCH '(first OR 1st) place'</codeblock>
10619**
10620**            except that, for the purposes of auxiliary functions, the query
10621**            still appears to contain just two phrases - "(first OR 1st)"
10622**            being treated as a single phrase.
10623**
10624**       <li> By adding multiple synonyms for a single term to the FTS index.
10625**            Using this method, when tokenizing document text, the tokenizer
10626**            provides multiple synonyms for each token. So that when a
10627**            document such as "I won first place" is tokenized, entries are
10628**            added to the FTS index for "i", "won", "first", "1st" and
10629**            "place".
10630**
10631**            This way, even if the tokenizer does not provide synonyms
10632**            when tokenizing query text (it should not - to do would be
10633**            inefficient), it doesn't matter if the user queries for
10634**            'first + place' or '1st + place', as there are entires in the
10635**            FTS index corresponding to both forms of the first token.
10636**   </ol>
10637**
10638**   Whether it is parsing document or query text, any call to xToken that
10639**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
10640**   is considered to supply a synonym for the previous token. For example,
10641**   when parsing the document "I won first place", a tokenizer that supports
10642**   synonyms would call xToken() 5 times, as follows:
10643**
10644**   <codeblock>
10645**       xToken(pCtx, 0, "i",                      1,  0,  1);
10646**       xToken(pCtx, 0, "won",                    3,  2,  5);
10647**       xToken(pCtx, 0, "first",                  5,  6, 11);
10648**       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
10649**       xToken(pCtx, 0, "place",                  5, 12, 17);
10650**</codeblock>
10651**
10652**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
10653**   xToken() is called. Multiple synonyms may be specified for a single token
10654**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
10655**   There is no limit to the number of synonyms that may be provided for a
10656**   single token.
10657**
10658**   In many cases, method (1) above is the best approach. It does not add
10659**   extra data to the FTS index or require FTS5 to query for multiple terms,
10660**   so it is efficient in terms of disk space and query speed. However, it
10661**   does not support prefix queries very well. If, as suggested above, the
10662**   token "first" is subsituted for "1st" by the tokenizer, then the query:
10663**
10664**   <codeblock>
10665**     ... MATCH '1s*'</codeblock>
10666**
10667**   will not match documents that contain the token "1st" (as the tokenizer
10668**   will probably not map "1s" to any prefix of "first").
10669**
10670**   For full prefix support, method (3) may be preferred. In this case,
10671**   because the index contains entries for both "first" and "1st", prefix
10672**   queries such as 'fi*' or '1s*' will match correctly. However, because
10673**   extra entries are added to the FTS index, this method uses more space
10674**   within the database.
10675**
10676**   Method (2) offers a midpoint between (1) and (3). Using this method,
10677**   a query such as '1s*' will match documents that contain the literal
10678**   token "1st", but not "first" (assuming the tokenizer is not able to
10679**   provide synonyms for prefixes). However, a non-prefix query like '1st'
10680**   will match against "1st" and "first". This method does not require
10681**   extra disk space, as no extra entries are added to the FTS index.
10682**   On the other hand, it may require more CPU cycles to run MATCH queries,
10683**   as separate queries of the FTS index are required for each synonym.
10684**
10685**   When using methods (2) or (3), it is important that the tokenizer only
10686**   provide synonyms when tokenizing document text (method (2)) or query
10687**   text (method (3)), not both. Doing so will not cause any errors, but is
10688**   inefficient.
10689*/
10690typedef struct Fts5Tokenizer Fts5Tokenizer;
10691typedef struct fts5_tokenizer fts5_tokenizer;
10692struct fts5_tokenizer {
10693  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
10694  void (*xDelete)(Fts5Tokenizer*);
10695  int (*xTokenize)(Fts5Tokenizer*,
10696      void *pCtx,
10697      int flags,            /* Mask of FTS5_TOKENIZE_* flags */
10698      const char *pText, int nText,
10699      int (*xToken)(
10700        void *pCtx,         /* Copy of 2nd argument to xTokenize() */
10701        int tflags,         /* Mask of FTS5_TOKEN_* flags */
10702        const char *pToken, /* Pointer to buffer containing token */
10703        int nToken,         /* Size of token in bytes */
10704        int iStart,         /* Byte offset of token within input text */
10705        int iEnd            /* Byte offset of end of token within input text */
10706      )
10707  );
10708};
10709
10710/* Flags that may be passed as the third argument to xTokenize() */
10711#define FTS5_TOKENIZE_QUERY     0x0001
10712#define FTS5_TOKENIZE_PREFIX    0x0002
10713#define FTS5_TOKENIZE_DOCUMENT  0x0004
10714#define FTS5_TOKENIZE_AUX       0x0008
10715
10716/* Flags that may be passed by the tokenizer implementation back to FTS5
10717** as the third argument to the supplied xToken callback. */
10718#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
10719
10720/*
10721** END OF CUSTOM TOKENIZERS
10722*************************************************************************/
10723
10724/*************************************************************************
10725** FTS5 EXTENSION REGISTRATION API
10726*/
10727typedef struct fts5_api fts5_api;
10728struct fts5_api {
10729  int iVersion;                   /* Currently always set to 2 */
10730
10731  /* Create a new tokenizer */
10732  int (*xCreateTokenizer)(
10733    fts5_api *pApi,
10734    const char *zName,
10735    void *pContext,
10736    fts5_tokenizer *pTokenizer,
10737    void (*xDestroy)(void*)
10738  );
10739
10740  /* Find an existing tokenizer */
10741  int (*xFindTokenizer)(
10742    fts5_api *pApi,
10743    const char *zName,
10744    void **ppContext,
10745    fts5_tokenizer *pTokenizer
10746  );
10747
10748  /* Create a new auxiliary function */
10749  int (*xCreateFunction)(
10750    fts5_api *pApi,
10751    const char *zName,
10752    void *pContext,
10753    fts5_extension_function xFunction,
10754    void (*xDestroy)(void*)
10755  );
10756};
10757
10758/*
10759** END OF REGISTRATION API
10760*************************************************************************/
10761
10762#if 0
10763}  /* end of the 'extern "C"' block */
10764#endif
10765
10766#endif /* _FTS5_H */
10767
10768/******** End of fts5.h *********/
10769
10770/************** End of sqlite3.h *********************************************/
10771/************** Continuing where we left off in sqliteInt.h ******************/
10772
10773/*
10774** Include the configuration header output by 'configure' if we're using the
10775** autoconf-based build
10776*/
10777#ifdef _HAVE_SQLITE_CONFIG_H
10778#include "config.h"
10779#endif
10780
10781/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
10782/************** Begin file sqliteLimit.h *************************************/
10783/*
10784** 2007 May 7
10785**
10786** The author disclaims copyright to this source code.  In place of
10787** a legal notice, here is a blessing:
10788**
10789**    May you do good and not evil.
10790**    May you find forgiveness for yourself and forgive others.
10791**    May you share freely, never taking more than you give.
10792**
10793*************************************************************************
10794**
10795** This file defines various limits of what SQLite can process.
10796*/
10797
10798/*
10799** The maximum length of a TEXT or BLOB in bytes.   This also
10800** limits the size of a row in a table or index.
10801**
10802** The hard limit is the ability of a 32-bit signed integer
10803** to count the size: 2^31-1 or 2147483647.
10804*/
10805#ifndef SQLITE_MAX_LENGTH
10806# define SQLITE_MAX_LENGTH 1000000000
10807#endif
10808
10809/*
10810** This is the maximum number of
10811**
10812**    * Columns in a table
10813**    * Columns in an index
10814**    * Columns in a view
10815**    * Terms in the SET clause of an UPDATE statement
10816**    * Terms in the result set of a SELECT statement
10817**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
10818**    * Terms in the VALUES clause of an INSERT statement
10819**
10820** The hard upper limit here is 32676.  Most database people will
10821** tell you that in a well-normalized database, you usually should
10822** not have more than a dozen or so columns in any table.  And if
10823** that is the case, there is no point in having more than a few
10824** dozen values in any of the other situations described above.
10825*/
10826#ifndef SQLITE_MAX_COLUMN
10827# define SQLITE_MAX_COLUMN 2000
10828#endif
10829
10830/*
10831** The maximum length of a single SQL statement in bytes.
10832**
10833** It used to be the case that setting this value to zero would
10834** turn the limit off.  That is no longer true.  It is not possible
10835** to turn this limit off.
10836*/
10837#ifndef SQLITE_MAX_SQL_LENGTH
10838# define SQLITE_MAX_SQL_LENGTH 1000000000
10839#endif
10840
10841/*
10842** The maximum depth of an expression tree. This is limited to
10843** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
10844** want to place more severe limits on the complexity of an
10845** expression.
10846**
10847** A value of 0 used to mean that the limit was not enforced.
10848** But that is no longer true.  The limit is now strictly enforced
10849** at all times.
10850*/
10851#ifndef SQLITE_MAX_EXPR_DEPTH
10852# define SQLITE_MAX_EXPR_DEPTH 1000
10853#endif
10854
10855/*
10856** The maximum number of terms in a compound SELECT statement.
10857** The code generator for compound SELECT statements does one
10858** level of recursion for each term.  A stack overflow can result
10859** if the number of terms is too large.  In practice, most SQL
10860** never has more than 3 or 4 terms.  Use a value of 0 to disable
10861** any limit on the number of terms in a compount SELECT.
10862*/
10863#ifndef SQLITE_MAX_COMPOUND_SELECT
10864# define SQLITE_MAX_COMPOUND_SELECT 500
10865#endif
10866
10867/*
10868** The maximum number of opcodes in a VDBE program.
10869** Not currently enforced.
10870*/
10871#ifndef SQLITE_MAX_VDBE_OP
10872# define SQLITE_MAX_VDBE_OP 250000000
10873#endif
10874
10875/*
10876** The maximum number of arguments to an SQL function.
10877*/
10878#ifndef SQLITE_MAX_FUNCTION_ARG
10879# define SQLITE_MAX_FUNCTION_ARG 127
10880#endif
10881
10882/*
10883** The suggested maximum number of in-memory pages to use for
10884** the main database table and for temporary tables.
10885**
10886** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
10887** which means the cache size is limited to 2048000 bytes of memory.
10888** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
10889** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
10890*/
10891#ifndef SQLITE_DEFAULT_CACHE_SIZE
10892# define SQLITE_DEFAULT_CACHE_SIZE  -2000
10893#endif
10894
10895/*
10896** The default number of frames to accumulate in the log file before
10897** checkpointing the database in WAL mode.
10898*/
10899#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
10900# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
10901#endif
10902
10903/*
10904** The maximum number of attached databases.  This must be between 0
10905** and 125.  The upper bound of 125 is because the attached databases are
10906** counted using a signed 8-bit integer which has a maximum value of 127
10907** and we have to allow 2 extra counts for the "main" and "temp" databases.
10908*/
10909#ifndef SQLITE_MAX_ATTACHED
10910# define SQLITE_MAX_ATTACHED 10
10911#endif
10912
10913
10914/*
10915** The maximum value of a ?nnn wildcard that the parser will accept.
10916*/
10917#ifndef SQLITE_MAX_VARIABLE_NUMBER
10918# define SQLITE_MAX_VARIABLE_NUMBER 999
10919#endif
10920
10921/* Maximum page size.  The upper bound on this value is 65536.  This a limit
10922** imposed by the use of 16-bit offsets within each page.
10923**
10924** Earlier versions of SQLite allowed the user to change this value at
10925** compile time. This is no longer permitted, on the grounds that it creates
10926** a library that is technically incompatible with an SQLite library
10927** compiled with a different limit. If a process operating on a database
10928** with a page-size of 65536 bytes crashes, then an instance of SQLite
10929** compiled with the default page-size limit will not be able to rollback
10930** the aborted transaction. This could lead to database corruption.
10931*/
10932#ifdef SQLITE_MAX_PAGE_SIZE
10933# undef SQLITE_MAX_PAGE_SIZE
10934#endif
10935#define SQLITE_MAX_PAGE_SIZE 65536
10936
10937
10938/*
10939** The default size of a database page.
10940*/
10941#ifndef SQLITE_DEFAULT_PAGE_SIZE
10942# define SQLITE_DEFAULT_PAGE_SIZE 4096
10943#endif
10944#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
10945# undef SQLITE_DEFAULT_PAGE_SIZE
10946# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
10947#endif
10948
10949/*
10950** Ordinarily, if no value is explicitly provided, SQLite creates databases
10951** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
10952** device characteristics (sector-size and atomic write() support),
10953** SQLite may choose a larger value. This constant is the maximum value
10954** SQLite will choose on its own.
10955*/
10956#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
10957# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
10958#endif
10959#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
10960# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
10961# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
10962#endif
10963
10964
10965/*
10966** Maximum number of pages in one database file.
10967**
10968** This is really just the default value for the max_page_count pragma.
10969** This value can be lowered (or raised) at run-time using that the
10970** max_page_count macro.
10971*/
10972#ifndef SQLITE_MAX_PAGE_COUNT
10973# define SQLITE_MAX_PAGE_COUNT 1073741823
10974#endif
10975
10976/*
10977** Maximum length (in bytes) of the pattern in a LIKE or GLOB
10978** operator.
10979*/
10980#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
10981# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
10982#endif
10983
10984/*
10985** Maximum depth of recursion for triggers.
10986**
10987** A value of 1 means that a trigger program will not be able to itself
10988** fire any triggers. A value of 0 means that no trigger programs at all
10989** may be executed.
10990*/
10991#ifndef SQLITE_MAX_TRIGGER_DEPTH
10992# define SQLITE_MAX_TRIGGER_DEPTH 1000
10993#endif
10994
10995/************** End of sqliteLimit.h *****************************************/
10996/************** Continuing where we left off in sqliteInt.h ******************/
10997
10998/* Disable nuisance warnings on Borland compilers */
10999#if defined(__BORLANDC__)
11000#pragma warn -rch /* unreachable code */
11001#pragma warn -ccc /* Condition is always true or false */
11002#pragma warn -aus /* Assigned value is never used */
11003#pragma warn -csu /* Comparing signed and unsigned */
11004#pragma warn -spa /* Suspicious pointer arithmetic */
11005#endif
11006
11007/*
11008** Include standard header files as necessary
11009*/
11010#ifdef HAVE_STDINT_H
11011#include <stdint.h>
11012#endif
11013#ifdef HAVE_INTTYPES_H
11014#include <inttypes.h>
11015#endif
11016
11017/*
11018** The following macros are used to cast pointers to integers and
11019** integers to pointers.  The way you do this varies from one compiler
11020** to the next, so we have developed the following set of #if statements
11021** to generate appropriate macros for a wide range of compilers.
11022**
11023** The correct "ANSI" way to do this is to use the intptr_t type.
11024** Unfortunately, that typedef is not available on all compilers, or
11025** if it is available, it requires an #include of specific headers
11026** that vary from one machine to the next.
11027**
11028** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
11029** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
11030** So we have to define the macros in different ways depending on the
11031** compiler.
11032*/
11033#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
11034# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
11035# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
11036#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
11037# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
11038# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
11039#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
11040# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
11041# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
11042#else                          /* Generates a warning - but it always works */
11043# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
11044# define SQLITE_PTR_TO_INT(X)  ((int)(X))
11045#endif
11046
11047/*
11048** A macro to hint to the compiler that a function should not be
11049** inlined.
11050*/
11051#if defined(__GNUC__)
11052#  define SQLITE_NOINLINE  __attribute__((noinline))
11053#elif defined(_MSC_VER) && _MSC_VER>=1310
11054#  define SQLITE_NOINLINE  __declspec(noinline)
11055#else
11056#  define SQLITE_NOINLINE
11057#endif
11058
11059/*
11060** Make sure that the compiler intrinsics we desire are enabled when
11061** compiling with an appropriate version of MSVC unless prevented by
11062** the SQLITE_DISABLE_INTRINSIC define.
11063*/
11064#if !defined(SQLITE_DISABLE_INTRINSIC)
11065#  if defined(_MSC_VER) && _MSC_VER>=1400
11066#    if !defined(_WIN32_WCE)
11067#      include <intrin.h>
11068#      pragma intrinsic(_byteswap_ushort)
11069#      pragma intrinsic(_byteswap_ulong)
11070#      pragma intrinsic(_byteswap_uint64)
11071#      pragma intrinsic(_ReadWriteBarrier)
11072#    else
11073#      include <cmnintrin.h>
11074#    endif
11075#  endif
11076#endif
11077
11078/*
11079** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
11080** 0 means mutexes are permanently disable and the library is never
11081** threadsafe.  1 means the library is serialized which is the highest
11082** level of threadsafety.  2 means the library is multithreaded - multiple
11083** threads can use SQLite as long as no two threads try to use the same
11084** database connection at the same time.
11085**
11086** Older versions of SQLite used an optional THREADSAFE macro.
11087** We support that for legacy.
11088*/
11089#if !defined(SQLITE_THREADSAFE)
11090# if defined(THREADSAFE)
11091#   define SQLITE_THREADSAFE THREADSAFE
11092# else
11093#   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
11094# endif
11095#endif
11096
11097/*
11098** Powersafe overwrite is on by default.  But can be turned off using
11099** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
11100*/
11101#ifndef SQLITE_POWERSAFE_OVERWRITE
11102# define SQLITE_POWERSAFE_OVERWRITE 1
11103#endif
11104
11105/*
11106** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
11107** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
11108** which case memory allocation statistics are disabled by default.
11109*/
11110#if !defined(SQLITE_DEFAULT_MEMSTATUS)
11111# define SQLITE_DEFAULT_MEMSTATUS 1
11112#endif
11113
11114/*
11115** Exactly one of the following macros must be defined in order to
11116** specify which memory allocation subsystem to use.
11117**
11118**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
11119**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
11120**     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
11121**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
11122**
11123** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
11124** assert() macro is enabled, each call into the Win32 native heap subsystem
11125** will cause HeapValidate to be called.  If heap validation should fail, an
11126** assertion will be triggered.
11127**
11128** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
11129** the default.
11130*/
11131#if defined(SQLITE_SYSTEM_MALLOC) \
11132  + defined(SQLITE_WIN32_MALLOC) \
11133  + defined(SQLITE_ZERO_MALLOC) \
11134  + defined(SQLITE_MEMDEBUG)>1
11135# error "Two or more of the following compile-time configuration options\
11136 are defined but at most one is allowed:\
11137 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
11138 SQLITE_ZERO_MALLOC"
11139#endif
11140#if defined(SQLITE_SYSTEM_MALLOC) \
11141  + defined(SQLITE_WIN32_MALLOC) \
11142  + defined(SQLITE_ZERO_MALLOC) \
11143  + defined(SQLITE_MEMDEBUG)==0
11144# define SQLITE_SYSTEM_MALLOC 1
11145#endif
11146
11147/*
11148** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
11149** sizes of memory allocations below this value where possible.
11150*/
11151#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
11152# define SQLITE_MALLOC_SOFT_LIMIT 1024
11153#endif
11154
11155/*
11156** We need to define _XOPEN_SOURCE as follows in order to enable
11157** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
11158** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
11159** it.
11160*/
11161#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
11162#  define _XOPEN_SOURCE 600
11163#endif
11164
11165/*
11166** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
11167** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
11168** make it true by defining or undefining NDEBUG.
11169**
11170** Setting NDEBUG makes the code smaller and faster by disabling the
11171** assert() statements in the code.  So we want the default action
11172** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
11173** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
11174** feature.
11175*/
11176#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
11177# define NDEBUG 1
11178#endif
11179#if defined(NDEBUG) && defined(SQLITE_DEBUG)
11180# undef NDEBUG
11181#endif
11182
11183/*
11184** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
11185*/
11186#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
11187# define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
11188#endif
11189
11190/*
11191** The testcase() macro is used to aid in coverage testing.  When
11192** doing coverage testing, the condition inside the argument to
11193** testcase() must be evaluated both true and false in order to
11194** get full branch coverage.  The testcase() macro is inserted
11195** to help ensure adequate test coverage in places where simple
11196** condition/decision coverage is inadequate.  For example, testcase()
11197** can be used to make sure boundary values are tested.  For
11198** bitmask tests, testcase() can be used to make sure each bit
11199** is significant and used at least once.  On switch statements
11200** where multiple cases go to the same block of code, testcase()
11201** can insure that all cases are evaluated.
11202**
11203*/
11204#ifdef SQLITE_COVERAGE_TEST
11205SQLITE_PRIVATE   void sqlite3Coverage(int);
11206# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
11207#else
11208# define testcase(X)
11209#endif
11210
11211/*
11212** The TESTONLY macro is used to enclose variable declarations or
11213** other bits of code that are needed to support the arguments
11214** within testcase() and assert() macros.
11215*/
11216#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
11217# define TESTONLY(X)  X
11218#else
11219# define TESTONLY(X)
11220#endif
11221
11222/*
11223** Sometimes we need a small amount of code such as a variable initialization
11224** to setup for a later assert() statement.  We do not want this code to
11225** appear when assert() is disabled.  The following macro is therefore
11226** used to contain that setup code.  The "VVA" acronym stands for
11227** "Verification, Validation, and Accreditation".  In other words, the
11228** code within VVA_ONLY() will only run during verification processes.
11229*/
11230#ifndef NDEBUG
11231# define VVA_ONLY(X)  X
11232#else
11233# define VVA_ONLY(X)
11234#endif
11235
11236/*
11237** The ALWAYS and NEVER macros surround boolean expressions which
11238** are intended to always be true or false, respectively.  Such
11239** expressions could be omitted from the code completely.  But they
11240** are included in a few cases in order to enhance the resilience
11241** of SQLite to unexpected behavior - to make the code "self-healing"
11242** or "ductile" rather than being "brittle" and crashing at the first
11243** hint of unplanned behavior.
11244**
11245** In other words, ALWAYS and NEVER are added for defensive code.
11246**
11247** When doing coverage testing ALWAYS and NEVER are hard-coded to
11248** be true and false so that the unreachable code they specify will
11249** not be counted as untested code.
11250*/
11251#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
11252# define ALWAYS(X)      (1)
11253# define NEVER(X)       (0)
11254#elif !defined(NDEBUG)
11255# define ALWAYS(X)      ((X)?1:(assert(0),0))
11256# define NEVER(X)       ((X)?(assert(0),1):0)
11257#else
11258# define ALWAYS(X)      (X)
11259# define NEVER(X)       (X)
11260#endif
11261
11262/*
11263** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
11264** defined.  We need to defend against those failures when testing with
11265** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
11266** during a normal build.  The following macro can be used to disable tests
11267** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
11268*/
11269#if defined(SQLITE_TEST_REALLOC_STRESS)
11270# define ONLY_IF_REALLOC_STRESS(X)  (X)
11271#elif !defined(NDEBUG)
11272# define ONLY_IF_REALLOC_STRESS(X)  ((X)?(assert(0),1):0)
11273#else
11274# define ONLY_IF_REALLOC_STRESS(X)  (0)
11275#endif
11276
11277/*
11278** Declarations used for tracing the operating system interfaces.
11279*/
11280#if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
11281    (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
11282  extern int sqlite3OSTrace;
11283# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
11284# define SQLITE_HAVE_OS_TRACE
11285#else
11286# define OSTRACE(X)
11287# undef  SQLITE_HAVE_OS_TRACE
11288#endif
11289
11290/*
11291** Is the sqlite3ErrName() function needed in the build?  Currently,
11292** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
11293** OSTRACE is enabled), and by several "test*.c" files (which are
11294** compiled using SQLITE_TEST).
11295*/
11296#if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
11297    (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
11298# define SQLITE_NEED_ERR_NAME
11299#else
11300# undef  SQLITE_NEED_ERR_NAME
11301#endif
11302
11303/*
11304** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
11305*/
11306#ifdef SQLITE_OMIT_EXPLAIN
11307# undef SQLITE_ENABLE_EXPLAIN_COMMENTS
11308#endif
11309
11310/*
11311** Return true (non-zero) if the input is an integer that is too large
11312** to fit in 32-bits.  This macro is used inside of various testcase()
11313** macros to verify that we have tested SQLite for large-file support.
11314*/
11315#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
11316
11317/*
11318** The macro unlikely() is a hint that surrounds a boolean
11319** expression that is usually false.  Macro likely() surrounds
11320** a boolean expression that is usually true.  These hints could,
11321** in theory, be used by the compiler to generate better code, but
11322** currently they are just comments for human readers.
11323*/
11324#define likely(X)    (X)
11325#define unlikely(X)  (X)
11326
11327/************** Include hash.h in the middle of sqliteInt.h ******************/
11328/************** Begin file hash.h ********************************************/
11329/*
11330** 2001 September 22
11331**
11332** The author disclaims copyright to this source code.  In place of
11333** a legal notice, here is a blessing:
11334**
11335**    May you do good and not evil.
11336**    May you find forgiveness for yourself and forgive others.
11337**    May you share freely, never taking more than you give.
11338**
11339*************************************************************************
11340** This is the header file for the generic hash-table implementation
11341** used in SQLite.
11342*/
11343#ifndef SQLITE_HASH_H
11344#define SQLITE_HASH_H
11345
11346/* Forward declarations of structures. */
11347typedef struct Hash Hash;
11348typedef struct HashElem HashElem;
11349
11350/* A complete hash table is an instance of the following structure.
11351** The internals of this structure are intended to be opaque -- client
11352** code should not attempt to access or modify the fields of this structure
11353** directly.  Change this structure only by using the routines below.
11354** However, some of the "procedures" and "functions" for modifying and
11355** accessing this structure are really macros, so we can't really make
11356** this structure opaque.
11357**
11358** All elements of the hash table are on a single doubly-linked list.
11359** Hash.first points to the head of this list.
11360**
11361** There are Hash.htsize buckets.  Each bucket points to a spot in
11362** the global doubly-linked list.  The contents of the bucket are the
11363** element pointed to plus the next _ht.count-1 elements in the list.
11364**
11365** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
11366** by a linear search of the global list.  For small tables, the
11367** Hash.ht table is never allocated because if there are few elements
11368** in the table, it is faster to do a linear search than to manage
11369** the hash table.
11370*/
11371struct Hash {
11372  unsigned int htsize;      /* Number of buckets in the hash table */
11373  unsigned int count;       /* Number of entries in this table */
11374  HashElem *first;          /* The first element of the array */
11375  struct _ht {              /* the hash table */
11376    int count;                 /* Number of entries with this hash */
11377    HashElem *chain;           /* Pointer to first entry with this hash */
11378  } *ht;
11379};
11380
11381/* Each element in the hash table is an instance of the following
11382** structure.  All elements are stored on a single doubly-linked list.
11383**
11384** Again, this structure is intended to be opaque, but it can't really
11385** be opaque because it is used by macros.
11386*/
11387struct HashElem {
11388  HashElem *next, *prev;       /* Next and previous elements in the table */
11389  void *data;                  /* Data associated with this element */
11390  const char *pKey;            /* Key associated with this element */
11391};
11392
11393/*
11394** Access routines.  To delete, insert a NULL pointer.
11395*/
11396SQLITE_PRIVATE void sqlite3HashInit(Hash*);
11397SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
11398SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
11399SQLITE_PRIVATE void sqlite3HashClear(Hash*);
11400
11401/*
11402** Macros for looping over all elements of a hash table.  The idiom is
11403** like this:
11404**
11405**   Hash h;
11406**   HashElem *p;
11407**   ...
11408**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
11409**     SomeStructure *pData = sqliteHashData(p);
11410**     // do something with pData
11411**   }
11412*/
11413#define sqliteHashFirst(H)  ((H)->first)
11414#define sqliteHashNext(E)   ((E)->next)
11415#define sqliteHashData(E)   ((E)->data)
11416/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
11417/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
11418
11419/*
11420** Number of entries in a hash table
11421*/
11422/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
11423
11424#endif /* SQLITE_HASH_H */
11425
11426/************** End of hash.h ************************************************/
11427/************** Continuing where we left off in sqliteInt.h ******************/
11428/************** Include parse.h in the middle of sqliteInt.h *****************/
11429/************** Begin file parse.h *******************************************/
11430#define TK_SEMI                             1
11431#define TK_EXPLAIN                          2
11432#define TK_QUERY                            3
11433#define TK_PLAN                             4
11434#define TK_BEGIN                            5
11435#define TK_TRANSACTION                      6
11436#define TK_DEFERRED                         7
11437#define TK_IMMEDIATE                        8
11438#define TK_EXCLUSIVE                        9
11439#define TK_COMMIT                          10
11440#define TK_END                             11
11441#define TK_ROLLBACK                        12
11442#define TK_SAVEPOINT                       13
11443#define TK_RELEASE                         14
11444#define TK_TO                              15
11445#define TK_TABLE                           16
11446#define TK_CREATE                          17
11447#define TK_IF                              18
11448#define TK_NOT                             19
11449#define TK_EXISTS                          20
11450#define TK_TEMP                            21
11451#define TK_LP                              22
11452#define TK_RP                              23
11453#define TK_AS                              24
11454#define TK_WITHOUT                         25
11455#define TK_COMMA                           26
11456#define TK_OR                              27
11457#define TK_AND                             28
11458#define TK_IS                              29
11459#define TK_MATCH                           30
11460#define TK_LIKE_KW                         31
11461#define TK_BETWEEN                         32
11462#define TK_IN                              33
11463#define TK_ISNULL                          34
11464#define TK_NOTNULL                         35
11465#define TK_NE                              36
11466#define TK_EQ                              37
11467#define TK_GT                              38
11468#define TK_LE                              39
11469#define TK_LT                              40
11470#define TK_GE                              41
11471#define TK_ESCAPE                          42
11472#define TK_BITAND                          43
11473#define TK_BITOR                           44
11474#define TK_LSHIFT                          45
11475#define TK_RSHIFT                          46
11476#define TK_PLUS                            47
11477#define TK_MINUS                           48
11478#define TK_STAR                            49
11479#define TK_SLASH                           50
11480#define TK_REM                             51
11481#define TK_CONCAT                          52
11482#define TK_COLLATE                         53
11483#define TK_BITNOT                          54
11484#define TK_ID                              55
11485#define TK_INDEXED                         56
11486#define TK_ABORT                           57
11487#define TK_ACTION                          58
11488#define TK_AFTER                           59
11489#define TK_ANALYZE                         60
11490#define TK_ASC                             61
11491#define TK_ATTACH                          62
11492#define TK_BEFORE                          63
11493#define TK_BY                              64
11494#define TK_CASCADE                         65
11495#define TK_CAST                            66
11496#define TK_COLUMNKW                        67
11497#define TK_CONFLICT                        68
11498#define TK_DATABASE                        69
11499#define TK_DESC                            70
11500#define TK_DETACH                          71
11501#define TK_EACH                            72
11502#define TK_FAIL                            73
11503#define TK_FOR                             74
11504#define TK_IGNORE                          75
11505#define TK_INITIALLY                       76
11506#define TK_INSTEAD                         77
11507#define TK_NO                              78
11508#define TK_KEY                             79
11509#define TK_OF                              80
11510#define TK_OFFSET                          81
11511#define TK_PRAGMA                          82
11512#define TK_RAISE                           83
11513#define TK_RECURSIVE                       84
11514#define TK_REPLACE                         85
11515#define TK_RESTRICT                        86
11516#define TK_ROW                             87
11517#define TK_TRIGGER                         88
11518#define TK_VACUUM                          89
11519#define TK_VIEW                            90
11520#define TK_VIRTUAL                         91
11521#define TK_WITH                            92
11522#define TK_REINDEX                         93
11523#define TK_RENAME                          94
11524#define TK_CTIME_KW                        95
11525#define TK_ANY                             96
11526#define TK_STRING                          97
11527#define TK_JOIN_KW                         98
11528#define TK_CONSTRAINT                      99
11529#define TK_DEFAULT                        100
11530#define TK_NULL                           101
11531#define TK_PRIMARY                        102
11532#define TK_UNIQUE                         103
11533#define TK_CHECK                          104
11534#define TK_REFERENCES                     105
11535#define TK_AUTOINCR                       106
11536#define TK_ON                             107
11537#define TK_INSERT                         108
11538#define TK_DELETE                         109
11539#define TK_UPDATE                         110
11540#define TK_SET                            111
11541#define TK_DEFERRABLE                     112
11542#define TK_FOREIGN                        113
11543#define TK_DROP                           114
11544#define TK_UNION                          115
11545#define TK_ALL                            116
11546#define TK_EXCEPT                         117
11547#define TK_INTERSECT                      118
11548#define TK_SELECT                         119
11549#define TK_VALUES                         120
11550#define TK_DISTINCT                       121
11551#define TK_DOT                            122
11552#define TK_FROM                           123
11553#define TK_JOIN                           124
11554#define TK_USING                          125
11555#define TK_ORDER                          126
11556#define TK_GROUP                          127
11557#define TK_HAVING                         128
11558#define TK_LIMIT                          129
11559#define TK_WHERE                          130
11560#define TK_INTO                           131
11561#define TK_FLOAT                          132
11562#define TK_BLOB                           133
11563#define TK_INTEGER                        134
11564#define TK_VARIABLE                       135
11565#define TK_CASE                           136
11566#define TK_WHEN                           137
11567#define TK_THEN                           138
11568#define TK_ELSE                           139
11569#define TK_INDEX                          140
11570#define TK_ALTER                          141
11571#define TK_ADD                            142
11572#define TK_TO_TEXT                        143
11573#define TK_TO_BLOB                        144
11574#define TK_TO_NUMERIC                     145
11575#define TK_TO_INT                         146
11576#define TK_TO_REAL                        147
11577#define TK_ISNOT                          148
11578#define TK_END_OF_FILE                    149
11579#define TK_UNCLOSED_STRING                150
11580#define TK_FUNCTION                       151
11581#define TK_COLUMN                         152
11582#define TK_AGG_FUNCTION                   153
11583#define TK_AGG_COLUMN                     154
11584#define TK_UMINUS                         155
11585#define TK_UPLUS                          156
11586#define TK_REGISTER                       157
11587#define TK_VECTOR                         158
11588#define TK_SELECT_COLUMN                  159
11589#define TK_ASTERISK                       160
11590#define TK_SPAN                           161
11591#define TK_SPACE                          162
11592#define TK_ILLEGAL                        163
11593
11594/* The token codes above must all fit in 8 bits */
11595#define TKFLG_MASK           0xff
11596
11597/* Flags that can be added to a token code when it is not
11598** being stored in a u8: */
11599#define TKFLG_DONTFOLD       0x100  /* Omit constant folding optimizations */
11600
11601/************** End of parse.h ***********************************************/
11602/************** Continuing where we left off in sqliteInt.h ******************/
11603#include <stdio.h>
11604#include <stdlib.h>
11605#include <string.h>
11606#include <assert.h>
11607#include <stddef.h>
11608
11609/*
11610** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
11611** This allows better measurements of where memcpy() is used when running
11612** cachegrind.  But this macro version of memcpy() is very slow so it
11613** should not be used in production.  This is a performance measurement
11614** hack only.
11615*/
11616#ifdef SQLITE_INLINE_MEMCPY
11617# define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
11618                        int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
11619#endif
11620
11621/*
11622** If compiling for a processor that lacks floating point support,
11623** substitute integer for floating-point
11624*/
11625#ifdef SQLITE_OMIT_FLOATING_POINT
11626# define double sqlite_int64
11627# define float sqlite_int64
11628# define LONGDOUBLE_TYPE sqlite_int64
11629# ifndef SQLITE_BIG_DBL
11630#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
11631# endif
11632# define SQLITE_OMIT_DATETIME_FUNCS 1
11633# define SQLITE_OMIT_TRACE 1
11634# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11635# undef SQLITE_HAVE_ISNAN
11636#endif
11637#ifndef SQLITE_BIG_DBL
11638# define SQLITE_BIG_DBL (1e99)
11639#endif
11640
11641/*
11642** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
11643** afterward. Having this macro allows us to cause the C compiler
11644** to omit code used by TEMP tables without messy #ifndef statements.
11645*/
11646#ifdef SQLITE_OMIT_TEMPDB
11647#define OMIT_TEMPDB 1
11648#else
11649#define OMIT_TEMPDB 0
11650#endif
11651
11652/*
11653** The "file format" number is an integer that is incremented whenever
11654** the VDBE-level file format changes.  The following macros define the
11655** the default file format for new databases and the maximum file format
11656** that the library can read.
11657*/
11658#define SQLITE_MAX_FILE_FORMAT 4
11659#ifndef SQLITE_DEFAULT_FILE_FORMAT
11660# define SQLITE_DEFAULT_FILE_FORMAT 4
11661#endif
11662
11663/*
11664** Determine whether triggers are recursive by default.  This can be
11665** changed at run-time using a pragma.
11666*/
11667#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
11668# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
11669#endif
11670
11671/*
11672** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
11673** on the command-line
11674*/
11675#ifndef SQLITE_TEMP_STORE
11676# define SQLITE_TEMP_STORE 1
11677# define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
11678#endif
11679
11680/*
11681** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
11682** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
11683** to zero.
11684*/
11685#if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
11686# undef SQLITE_MAX_WORKER_THREADS
11687# define SQLITE_MAX_WORKER_THREADS 0
11688#endif
11689#ifndef SQLITE_MAX_WORKER_THREADS
11690# define SQLITE_MAX_WORKER_THREADS 8
11691#endif
11692#ifndef SQLITE_DEFAULT_WORKER_THREADS
11693# define SQLITE_DEFAULT_WORKER_THREADS 0
11694#endif
11695#if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
11696# undef SQLITE_MAX_WORKER_THREADS
11697# define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
11698#endif
11699
11700/*
11701** The default initial allocation for the pagecache when using separate
11702** pagecaches for each database connection.  A positive number is the
11703** number of pages.  A negative number N translations means that a buffer
11704** of -1024*N bytes is allocated and used for as many pages as it will hold.
11705**
11706** The default value of "20" was choosen to minimize the run-time of the
11707** speedtest1 test program with options: --shrink-memory --reprepare
11708*/
11709#ifndef SQLITE_DEFAULT_PCACHE_INITSZ
11710# define SQLITE_DEFAULT_PCACHE_INITSZ 20
11711#endif
11712
11713/*
11714** GCC does not define the offsetof() macro so we'll have to do it
11715** ourselves.
11716*/
11717#ifndef offsetof
11718#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
11719#endif
11720
11721/*
11722** Macros to compute minimum and maximum of two numbers.
11723*/
11724#ifndef MIN
11725# define MIN(A,B) ((A)<(B)?(A):(B))
11726#endif
11727#ifndef MAX
11728# define MAX(A,B) ((A)>(B)?(A):(B))
11729#endif
11730
11731/*
11732** Swap two objects of type TYPE.
11733*/
11734#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
11735
11736/*
11737** Check to see if this machine uses EBCDIC.  (Yes, believe it or
11738** not, there are still machines out there that use EBCDIC.)
11739*/
11740#if 'A' == '\301'
11741# define SQLITE_EBCDIC 1
11742#else
11743# define SQLITE_ASCII 1
11744#endif
11745
11746/*
11747** Integers of known sizes.  These typedefs might change for architectures
11748** where the sizes very.  Preprocessor macros are available so that the
11749** types can be conveniently redefined at compile-type.  Like this:
11750**
11751**         cc '-DUINTPTR_TYPE=long long int' ...
11752*/
11753#ifndef UINT32_TYPE
11754# ifdef HAVE_UINT32_T
11755#  define UINT32_TYPE uint32_t
11756# else
11757#  define UINT32_TYPE unsigned int
11758# endif
11759#endif
11760#ifndef UINT16_TYPE
11761# ifdef HAVE_UINT16_T
11762#  define UINT16_TYPE uint16_t
11763# else
11764#  define UINT16_TYPE unsigned short int
11765# endif
11766#endif
11767#ifndef INT16_TYPE
11768# ifdef HAVE_INT16_T
11769#  define INT16_TYPE int16_t
11770# else
11771#  define INT16_TYPE short int
11772# endif
11773#endif
11774#ifndef UINT8_TYPE
11775# ifdef HAVE_UINT8_T
11776#  define UINT8_TYPE uint8_t
11777# else
11778#  define UINT8_TYPE unsigned char
11779# endif
11780#endif
11781#ifndef INT8_TYPE
11782# ifdef HAVE_INT8_T
11783#  define INT8_TYPE int8_t
11784# else
11785#  define INT8_TYPE signed char
11786# endif
11787#endif
11788#ifndef LONGDOUBLE_TYPE
11789# define LONGDOUBLE_TYPE long double
11790#endif
11791typedef sqlite_int64 i64;          /* 8-byte signed integer */
11792typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
11793typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
11794typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
11795typedef INT16_TYPE i16;            /* 2-byte signed integer */
11796typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
11797typedef INT8_TYPE i8;              /* 1-byte signed integer */
11798
11799/*
11800** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
11801** that can be stored in a u32 without loss of data.  The value
11802** is 0x00000000ffffffff.  But because of quirks of some compilers, we
11803** have to specify the value in the less intuitive manner shown:
11804*/
11805#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
11806
11807/*
11808** The datatype used to store estimates of the number of rows in a
11809** table or index.  This is an unsigned integer type.  For 99.9% of
11810** the world, a 32-bit integer is sufficient.  But a 64-bit integer
11811** can be used at compile-time if desired.
11812*/
11813#ifdef SQLITE_64BIT_STATS
11814 typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
11815#else
11816 typedef u32 tRowcnt;    /* 32-bit is the default */
11817#endif
11818
11819/*
11820** Estimated quantities used for query planning are stored as 16-bit
11821** logarithms.  For quantity X, the value stored is 10*log2(X).  This
11822** gives a possible range of values of approximately 1.0e986 to 1e-986.
11823** But the allowed values are "grainy".  Not every value is representable.
11824** For example, quantities 16 and 17 are both represented by a LogEst
11825** of 40.  However, since LogEst quantities are suppose to be estimates,
11826** not exact values, this imprecision is not a problem.
11827**
11828** "LogEst" is short for "Logarithmic Estimate".
11829**
11830** Examples:
11831**      1 -> 0              20 -> 43          10000 -> 132
11832**      2 -> 10             25 -> 46          25000 -> 146
11833**      3 -> 16            100 -> 66        1000000 -> 199
11834**      4 -> 20           1000 -> 99        1048576 -> 200
11835**     10 -> 33           1024 -> 100    4294967296 -> 320
11836**
11837** The LogEst can be negative to indicate fractional values.
11838** Examples:
11839**
11840**    0.5 -> -10           0.1 -> -33        0.0625 -> -40
11841*/
11842typedef INT16_TYPE LogEst;
11843
11844/*
11845** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
11846*/
11847#ifndef SQLITE_PTRSIZE
11848# if defined(__SIZEOF_POINTER__)
11849#   define SQLITE_PTRSIZE __SIZEOF_POINTER__
11850# elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
11851       defined(_M_ARM)   || defined(__arm__)    || defined(__x86)
11852#   define SQLITE_PTRSIZE 4
11853# else
11854#   define SQLITE_PTRSIZE 8
11855# endif
11856#endif
11857
11858/* The uptr type is an unsigned integer large enough to hold a pointer
11859*/
11860#if defined(HAVE_STDINT_H)
11861  typedef uintptr_t uptr;
11862#elif SQLITE_PTRSIZE==4
11863  typedef u32 uptr;
11864#else
11865  typedef u64 uptr;
11866#endif
11867
11868/*
11869** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
11870** something between S (inclusive) and E (exclusive).
11871**
11872** In other words, S is a buffer and E is a pointer to the first byte after
11873** the end of buffer S.  This macro returns true if P points to something
11874** contained within the buffer S.
11875*/
11876#define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
11877
11878
11879/*
11880** Macros to determine whether the machine is big or little endian,
11881** and whether or not that determination is run-time or compile-time.
11882**
11883** For best performance, an attempt is made to guess at the byte-order
11884** using C-preprocessor macros.  If that is unsuccessful, or if
11885** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
11886** at run-time.
11887*/
11888#ifndef SQLITE_BYTEORDER
11889# if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
11890     defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
11891     defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
11892     defined(__arm__)
11893#   define SQLITE_BYTEORDER    1234
11894# elif defined(sparc)    || defined(__ppc__)
11895#   define SQLITE_BYTEORDER    4321
11896# else
11897#   define SQLITE_BYTEORDER 0
11898# endif
11899#endif
11900#if SQLITE_BYTEORDER==4321
11901# define SQLITE_BIGENDIAN    1
11902# define SQLITE_LITTLEENDIAN 0
11903# define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
11904#elif SQLITE_BYTEORDER==1234
11905# define SQLITE_BIGENDIAN    0
11906# define SQLITE_LITTLEENDIAN 1
11907# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
11908#else
11909# ifdef SQLITE_AMALGAMATION
11910  const int sqlite3one = 1;
11911# else
11912  extern const int sqlite3one;
11913# endif
11914# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
11915# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
11916# define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
11917#endif
11918
11919/*
11920** Constants for the largest and smallest possible 64-bit signed integers.
11921** These macros are designed to work correctly on both 32-bit and 64-bit
11922** compilers.
11923*/
11924#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
11925#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
11926
11927/*
11928** Round up a number to the next larger multiple of 8.  This is used
11929** to force 8-byte alignment on 64-bit architectures.
11930*/
11931#define ROUND8(x)     (((x)+7)&~7)
11932
11933/*
11934** Round down to the nearest multiple of 8
11935*/
11936#define ROUNDDOWN8(x) ((x)&~7)
11937
11938/*
11939** Assert that the pointer X is aligned to an 8-byte boundary.  This
11940** macro is used only within assert() to verify that the code gets
11941** all alignment restrictions correct.
11942**
11943** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
11944** underlying malloc() implementation might return us 4-byte aligned
11945** pointers.  In that case, only verify 4-byte alignment.
11946*/
11947#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11948# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
11949#else
11950# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
11951#endif
11952
11953/*
11954** Disable MMAP on platforms where it is known to not work
11955*/
11956#if defined(__OpenBSD__) || defined(__QNXNTO__)
11957# undef SQLITE_MAX_MMAP_SIZE
11958# define SQLITE_MAX_MMAP_SIZE 0
11959#endif
11960
11961/*
11962** Default maximum size of memory used by memory-mapped I/O in the VFS
11963*/
11964#ifdef __APPLE__
11965# include <TargetConditionals.h>
11966#endif
11967#ifndef SQLITE_MAX_MMAP_SIZE
11968# if defined(__linux__) \
11969  || defined(_WIN32) \
11970  || (defined(__APPLE__) && defined(__MACH__)) \
11971  || defined(__sun) \
11972  || defined(__FreeBSD__) \
11973  || defined(__DragonFly__)
11974#   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
11975# else
11976#   define SQLITE_MAX_MMAP_SIZE 0
11977# endif
11978# define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
11979#endif
11980
11981/*
11982** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
11983** default MMAP_SIZE is specified at compile-time, make sure that it does
11984** not exceed the maximum mmap size.
11985*/
11986#ifndef SQLITE_DEFAULT_MMAP_SIZE
11987# define SQLITE_DEFAULT_MMAP_SIZE 0
11988# define SQLITE_DEFAULT_MMAP_SIZE_xc 1  /* Exclude from ctime.c */
11989#endif
11990#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
11991# undef SQLITE_DEFAULT_MMAP_SIZE
11992# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
11993#endif
11994
11995/*
11996** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
11997** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
11998** define SQLITE_ENABLE_STAT3_OR_STAT4
11999*/
12000#ifdef SQLITE_ENABLE_STAT4
12001# undef SQLITE_ENABLE_STAT3
12002# define SQLITE_ENABLE_STAT3_OR_STAT4 1
12003#elif SQLITE_ENABLE_STAT3
12004# define SQLITE_ENABLE_STAT3_OR_STAT4 1
12005#elif SQLITE_ENABLE_STAT3_OR_STAT4
12006# undef SQLITE_ENABLE_STAT3_OR_STAT4
12007#endif
12008
12009/*
12010** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
12011** the Select query generator tracing logic is turned on.
12012*/
12013#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
12014# define SELECTTRACE_ENABLED 1
12015#else
12016# define SELECTTRACE_ENABLED 0
12017#endif
12018
12019/*
12020** An instance of the following structure is used to store the busy-handler
12021** callback for a given sqlite handle.
12022**
12023** The sqlite.busyHandler member of the sqlite struct contains the busy
12024** callback for the database handle. Each pager opened via the sqlite
12025** handle is passed a pointer to sqlite.busyHandler. The busy-handler
12026** callback is currently invoked only from within pager.c.
12027*/
12028typedef struct BusyHandler BusyHandler;
12029struct BusyHandler {
12030  int (*xFunc)(void *,int);  /* The busy callback */
12031  void *pArg;                /* First arg to busy callback */
12032  int nBusy;                 /* Incremented with each busy call */
12033};
12034
12035/*
12036** Name of the master database table.  The master database table
12037** is a special table that holds the names and attributes of all
12038** user tables and indices.
12039*/
12040#define MASTER_NAME       "sqlite_master"
12041#define TEMP_MASTER_NAME  "sqlite_temp_master"
12042
12043/*
12044** The root-page of the master database table.
12045*/
12046#define MASTER_ROOT       1
12047
12048/*
12049** The name of the schema table.
12050*/
12051#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
12052
12053/*
12054** A convenience macro that returns the number of elements in
12055** an array.
12056*/
12057#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
12058
12059/*
12060** Determine if the argument is a power of two
12061*/
12062#define IsPowerOfTwo(X) (((X)&((X)-1))==0)
12063
12064/*
12065** The following value as a destructor means to use sqlite3DbFree().
12066** The sqlite3DbFree() routine requires two parameters instead of the
12067** one parameter that destructors normally want.  So we have to introduce
12068** this magic value that the code knows to handle differently.  Any
12069** pointer will work here as long as it is distinct from SQLITE_STATIC
12070** and SQLITE_TRANSIENT.
12071*/
12072#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
12073
12074/*
12075** When SQLITE_OMIT_WSD is defined, it means that the target platform does
12076** not support Writable Static Data (WSD) such as global and static variables.
12077** All variables must either be on the stack or dynamically allocated from
12078** the heap.  When WSD is unsupported, the variable declarations scattered
12079** throughout the SQLite code must become constants instead.  The SQLITE_WSD
12080** macro is used for this purpose.  And instead of referencing the variable
12081** directly, we use its constant as a key to lookup the run-time allocated
12082** buffer that holds real variable.  The constant is also the initializer
12083** for the run-time allocated buffer.
12084**
12085** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
12086** macros become no-ops and have zero performance impact.
12087*/
12088#ifdef SQLITE_OMIT_WSD
12089  #define SQLITE_WSD const
12090  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
12091  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
12092SQLITE_API int sqlite3_wsd_init(int N, int J);
12093SQLITE_API void *sqlite3_wsd_find(void *K, int L);
12094#else
12095  #define SQLITE_WSD
12096  #define GLOBAL(t,v) v
12097  #define sqlite3GlobalConfig sqlite3Config
12098#endif
12099
12100/*
12101** The following macros are used to suppress compiler warnings and to
12102** make it clear to human readers when a function parameter is deliberately
12103** left unused within the body of a function. This usually happens when
12104** a function is called via a function pointer. For example the
12105** implementation of an SQL aggregate step callback may not use the
12106** parameter indicating the number of arguments passed to the aggregate,
12107** if it knows that this is enforced elsewhere.
12108**
12109** When a function parameter is not used at all within the body of a function,
12110** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
12111** However, these macros may also be used to suppress warnings related to
12112** parameters that may or may not be used depending on compilation options.
12113** For example those parameters only used in assert() statements. In these
12114** cases the parameters are named as per the usual conventions.
12115*/
12116#define UNUSED_PARAMETER(x) (void)(x)
12117#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
12118
12119/*
12120** Forward references to structures
12121*/
12122typedef struct AggInfo AggInfo;
12123typedef struct AuthContext AuthContext;
12124typedef struct AutoincInfo AutoincInfo;
12125typedef struct Bitvec Bitvec;
12126typedef struct CollSeq CollSeq;
12127typedef struct Column Column;
12128typedef struct Db Db;
12129typedef struct Schema Schema;
12130typedef struct Expr Expr;
12131typedef struct ExprList ExprList;
12132typedef struct ExprSpan ExprSpan;
12133typedef struct FKey FKey;
12134typedef struct FuncDestructor FuncDestructor;
12135typedef struct FuncDef FuncDef;
12136typedef struct FuncDefHash FuncDefHash;
12137typedef struct IdList IdList;
12138typedef struct Index Index;
12139typedef struct IndexSample IndexSample;
12140typedef struct KeyClass KeyClass;
12141typedef struct KeyInfo KeyInfo;
12142typedef struct Lookaside Lookaside;
12143typedef struct LookasideSlot LookasideSlot;
12144typedef struct Module Module;
12145typedef struct NameContext NameContext;
12146typedef struct Parse Parse;
12147typedef struct PreUpdate PreUpdate;
12148typedef struct PrintfArguments PrintfArguments;
12149typedef struct RowSet RowSet;
12150typedef struct Savepoint Savepoint;
12151typedef struct Select Select;
12152typedef struct SQLiteThread SQLiteThread;
12153typedef struct SelectDest SelectDest;
12154typedef struct SrcList SrcList;
12155typedef struct StrAccum StrAccum;
12156typedef struct Table Table;
12157typedef struct TableLock TableLock;
12158typedef struct Token Token;
12159typedef struct TreeView TreeView;
12160typedef struct Trigger Trigger;
12161typedef struct TriggerPrg TriggerPrg;
12162typedef struct TriggerStep TriggerStep;
12163typedef struct UnpackedRecord UnpackedRecord;
12164typedef struct VTable VTable;
12165typedef struct VtabCtx VtabCtx;
12166typedef struct Walker Walker;
12167typedef struct WhereInfo WhereInfo;
12168typedef struct With With;
12169
12170/* A VList object records a mapping between parameters/variables/wildcards
12171** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
12172** variable number associated with that parameter.  See the format description
12173** on the sqlite3VListAdd() routine for more information.  A VList is really
12174** just an array of integers.
12175*/
12176typedef int VList;
12177
12178/*
12179** Defer sourcing vdbe.h and btree.h until after the "u8" and
12180** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
12181** pointer types (i.e. FuncDef) defined above.
12182*/
12183/************** Include btree.h in the middle of sqliteInt.h *****************/
12184/************** Begin file btree.h *******************************************/
12185/*
12186** 2001 September 15
12187**
12188** The author disclaims copyright to this source code.  In place of
12189** a legal notice, here is a blessing:
12190**
12191**    May you do good and not evil.
12192**    May you find forgiveness for yourself and forgive others.
12193**    May you share freely, never taking more than you give.
12194**
12195*************************************************************************
12196** This header file defines the interface that the sqlite B-Tree file
12197** subsystem.  See comments in the source code for a detailed description
12198** of what each interface routine does.
12199*/
12200#ifndef SQLITE_BTREE_H
12201#define SQLITE_BTREE_H
12202
12203/* TODO: This definition is just included so other modules compile. It
12204** needs to be revisited.
12205*/
12206#define SQLITE_N_BTREE_META 16
12207
12208/*
12209** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
12210** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
12211*/
12212#ifndef SQLITE_DEFAULT_AUTOVACUUM
12213  #define SQLITE_DEFAULT_AUTOVACUUM 0
12214#endif
12215
12216#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
12217#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
12218#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
12219
12220/*
12221** Forward declarations of structure
12222*/
12223typedef struct Btree Btree;
12224typedef struct BtCursor BtCursor;
12225typedef struct BtShared BtShared;
12226typedef struct BtreePayload BtreePayload;
12227
12228
12229SQLITE_PRIVATE int sqlite3BtreeOpen(
12230  sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
12231  const char *zFilename,   /* Name of database file to open */
12232  sqlite3 *db,             /* Associated database connection */
12233  Btree **ppBtree,         /* Return open Btree* here */
12234  int flags,               /* Flags */
12235  int vfsFlags             /* Flags passed through to VFS open */
12236);
12237
12238/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
12239** following values.
12240**
12241** NOTE:  These values must match the corresponding PAGER_ values in
12242** pager.h.
12243*/
12244#define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
12245#define BTREE_MEMORY        2  /* This is an in-memory DB */
12246#define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
12247#define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
12248
12249SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
12250SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
12251SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
12252#if SQLITE_MAX_MMAP_SIZE>0
12253SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
12254#endif
12255SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
12256SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
12257SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
12258SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
12259SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
12260SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
12261SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
12262SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
12263SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
12264SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
12265SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
12266SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
12267SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
12268SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
12269SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
12270SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
12271SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
12272SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
12273SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
12274SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
12275SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
12276SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
12277#ifndef SQLITE_OMIT_SHARED_CACHE
12278SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
12279#endif
12280SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
12281
12282SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
12283SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
12284SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
12285
12286SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
12287
12288/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
12289** of the flags shown below.
12290**
12291** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
12292** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
12293** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
12294** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
12295** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
12296** indices.)
12297*/
12298#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
12299#define BTREE_BLOBKEY    2    /* Table has keys only - no data */
12300
12301SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
12302SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
12303SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
12304SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
12305
12306SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
12307SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
12308
12309SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
12310
12311/*
12312** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
12313** should be one of the following values. The integer values are assigned
12314** to constants so that the offset of the corresponding field in an
12315** SQLite database header may be found using the following formula:
12316**
12317**   offset = 36 + (idx * 4)
12318**
12319** For example, the free-page-count field is located at byte offset 36 of
12320** the database file header. The incr-vacuum-flag field is located at
12321** byte offset 64 (== 36+4*7).
12322**
12323** The BTREE_DATA_VERSION value is not really a value stored in the header.
12324** It is a read-only number computed by the pager.  But we merge it with
12325** the header value access routines since its access pattern is the same.
12326** Call it a "virtual meta value".
12327*/
12328#define BTREE_FREE_PAGE_COUNT     0
12329#define BTREE_SCHEMA_VERSION      1
12330#define BTREE_FILE_FORMAT         2
12331#define BTREE_DEFAULT_CACHE_SIZE  3
12332#define BTREE_LARGEST_ROOT_PAGE   4
12333#define BTREE_TEXT_ENCODING       5
12334#define BTREE_USER_VERSION        6
12335#define BTREE_INCR_VACUUM         7
12336#define BTREE_APPLICATION_ID      8
12337#define BTREE_DATA_VERSION        15  /* A virtual meta-value */
12338
12339/*
12340** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
12341** interface.
12342**
12343** BTREE_HINT_RANGE  (arguments: Expr*, Mem*)
12344**
12345**     The first argument is an Expr* (which is guaranteed to be constant for
12346**     the lifetime of the cursor) that defines constraints on which rows
12347**     might be fetched with this cursor.  The Expr* tree may contain
12348**     TK_REGISTER nodes that refer to values stored in the array of registers
12349**     passed as the second parameter.  In other words, if Expr.op==TK_REGISTER
12350**     then the value of the node is the value in Mem[pExpr.iTable].  Any
12351**     TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
12352**     column of the b-tree of the cursor.  The Expr tree will not contain
12353**     any function calls nor subqueries nor references to b-trees other than
12354**     the cursor being hinted.
12355**
12356**     The design of the _RANGE hint is aid b-tree implementations that try
12357**     to prefetch content from remote machines - to provide those
12358**     implementations with limits on what needs to be prefetched and thereby
12359**     reduce network bandwidth.
12360**
12361** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
12362** standard SQLite.  The other hints are provided for extentions that use
12363** the SQLite parser and code generator but substitute their own storage
12364** engine.
12365*/
12366#define BTREE_HINT_RANGE 0       /* Range constraints on queries */
12367
12368/*
12369** Values that may be OR'd together to form the argument to the
12370** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
12371**
12372** The BTREE_BULKLOAD flag is set on index cursors when the index is going
12373** to be filled with content that is already in sorted order.
12374**
12375** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
12376** OP_SeekLE opcodes for a range search, but where the range of entries
12377** selected will all have the same key.  In other words, the cursor will
12378** be used only for equality key searches.
12379**
12380*/
12381#define BTREE_BULKLOAD 0x00000001  /* Used to full index in sorted order */
12382#define BTREE_SEEK_EQ  0x00000002  /* EQ seeks only - no range seeks */
12383
12384/*
12385** Flags passed as the third argument to sqlite3BtreeCursor().
12386**
12387** For read-only cursors the wrFlag argument is always zero. For read-write
12388** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
12389** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
12390** only be used by SQLite for the following:
12391**
12392**   * to seek to and then delete specific entries, and/or
12393**
12394**   * to read values that will be used to create keys that other
12395**     BTREE_FORDELETE cursors will seek to and delete.
12396**
12397** The BTREE_FORDELETE flag is an optimization hint.  It is not used by
12398** by this, the native b-tree engine of SQLite, but it is available to
12399** alternative storage engines that might be substituted in place of this
12400** b-tree system.  For alternative storage engines in which a delete of
12401** the main table row automatically deletes corresponding index rows,
12402** the FORDELETE flag hint allows those alternative storage engines to
12403** skip a lot of work.  Namely:  FORDELETE cursors may treat all SEEK
12404** and DELETE operations as no-ops, and any READ operation against a
12405** FORDELETE cursor may return a null row: 0x01 0x00.
12406*/
12407#define BTREE_WRCSR     0x00000004     /* read-write cursor */
12408#define BTREE_FORDELETE 0x00000008     /* Cursor is for seek/delete only */
12409
12410SQLITE_PRIVATE int sqlite3BtreeCursor(
12411  Btree*,                              /* BTree containing table to open */
12412  int iTable,                          /* Index of root page */
12413  int wrFlag,                          /* 1 for writing.  0 for read-only */
12414  struct KeyInfo*,                     /* First argument to compare function */
12415  BtCursor *pCursor                    /* Space to write cursor structure */
12416);
12417SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
12418SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
12419SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
12420#ifdef SQLITE_ENABLE_CURSOR_HINTS
12421SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
12422#endif
12423
12424SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
12425SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
12426  BtCursor*,
12427  UnpackedRecord *pUnKey,
12428  i64 intKey,
12429  int bias,
12430  int *pRes
12431);
12432SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
12433SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
12434SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
12435
12436/* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
12437#define BTREE_SAVEPOSITION 0x02  /* Leave cursor pointing at NEXT or PREV */
12438#define BTREE_AUXDELETE    0x04  /* not the primary delete operation */
12439#define BTREE_APPEND       0x08  /* Insert is likely an append */
12440
12441/* An instance of the BtreePayload object describes the content of a single
12442** entry in either an index or table btree.
12443**
12444** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
12445** an arbitrary key and no data.  These btrees have pKey,nKey set to their
12446** key and pData,nData,nZero set to zero.
12447**
12448** Table btrees (used for rowid tables) contain an integer rowid used as
12449** the key and passed in the nKey field.  The pKey field is zero.
12450** pData,nData hold the content of the new entry.  nZero extra zero bytes
12451** are appended to the end of the content when constructing the entry.
12452**
12453** This object is used to pass information into sqlite3BtreeInsert().  The
12454** same information used to be passed as five separate parameters.  But placing
12455** the information into this object helps to keep the interface more
12456** organized and understandable, and it also helps the resulting code to
12457** run a little faster by using fewer registers for parameter passing.
12458*/
12459struct BtreePayload {
12460  const void *pKey;       /* Key content for indexes.  NULL for tables */
12461  sqlite3_int64 nKey;     /* Size of pKey for indexes.  PRIMARY KEY for tabs */
12462  const void *pData;      /* Data for tables.  NULL for indexes */
12463  struct Mem *aMem;       /* First of nMem value in the unpacked pKey */
12464  u16 nMem;               /* Number of aMem[] value.  Might be zero */
12465  int nData;              /* Size of pData.  0 if none. */
12466  int nZero;              /* Extra zero data appended after pData,nData */
12467};
12468
12469SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
12470                       int flags, int seekResult);
12471SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
12472SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
12473SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
12474SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
12475SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
12476SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
12477SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
12478SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
12479SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
12480
12481SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
12482SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
12483SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
12484
12485#ifndef SQLITE_OMIT_INCRBLOB
12486SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
12487SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
12488SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
12489#endif
12490SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
12491SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
12492SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
12493SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
12494SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
12495
12496#ifndef NDEBUG
12497SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
12498#endif
12499SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
12500
12501#ifndef SQLITE_OMIT_BTREECOUNT
12502SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
12503#endif
12504
12505#ifdef SQLITE_TEST
12506SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
12507SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
12508#endif
12509
12510#ifndef SQLITE_OMIT_WAL
12511SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
12512#endif
12513
12514/*
12515** If we are not using shared cache, then there is no need to
12516** use mutexes to access the BtShared structures.  So make the
12517** Enter and Leave procedures no-ops.
12518*/
12519#ifndef SQLITE_OMIT_SHARED_CACHE
12520SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
12521SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
12522SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
12523SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
12524SQLITE_PRIVATE   int sqlite3BtreeConnectionCount(Btree*);
12525#else
12526# define sqlite3BtreeEnter(X)
12527# define sqlite3BtreeEnterAll(X)
12528# define sqlite3BtreeSharable(X) 0
12529# define sqlite3BtreeEnterCursor(X)
12530# define sqlite3BtreeConnectionCount(X) 1
12531#endif
12532
12533#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
12534SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
12535SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
12536SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
12537#ifndef NDEBUG
12538  /* These routines are used inside assert() statements only. */
12539SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
12540SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
12541SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
12542#endif
12543#else
12544
12545# define sqlite3BtreeLeave(X)
12546# define sqlite3BtreeLeaveCursor(X)
12547# define sqlite3BtreeLeaveAll(X)
12548
12549# define sqlite3BtreeHoldsMutex(X) 1
12550# define sqlite3BtreeHoldsAllMutexes(X) 1
12551# define sqlite3SchemaMutexHeld(X,Y,Z) 1
12552#endif
12553
12554
12555#endif /* SQLITE_BTREE_H */
12556
12557/************** End of btree.h ***********************************************/
12558/************** Continuing where we left off in sqliteInt.h ******************/
12559/************** Include vdbe.h in the middle of sqliteInt.h ******************/
12560/************** Begin file vdbe.h ********************************************/
12561/*
12562** 2001 September 15
12563**
12564** The author disclaims copyright to this source code.  In place of
12565** a legal notice, here is a blessing:
12566**
12567**    May you do good and not evil.
12568**    May you find forgiveness for yourself and forgive others.
12569**    May you share freely, never taking more than you give.
12570**
12571*************************************************************************
12572** Header file for the Virtual DataBase Engine (VDBE)
12573**
12574** This header defines the interface to the virtual database engine
12575** or VDBE.  The VDBE implements an abstract machine that runs a
12576** simple program to access and modify the underlying database.
12577*/
12578#ifndef SQLITE_VDBE_H
12579#define SQLITE_VDBE_H
12580/* #include <stdio.h> */
12581
12582/*
12583** A single VDBE is an opaque structure named "Vdbe".  Only routines
12584** in the source file sqliteVdbe.c are allowed to see the insides
12585** of this structure.
12586*/
12587typedef struct Vdbe Vdbe;
12588
12589/*
12590** The names of the following types declared in vdbeInt.h are required
12591** for the VdbeOp definition.
12592*/
12593typedef struct Mem Mem;
12594typedef struct SubProgram SubProgram;
12595
12596/*
12597** A single instruction of the virtual machine has an opcode
12598** and as many as three operands.  The instruction is recorded
12599** as an instance of the following structure:
12600*/
12601struct VdbeOp {
12602  u8 opcode;          /* What operation to perform */
12603  signed char p4type; /* One of the P4_xxx constants for p4 */
12604  u16 p5;             /* Fifth parameter is an unsigned 16-bit integer */
12605  int p1;             /* First operand */
12606  int p2;             /* Second parameter (often the jump destination) */
12607  int p3;             /* The third parameter */
12608  union p4union {     /* fourth parameter */
12609    int i;                 /* Integer value if p4type==P4_INT32 */
12610    void *p;               /* Generic pointer */
12611    char *z;               /* Pointer to data for string (char array) types */
12612    i64 *pI64;             /* Used when p4type is P4_INT64 */
12613    double *pReal;         /* Used when p4type is P4_REAL */
12614    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
12615    sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
12616    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
12617    Mem *pMem;             /* Used when p4type is P4_MEM */
12618    VTable *pVtab;         /* Used when p4type is P4_VTAB */
12619    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
12620    int *ai;               /* Used when p4type is P4_INTARRAY */
12621    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
12622    Table *pTab;           /* Used when p4type is P4_TABLE */
12623#ifdef SQLITE_ENABLE_CURSOR_HINTS
12624    Expr *pExpr;           /* Used when p4type is P4_EXPR */
12625#endif
12626    int (*xAdvance)(BtCursor *, int *);
12627  } p4;
12628#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
12629  char *zComment;          /* Comment to improve readability */
12630#endif
12631#ifdef VDBE_PROFILE
12632  u32 cnt;                 /* Number of times this instruction was executed */
12633  u64 cycles;              /* Total time spent executing this instruction */
12634#endif
12635#ifdef SQLITE_VDBE_COVERAGE
12636  int iSrcLine;            /* Source-code line that generated this opcode */
12637#endif
12638};
12639typedef struct VdbeOp VdbeOp;
12640
12641
12642/*
12643** A sub-routine used to implement a trigger program.
12644*/
12645struct SubProgram {
12646  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
12647  int nOp;                      /* Elements in aOp[] */
12648  int nMem;                     /* Number of memory cells required */
12649  int nCsr;                     /* Number of cursors required */
12650  u8 *aOnce;                    /* Array of OP_Once flags */
12651  void *token;                  /* id that may be used to recursive triggers */
12652  SubProgram *pNext;            /* Next sub-program already visited */
12653};
12654
12655/*
12656** A smaller version of VdbeOp used for the VdbeAddOpList() function because
12657** it takes up less space.
12658*/
12659struct VdbeOpList {
12660  u8 opcode;          /* What operation to perform */
12661  signed char p1;     /* First operand */
12662  signed char p2;     /* Second parameter (often the jump destination) */
12663  signed char p3;     /* Third parameter */
12664};
12665typedef struct VdbeOpList VdbeOpList;
12666
12667/*
12668** Allowed values of VdbeOp.p4type
12669*/
12670#define P4_NOTUSED    0   /* The P4 parameter is not used */
12671#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
12672#define P4_STATIC   (-2)  /* Pointer to a static string */
12673#define P4_COLLSEQ  (-3)  /* P4 is a pointer to a CollSeq structure */
12674#define P4_FUNCDEF  (-4)  /* P4 is a pointer to a FuncDef structure */
12675#define P4_KEYINFO  (-5)  /* P4 is a pointer to a KeyInfo structure */
12676#define P4_EXPR     (-6)  /* P4 is a pointer to an Expr tree */
12677#define P4_MEM      (-7)  /* P4 is a pointer to a Mem*    structure */
12678#define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
12679#define P4_VTAB     (-8) /* P4 is a pointer to an sqlite3_vtab structure */
12680#define P4_REAL     (-9) /* P4 is a 64-bit floating point value */
12681#define P4_INT64    (-10) /* P4 is a 64-bit signed integer */
12682#define P4_INT32    (-11) /* P4 is a 32-bit signed integer */
12683#define P4_INTARRAY (-12) /* P4 is a vector of 32-bit integers */
12684#define P4_SUBPROGRAM  (-13) /* P4 is a pointer to a SubProgram structure */
12685#define P4_ADVANCE  (-14) /* P4 is a pointer to BtreeNext() or BtreePrev() */
12686#define P4_TABLE    (-15) /* P4 is a pointer to a Table structure */
12687#define P4_FUNCCTX  (-16) /* P4 is a pointer to an sqlite3_context object */
12688
12689/* Error message codes for OP_Halt */
12690#define P5_ConstraintNotNull 1
12691#define P5_ConstraintUnique  2
12692#define P5_ConstraintCheck   3
12693#define P5_ConstraintFK      4
12694
12695/*
12696** The Vdbe.aColName array contains 5n Mem structures, where n is the
12697** number of columns of data returned by the statement.
12698*/
12699#define COLNAME_NAME     0
12700#define COLNAME_DECLTYPE 1
12701#define COLNAME_DATABASE 2
12702#define COLNAME_TABLE    3
12703#define COLNAME_COLUMN   4
12704#ifdef SQLITE_ENABLE_COLUMN_METADATA
12705# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
12706#else
12707# ifdef SQLITE_OMIT_DECLTYPE
12708#   define COLNAME_N      1      /* Store only the name */
12709# else
12710#   define COLNAME_N      2      /* Store the name and decltype */
12711# endif
12712#endif
12713
12714/*
12715** The following macro converts a relative address in the p2 field
12716** of a VdbeOp structure into a negative number so that
12717** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
12718** the macro again restores the address.
12719*/
12720#define ADDR(X)  (-1-(X))
12721
12722/*
12723** The makefile scans the vdbe.c source file and creates the "opcodes.h"
12724** header file that defines a number for each opcode used by the VDBE.
12725*/
12726/************** Include opcodes.h in the middle of vdbe.h ********************/
12727/************** Begin file opcodes.h *****************************************/
12728/* Automatically generated.  Do not edit */
12729/* See the tool/mkopcodeh.tcl script for details */
12730#define OP_Savepoint       0
12731#define OP_AutoCommit      1
12732#define OP_Transaction     2
12733#define OP_SorterNext      3
12734#define OP_PrevIfOpen      4
12735#define OP_NextIfOpen      5
12736#define OP_Prev            6
12737#define OP_Next            7
12738#define OP_Checkpoint      8
12739#define OP_JournalMode     9
12740#define OP_Vacuum         10
12741#define OP_VFilter        11 /* synopsis: iplan=r[P3] zplan='P4'           */
12742#define OP_VUpdate        12 /* synopsis: data=r[P3@P2]                    */
12743#define OP_Goto           13
12744#define OP_Gosub          14
12745#define OP_InitCoroutine  15
12746#define OP_Yield          16
12747#define OP_MustBeInt      17
12748#define OP_Jump           18
12749#define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
12750#define OP_Once           20
12751#define OP_If             21
12752#define OP_IfNot          22
12753#define OP_SeekLT         23 /* synopsis: key=r[P3@P4]                     */
12754#define OP_SeekLE         24 /* synopsis: key=r[P3@P4]                     */
12755#define OP_SeekGE         25 /* synopsis: key=r[P3@P4]                     */
12756#define OP_SeekGT         26 /* synopsis: key=r[P3@P4]                     */
12757#define OP_Or             27 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
12758#define OP_And            28 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
12759#define OP_NoConflict     29 /* synopsis: key=r[P3@P4]                     */
12760#define OP_NotFound       30 /* synopsis: key=r[P3@P4]                     */
12761#define OP_Found          31 /* synopsis: key=r[P3@P4]                     */
12762#define OP_SeekRowid      32 /* synopsis: intkey=r[P3]                     */
12763#define OP_NotExists      33 /* synopsis: intkey=r[P3]                     */
12764#define OP_IsNull         34 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
12765#define OP_NotNull        35 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
12766#define OP_Ne             36 /* same as TK_NE, synopsis: IF r[P3]!=r[P1]   */
12767#define OP_Eq             37 /* same as TK_EQ, synopsis: IF r[P3]==r[P1]   */
12768#define OP_Gt             38 /* same as TK_GT, synopsis: IF r[P3]>r[P1]    */
12769#define OP_Le             39 /* same as TK_LE, synopsis: IF r[P3]<=r[P1]   */
12770#define OP_Lt             40 /* same as TK_LT, synopsis: IF r[P3]<r[P1]    */
12771#define OP_Ge             41 /* same as TK_GE, synopsis: IF r[P3]>=r[P1]   */
12772#define OP_ElseNotEq      42 /* same as TK_ESCAPE                          */
12773#define OP_BitAnd         43 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
12774#define OP_BitOr          44 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
12775#define OP_ShiftLeft      45 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
12776#define OP_ShiftRight     46 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
12777#define OP_Add            47 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
12778#define OP_Subtract       48 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
12779#define OP_Multiply       49 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
12780#define OP_Divide         50 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
12781#define OP_Remainder      51 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
12782#define OP_Concat         52 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
12783#define OP_Last           53
12784#define OP_BitNot         54 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
12785#define OP_IfSmaller      55
12786#define OP_SorterSort     56
12787#define OP_Sort           57
12788#define OP_Rewind         58
12789#define OP_IdxLE          59 /* synopsis: key=r[P3@P4]                     */
12790#define OP_IdxGT          60 /* synopsis: key=r[P3@P4]                     */
12791#define OP_IdxLT          61 /* synopsis: key=r[P3@P4]                     */
12792#define OP_IdxGE          62 /* synopsis: key=r[P3@P4]                     */
12793#define OP_RowSetRead     63 /* synopsis: r[P3]=rowset(P1)                 */
12794#define OP_RowSetTest     64 /* synopsis: if r[P3] in rowset(P1) goto P2   */
12795#define OP_Program        65
12796#define OP_FkIfZero       66 /* synopsis: if fkctr[P1]==0 goto P2          */
12797#define OP_IfPos          67 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
12798#define OP_IfNotZero      68 /* synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
12799#define OP_DecrJumpZero   69 /* synopsis: if (--r[P1])==0 goto P2          */
12800#define OP_IncrVacuum     70
12801#define OP_VNext          71
12802#define OP_Init           72 /* synopsis: Start at P2                      */
12803#define OP_Return         73
12804#define OP_EndCoroutine   74
12805#define OP_HaltIfNull     75 /* synopsis: if r[P3]=null halt               */
12806#define OP_Halt           76
12807#define OP_Integer        77 /* synopsis: r[P2]=P1                         */
12808#define OP_Int64          78 /* synopsis: r[P2]=P4                         */
12809#define OP_String         79 /* synopsis: r[P2]='P4' (len=P1)              */
12810#define OP_Null           80 /* synopsis: r[P2..P3]=NULL                   */
12811#define OP_SoftNull       81 /* synopsis: r[P1]=NULL                       */
12812#define OP_Blob           82 /* synopsis: r[P2]=P4 (len=P1)                */
12813#define OP_Variable       83 /* synopsis: r[P2]=parameter(P1,P4)           */
12814#define OP_Move           84 /* synopsis: r[P2@P3]=r[P1@P3]                */
12815#define OP_Copy           85 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
12816#define OP_SCopy          86 /* synopsis: r[P2]=r[P1]                      */
12817#define OP_IntCopy        87 /* synopsis: r[P2]=r[P1]                      */
12818#define OP_ResultRow      88 /* synopsis: output=r[P1@P2]                  */
12819#define OP_CollSeq        89
12820#define OP_Function0      90 /* synopsis: r[P3]=func(r[P2@P5])             */
12821#define OP_Function       91 /* synopsis: r[P3]=func(r[P2@P5])             */
12822#define OP_AddImm         92 /* synopsis: r[P1]=r[P1]+P2                   */
12823#define OP_RealAffinity   93
12824#define OP_Cast           94 /* synopsis: affinity(r[P1])                  */
12825#define OP_Permutation    95
12826#define OP_Compare        96 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
12827#define OP_String8        97 /* same as TK_STRING, synopsis: r[P2]='P4'    */
12828#define OP_Column         98 /* synopsis: r[P3]=PX                         */
12829#define OP_Affinity       99 /* synopsis: affinity(r[P1@P2])               */
12830#define OP_MakeRecord    100 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
12831#define OP_Count         101 /* synopsis: r[P2]=count()                    */
12832#define OP_ReadCookie    102
12833#define OP_SetCookie     103
12834#define OP_ReopenIdx     104 /* synopsis: root=P2 iDb=P3                   */
12835#define OP_OpenRead      105 /* synopsis: root=P2 iDb=P3                   */
12836#define OP_OpenWrite     106 /* synopsis: root=P2 iDb=P3                   */
12837#define OP_OpenAutoindex 107 /* synopsis: nColumn=P2                       */
12838#define OP_OpenEphemeral 108 /* synopsis: nColumn=P2                       */
12839#define OP_SorterOpen    109
12840#define OP_SequenceTest  110 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
12841#define OP_OpenPseudo    111 /* synopsis: P3 columns in r[P2]              */
12842#define OP_Close         112
12843#define OP_ColumnsUsed   113
12844#define OP_Sequence      114 /* synopsis: r[P2]=cursor[P1].ctr++           */
12845#define OP_NewRowid      115 /* synopsis: r[P2]=rowid                      */
12846#define OP_Insert        116 /* synopsis: intkey=r[P3] data=r[P2]          */
12847#define OP_InsertInt     117 /* synopsis: intkey=P3 data=r[P2]             */
12848#define OP_Delete        118
12849#define OP_ResetCount    119
12850#define OP_SorterCompare 120 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
12851#define OP_SorterData    121 /* synopsis: r[P2]=data                       */
12852#define OP_RowData       122 /* synopsis: r[P2]=data                       */
12853#define OP_Rowid         123 /* synopsis: r[P2]=rowid                      */
12854#define OP_NullRow       124
12855#define OP_SorterInsert  125 /* synopsis: key=r[P2]                        */
12856#define OP_IdxInsert     126 /* synopsis: key=r[P2]                        */
12857#define OP_IdxDelete     127 /* synopsis: key=r[P2@P3]                     */
12858#define OP_Seek          128 /* synopsis: Move P3 to P1.rowid              */
12859#define OP_IdxRowid      129 /* synopsis: r[P2]=rowid                      */
12860#define OP_Destroy       130
12861#define OP_Clear         131
12862#define OP_Real          132 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
12863#define OP_ResetSorter   133
12864#define OP_CreateIndex   134 /* synopsis: r[P2]=root iDb=P1                */
12865#define OP_CreateTable   135 /* synopsis: r[P2]=root iDb=P1                */
12866#define OP_SqlExec       136
12867#define OP_ParseSchema   137
12868#define OP_LoadAnalysis  138
12869#define OP_DropTable     139
12870#define OP_DropIndex     140
12871#define OP_DropTrigger   141
12872#define OP_IntegrityCk   142
12873#define OP_RowSetAdd     143 /* synopsis: rowset(P1)=r[P2]                 */
12874#define OP_Param         144
12875#define OP_FkCounter     145 /* synopsis: fkctr[P1]+=P2                    */
12876#define OP_MemMax        146 /* synopsis: r[P1]=max(r[P1],r[P2])           */
12877#define OP_OffsetLimit   147 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
12878#define OP_AggStep0      148 /* synopsis: accum=r[P3] step(r[P2@P5])       */
12879#define OP_AggStep       149 /* synopsis: accum=r[P3] step(r[P2@P5])       */
12880#define OP_AggFinal      150 /* synopsis: accum=r[P1] N=P2                 */
12881#define OP_Expire        151
12882#define OP_TableLock     152 /* synopsis: iDb=P1 root=P2 write=P3          */
12883#define OP_VBegin        153
12884#define OP_VCreate       154
12885#define OP_VDestroy      155
12886#define OP_VOpen         156
12887#define OP_VColumn       157 /* synopsis: r[P3]=vcolumn(P2)                */
12888#define OP_VRename       158
12889#define OP_Pagecount     159
12890#define OP_MaxPgcnt      160
12891#define OP_CursorHint    161
12892#define OP_Noop          162
12893#define OP_Explain       163
12894
12895/* Properties such as "out2" or "jump" that are specified in
12896** comments following the "case" for each opcode in the vdbe.c
12897** are encoded into bitvectors as follows:
12898*/
12899#define OPFLG_JUMP        0x01  /* jump:  P2 holds jmp target */
12900#define OPFLG_IN1         0x02  /* in1:   P1 is an input */
12901#define OPFLG_IN2         0x04  /* in2:   P2 is an input */
12902#define OPFLG_IN3         0x08  /* in3:   P3 is an input */
12903#define OPFLG_OUT2        0x10  /* out2:  P2 is an output */
12904#define OPFLG_OUT3        0x20  /* out3:  P3 is an output */
12905#define OPFLG_INITIALIZER {\
12906/*   0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
12907/*   8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
12908/*  16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x09,\
12909/*  24 */ 0x09, 0x09, 0x09, 0x26, 0x26, 0x09, 0x09, 0x09,\
12910/*  32 */ 0x09, 0x09, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
12911/*  40 */ 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26, 0x26,\
12912/*  48 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x01, 0x12, 0x01,\
12913/*  56 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x23,\
12914/*  64 */ 0x0b, 0x01, 0x01, 0x03, 0x03, 0x03, 0x01, 0x01,\
12915/*  72 */ 0x01, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10,\
12916/*  80 */ 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10,\
12917/*  88 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00,\
12918/*  96 */ 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00,\
12919/* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12920/* 112 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,\
12921/* 120 */ 0x00, 0x00, 0x00, 0x10, 0x00, 0x04, 0x04, 0x00,\
12922/* 128 */ 0x00, 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10,\
12923/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,\
12924/* 144 */ 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00,\
12925/* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
12926/* 160 */ 0x10, 0x00, 0x00, 0x00,}
12927
12928/* The sqlite3P2Values() routine is able to run faster if it knows
12929** the value of the largest JUMP opcode.  The smaller the maximum
12930** JUMP opcode the better, so the mkopcodeh.tcl script that
12931** generated this include file strives to group all JUMP opcodes
12932** together near the beginning of the list.
12933*/
12934#define SQLITE_MX_JUMP_OPCODE  72  /* Maximum JUMP opcode */
12935
12936/************** End of opcodes.h *********************************************/
12937/************** Continuing where we left off in vdbe.h ***********************/
12938
12939/*
12940** Prototypes for the VDBE interface.  See comments on the implementation
12941** for a description of what each of these routines does.
12942*/
12943SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
12944SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
12945SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
12946SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
12947SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
12948SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
12949SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
12950SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
12951SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
12952SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
12953SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
12954SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
12955#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
12956SQLITE_PRIVATE   void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
12957SQLITE_PRIVATE   void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
12958#else
12959# define sqlite3VdbeVerifyNoMallocRequired(A,B)
12960# define sqlite3VdbeVerifyNoResultRow(A)
12961#endif
12962SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
12963SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
12964SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
12965SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
12966SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
12967SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
12968SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
12969SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
12970SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
12971SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
12972SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
12973SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
12974SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
12975SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
12976SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
12977SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
12978SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
12979SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
12980SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
12981SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
12982SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
12983SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
12984SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
12985SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
12986#ifdef SQLITE_DEBUG
12987SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
12988#endif
12989SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
12990SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
12991SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
12992SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
12993SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
12994SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
12995SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
12996SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
12997SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
12998SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
12999SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
13000SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
13001#ifndef SQLITE_OMIT_TRACE
13002SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
13003#endif
13004SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
13005
13006SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
13007SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
13008SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
13009SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
13010
13011typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
13012SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
13013
13014#ifndef SQLITE_OMIT_TRIGGER
13015SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
13016#endif
13017
13018/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
13019** each VDBE opcode.
13020**
13021** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
13022** comments in VDBE programs that show key decision points in the code
13023** generator.
13024*/
13025#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
13026SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
13027# define VdbeComment(X)  sqlite3VdbeComment X
13028SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
13029# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
13030# ifdef SQLITE_ENABLE_MODULE_COMMENTS
13031#   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
13032# else
13033#   define VdbeModuleComment(X)
13034# endif
13035#else
13036# define VdbeComment(X)
13037# define VdbeNoopComment(X)
13038# define VdbeModuleComment(X)
13039#endif
13040
13041/*
13042** The VdbeCoverage macros are used to set a coverage testing point
13043** for VDBE branch instructions.  The coverage testing points are line
13044** numbers in the sqlite3.c source file.  VDBE branch coverage testing
13045** only works with an amalagmation build.  That's ok since a VDBE branch
13046** coverage build designed for testing the test suite only.  No application
13047** should ever ship with VDBE branch coverage measuring turned on.
13048**
13049**    VdbeCoverage(v)                  // Mark the previously coded instruction
13050**                                     // as a branch
13051**
13052**    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
13053**
13054**    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
13055**
13056**    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
13057**
13058** Every VDBE branch operation must be tagged with one of the macros above.
13059** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
13060** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
13061** routine in vdbe.c, alerting the developer to the missed tag.
13062*/
13063#ifdef SQLITE_VDBE_COVERAGE
13064SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
13065# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
13066# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
13067# define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
13068# define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
13069# define VDBE_OFFSET_LINENO(x) (__LINE__+x)
13070#else
13071# define VdbeCoverage(v)
13072# define VdbeCoverageIf(v,x)
13073# define VdbeCoverageAlwaysTaken(v)
13074# define VdbeCoverageNeverTaken(v)
13075# define VDBE_OFFSET_LINENO(x) 0
13076#endif
13077
13078#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
13079SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
13080#else
13081# define sqlite3VdbeScanStatus(a,b,c,d,e)
13082#endif
13083
13084#endif /* SQLITE_VDBE_H */
13085
13086/************** End of vdbe.h ************************************************/
13087/************** Continuing where we left off in sqliteInt.h ******************/
13088/************** Include pager.h in the middle of sqliteInt.h *****************/
13089/************** Begin file pager.h *******************************************/
13090/*
13091** 2001 September 15
13092**
13093** The author disclaims copyright to this source code.  In place of
13094** a legal notice, here is a blessing:
13095**
13096**    May you do good and not evil.
13097**    May you find forgiveness for yourself and forgive others.
13098**    May you share freely, never taking more than you give.
13099**
13100*************************************************************************
13101** This header file defines the interface that the sqlite page cache
13102** subsystem.  The page cache subsystem reads and writes a file a page
13103** at a time and provides a journal for rollback.
13104*/
13105
13106#ifndef SQLITE_PAGER_H
13107#define SQLITE_PAGER_H
13108
13109/*
13110** Default maximum size for persistent journal files. A negative
13111** value means no limit. This value may be overridden using the
13112** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
13113*/
13114#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
13115  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
13116#endif
13117
13118/*
13119** The type used to represent a page number.  The first page in a file
13120** is called page 1.  0 is used to represent "not a page".
13121*/
13122typedef u32 Pgno;
13123
13124/*
13125** Each open file is managed by a separate instance of the "Pager" structure.
13126*/
13127typedef struct Pager Pager;
13128
13129/*
13130** Handle type for pages.
13131*/
13132typedef struct PgHdr DbPage;
13133
13134/*
13135** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
13136** reserved for working around a windows/posix incompatibility). It is
13137** used in the journal to signify that the remainder of the journal file
13138** is devoted to storing a master journal name - there are no more pages to
13139** roll back. See comments for function writeMasterJournal() in pager.c
13140** for details.
13141*/
13142#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
13143
13144/*
13145** Allowed values for the flags parameter to sqlite3PagerOpen().
13146**
13147** NOTE: These values must match the corresponding BTREE_ values in btree.h.
13148*/
13149#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
13150#define PAGER_MEMORY        0x0002    /* In-memory database */
13151
13152/*
13153** Valid values for the second argument to sqlite3PagerLockingMode().
13154*/
13155#define PAGER_LOCKINGMODE_QUERY      -1
13156#define PAGER_LOCKINGMODE_NORMAL      0
13157#define PAGER_LOCKINGMODE_EXCLUSIVE   1
13158
13159/*
13160** Numeric constants that encode the journalmode.
13161**
13162** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
13163** are exposed in the API via the "PRAGMA journal_mode" command and
13164** therefore cannot be changed without a compatibility break.
13165*/
13166#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
13167#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
13168#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
13169#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
13170#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
13171#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
13172#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
13173
13174/*
13175** Flags that make up the mask passed to sqlite3PagerGet().
13176*/
13177#define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
13178#define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
13179
13180/*
13181** Flags for sqlite3PagerSetFlags()
13182**
13183** Value constraints (enforced via assert()):
13184**    PAGER_FULLFSYNC      == SQLITE_FullFSync
13185**    PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
13186**    PAGER_CACHE_SPILL    == SQLITE_CacheSpill
13187*/
13188#define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
13189#define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
13190#define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
13191#define PAGER_SYNCHRONOUS_EXTRA     0x04  /* PRAGMA synchronous=EXTRA */
13192#define PAGER_SYNCHRONOUS_MASK      0x07  /* Mask for four values above */
13193#define PAGER_FULLFSYNC             0x08  /* PRAGMA fullfsync=ON */
13194#define PAGER_CKPT_FULLFSYNC        0x10  /* PRAGMA checkpoint_fullfsync=ON */
13195#define PAGER_CACHESPILL            0x20  /* PRAGMA cache_spill=ON */
13196#define PAGER_FLAGS_MASK            0x38  /* All above except SYNCHRONOUS */
13197
13198/*
13199** The remainder of this file contains the declarations of the functions
13200** that make up the Pager sub-system API. See source code comments for
13201** a detailed description of each routine.
13202*/
13203
13204/* Open and close a Pager connection. */
13205SQLITE_PRIVATE int sqlite3PagerOpen(
13206  sqlite3_vfs*,
13207  Pager **ppPager,
13208  const char*,
13209  int,
13210  int,
13211  int,
13212  void(*)(DbPage*)
13213);
13214SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
13215SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
13216
13217/* Functions used to configure a Pager object. */
13218SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
13219SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
13220#ifdef SQLITE_HAS_CODEC
13221SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
13222#endif
13223SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
13224SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
13225SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
13226SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
13227SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
13228SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
13229SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
13230SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
13231SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
13232SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
13233SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
13234SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
13235SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
13236
13237/* Functions used to obtain and release page references. */
13238SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
13239SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
13240SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
13241SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
13242SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
13243
13244/* Operations on page references. */
13245SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
13246SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
13247SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
13248SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
13249SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
13250SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
13251
13252/* Functions used to manage pager transactions and savepoints. */
13253SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
13254SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
13255SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
13256SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
13257SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
13258SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
13259SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
13260SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
13261SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
13262SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
13263
13264#ifndef SQLITE_OMIT_WAL
13265SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
13266SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
13267SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
13268SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
13269SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
13270# ifdef SQLITE_DIRECT_OVERFLOW_READ
13271SQLITE_PRIVATE   int sqlite3PagerUseWal(Pager *pPager, Pgno);
13272# endif
13273# ifdef SQLITE_ENABLE_SNAPSHOT
13274SQLITE_PRIVATE   int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
13275SQLITE_PRIVATE   int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
13276SQLITE_PRIVATE   int sqlite3PagerSnapshotRecover(Pager *pPager);
13277# endif
13278#else
13279# define sqlite3PagerUseWal(x,y) 0
13280#endif
13281
13282#ifdef SQLITE_ENABLE_ZIPVFS
13283SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
13284#endif
13285
13286/* Functions used to query pager state and configuration. */
13287SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
13288SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
13289#ifdef SQLITE_DEBUG
13290SQLITE_PRIVATE   int sqlite3PagerRefcount(Pager*);
13291#endif
13292SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
13293SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
13294SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
13295SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
13296SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
13297SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
13298SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
13299SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
13300SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
13301SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
13302SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
13303
13304/* Functions used to truncate the database file. */
13305SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
13306
13307SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
13308
13309#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
13310SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
13311#endif
13312
13313/* Functions to support testing and debugging. */
13314#if !defined(NDEBUG) || defined(SQLITE_TEST)
13315SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
13316SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
13317#endif
13318#ifdef SQLITE_TEST
13319SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
13320SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
13321  void disable_simulated_io_errors(void);
13322  void enable_simulated_io_errors(void);
13323#else
13324# define disable_simulated_io_errors()
13325# define enable_simulated_io_errors()
13326#endif
13327
13328#endif /* SQLITE_PAGER_H */
13329
13330/************** End of pager.h ***********************************************/
13331/************** Continuing where we left off in sqliteInt.h ******************/
13332/************** Include pcache.h in the middle of sqliteInt.h ****************/
13333/************** Begin file pcache.h ******************************************/
13334/*
13335** 2008 August 05
13336**
13337** The author disclaims copyright to this source code.  In place of
13338** a legal notice, here is a blessing:
13339**
13340**    May you do good and not evil.
13341**    May you find forgiveness for yourself and forgive others.
13342**    May you share freely, never taking more than you give.
13343**
13344*************************************************************************
13345** This header file defines the interface that the sqlite page cache
13346** subsystem.
13347*/
13348
13349#ifndef _PCACHE_H_
13350
13351typedef struct PgHdr PgHdr;
13352typedef struct PCache PCache;
13353
13354/*
13355** Every page in the cache is controlled by an instance of the following
13356** structure.
13357*/
13358struct PgHdr {
13359  sqlite3_pcache_page *pPage;    /* Pcache object page handle */
13360  void *pData;                   /* Page data */
13361  void *pExtra;                  /* Extra content */
13362  PgHdr *pDirty;                 /* Transient list of dirty sorted by pgno */
13363  Pager *pPager;                 /* The pager this page is part of */
13364  Pgno pgno;                     /* Page number for this page */
13365#ifdef SQLITE_CHECK_PAGES
13366  u32 pageHash;                  /* Hash of page content */
13367#endif
13368  u16 flags;                     /* PGHDR flags defined below */
13369
13370  /**********************************************************************
13371  ** Elements above are public.  All that follows is private to pcache.c
13372  ** and should not be accessed by other modules.
13373  */
13374  i16 nRef;                      /* Number of users of this page */
13375  PCache *pCache;                /* Cache that owns this page */
13376
13377  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
13378  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
13379};
13380
13381/* Bit values for PgHdr.flags */
13382#define PGHDR_CLEAN           0x001  /* Page not on the PCache.pDirty list */
13383#define PGHDR_DIRTY           0x002  /* Page is on the PCache.pDirty list */
13384#define PGHDR_WRITEABLE       0x004  /* Journaled and ready to modify */
13385#define PGHDR_NEED_SYNC       0x008  /* Fsync the rollback journal before
13386                                     ** writing this page to the database */
13387#define PGHDR_DONT_WRITE      0x010  /* Do not write content to disk */
13388#define PGHDR_MMAP            0x020  /* This is an mmap page object */
13389
13390#define PGHDR_WAL_APPEND      0x040  /* Appended to wal file */
13391
13392/* Initialize and shutdown the page cache subsystem */
13393SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
13394SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
13395
13396/* Page cache buffer management:
13397** These routines implement SQLITE_CONFIG_PAGECACHE.
13398*/
13399SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
13400
13401/* Create a new pager cache.
13402** Under memory stress, invoke xStress to try to make pages clean.
13403** Only clean and unpinned pages can be reclaimed.
13404*/
13405SQLITE_PRIVATE int sqlite3PcacheOpen(
13406  int szPage,                    /* Size of every page */
13407  int szExtra,                   /* Extra space associated with each page */
13408  int bPurgeable,                /* True if pages are on backing store */
13409  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
13410  void *pStress,                 /* Argument to xStress */
13411  PCache *pToInit                /* Preallocated space for the PCache */
13412);
13413
13414/* Modify the page-size after the cache has been created. */
13415SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
13416
13417/* Return the size in bytes of a PCache object.  Used to preallocate
13418** storage space.
13419*/
13420SQLITE_PRIVATE int sqlite3PcacheSize(void);
13421
13422/* One release per successful fetch.  Page is pinned until released.
13423** Reference counted.
13424*/
13425SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
13426SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
13427SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
13428SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
13429
13430SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
13431SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
13432SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
13433SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
13434SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
13435
13436/* Change a page number.  Used by incr-vacuum. */
13437SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
13438
13439/* Remove all pages with pgno>x.  Reset the cache if x==0 */
13440SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
13441
13442/* Get a list of all dirty pages in the cache, sorted by page number */
13443SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
13444
13445/* Reset and close the cache object */
13446SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
13447
13448/* Clear flags from pages of the page cache */
13449SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
13450
13451/* Discard the contents of the cache */
13452SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
13453
13454/* Return the total number of outstanding page references */
13455SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
13456
13457/* Increment the reference count of an existing page */
13458SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
13459
13460SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
13461
13462/* Return the total number of pages stored in the cache */
13463SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
13464
13465#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
13466/* Iterate through all dirty pages currently stored in the cache. This
13467** interface is only available if SQLITE_CHECK_PAGES is defined when the
13468** library is built.
13469*/
13470SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
13471#endif
13472
13473#if defined(SQLITE_DEBUG)
13474/* Check invariants on a PgHdr object */
13475SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
13476#endif
13477
13478/* Set and get the suggested cache-size for the specified pager-cache.
13479**
13480** If no global maximum is configured, then the system attempts to limit
13481** the total number of pages cached by purgeable pager-caches to the sum
13482** of the suggested cache-sizes.
13483*/
13484SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
13485#ifdef SQLITE_TEST
13486SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
13487#endif
13488
13489/* Set or get the suggested spill-size for the specified pager-cache.
13490**
13491** The spill-size is the minimum number of pages in cache before the cache
13492** will attempt to spill dirty pages by calling xStress.
13493*/
13494SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
13495
13496/* Free up as much memory as possible from the page cache */
13497SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
13498
13499#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13500/* Try to return memory used by the pcache module to the main memory heap */
13501SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
13502#endif
13503
13504#ifdef SQLITE_TEST
13505SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
13506#endif
13507
13508SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
13509
13510/* Return the header size */
13511SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
13512SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
13513
13514/* Number of dirty pages as a percentage of the configured cache size */
13515SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
13516
13517#endif /* _PCACHE_H_ */
13518
13519/************** End of pcache.h **********************************************/
13520/************** Continuing where we left off in sqliteInt.h ******************/
13521/************** Include os.h in the middle of sqliteInt.h ********************/
13522/************** Begin file os.h **********************************************/
13523/*
13524** 2001 September 16
13525**
13526** The author disclaims copyright to this source code.  In place of
13527** a legal notice, here is a blessing:
13528**
13529**    May you do good and not evil.
13530**    May you find forgiveness for yourself and forgive others.
13531**    May you share freely, never taking more than you give.
13532**
13533******************************************************************************
13534**
13535** This header file (together with is companion C source-code file
13536** "os.c") attempt to abstract the underlying operating system so that
13537** the SQLite library will work on both POSIX and windows systems.
13538**
13539** This header file is #include-ed by sqliteInt.h and thus ends up
13540** being included by every source file.
13541*/
13542#ifndef _SQLITE_OS_H_
13543#define _SQLITE_OS_H_
13544
13545/*
13546** Attempt to automatically detect the operating system and setup the
13547** necessary pre-processor macros for it.
13548*/
13549/************** Include os_setup.h in the middle of os.h *********************/
13550/************** Begin file os_setup.h ****************************************/
13551/*
13552** 2013 November 25
13553**
13554** The author disclaims copyright to this source code.  In place of
13555** a legal notice, here is a blessing:
13556**
13557**    May you do good and not evil.
13558**    May you find forgiveness for yourself and forgive others.
13559**    May you share freely, never taking more than you give.
13560**
13561******************************************************************************
13562**
13563** This file contains pre-processor directives related to operating system
13564** detection and/or setup.
13565*/
13566#ifndef SQLITE_OS_SETUP_H
13567#define SQLITE_OS_SETUP_H
13568
13569/*
13570** Figure out if we are dealing with Unix, Windows, or some other operating
13571** system.
13572**
13573** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
13574** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0.  One of
13575** the three will be 1.  The other two will be 0.
13576*/
13577#if defined(SQLITE_OS_OTHER)
13578#  if SQLITE_OS_OTHER==1
13579#    undef SQLITE_OS_UNIX
13580#    define SQLITE_OS_UNIX 0
13581#    undef SQLITE_OS_WIN
13582#    define SQLITE_OS_WIN 0
13583#  else
13584#    undef SQLITE_OS_OTHER
13585#  endif
13586#endif
13587#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
13588#  define SQLITE_OS_OTHER 0
13589#  ifndef SQLITE_OS_WIN
13590#    if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
13591        defined(__MINGW32__) || defined(__BORLANDC__)
13592#      define SQLITE_OS_WIN 1
13593#      define SQLITE_OS_UNIX 0
13594#    else
13595#      define SQLITE_OS_WIN 0
13596#      define SQLITE_OS_UNIX 1
13597#    endif
13598#  else
13599#    define SQLITE_OS_UNIX 0
13600#  endif
13601#else
13602#  ifndef SQLITE_OS_WIN
13603#    define SQLITE_OS_WIN 0
13604#  endif
13605#endif
13606
13607#endif /* SQLITE_OS_SETUP_H */
13608
13609/************** End of os_setup.h ********************************************/
13610/************** Continuing where we left off in os.h *************************/
13611
13612/* If the SET_FULLSYNC macro is not defined above, then make it
13613** a no-op
13614*/
13615#ifndef SET_FULLSYNC
13616# define SET_FULLSYNC(x,y)
13617#endif
13618
13619/*
13620** The default size of a disk sector
13621*/
13622#ifndef SQLITE_DEFAULT_SECTOR_SIZE
13623# define SQLITE_DEFAULT_SECTOR_SIZE 4096
13624#endif
13625
13626/*
13627** Temporary files are named starting with this prefix followed by 16 random
13628** alphanumeric characters, and no file extension. They are stored in the
13629** OS's standard temporary file directory, and are deleted prior to exit.
13630** If sqlite is being embedded in another program, you may wish to change the
13631** prefix to reflect your program's name, so that if your program exits
13632** prematurely, old temporary files can be easily identified. This can be done
13633** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
13634**
13635** 2006-10-31:  The default prefix used to be "sqlite_".  But then
13636** Mcafee started using SQLite in their anti-virus product and it
13637** started putting files with the "sqlite" name in the c:/temp folder.
13638** This annoyed many windows users.  Those users would then do a
13639** Google search for "sqlite", find the telephone numbers of the
13640** developers and call to wake them up at night and complain.
13641** For this reason, the default name prefix is changed to be "sqlite"
13642** spelled backwards.  So the temp files are still identified, but
13643** anybody smart enough to figure out the code is also likely smart
13644** enough to know that calling the developer will not help get rid
13645** of the file.
13646*/
13647#ifndef SQLITE_TEMP_FILE_PREFIX
13648# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
13649#endif
13650
13651/*
13652** The following values may be passed as the second argument to
13653** sqlite3OsLock(). The various locks exhibit the following semantics:
13654**
13655** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
13656** RESERVED:  A single process may hold a RESERVED lock on a file at
13657**            any time. Other processes may hold and obtain new SHARED locks.
13658** PENDING:   A single process may hold a PENDING lock on a file at
13659**            any one time. Existing SHARED locks may persist, but no new
13660**            SHARED locks may be obtained by other processes.
13661** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
13662**
13663** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
13664** process that requests an EXCLUSIVE lock may actually obtain a PENDING
13665** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
13666** sqlite3OsLock().
13667*/
13668#define NO_LOCK         0
13669#define SHARED_LOCK     1
13670#define RESERVED_LOCK   2
13671#define PENDING_LOCK    3
13672#define EXCLUSIVE_LOCK  4
13673
13674/*
13675** File Locking Notes:  (Mostly about windows but also some info for Unix)
13676**
13677** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
13678** those functions are not available.  So we use only LockFile() and
13679** UnlockFile().
13680**
13681** LockFile() prevents not just writing but also reading by other processes.
13682** A SHARED_LOCK is obtained by locking a single randomly-chosen
13683** byte out of a specific range of bytes. The lock byte is obtained at
13684** random so two separate readers can probably access the file at the
13685** same time, unless they are unlucky and choose the same lock byte.
13686** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
13687** There can only be one writer.  A RESERVED_LOCK is obtained by locking
13688** a single byte of the file that is designated as the reserved lock byte.
13689** A PENDING_LOCK is obtained by locking a designated byte different from
13690** the RESERVED_LOCK byte.
13691**
13692** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
13693** which means we can use reader/writer locks.  When reader/writer locks
13694** are used, the lock is placed on the same range of bytes that is used
13695** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
13696** will support two or more Win95 readers or two or more WinNT readers.
13697** But a single Win95 reader will lock out all WinNT readers and a single
13698** WinNT reader will lock out all other Win95 readers.
13699**
13700** The following #defines specify the range of bytes used for locking.
13701** SHARED_SIZE is the number of bytes available in the pool from which
13702** a random byte is selected for a shared lock.  The pool of bytes for
13703** shared locks begins at SHARED_FIRST.
13704**
13705** The same locking strategy and
13706** byte ranges are used for Unix.  This leaves open the possibility of having
13707** clients on win95, winNT, and unix all talking to the same shared file
13708** and all locking correctly.  To do so would require that samba (or whatever
13709** tool is being used for file sharing) implements locks correctly between
13710** windows and unix.  I'm guessing that isn't likely to happen, but by
13711** using the same locking range we are at least open to the possibility.
13712**
13713** Locking in windows is manditory.  For this reason, we cannot store
13714** actual data in the bytes used for locking.  The pager never allocates
13715** the pages involved in locking therefore.  SHARED_SIZE is selected so
13716** that all locks will fit on a single page even at the minimum page size.
13717** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
13718** is set high so that we don't have to allocate an unused page except
13719** for very large databases.  But one should test the page skipping logic
13720** by setting PENDING_BYTE low and running the entire regression suite.
13721**
13722** Changing the value of PENDING_BYTE results in a subtly incompatible
13723** file format.  Depending on how it is changed, you might not notice
13724** the incompatibility right away, even running a full regression test.
13725** The default location of PENDING_BYTE is the first byte past the
13726** 1GB boundary.
13727**
13728*/
13729#ifdef SQLITE_OMIT_WSD
13730# define PENDING_BYTE     (0x40000000)
13731#else
13732# define PENDING_BYTE      sqlite3PendingByte
13733#endif
13734#define RESERVED_BYTE     (PENDING_BYTE+1)
13735#define SHARED_FIRST      (PENDING_BYTE+2)
13736#define SHARED_SIZE       510
13737
13738/*
13739** Wrapper around OS specific sqlite3_os_init() function.
13740*/
13741SQLITE_PRIVATE int sqlite3OsInit(void);
13742
13743/*
13744** Functions for accessing sqlite3_file methods
13745*/
13746SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
13747SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
13748SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
13749SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
13750SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
13751SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
13752SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
13753SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
13754SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
13755SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
13756SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
13757#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
13758SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
13759SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
13760SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
13761SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
13762SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
13763SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
13764SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
13765SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
13766
13767
13768/*
13769** Functions for accessing sqlite3_vfs methods
13770*/
13771SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
13772SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
13773SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
13774SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
13775#ifndef SQLITE_OMIT_LOAD_EXTENSION
13776SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
13777SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
13778SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
13779SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
13780#endif /* SQLITE_OMIT_LOAD_EXTENSION */
13781SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
13782SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
13783SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
13784SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
13785
13786/*
13787** Convenience functions for opening and closing files using
13788** sqlite3_malloc() to obtain space for the file-handle structure.
13789*/
13790SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
13791SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
13792
13793#endif /* _SQLITE_OS_H_ */
13794
13795/************** End of os.h **************************************************/
13796/************** Continuing where we left off in sqliteInt.h ******************/
13797/************** Include mutex.h in the middle of sqliteInt.h *****************/
13798/************** Begin file mutex.h *******************************************/
13799/*
13800** 2007 August 28
13801**
13802** The author disclaims copyright to this source code.  In place of
13803** a legal notice, here is a blessing:
13804**
13805**    May you do good and not evil.
13806**    May you find forgiveness for yourself and forgive others.
13807**    May you share freely, never taking more than you give.
13808**
13809*************************************************************************
13810**
13811** This file contains the common header for all mutex implementations.
13812** The sqliteInt.h header #includes this file so that it is available
13813** to all source files.  We break it out in an effort to keep the code
13814** better organized.
13815**
13816** NOTE:  source files should *not* #include this header file directly.
13817** Source files should #include the sqliteInt.h file and let that file
13818** include this one indirectly.
13819*/
13820
13821
13822/*
13823** Figure out what version of the code to use.  The choices are
13824**
13825**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
13826**                             mutexes implementation cannot be overridden
13827**                             at start-time.
13828**
13829**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
13830**                             mutual exclusion is provided.  But this
13831**                             implementation can be overridden at
13832**                             start-time.
13833**
13834**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
13835**
13836**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
13837*/
13838#if !SQLITE_THREADSAFE
13839# define SQLITE_MUTEX_OMIT
13840#endif
13841#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
13842#  if SQLITE_OS_UNIX
13843#    define SQLITE_MUTEX_PTHREADS
13844#  elif SQLITE_OS_WIN
13845#    define SQLITE_MUTEX_W32
13846#  else
13847#    define SQLITE_MUTEX_NOOP
13848#  endif
13849#endif
13850
13851#ifdef SQLITE_MUTEX_OMIT
13852/*
13853** If this is a no-op implementation, implement everything as macros.
13854*/
13855#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
13856#define sqlite3_mutex_free(X)
13857#define sqlite3_mutex_enter(X)
13858#define sqlite3_mutex_try(X)      SQLITE_OK
13859#define sqlite3_mutex_leave(X)
13860#define sqlite3_mutex_held(X)     ((void)(X),1)
13861#define sqlite3_mutex_notheld(X)  ((void)(X),1)
13862#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
13863#define sqlite3MutexInit()        SQLITE_OK
13864#define sqlite3MutexEnd()
13865#define MUTEX_LOGIC(X)
13866#else
13867#define MUTEX_LOGIC(X)            X
13868#endif /* defined(SQLITE_MUTEX_OMIT) */
13869
13870/************** End of mutex.h ***********************************************/
13871/************** Continuing where we left off in sqliteInt.h ******************/
13872
13873/* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
13874** synchronous setting to EXTRA.  It is no longer supported.
13875*/
13876#ifdef SQLITE_EXTRA_DURABLE
13877# warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
13878# define SQLITE_DEFAULT_SYNCHRONOUS 3
13879#endif
13880
13881/*
13882** Default synchronous levels.
13883**
13884** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
13885** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
13886**
13887**           PAGER_SYNCHRONOUS       DEFAULT_SYNCHRONOUS
13888**   OFF           1                         0
13889**   NORMAL        2                         1
13890**   FULL          3                         2
13891**   EXTRA         4                         3
13892**
13893** The "PRAGMA synchronous" statement also uses the zero-based numbers.
13894** In other words, the zero-based numbers are used for all external interfaces
13895** and the one-based values are used internally.
13896*/
13897#ifndef SQLITE_DEFAULT_SYNCHRONOUS
13898# define SQLITE_DEFAULT_SYNCHRONOUS 2
13899#endif
13900#ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
13901# define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
13902#endif
13903
13904/*
13905** Each database file to be accessed by the system is an instance
13906** of the following structure.  There are normally two of these structures
13907** in the sqlite.aDb[] array.  aDb[0] is the main database file and
13908** aDb[1] is the database file used to hold temporary tables.  Additional
13909** databases may be attached.
13910*/
13911struct Db {
13912  char *zDbSName;      /* Name of this database. (schema name, not filename) */
13913  Btree *pBt;          /* The B*Tree structure for this database file */
13914  u8 safety_level;     /* How aggressive at syncing data to disk */
13915  u8 bSyncSet;         /* True if "PRAGMA synchronous=N" has been run */
13916  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
13917};
13918
13919/*
13920** An instance of the following structure stores a database schema.
13921**
13922** Most Schema objects are associated with a Btree.  The exception is
13923** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
13924** In shared cache mode, a single Schema object can be shared by multiple
13925** Btrees that refer to the same underlying BtShared object.
13926**
13927** Schema objects are automatically deallocated when the last Btree that
13928** references them is destroyed.   The TEMP Schema is manually freed by
13929** sqlite3_close().
13930*
13931** A thread must be holding a mutex on the corresponding Btree in order
13932** to access Schema content.  This implies that the thread must also be
13933** holding a mutex on the sqlite3 connection pointer that owns the Btree.
13934** For a TEMP Schema, only the connection mutex is required.
13935*/
13936struct Schema {
13937  int schema_cookie;   /* Database schema version number for this file */
13938  int iGeneration;     /* Generation counter.  Incremented with each change */
13939  Hash tblHash;        /* All tables indexed by name */
13940  Hash idxHash;        /* All (named) indices indexed by name */
13941  Hash trigHash;       /* All triggers indexed by name */
13942  Hash fkeyHash;       /* All foreign keys by referenced table name */
13943  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
13944  u8 file_format;      /* Schema format version for this file */
13945  u8 enc;              /* Text encoding used by this database */
13946  u16 schemaFlags;     /* Flags associated with this schema */
13947  int cache_size;      /* Number of pages to use in the cache */
13948};
13949
13950/*
13951** These macros can be used to test, set, or clear bits in the
13952** Db.pSchema->flags field.
13953*/
13954#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
13955#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
13956#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
13957#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
13958
13959/*
13960** Allowed values for the DB.pSchema->flags field.
13961**
13962** The DB_SchemaLoaded flag is set after the database schema has been
13963** read into internal hash tables.
13964**
13965** DB_UnresetViews means that one or more views have column names that
13966** have been filled out.  If the schema changes, these column names might
13967** changes and so the view will need to be reset.
13968*/
13969#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
13970#define DB_UnresetViews    0x0002  /* Some views have defined column names */
13971#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
13972
13973/*
13974** The number of different kinds of things that can be limited
13975** using the sqlite3_limit() interface.
13976*/
13977#define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
13978
13979/*
13980** Lookaside malloc is a set of fixed-size buffers that can be used
13981** to satisfy small transient memory allocation requests for objects
13982** associated with a particular database connection.  The use of
13983** lookaside malloc provides a significant performance enhancement
13984** (approx 10%) by avoiding numerous malloc/free requests while parsing
13985** SQL statements.
13986**
13987** The Lookaside structure holds configuration information about the
13988** lookaside malloc subsystem.  Each available memory allocation in
13989** the lookaside subsystem is stored on a linked list of LookasideSlot
13990** objects.
13991**
13992** Lookaside allocations are only allowed for objects that are associated
13993** with a particular database connection.  Hence, schema information cannot
13994** be stored in lookaside because in shared cache mode the schema information
13995** is shared by multiple database connections.  Therefore, while parsing
13996** schema information, the Lookaside.bEnabled flag is cleared so that
13997** lookaside allocations are not used to construct the schema objects.
13998*/
13999struct Lookaside {
14000  u32 bDisable;           /* Only operate the lookaside when zero */
14001  u16 sz;                 /* Size of each buffer in bytes */
14002  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
14003  int nOut;               /* Number of buffers currently checked out */
14004  int mxOut;              /* Highwater mark for nOut */
14005  int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
14006  LookasideSlot *pFree;   /* List of available buffers */
14007  void *pStart;           /* First byte of available memory space */
14008  void *pEnd;             /* First byte past end of available space */
14009};
14010struct LookasideSlot {
14011  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
14012};
14013
14014/*
14015** A hash table for built-in function definitions.  (Application-defined
14016** functions use a regular table table from hash.h.)
14017**
14018** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
14019** Collisions are on the FuncDef.u.pHash chain.
14020*/
14021#define SQLITE_FUNC_HASH_SZ 23
14022struct FuncDefHash {
14023  FuncDef *a[SQLITE_FUNC_HASH_SZ];       /* Hash table for functions */
14024};
14025
14026#ifdef SQLITE_USER_AUTHENTICATION
14027/*
14028** Information held in the "sqlite3" database connection object and used
14029** to manage user authentication.
14030*/
14031typedef struct sqlite3_userauth sqlite3_userauth;
14032struct sqlite3_userauth {
14033  u8 authLevel;                 /* Current authentication level */
14034  int nAuthPW;                  /* Size of the zAuthPW in bytes */
14035  char *zAuthPW;                /* Password used to authenticate */
14036  char *zAuthUser;              /* User name used to authenticate */
14037};
14038
14039/* Allowed values for sqlite3_userauth.authLevel */
14040#define UAUTH_Unknown     0     /* Authentication not yet checked */
14041#define UAUTH_Fail        1     /* User authentication failed */
14042#define UAUTH_User        2     /* Authenticated as a normal user */
14043#define UAUTH_Admin       3     /* Authenticated as an administrator */
14044
14045/* Functions used only by user authorization logic */
14046SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
14047SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
14048SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
14049SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
14050
14051#endif /* SQLITE_USER_AUTHENTICATION */
14052
14053/*
14054** typedef for the authorization callback function.
14055*/
14056#ifdef SQLITE_USER_AUTHENTICATION
14057  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
14058                               const char*, const char*);
14059#else
14060  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
14061                               const char*);
14062#endif
14063
14064#ifndef SQLITE_OMIT_DEPRECATED
14065/* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
14066** in the style of sqlite3_trace()
14067*/
14068#define SQLITE_TRACE_LEGACY  0x80
14069#else
14070#define SQLITE_TRACE_LEGACY  0
14071#endif /* SQLITE_OMIT_DEPRECATED */
14072
14073
14074/*
14075** Each database connection is an instance of the following structure.
14076*/
14077struct sqlite3 {
14078  sqlite3_vfs *pVfs;            /* OS Interface */
14079  struct Vdbe *pVdbe;           /* List of active virtual machines */
14080  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
14081  sqlite3_mutex *mutex;         /* Connection mutex */
14082  Db *aDb;                      /* All backends */
14083  int nDb;                      /* Number of backends currently in use */
14084  int flags;                    /* Miscellaneous flags. See below */
14085  i64 lastRowid;                /* ROWID of most recent insert (see above) */
14086  i64 szMmap;                   /* Default mmap_size setting */
14087  unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
14088  int errCode;                  /* Most recent error code (SQLITE_*) */
14089  int errMask;                  /* & result codes with this before returning */
14090  int iSysErrno;                /* Errno value from last system error */
14091  u16 dbOptFlags;               /* Flags to enable/disable optimizations */
14092  u8 enc;                       /* Text encoding */
14093  u8 autoCommit;                /* The auto-commit flag. */
14094  u8 temp_store;                /* 1: file 2: memory 0: default */
14095  u8 mallocFailed;              /* True if we have seen a malloc failure */
14096  u8 bBenignMalloc;             /* Do not require OOMs if true */
14097  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
14098  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
14099  u8 suppressErr;               /* Do not issue error messages if true */
14100  u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
14101  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
14102  u8 mTrace;                    /* zero or more SQLITE_TRACE flags */
14103  u8 skipBtreeMutex;            /* True if no shared-cache backends */
14104  u8 nSqlExec;                  /* Number of pending OP_SqlExec opcodes */
14105  int nextPagesize;             /* Pagesize after VACUUM if >0 */
14106  u32 magic;                    /* Magic number for detect library misuse */
14107  int nChange;                  /* Value returned by sqlite3_changes() */
14108  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
14109  int aLimit[SQLITE_N_LIMIT];   /* Limits */
14110  int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
14111  struct sqlite3InitInfo {      /* Information used during initialization */
14112    int newTnum;                /* Rootpage of table being initialized */
14113    u8 iDb;                     /* Which db file is being initialized */
14114    u8 busy;                    /* TRUE if currently initializing */
14115    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
14116    u8 imposterTable;           /* Building an imposter table */
14117  } init;
14118  int nVdbeActive;              /* Number of VDBEs currently running */
14119  int nVdbeRead;                /* Number of active VDBEs that read or write */
14120  int nVdbeWrite;               /* Number of active VDBEs that read and write */
14121  int nVdbeExec;                /* Number of nested calls to VdbeExec() */
14122  int nVDestroy;                /* Number of active OP_VDestroy operations */
14123  int nExtension;               /* Number of loaded extensions */
14124  void **aExtension;            /* Array of shared library handles */
14125  int (*xTrace)(u32,void*,void*,void*);     /* Trace function */
14126  void *pTraceArg;                          /* Argument to the trace function */
14127  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
14128  void *pProfileArg;                        /* Argument to profile function */
14129  void *pCommitArg;                 /* Argument to xCommitCallback() */
14130  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
14131  void *pRollbackArg;               /* Argument to xRollbackCallback() */
14132  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
14133  void *pUpdateArg;
14134  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
14135#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
14136  void *pPreUpdateArg;          /* First argument to xPreUpdateCallback */
14137  void (*xPreUpdateCallback)(   /* Registered using sqlite3_preupdate_hook() */
14138    void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
14139  );
14140  PreUpdate *pPreUpdate;        /* Context for active pre-update callback */
14141#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
14142#ifndef SQLITE_OMIT_WAL
14143  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
14144  void *pWalArg;
14145#endif
14146  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
14147  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
14148  void *pCollNeededArg;
14149  sqlite3_value *pErr;          /* Most recent error message */
14150  union {
14151    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
14152    double notUsed1;            /* Spacer */
14153  } u1;
14154  Lookaside lookaside;          /* Lookaside malloc configuration */
14155#ifndef SQLITE_OMIT_AUTHORIZATION
14156  sqlite3_xauth xAuth;          /* Access authorization function */
14157  void *pAuthArg;               /* 1st argument to the access auth function */
14158#endif
14159#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
14160  int (*xProgress)(void *);     /* The progress callback */
14161  void *pProgressArg;           /* Argument to the progress callback */
14162  unsigned nProgressOps;        /* Number of opcodes for progress callback */
14163#endif
14164#ifndef SQLITE_OMIT_VIRTUALTABLE
14165  int nVTrans;                  /* Allocated size of aVTrans */
14166  Hash aModule;                 /* populated by sqlite3_create_module() */
14167  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
14168  VTable **aVTrans;             /* Virtual tables with open transactions */
14169  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
14170#endif
14171  Hash aFunc;                   /* Hash table of connection functions */
14172  Hash aCollSeq;                /* All collating sequences */
14173  BusyHandler busyHandler;      /* Busy callback */
14174  Db aDbStatic[2];              /* Static space for the 2 default backends */
14175  Savepoint *pSavepoint;        /* List of active savepoints */
14176  int busyTimeout;              /* Busy handler timeout, in msec */
14177  int nSavepoint;               /* Number of non-transaction savepoints */
14178  int nStatement;               /* Number of nested statement-transactions  */
14179  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
14180  i64 nDeferredImmCons;         /* Net deferred immediate constraints */
14181  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
14182#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
14183  /* The following variables are all protected by the STATIC_MASTER
14184  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
14185  **
14186  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
14187  ** unlock so that it can proceed.
14188  **
14189  ** When X.pBlockingConnection==Y, that means that something that X tried
14190  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
14191  ** held by Y.
14192  */
14193  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
14194  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
14195  void *pUnlockArg;                     /* Argument to xUnlockNotify */
14196  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
14197  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
14198#endif
14199#ifdef SQLITE_USER_AUTHENTICATION
14200  sqlite3_userauth auth;        /* User authentication information */
14201#endif
14202};
14203
14204/*
14205** A macro to discover the encoding of a database.
14206*/
14207#define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
14208#define ENC(db)        ((db)->enc)
14209
14210/*
14211** Possible values for the sqlite3.flags.
14212**
14213** Value constraints (enforced via assert()):
14214**      SQLITE_FullFSync     == PAGER_FULLFSYNC
14215**      SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
14216**      SQLITE_CacheSpill    == PAGER_CACHE_SPILL
14217*/
14218#define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
14219#define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
14220#define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
14221#define SQLITE_FullFSync      0x00000008  /* Use full fsync on the backend */
14222#define SQLITE_CkptFullFSync  0x00000010  /* Use full fsync for checkpoint */
14223#define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */
14224#define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
14225#define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
14226                                          /*   DELETE, or UPDATE and return */
14227                                          /*   the count using a callback. */
14228#define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
14229                                          /*   result set is empty */
14230#define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
14231#define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
14232#define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
14233#define SQLITE_VdbeAddopTrace 0x00001000  /* Trace sqlite3VdbeAddOp() calls */
14234#define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
14235#define SQLITE_ReadUncommitted 0x0004000  /* For shared-cache mode */
14236#define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
14237#define SQLITE_RecoveryMode   0x00010000  /* Ignore schema errors */
14238#define SQLITE_ReverseOrder   0x00020000  /* Reverse unordered SELECTs */
14239#define SQLITE_RecTriggers    0x00040000  /* Enable recursive triggers */
14240#define SQLITE_ForeignKeys    0x00080000  /* Enforce foreign key constraints  */
14241#define SQLITE_AutoIndex      0x00100000  /* Enable automatic indexes */
14242#define SQLITE_PreferBuiltin  0x00200000  /* Preference to built-in funcs */
14243#define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
14244#define SQLITE_LoadExtFunc    0x00800000  /* Enable load_extension() SQL func */
14245#define SQLITE_EnableTrigger  0x01000000  /* True to enable triggers */
14246#define SQLITE_DeferFKs       0x02000000  /* Defer all FK constraints */
14247#define SQLITE_QueryOnly      0x04000000  /* Disable database changes */
14248#define SQLITE_VdbeEQP        0x08000000  /* Debug EXPLAIN QUERY PLAN */
14249#define SQLITE_Vacuum         0x10000000  /* Currently in a VACUUM */
14250#define SQLITE_CellSizeCk     0x20000000  /* Check btree cell sizes on load */
14251#define SQLITE_Fts3Tokenizer  0x40000000  /* Enable fts3_tokenizer(2) */
14252#define SQLITE_NoCkptOnClose  0x80000000  /* No checkpoint on close()/DETACH */
14253
14254
14255/*
14256** Bits of the sqlite3.dbOptFlags field that are used by the
14257** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
14258** selectively disable various optimizations.
14259*/
14260#define SQLITE_QueryFlattener 0x0001   /* Query flattening */
14261#define SQLITE_ColumnCache    0x0002   /* Column cache */
14262#define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
14263#define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
14264/*                not used    0x0010   // Was: SQLITE_IdxRealAsInt */
14265#define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
14266#define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
14267#define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
14268#define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
14269#define SQLITE_Transitive     0x0200   /* Transitive constraints */
14270#define SQLITE_OmitNoopJoin   0x0400   /* Omit unused tables in joins */
14271#define SQLITE_Stat34         0x0800   /* Use STAT3 or STAT4 data */
14272#define SQLITE_CursorHints    0x2000   /* Add OP_CursorHint opcodes */
14273#define SQLITE_AllOpts        0xffff   /* All optimizations */
14274
14275/*
14276** Macros for testing whether or not optimizations are enabled or disabled.
14277*/
14278#define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
14279#define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
14280
14281/*
14282** Return true if it OK to factor constant expressions into the initialization
14283** code. The argument is a Parse object for the code generator.
14284*/
14285#define ConstFactorOk(P) ((P)->okConstFactor)
14286
14287/*
14288** Possible values for the sqlite.magic field.
14289** The numbers are obtained at random and have no special meaning, other
14290** than being distinct from one another.
14291*/
14292#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
14293#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
14294#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
14295#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
14296#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
14297#define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
14298
14299/*
14300** Each SQL function is defined by an instance of the following
14301** structure.  For global built-in functions (ex: substr(), max(), count())
14302** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
14303** For per-connection application-defined functions, a pointer to this
14304** structure is held in the db->aHash hash table.
14305**
14306** The u.pHash field is used by the global built-ins.  The u.pDestructor
14307** field is used by per-connection app-def functions.
14308*/
14309struct FuncDef {
14310  i8 nArg;             /* Number of arguments.  -1 means unlimited */
14311  u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
14312  void *pUserData;     /* User data parameter */
14313  FuncDef *pNext;      /* Next function with same name */
14314  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
14315  void (*xFinalize)(sqlite3_context*);                  /* Agg finalizer */
14316  const char *zName;   /* SQL name of the function. */
14317  union {
14318    FuncDef *pHash;      /* Next with a different name but the same hash */
14319    FuncDestructor *pDestructor;   /* Reference counted destructor function */
14320  } u;
14321};
14322
14323/*
14324** This structure encapsulates a user-function destructor callback (as
14325** configured using create_function_v2()) and a reference counter. When
14326** create_function_v2() is called to create a function with a destructor,
14327** a single object of this type is allocated. FuncDestructor.nRef is set to
14328** the number of FuncDef objects created (either 1 or 3, depending on whether
14329** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
14330** member of each of the new FuncDef objects is set to point to the allocated
14331** FuncDestructor.
14332**
14333** Thereafter, when one of the FuncDef objects is deleted, the reference
14334** count on this object is decremented. When it reaches 0, the destructor
14335** is invoked and the FuncDestructor structure freed.
14336*/
14337struct FuncDestructor {
14338  int nRef;
14339  void (*xDestroy)(void *);
14340  void *pUserData;
14341};
14342
14343/*
14344** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
14345** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  And
14346** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC.  There
14347** are assert() statements in the code to verify this.
14348**
14349** Value constraints (enforced via assert()):
14350**     SQLITE_FUNC_MINMAX    ==  NC_MinMaxAgg      == SF_MinMaxAgg
14351**     SQLITE_FUNC_LENGTH    ==  OPFLAG_LENGTHARG
14352**     SQLITE_FUNC_TYPEOF    ==  OPFLAG_TYPEOFARG
14353**     SQLITE_FUNC_CONSTANT  ==  SQLITE_DETERMINISTIC from the API
14354**     SQLITE_FUNC_ENCMASK   depends on SQLITE_UTF* macros in the API
14355*/
14356#define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
14357#define SQLITE_FUNC_LIKE     0x0004 /* Candidate for the LIKE optimization */
14358#define SQLITE_FUNC_CASE     0x0008 /* Case-sensitive LIKE-type function */
14359#define SQLITE_FUNC_EPHEM    0x0010 /* Ephemeral.  Delete with VDBE */
14360#define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
14361#define SQLITE_FUNC_LENGTH   0x0040 /* Built-in length() function */
14362#define SQLITE_FUNC_TYPEOF   0x0080 /* Built-in typeof() function */
14363#define SQLITE_FUNC_COUNT    0x0100 /* Built-in count(*) aggregate */
14364#define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
14365#define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
14366#define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
14367#define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */
14368#define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a
14369                                    ** single query - might change over time */
14370#define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
14371
14372/*
14373** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
14374** used to create the initializers for the FuncDef structures.
14375**
14376**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
14377**     Used to create a scalar function definition of a function zName
14378**     implemented by C function xFunc that accepts nArg arguments. The
14379**     value passed as iArg is cast to a (void*) and made available
14380**     as the user-data (sqlite3_user_data()) for the function. If
14381**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
14382**
14383**   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
14384**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
14385**
14386**   DFUNCTION(zName, nArg, iArg, bNC, xFunc)
14387**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
14388**     adds the SQLITE_FUNC_SLOCHNG flag.  Used for date & time functions
14389**     and functions like sqlite_version() that can change, but not during
14390**     a single query.
14391**
14392**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
14393**     Used to create an aggregate function definition implemented by
14394**     the C functions xStep and xFinal. The first four parameters
14395**     are interpreted in the same way as the first 4 parameters to
14396**     FUNCTION().
14397**
14398**   LIKEFUNC(zName, nArg, pArg, flags)
14399**     Used to create a scalar function definition of a function zName
14400**     that accepts nArg arguments and is implemented by a call to C
14401**     function likeFunc. Argument pArg is cast to a (void *) and made
14402**     available as the function user-data (sqlite3_user_data()). The
14403**     FuncDef.flags variable is set to the value passed as the flags
14404**     parameter.
14405*/
14406#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
14407  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14408   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14409#define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
14410  {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14411   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14412#define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
14413  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14414   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14415#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
14416  {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
14417   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14418#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
14419  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14420   pArg, 0, xFunc, 0, #zName, }
14421#define LIKEFUNC(zName, nArg, arg, flags) \
14422  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
14423   (void *)arg, 0, likeFunc, 0, #zName, {0} }
14424#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
14425  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
14426   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
14427#define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
14428  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
14429   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
14430
14431/*
14432** All current savepoints are stored in a linked list starting at
14433** sqlite3.pSavepoint. The first element in the list is the most recently
14434** opened savepoint. Savepoints are added to the list by the vdbe
14435** OP_Savepoint instruction.
14436*/
14437struct Savepoint {
14438  char *zName;                        /* Savepoint name (nul-terminated) */
14439  i64 nDeferredCons;                  /* Number of deferred fk violations */
14440  i64 nDeferredImmCons;               /* Number of deferred imm fk. */
14441  Savepoint *pNext;                   /* Parent savepoint (if any) */
14442};
14443
14444/*
14445** The following are used as the second parameter to sqlite3Savepoint(),
14446** and as the P1 argument to the OP_Savepoint instruction.
14447*/
14448#define SAVEPOINT_BEGIN      0
14449#define SAVEPOINT_RELEASE    1
14450#define SAVEPOINT_ROLLBACK   2
14451
14452
14453/*
14454** Each SQLite module (virtual table definition) is defined by an
14455** instance of the following structure, stored in the sqlite3.aModule
14456** hash table.
14457*/
14458struct Module {
14459  const sqlite3_module *pModule;       /* Callback pointers */
14460  const char *zName;                   /* Name passed to create_module() */
14461  void *pAux;                          /* pAux passed to create_module() */
14462  void (*xDestroy)(void *);            /* Module destructor function */
14463  Table *pEpoTab;                      /* Eponymous table for this module */
14464};
14465
14466/*
14467** information about each column of an SQL table is held in an instance
14468** of this structure.
14469*/
14470struct Column {
14471  char *zName;     /* Name of this column, \000, then the type */
14472  Expr *pDflt;     /* Default value of this column */
14473  char *zColl;     /* Collating sequence.  If NULL, use the default */
14474  u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
14475  char affinity;   /* One of the SQLITE_AFF_... values */
14476  u8 szEst;        /* Estimated size of value in this column. sizeof(INT)==1 */
14477  u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
14478};
14479
14480/* Allowed values for Column.colFlags:
14481*/
14482#define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
14483#define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
14484#define COLFLAG_HASTYPE  0x0004    /* Type name follows column name */
14485
14486/*
14487** A "Collating Sequence" is defined by an instance of the following
14488** structure. Conceptually, a collating sequence consists of a name and
14489** a comparison routine that defines the order of that sequence.
14490**
14491** If CollSeq.xCmp is NULL, it means that the
14492** collating sequence is undefined.  Indices built on an undefined
14493** collating sequence may not be read or written.
14494*/
14495struct CollSeq {
14496  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
14497  u8 enc;               /* Text encoding handled by xCmp() */
14498  void *pUser;          /* First argument to xCmp() */
14499  int (*xCmp)(void*,int, const void*, int, const void*);
14500  void (*xDel)(void*);  /* Destructor for pUser */
14501};
14502
14503/*
14504** A sort order can be either ASC or DESC.
14505*/
14506#define SQLITE_SO_ASC       0  /* Sort in ascending order */
14507#define SQLITE_SO_DESC      1  /* Sort in ascending order */
14508#define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
14509
14510/*
14511** Column affinity types.
14512**
14513** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
14514** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
14515** the speed a little by numbering the values consecutively.
14516**
14517** But rather than start with 0 or 1, we begin with 'A'.  That way,
14518** when multiple affinity types are concatenated into a string and
14519** used as the P4 operand, they will be more readable.
14520**
14521** Note also that the numeric types are grouped together so that testing
14522** for a numeric type is a single comparison.  And the BLOB type is first.
14523*/
14524#define SQLITE_AFF_BLOB     'A'
14525#define SQLITE_AFF_TEXT     'B'
14526#define SQLITE_AFF_NUMERIC  'C'
14527#define SQLITE_AFF_INTEGER  'D'
14528#define SQLITE_AFF_REAL     'E'
14529
14530#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
14531
14532/*
14533** The SQLITE_AFF_MASK values masks off the significant bits of an
14534** affinity value.
14535*/
14536#define SQLITE_AFF_MASK     0x47
14537
14538/*
14539** Additional bit values that can be ORed with an affinity without
14540** changing the affinity.
14541**
14542** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
14543** It causes an assert() to fire if either operand to a comparison
14544** operator is NULL.  It is added to certain comparison operators to
14545** prove that the operands are always NOT NULL.
14546*/
14547#define SQLITE_KEEPNULL     0x08  /* Used by vector == or <> */
14548#define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
14549#define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */
14550#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
14551#define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
14552
14553/*
14554** An object of this type is created for each virtual table present in
14555** the database schema.
14556**
14557** If the database schema is shared, then there is one instance of this
14558** structure for each database connection (sqlite3*) that uses the shared
14559** schema. This is because each database connection requires its own unique
14560** instance of the sqlite3_vtab* handle used to access the virtual table
14561** implementation. sqlite3_vtab* handles can not be shared between
14562** database connections, even when the rest of the in-memory database
14563** schema is shared, as the implementation often stores the database
14564** connection handle passed to it via the xConnect() or xCreate() method
14565** during initialization internally. This database connection handle may
14566** then be used by the virtual table implementation to access real tables
14567** within the database. So that they appear as part of the callers
14568** transaction, these accesses need to be made via the same database
14569** connection as that used to execute SQL operations on the virtual table.
14570**
14571** All VTable objects that correspond to a single table in a shared
14572** database schema are initially stored in a linked-list pointed to by
14573** the Table.pVTable member variable of the corresponding Table object.
14574** When an sqlite3_prepare() operation is required to access the virtual
14575** table, it searches the list for the VTable that corresponds to the
14576** database connection doing the preparing so as to use the correct
14577** sqlite3_vtab* handle in the compiled query.
14578**
14579** When an in-memory Table object is deleted (for example when the
14580** schema is being reloaded for some reason), the VTable objects are not
14581** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
14582** immediately. Instead, they are moved from the Table.pVTable list to
14583** another linked list headed by the sqlite3.pDisconnect member of the
14584** corresponding sqlite3 structure. They are then deleted/xDisconnected
14585** next time a statement is prepared using said sqlite3*. This is done
14586** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
14587** Refer to comments above function sqlite3VtabUnlockList() for an
14588** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
14589** list without holding the corresponding sqlite3.mutex mutex.
14590**
14591** The memory for objects of this type is always allocated by
14592** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
14593** the first argument.
14594*/
14595struct VTable {
14596  sqlite3 *db;              /* Database connection associated with this table */
14597  Module *pMod;             /* Pointer to module implementation */
14598  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
14599  int nRef;                 /* Number of pointers to this structure */
14600  u8 bConstraint;           /* True if constraints are supported */
14601  int iSavepoint;           /* Depth of the SAVEPOINT stack */
14602  VTable *pNext;            /* Next in linked list (see above) */
14603};
14604
14605/*
14606** The schema for each SQL table and view is represented in memory
14607** by an instance of the following structure.
14608*/
14609struct Table {
14610  char *zName;         /* Name of the table or view */
14611  Column *aCol;        /* Information about each column */
14612  Index *pIndex;       /* List of SQL indexes on this table. */
14613  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
14614  FKey *pFKey;         /* Linked list of all foreign keys in this table */
14615  char *zColAff;       /* String defining the affinity of each column */
14616  ExprList *pCheck;    /* All CHECK constraints */
14617                       /*   ... also used as column name list in a VIEW */
14618  int tnum;            /* Root BTree page for this table */
14619  u32 nTabRef;         /* Number of pointers to this Table */
14620  u32 tabFlags;        /* Mask of TF_* values */
14621  i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */
14622  i16 nCol;            /* Number of columns in this table */
14623  LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
14624  LogEst szTabRow;     /* Estimated size of each table row in bytes */
14625#ifdef SQLITE_ENABLE_COSTMULT
14626  LogEst costMult;     /* Cost multiplier for using this table */
14627#endif
14628  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
14629#ifndef SQLITE_OMIT_ALTERTABLE
14630  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
14631#endif
14632#ifndef SQLITE_OMIT_VIRTUALTABLE
14633  int nModuleArg;      /* Number of arguments to the module */
14634  char **azModuleArg;  /* 0: module 1: schema 2: vtab name 3...: args */
14635  VTable *pVTable;     /* List of VTable objects. */
14636#endif
14637  Trigger *pTrigger;   /* List of triggers stored in pSchema */
14638  Schema *pSchema;     /* Schema that contains this table */
14639  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
14640};
14641
14642/*
14643** Allowed values for Table.tabFlags.
14644**
14645** TF_OOOHidden applies to tables or view that have hidden columns that are
14646** followed by non-hidden columns.  Example:  "CREATE VIRTUAL TABLE x USING
14647** vtab1(a HIDDEN, b);".  Since "b" is a non-hidden column but "a" is hidden,
14648** the TF_OOOHidden attribute would apply in this case.  Such tables require
14649** special handling during INSERT processing.
14650*/
14651#define TF_Readonly        0x0001    /* Read-only system table */
14652#define TF_Ephemeral       0x0002    /* An ephemeral table */
14653#define TF_HasPrimaryKey   0x0004    /* Table has a primary key */
14654#define TF_Autoincrement   0x0008    /* Integer primary key is autoincrement */
14655#define TF_HasStat1        0x0010    /* nRowLogEst set from sqlite_stat1 */
14656#define TF_WithoutRowid    0x0020    /* No rowid.  PRIMARY KEY is the key */
14657#define TF_NoVisibleRowid  0x0040    /* No user-visible "rowid" column */
14658#define TF_OOOHidden       0x0080    /* Out-of-Order hidden columns */
14659#define TF_StatsUsed       0x0100    /* Query planner decisions affected by
14660                                     ** Index.aiRowLogEst[] values */
14661#define TF_HasNotNull      0x0200    /* Contains NOT NULL constraints */
14662
14663/*
14664** Test to see whether or not a table is a virtual table.  This is
14665** done as a macro so that it will be optimized out when virtual
14666** table support is omitted from the build.
14667*/
14668#ifndef SQLITE_OMIT_VIRTUALTABLE
14669#  define IsVirtual(X)      ((X)->nModuleArg)
14670#else
14671#  define IsVirtual(X)      0
14672#endif
14673
14674/*
14675** Macros to determine if a column is hidden.  IsOrdinaryHiddenColumn()
14676** only works for non-virtual tables (ordinary tables and views) and is
14677** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined.  The
14678** IsHiddenColumn() macro is general purpose.
14679*/
14680#if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
14681#  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14682#  define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14683#elif !defined(SQLITE_OMIT_VIRTUALTABLE)
14684#  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14685#  define IsOrdinaryHiddenColumn(X) 0
14686#else
14687#  define IsHiddenColumn(X)         0
14688#  define IsOrdinaryHiddenColumn(X) 0
14689#endif
14690
14691
14692/* Does the table have a rowid */
14693#define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
14694#define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
14695
14696/*
14697** Each foreign key constraint is an instance of the following structure.
14698**
14699** A foreign key is associated with two tables.  The "from" table is
14700** the table that contains the REFERENCES clause that creates the foreign
14701** key.  The "to" table is the table that is named in the REFERENCES clause.
14702** Consider this example:
14703**
14704**     CREATE TABLE ex1(
14705**       a INTEGER PRIMARY KEY,
14706**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
14707**     );
14708**
14709** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
14710** Equivalent names:
14711**
14712**     from-table == child-table
14713**       to-table == parent-table
14714**
14715** Each REFERENCES clause generates an instance of the following structure
14716** which is attached to the from-table.  The to-table need not exist when
14717** the from-table is created.  The existence of the to-table is not checked.
14718**
14719** The list of all parents for child Table X is held at X.pFKey.
14720**
14721** A list of all children for a table named Z (which might not even exist)
14722** is held in Schema.fkeyHash with a hash key of Z.
14723*/
14724struct FKey {
14725  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
14726  FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
14727  char *zTo;        /* Name of table that the key points to (aka: Parent) */
14728  FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
14729  FKey *pPrevTo;    /* Previous with the same zTo */
14730  int nCol;         /* Number of columns in this key */
14731  /* EV: R-30323-21917 */
14732  u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
14733  u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
14734  Trigger *apTrigger[2];/* Triggers for aAction[] actions */
14735  struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
14736    int iFrom;            /* Index of column in pFrom */
14737    char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
14738  } aCol[1];            /* One entry for each of nCol columns */
14739};
14740
14741/*
14742** SQLite supports many different ways to resolve a constraint
14743** error.  ROLLBACK processing means that a constraint violation
14744** causes the operation in process to fail and for the current transaction
14745** to be rolled back.  ABORT processing means the operation in process
14746** fails and any prior changes from that one operation are backed out,
14747** but the transaction is not rolled back.  FAIL processing means that
14748** the operation in progress stops and returns an error code.  But prior
14749** changes due to the same operation are not backed out and no rollback
14750** occurs.  IGNORE means that the particular row that caused the constraint
14751** error is not inserted or updated.  Processing continues and no error
14752** is returned.  REPLACE means that preexisting database rows that caused
14753** a UNIQUE constraint violation are removed so that the new insert or
14754** update can proceed.  Processing continues and no error is reported.
14755**
14756** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
14757** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
14758** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
14759** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
14760** referenced table row is propagated into the row that holds the
14761** foreign key.
14762**
14763** The following symbolic values are used to record which type
14764** of action to take.
14765*/
14766#define OE_None     0   /* There is no constraint to check */
14767#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
14768#define OE_Abort    2   /* Back out changes but do no rollback transaction */
14769#define OE_Fail     3   /* Stop the operation but leave all prior changes */
14770#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
14771#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
14772
14773#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
14774#define OE_SetNull  7   /* Set the foreign key value to NULL */
14775#define OE_SetDflt  8   /* Set the foreign key value to its default */
14776#define OE_Cascade  9   /* Cascade the changes */
14777
14778#define OE_Default  10  /* Do whatever the default action is */
14779
14780
14781/*
14782** An instance of the following structure is passed as the first
14783** argument to sqlite3VdbeKeyCompare and is used to control the
14784** comparison of the two index keys.
14785**
14786** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
14787** are nField slots for the columns of an index then one extra slot
14788** for the rowid at the end.
14789*/
14790struct KeyInfo {
14791  u32 nRef;           /* Number of references to this KeyInfo object */
14792  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
14793  u16 nField;         /* Number of key columns in the index */
14794  u16 nXField;        /* Number of columns beyond the key columns */
14795  sqlite3 *db;        /* The database connection */
14796  u8 *aSortOrder;     /* Sort order for each column. */
14797  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
14798};
14799
14800/*
14801** This object holds a record which has been parsed out into individual
14802** fields, for the purposes of doing a comparison.
14803**
14804** A record is an object that contains one or more fields of data.
14805** Records are used to store the content of a table row and to store
14806** the key of an index.  A blob encoding of a record is created by
14807** the OP_MakeRecord opcode of the VDBE and is disassembled by the
14808** OP_Column opcode.
14809**
14810** An instance of this object serves as a "key" for doing a search on
14811** an index b+tree. The goal of the search is to find the entry that
14812** is closed to the key described by this object.  This object might hold
14813** just a prefix of the key.  The number of fields is given by
14814** pKeyInfo->nField.
14815**
14816** The r1 and r2 fields are the values to return if this key is less than
14817** or greater than a key in the btree, respectively.  These are normally
14818** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
14819** is in DESC order.
14820**
14821** The key comparison functions actually return default_rc when they find
14822** an equals comparison.  default_rc can be -1, 0, or +1.  If there are
14823** multiple entries in the b-tree with the same key (when only looking
14824** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
14825** cause the search to find the last match, or +1 to cause the search to
14826** find the first match.
14827**
14828** The key comparison functions will set eqSeen to true if they ever
14829** get and equal results when comparing this structure to a b-tree record.
14830** When default_rc!=0, the search might end up on the record immediately
14831** before the first match or immediately after the last match.  The
14832** eqSeen field will indicate whether or not an exact match exists in the
14833** b-tree.
14834*/
14835struct UnpackedRecord {
14836  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
14837  Mem *aMem;          /* Values */
14838  u16 nField;         /* Number of entries in apMem[] */
14839  i8 default_rc;      /* Comparison result if keys are equal */
14840  u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
14841  i8 r1;              /* Value to return if (lhs > rhs) */
14842  i8 r2;              /* Value to return if (rhs < lhs) */
14843  u8 eqSeen;          /* True if an equality comparison has been seen */
14844};
14845
14846
14847/*
14848** Each SQL index is represented in memory by an
14849** instance of the following structure.
14850**
14851** The columns of the table that are to be indexed are described
14852** by the aiColumn[] field of this structure.  For example, suppose
14853** we have the following table and index:
14854**
14855**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
14856**     CREATE INDEX Ex2 ON Ex1(c3,c1);
14857**
14858** In the Table structure describing Ex1, nCol==3 because there are
14859** three columns in the table.  In the Index structure describing
14860** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
14861** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
14862** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
14863** The second column to be indexed (c1) has an index of 0 in
14864** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
14865**
14866** The Index.onError field determines whether or not the indexed columns
14867** must be unique and what to do if they are not.  When Index.onError=OE_None,
14868** it means this is not a unique index.  Otherwise it is a unique index
14869** and the value of Index.onError indicate the which conflict resolution
14870** algorithm to employ whenever an attempt is made to insert a non-unique
14871** element.
14872**
14873** While parsing a CREATE TABLE or CREATE INDEX statement in order to
14874** generate VDBE code (as opposed to parsing one read from an sqlite_master
14875** table as part of parsing an existing database schema), transient instances
14876** of this structure may be created. In this case the Index.tnum variable is
14877** used to store the address of a VDBE instruction, not a database page
14878** number (it cannot - the database page is not allocated until the VDBE
14879** program is executed). See convertToWithoutRowidTable() for details.
14880*/
14881struct Index {
14882  char *zName;             /* Name of this index */
14883  i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
14884  LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
14885  Table *pTable;           /* The SQL table being indexed */
14886  char *zColAff;           /* String defining the affinity of each column */
14887  Index *pNext;            /* The next index associated with the same table */
14888  Schema *pSchema;         /* Schema containing this index */
14889  u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
14890  const char **azColl;     /* Array of collation sequence names for index */
14891  Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
14892  ExprList *aColExpr;      /* Column expressions */
14893  int tnum;                /* DB Page containing root of this index */
14894  LogEst szIdxRow;         /* Estimated average row size in bytes */
14895  u16 nKeyCol;             /* Number of columns forming the key */
14896  u16 nColumn;             /* Number of columns stored in the index */
14897  u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
14898  unsigned idxType:2;      /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
14899  unsigned bUnordered:1;   /* Use this index for == or IN queries only */
14900  unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
14901  unsigned isResized:1;    /* True if resizeIndexObject() has been called */
14902  unsigned isCovering:1;   /* True if this is a covering index */
14903  unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */
14904  unsigned hasStat1:1;     /* aiRowLogEst values come from sqlite_stat1 */
14905#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
14906  int nSample;             /* Number of elements in aSample[] */
14907  int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
14908  tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
14909  IndexSample *aSample;    /* Samples of the left-most key */
14910  tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
14911  tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
14912#endif
14913};
14914
14915/*
14916** Allowed values for Index.idxType
14917*/
14918#define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
14919#define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
14920#define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
14921
14922/* Return true if index X is a PRIMARY KEY index */
14923#define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
14924
14925/* Return true if index X is a UNIQUE index */
14926#define IsUniqueIndex(X)      ((X)->onError!=OE_None)
14927
14928/* The Index.aiColumn[] values are normally positive integer.  But
14929** there are some negative values that have special meaning:
14930*/
14931#define XN_ROWID     (-1)     /* Indexed column is the rowid */
14932#define XN_EXPR      (-2)     /* Indexed column is an expression */
14933
14934/*
14935** Each sample stored in the sqlite_stat3 table is represented in memory
14936** using a structure of this type.  See documentation at the top of the
14937** analyze.c source file for additional information.
14938*/
14939struct IndexSample {
14940  void *p;          /* Pointer to sampled record */
14941  int n;            /* Size of record in bytes */
14942  tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
14943  tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
14944  tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
14945};
14946
14947/*
14948** Each token coming out of the lexer is an instance of
14949** this structure.  Tokens are also used as part of an expression.
14950**
14951** Note if Token.z==0 then Token.dyn and Token.n are undefined and
14952** may contain random values.  Do not make any assumptions about Token.dyn
14953** and Token.n when Token.z==0.
14954*/
14955struct Token {
14956  const char *z;     /* Text of the token.  Not NULL-terminated! */
14957  unsigned int n;    /* Number of characters in this token */
14958};
14959
14960/*
14961** An instance of this structure contains information needed to generate
14962** code for a SELECT that contains aggregate functions.
14963**
14964** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
14965** pointer to this structure.  The Expr.iColumn field is the index in
14966** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
14967** code for that node.
14968**
14969** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
14970** original Select structure that describes the SELECT statement.  These
14971** fields do not need to be freed when deallocating the AggInfo structure.
14972*/
14973struct AggInfo {
14974  u8 directMode;          /* Direct rendering mode means take data directly
14975                          ** from source tables rather than from accumulators */
14976  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
14977                          ** than the source table */
14978  int sortingIdx;         /* Cursor number of the sorting index */
14979  int sortingIdxPTab;     /* Cursor number of pseudo-table */
14980  int nSortingColumn;     /* Number of columns in the sorting index */
14981  int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
14982  ExprList *pGroupBy;     /* The group by clause */
14983  struct AggInfo_col {    /* For each column used in source tables */
14984    Table *pTab;             /* Source table */
14985    int iTable;              /* Cursor number of the source table */
14986    int iColumn;             /* Column number within the source table */
14987    int iSorterColumn;       /* Column number in the sorting index */
14988    int iMem;                /* Memory location that acts as accumulator */
14989    Expr *pExpr;             /* The original expression */
14990  } *aCol;
14991  int nColumn;            /* Number of used entries in aCol[] */
14992  int nAccumulator;       /* Number of columns that show through to the output.
14993                          ** Additional columns are used only as parameters to
14994                          ** aggregate functions */
14995  struct AggInfo_func {   /* For each aggregate function */
14996    Expr *pExpr;             /* Expression encoding the function */
14997    FuncDef *pFunc;          /* The aggregate function implementation */
14998    int iMem;                /* Memory location that acts as accumulator */
14999    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
15000  } *aFunc;
15001  int nFunc;              /* Number of entries in aFunc[] */
15002};
15003
15004/*
15005** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
15006** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
15007** than 32767 we have to make it 32-bit.  16-bit is preferred because
15008** it uses less memory in the Expr object, which is a big memory user
15009** in systems with lots of prepared statements.  And few applications
15010** need more than about 10 or 20 variables.  But some extreme users want
15011** to have prepared statements with over 32767 variables, and for them
15012** the option is available (at compile-time).
15013*/
15014#if SQLITE_MAX_VARIABLE_NUMBER<=32767
15015typedef i16 ynVar;
15016#else
15017typedef int ynVar;
15018#endif
15019
15020/*
15021** Each node of an expression in the parse tree is an instance
15022** of this structure.
15023**
15024** Expr.op is the opcode. The integer parser token codes are reused
15025** as opcodes here. For example, the parser defines TK_GE to be an integer
15026** code representing the ">=" operator. This same integer code is reused
15027** to represent the greater-than-or-equal-to operator in the expression
15028** tree.
15029**
15030** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
15031** or TK_STRING), then Expr.token contains the text of the SQL literal. If
15032** the expression is a variable (TK_VARIABLE), then Expr.token contains the
15033** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
15034** then Expr.token contains the name of the function.
15035**
15036** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
15037** binary operator. Either or both may be NULL.
15038**
15039** Expr.x.pList is a list of arguments if the expression is an SQL function,
15040** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
15041** Expr.x.pSelect is used if the expression is a sub-select or an expression of
15042** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
15043** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
15044** valid.
15045**
15046** An expression of the form ID or ID.ID refers to a column in a table.
15047** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
15048** the integer cursor number of a VDBE cursor pointing to that table and
15049** Expr.iColumn is the column number for the specific column.  If the
15050** expression is used as a result in an aggregate SELECT, then the
15051** value is also stored in the Expr.iAgg column in the aggregate so that
15052** it can be accessed after all aggregates are computed.
15053**
15054** If the expression is an unbound variable marker (a question mark
15055** character '?' in the original SQL) then the Expr.iTable holds the index
15056** number for that variable.
15057**
15058** If the expression is a subquery then Expr.iColumn holds an integer
15059** register number containing the result of the subquery.  If the
15060** subquery gives a constant result, then iTable is -1.  If the subquery
15061** gives a different answer at different times during statement processing
15062** then iTable is the address of a subroutine that computes the subquery.
15063**
15064** If the Expr is of type OP_Column, and the table it is selecting from
15065** is a disk table or the "old.*" pseudo-table, then pTab points to the
15066** corresponding table definition.
15067**
15068** ALLOCATION NOTES:
15069**
15070** Expr objects can use a lot of memory space in database schema.  To
15071** help reduce memory requirements, sometimes an Expr object will be
15072** truncated.  And to reduce the number of memory allocations, sometimes
15073** two or more Expr objects will be stored in a single memory allocation,
15074** together with Expr.zToken strings.
15075**
15076** If the EP_Reduced and EP_TokenOnly flags are set when
15077** an Expr object is truncated.  When EP_Reduced is set, then all
15078** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
15079** are contained within the same memory allocation.  Note, however, that
15080** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
15081** allocated, regardless of whether or not EP_Reduced is set.
15082*/
15083struct Expr {
15084  u8 op;                 /* Operation performed by this node */
15085  char affinity;         /* The affinity of the column or 0 if not a column */
15086  u32 flags;             /* Various flags.  EP_* See below */
15087  union {
15088    char *zToken;          /* Token value. Zero terminated and dequoted */
15089    int iValue;            /* Non-negative integer value if EP_IntValue */
15090  } u;
15091
15092  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
15093  ** space is allocated for the fields below this point. An attempt to
15094  ** access them will result in a segfault or malfunction.
15095  *********************************************************************/
15096
15097  Expr *pLeft;           /* Left subnode */
15098  Expr *pRight;          /* Right subnode */
15099  union {
15100    ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
15101    Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
15102  } x;
15103
15104  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
15105  ** space is allocated for the fields below this point. An attempt to
15106  ** access them will result in a segfault or malfunction.
15107  *********************************************************************/
15108
15109#if SQLITE_MAX_EXPR_DEPTH>0
15110  int nHeight;           /* Height of the tree headed by this node */
15111#endif
15112  int iTable;            /* TK_COLUMN: cursor number of table holding column
15113                         ** TK_REGISTER: register number
15114                         ** TK_TRIGGER: 1 -> new, 0 -> old
15115                         ** EP_Unlikely:  134217728 times likelihood
15116                         ** TK_SELECT: 1st register of result vector */
15117  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
15118                         ** TK_VARIABLE: variable number (always >= 1).
15119                         ** TK_SELECT_COLUMN: column of the result vector */
15120  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
15121  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
15122  u8 op2;                /* TK_REGISTER: original value of Expr.op
15123                         ** TK_COLUMN: the value of p5 for OP_Column
15124                         ** TK_AGG_FUNCTION: nesting depth */
15125  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
15126  Table *pTab;           /* Table for TK_COLUMN expressions. */
15127};
15128
15129/*
15130** The following are the meanings of bits in the Expr.flags field.
15131*/
15132#define EP_FromJoin  0x000001 /* Originates in ON/USING clause of outer join */
15133#define EP_Agg       0x000002 /* Contains one or more aggregate functions */
15134#define EP_Resolved  0x000004 /* IDs have been resolved to COLUMNs */
15135#define EP_Error     0x000008 /* Expression contains one or more errors */
15136#define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
15137#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
15138#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
15139#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
15140#define EP_Collate   0x000100 /* Tree contains a TK_COLLATE operator */
15141#define EP_Generic   0x000200 /* Ignore COLLATE or affinity on this tree */
15142#define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
15143#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
15144#define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
15145#define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
15146#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
15147#define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
15148#define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
15149#define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
15150#define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
15151#define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
15152#define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
15153#define EP_Subquery  0x200000 /* Tree contains a TK_SELECT operator */
15154#define EP_Alias     0x400000 /* Is an alias for a result set column */
15155#define EP_Leaf      0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
15156
15157/*
15158** Combinations of two or more EP_* flags
15159*/
15160#define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
15161
15162/*
15163** These macros can be used to test, set, or clear bits in the
15164** Expr.flags field.
15165*/
15166#define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
15167#define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
15168#define ExprSetProperty(E,P)     (E)->flags|=(P)
15169#define ExprClearProperty(E,P)   (E)->flags&=~(P)
15170
15171/* The ExprSetVVAProperty() macro is used for Verification, Validation,
15172** and Accreditation only.  It works like ExprSetProperty() during VVA
15173** processes but is a no-op for delivery.
15174*/
15175#ifdef SQLITE_DEBUG
15176# define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
15177#else
15178# define ExprSetVVAProperty(E,P)
15179#endif
15180
15181/*
15182** Macros to determine the number of bytes required by a normal Expr
15183** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
15184** and an Expr struct with the EP_TokenOnly flag set.
15185*/
15186#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
15187#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
15188#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
15189
15190/*
15191** Flags passed to the sqlite3ExprDup() function. See the header comment
15192** above sqlite3ExprDup() for details.
15193*/
15194#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
15195
15196/*
15197** A list of expressions.  Each expression may optionally have a
15198** name.  An expr/name combination can be used in several ways, such
15199** as the list of "expr AS ID" fields following a "SELECT" or in the
15200** list of "ID = expr" items in an UPDATE.  A list of expressions can
15201** also be used as the argument to a function, in which case the a.zName
15202** field is not used.
15203**
15204** By default the Expr.zSpan field holds a human-readable description of
15205** the expression that is used in the generation of error messages and
15206** column labels.  In this case, Expr.zSpan is typically the text of a
15207** column expression as it exists in a SELECT statement.  However, if
15208** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
15209** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
15210** form is used for name resolution with nested FROM clauses.
15211*/
15212struct ExprList {
15213  int nExpr;             /* Number of expressions on the list */
15214  struct ExprList_item { /* For each expression in the list */
15215    Expr *pExpr;            /* The parse tree for this expression */
15216    char *zName;            /* Token associated with this expression */
15217    char *zSpan;            /* Original text of the expression */
15218    u8 sortOrder;           /* 1 for DESC or 0 for ASC */
15219    unsigned done :1;       /* A flag to indicate when processing is finished */
15220    unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
15221    unsigned reusable :1;   /* Constant expression is reusable */
15222    union {
15223      struct {
15224        u16 iOrderByCol;      /* For ORDER BY, column number in result set */
15225        u16 iAlias;           /* Index into Parse.aAlias[] for zName */
15226      } x;
15227      int iConstExprReg;      /* Register in which Expr value is cached */
15228    } u;
15229  } *a;                  /* Alloc a power of two greater or equal to nExpr */
15230};
15231
15232/*
15233** An instance of this structure is used by the parser to record both
15234** the parse tree for an expression and the span of input text for an
15235** expression.
15236*/
15237struct ExprSpan {
15238  Expr *pExpr;          /* The expression parse tree */
15239  const char *zStart;   /* First character of input text */
15240  const char *zEnd;     /* One character past the end of input text */
15241};
15242
15243/*
15244** An instance of this structure can hold a simple list of identifiers,
15245** such as the list "a,b,c" in the following statements:
15246**
15247**      INSERT INTO t(a,b,c) VALUES ...;
15248**      CREATE INDEX idx ON t(a,b,c);
15249**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
15250**
15251** The IdList.a.idx field is used when the IdList represents the list of
15252** column names after a table name in an INSERT statement.  In the statement
15253**
15254**     INSERT INTO t(a,b,c) ...
15255**
15256** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
15257*/
15258struct IdList {
15259  struct IdList_item {
15260    char *zName;      /* Name of the identifier */
15261    int idx;          /* Index in some Table.aCol[] of a column named zName */
15262  } *a;
15263  int nId;         /* Number of identifiers on the list */
15264};
15265
15266/*
15267** The bitmask datatype defined below is used for various optimizations.
15268**
15269** Changing this from a 64-bit to a 32-bit type limits the number of
15270** tables in a join to 32 instead of 64.  But it also reduces the size
15271** of the library by 738 bytes on ix86.
15272*/
15273#ifdef SQLITE_BITMASK_TYPE
15274  typedef SQLITE_BITMASK_TYPE Bitmask;
15275#else
15276  typedef u64 Bitmask;
15277#endif
15278
15279/*
15280** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
15281*/
15282#define BMS  ((int)(sizeof(Bitmask)*8))
15283
15284/*
15285** A bit in a Bitmask
15286*/
15287#define MASKBIT(n)   (((Bitmask)1)<<(n))
15288#define MASKBIT32(n) (((unsigned int)1)<<(n))
15289#define ALLBITS      ((Bitmask)-1)
15290
15291/*
15292** The following structure describes the FROM clause of a SELECT statement.
15293** Each table or subquery in the FROM clause is a separate element of
15294** the SrcList.a[] array.
15295**
15296** With the addition of multiple database support, the following structure
15297** can also be used to describe a particular table such as the table that
15298** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
15299** such a table must be a simple name: ID.  But in SQLite, the table can
15300** now be identified by a database name, a dot, then the table name: ID.ID.
15301**
15302** The jointype starts out showing the join type between the current table
15303** and the next table on the list.  The parser builds the list this way.
15304** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
15305** jointype expresses the join between the table and the previous table.
15306**
15307** In the colUsed field, the high-order bit (bit 63) is set if the table
15308** contains more than 63 columns and the 64-th or later column is used.
15309*/
15310struct SrcList {
15311  int nSrc;        /* Number of tables or subqueries in the FROM clause */
15312  u32 nAlloc;      /* Number of entries allocated in a[] below */
15313  struct SrcList_item {
15314    Schema *pSchema;  /* Schema to which this item is fixed */
15315    char *zDatabase;  /* Name of database holding this table */
15316    char *zName;      /* Name of the table */
15317    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
15318    Table *pTab;      /* An SQL table corresponding to zName */
15319    Select *pSelect;  /* A SELECT statement used in place of a table name */
15320    int addrFillSub;  /* Address of subroutine to manifest a subquery */
15321    int regReturn;    /* Register holding return address of addrFillSub */
15322    int regResult;    /* Registers holding results of a co-routine */
15323    struct {
15324      u8 jointype;      /* Type of join between this table and the previous */
15325      unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
15326      unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */
15327      unsigned isTabFunc :1;     /* True if table-valued-function syntax */
15328      unsigned isCorrelated :1;  /* True if sub-query is correlated */
15329      unsigned viaCoroutine :1;  /* Implemented as a co-routine */
15330      unsigned isRecursive :1;   /* True for recursive reference in WITH */
15331    } fg;
15332#ifndef SQLITE_OMIT_EXPLAIN
15333    u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
15334#endif
15335    int iCursor;      /* The VDBE cursor number used to access this table */
15336    Expr *pOn;        /* The ON clause of a join */
15337    IdList *pUsing;   /* The USING clause of a join */
15338    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
15339    union {
15340      char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */
15341      ExprList *pFuncArg;  /* Arguments to table-valued-function */
15342    } u1;
15343    Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */
15344  } a[1];             /* One entry for each identifier on the list */
15345};
15346
15347/*
15348** Permitted values of the SrcList.a.jointype field
15349*/
15350#define JT_INNER     0x0001    /* Any kind of inner or cross join */
15351#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
15352#define JT_NATURAL   0x0004    /* True for a "natural" join */
15353#define JT_LEFT      0x0008    /* Left outer join */
15354#define JT_RIGHT     0x0010    /* Right outer join */
15355#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
15356#define JT_ERROR     0x0040    /* unknown or unsupported join type */
15357
15358
15359/*
15360** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
15361** and the WhereInfo.wctrlFlags member.
15362**
15363** Value constraints (enforced via assert()):
15364**     WHERE_USE_LIMIT  == SF_FixedLimit
15365*/
15366#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
15367#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
15368#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
15369#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
15370#define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
15371#define WHERE_DUPLICATES_OK    0x0010 /* Ok to return a row more than once */
15372#define WHERE_OR_SUBCLAUSE     0x0020 /* Processing a sub-WHERE as part of
15373                                      ** the OR optimization  */
15374#define WHERE_GROUPBY          0x0040 /* pOrderBy is really a GROUP BY */
15375#define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */
15376#define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */
15377#define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */
15378#define WHERE_SEEK_TABLE       0x0400 /* Do not defer seeks on main table */
15379#define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */
15380#define WHERE_SEEK_UNIQ_TABLE  0x1000 /* Do not defer seeks if unique */
15381                        /*     0x2000    not currently used */
15382#define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */
15383                        /*     0x8000    not currently used */
15384
15385/* Allowed return values from sqlite3WhereIsDistinct()
15386*/
15387#define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
15388#define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
15389#define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
15390#define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
15391
15392/*
15393** A NameContext defines a context in which to resolve table and column
15394** names.  The context consists of a list of tables (the pSrcList) field and
15395** a list of named expression (pEList).  The named expression list may
15396** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
15397** to the table being operated on by INSERT, UPDATE, or DELETE.  The
15398** pEList corresponds to the result set of a SELECT and is NULL for
15399** other statements.
15400**
15401** NameContexts can be nested.  When resolving names, the inner-most
15402** context is searched first.  If no match is found, the next outer
15403** context is checked.  If there is still no match, the next context
15404** is checked.  This process continues until either a match is found
15405** or all contexts are check.  When a match is found, the nRef member of
15406** the context containing the match is incremented.
15407**
15408** Each subquery gets a new NameContext.  The pNext field points to the
15409** NameContext in the parent query.  Thus the process of scanning the
15410** NameContext list corresponds to searching through successively outer
15411** subqueries looking for a match.
15412*/
15413struct NameContext {
15414  Parse *pParse;       /* The parser */
15415  SrcList *pSrcList;   /* One or more tables used to resolve names */
15416  ExprList *pEList;    /* Optional list of result-set columns */
15417  AggInfo *pAggInfo;   /* Information about aggregates at this level */
15418  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
15419  int nRef;            /* Number of names resolved by this context */
15420  int nErr;            /* Number of errors encountered while resolving names */
15421  u16 ncFlags;         /* Zero or more NC_* flags defined below */
15422};
15423
15424/*
15425** Allowed values for the NameContext, ncFlags field.
15426**
15427** Value constraints (all checked via assert()):
15428**    NC_HasAgg    == SF_HasAgg
15429**    NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
15430**
15431*/
15432#define NC_AllowAgg  0x0001  /* Aggregate functions are allowed here */
15433#define NC_PartIdx   0x0002  /* True if resolving a partial index WHERE */
15434#define NC_IsCheck   0x0004  /* True if resolving names in a CHECK constraint */
15435#define NC_InAggFunc 0x0008  /* True if analyzing arguments to an agg func */
15436#define NC_HasAgg    0x0010  /* One or more aggregate functions seen */
15437#define NC_IdxExpr   0x0020  /* True if resolving columns of CREATE INDEX */
15438#define NC_VarSelect 0x0040  /* A correlated subquery has been seen */
15439#define NC_MinMaxAgg 0x1000  /* min/max aggregates seen.  See note above */
15440
15441/*
15442** An instance of the following structure contains all information
15443** needed to generate code for a single SELECT statement.
15444**
15445** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
15446** If there is a LIMIT clause, the parser sets nLimit to the value of the
15447** limit and nOffset to the value of the offset (or 0 if there is not
15448** offset).  But later on, nLimit and nOffset become the memory locations
15449** in the VDBE that record the limit and offset counters.
15450**
15451** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
15452** These addresses must be stored so that we can go back and fill in
15453** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
15454** the number of columns in P2 can be computed at the same time
15455** as the OP_OpenEphm instruction is coded because not
15456** enough information about the compound query is known at that point.
15457** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
15458** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
15459** sequences for the ORDER BY clause.
15460*/
15461struct Select {
15462  ExprList *pEList;      /* The fields of the result */
15463  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
15464  LogEst nSelectRow;     /* Estimated number of result rows */
15465  u32 selFlags;          /* Various SF_* values */
15466  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
15467#if SELECTTRACE_ENABLED
15468  char zSelName[12];     /* Symbolic name of this SELECT use for debugging */
15469#endif
15470  int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
15471  SrcList *pSrc;         /* The FROM clause */
15472  Expr *pWhere;          /* The WHERE clause */
15473  ExprList *pGroupBy;    /* The GROUP BY clause */
15474  Expr *pHaving;         /* The HAVING clause */
15475  ExprList *pOrderBy;    /* The ORDER BY clause */
15476  Select *pPrior;        /* Prior select in a compound select statement */
15477  Select *pNext;         /* Next select to the left in a compound */
15478  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
15479  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
15480  With *pWith;           /* WITH clause attached to this select. Or NULL. */
15481};
15482
15483/*
15484** Allowed values for Select.selFlags.  The "SF" prefix stands for
15485** "Select Flag".
15486**
15487** Value constraints (all checked via assert())
15488**     SF_HasAgg     == NC_HasAgg
15489**     SF_MinMaxAgg  == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX
15490**     SF_FixedLimit == WHERE_USE_LIMIT
15491*/
15492#define SF_Distinct       0x00001  /* Output should be DISTINCT */
15493#define SF_All            0x00002  /* Includes the ALL keyword */
15494#define SF_Resolved       0x00004  /* Identifiers have been resolved */
15495#define SF_Aggregate      0x00008  /* Contains agg functions or a GROUP BY */
15496#define SF_HasAgg         0x00010  /* Contains aggregate functions */
15497#define SF_UsesEphemeral  0x00020  /* Uses the OpenEphemeral opcode */
15498#define SF_Expanded       0x00040  /* sqlite3SelectExpand() called on this */
15499#define SF_HasTypeInfo    0x00080  /* FROM subqueries have Table metadata */
15500#define SF_Compound       0x00100  /* Part of a compound query */
15501#define SF_Values         0x00200  /* Synthesized from VALUES clause */
15502#define SF_MultiValue     0x00400  /* Single VALUES term with multiple rows */
15503#define SF_NestedFrom     0x00800  /* Part of a parenthesized FROM clause */
15504#define SF_MinMaxAgg      0x01000  /* Aggregate containing min() or max() */
15505#define SF_Recursive      0x02000  /* The recursive part of a recursive CTE */
15506#define SF_FixedLimit     0x04000  /* nSelectRow set by a constant LIMIT */
15507#define SF_MaybeConvert   0x08000  /* Need convertCompoundSelectToSubquery() */
15508#define SF_Converted      0x10000  /* By convertCompoundSelectToSubquery() */
15509#define SF_IncludeHidden  0x20000  /* Include hidden columns in output */
15510
15511
15512/*
15513** The results of a SELECT can be distributed in several ways, as defined
15514** by one of the following macros.  The "SRT" prefix means "SELECT Result
15515** Type".
15516**
15517**     SRT_Union       Store results as a key in a temporary index
15518**                     identified by pDest->iSDParm.
15519**
15520**     SRT_Except      Remove results from the temporary index pDest->iSDParm.
15521**
15522**     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
15523**                     set is not empty.
15524**
15525**     SRT_Discard     Throw the results away.  This is used by SELECT
15526**                     statements within triggers whose only purpose is
15527**                     the side-effects of functions.
15528**
15529** All of the above are free to ignore their ORDER BY clause. Those that
15530** follow must honor the ORDER BY clause.
15531**
15532**     SRT_Output      Generate a row of output (using the OP_ResultRow
15533**                     opcode) for each row in the result set.
15534**
15535**     SRT_Mem         Only valid if the result is a single column.
15536**                     Store the first column of the first result row
15537**                     in register pDest->iSDParm then abandon the rest
15538**                     of the query.  This destination implies "LIMIT 1".
15539**
15540**     SRT_Set         The result must be a single column.  Store each
15541**                     row of result as the key in table pDest->iSDParm.
15542**                     Apply the affinity pDest->affSdst before storing
15543**                     results.  Used to implement "IN (SELECT ...)".
15544**
15545**     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
15546**                     the result there. The cursor is left open after
15547**                     returning.  This is like SRT_Table except that
15548**                     this destination uses OP_OpenEphemeral to create
15549**                     the table first.
15550**
15551**     SRT_Coroutine   Generate a co-routine that returns a new row of
15552**                     results each time it is invoked.  The entry point
15553**                     of the co-routine is stored in register pDest->iSDParm
15554**                     and the result row is stored in pDest->nDest registers
15555**                     starting with pDest->iSdst.
15556**
15557**     SRT_Table       Store results in temporary table pDest->iSDParm.
15558**     SRT_Fifo        This is like SRT_EphemTab except that the table
15559**                     is assumed to already be open.  SRT_Fifo has
15560**                     the additional property of being able to ignore
15561**                     the ORDER BY clause.
15562**
15563**     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
15564**                     But also use temporary table pDest->iSDParm+1 as
15565**                     a record of all prior results and ignore any duplicate
15566**                     rows.  Name means:  "Distinct Fifo".
15567**
15568**     SRT_Queue       Store results in priority queue pDest->iSDParm (really
15569**                     an index).  Append a sequence number so that all entries
15570**                     are distinct.
15571**
15572**     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
15573**                     the same record has never been stored before.  The
15574**                     index at pDest->iSDParm+1 hold all prior stores.
15575*/
15576#define SRT_Union        1  /* Store result as keys in an index */
15577#define SRT_Except       2  /* Remove result from a UNION index */
15578#define SRT_Exists       3  /* Store 1 if the result is not empty */
15579#define SRT_Discard      4  /* Do not save the results anywhere */
15580#define SRT_Fifo         5  /* Store result as data with an automatic rowid */
15581#define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
15582#define SRT_Queue        7  /* Store result in an queue */
15583#define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
15584
15585/* The ORDER BY clause is ignored for all of the above */
15586#define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
15587
15588#define SRT_Output       9  /* Output each row of result */
15589#define SRT_Mem         10  /* Store result in a memory cell */
15590#define SRT_Set         11  /* Store results as keys in an index */
15591#define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
15592#define SRT_Coroutine   13  /* Generate a single row of result */
15593#define SRT_Table       14  /* Store result as data with an automatic rowid */
15594
15595/*
15596** An instance of this object describes where to put of the results of
15597** a SELECT statement.
15598*/
15599struct SelectDest {
15600  u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
15601  char *zAffSdst;      /* Affinity used when eDest==SRT_Set */
15602  int iSDParm;         /* A parameter used by the eDest disposal method */
15603  int iSdst;           /* Base register where results are written */
15604  int nSdst;           /* Number of registers allocated */
15605  ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
15606};
15607
15608/*
15609** During code generation of statements that do inserts into AUTOINCREMENT
15610** tables, the following information is attached to the Table.u.autoInc.p
15611** pointer of each autoincrement table to record some side information that
15612** the code generator needs.  We have to keep per-table autoincrement
15613** information in case inserts are done within triggers.  Triggers do not
15614** normally coordinate their activities, but we do need to coordinate the
15615** loading and saving of autoincrement information.
15616*/
15617struct AutoincInfo {
15618  AutoincInfo *pNext;   /* Next info block in a list of them all */
15619  Table *pTab;          /* Table this info block refers to */
15620  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
15621  int regCtr;           /* Memory register holding the rowid counter */
15622};
15623
15624/*
15625** Size of the column cache
15626*/
15627#ifndef SQLITE_N_COLCACHE
15628# define SQLITE_N_COLCACHE 10
15629#endif
15630
15631/*
15632** At least one instance of the following structure is created for each
15633** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
15634** statement. All such objects are stored in the linked list headed at
15635** Parse.pTriggerPrg and deleted once statement compilation has been
15636** completed.
15637**
15638** A Vdbe sub-program that implements the body and WHEN clause of trigger
15639** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
15640** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
15641** The Parse.pTriggerPrg list never contains two entries with the same
15642** values for both pTrigger and orconf.
15643**
15644** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
15645** accessed (or set to 0 for triggers fired as a result of INSERT
15646** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
15647** a mask of new.* columns used by the program.
15648*/
15649struct TriggerPrg {
15650  Trigger *pTrigger;      /* Trigger this program was coded from */
15651  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
15652  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
15653  int orconf;             /* Default ON CONFLICT policy */
15654  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
15655};
15656
15657/*
15658** The yDbMask datatype for the bitmask of all attached databases.
15659*/
15660#if SQLITE_MAX_ATTACHED>30
15661  typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
15662# define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
15663# define DbMaskZero(M)      memset((M),0,sizeof(M))
15664# define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
15665# define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
15666# define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
15667#else
15668  typedef unsigned int yDbMask;
15669# define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
15670# define DbMaskZero(M)      (M)=0
15671# define DbMaskSet(M,I)     (M)|=(((yDbMask)1)<<(I))
15672# define DbMaskAllZero(M)   (M)==0
15673# define DbMaskNonZero(M)   (M)!=0
15674#endif
15675
15676/*
15677** An SQL parser context.  A copy of this structure is passed through
15678** the parser and down into all the parser action routine in order to
15679** carry around information that is global to the entire parse.
15680**
15681** The structure is divided into two parts.  When the parser and code
15682** generate call themselves recursively, the first part of the structure
15683** is constant but the second part is reset at the beginning and end of
15684** each recursion.
15685**
15686** The nTableLock and aTableLock variables are only used if the shared-cache
15687** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
15688** used to store the set of table-locks required by the statement being
15689** compiled. Function sqlite3TableLock() is used to add entries to the
15690** list.
15691*/
15692struct Parse {
15693  sqlite3 *db;         /* The main database structure */
15694  char *zErrMsg;       /* An error message */
15695  Vdbe *pVdbe;         /* An engine for executing database bytecode */
15696  int rc;              /* Return code from execution */
15697  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
15698  u8 checkSchema;      /* Causes schema cookie check after an error */
15699  u8 nested;           /* Number of nested calls to the parser/code generator */
15700  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
15701  u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
15702  u8 mayAbort;         /* True if statement may throw an ABORT exception */
15703  u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
15704  u8 okConstFactor;    /* OK to factor out constants */
15705  u8 disableLookaside; /* Number of times lookaside has been disabled */
15706  u8 nColCache;        /* Number of entries in aColCache[] */
15707  int nRangeReg;       /* Size of the temporary register block */
15708  int iRangeReg;       /* First register in temporary register block */
15709  int nErr;            /* Number of errors seen */
15710  int nTab;            /* Number of previously allocated VDBE cursors */
15711  int nMem;            /* Number of memory cells used so far */
15712  int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
15713  int szOpAlloc;       /* Bytes of memory space allocated for Vdbe.aOp[] */
15714  int ckBase;          /* Base register of data during check constraints */
15715  int iSelfTab;        /* Table of an index whose exprs are being coded */
15716  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
15717  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
15718  int nLabel;          /* Number of labels used */
15719  int *aLabel;         /* Space to hold the labels */
15720  ExprList *pConstExpr;/* Constant expressions */
15721  Token constraintName;/* Name of the constraint currently being parsed */
15722  yDbMask writeMask;   /* Start a write transaction on these databases */
15723  yDbMask cookieMask;  /* Bitmask of schema verified databases */
15724  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
15725  int regRoot;         /* Register holding root page number for new objects */
15726  int nMaxArg;         /* Max args passed to user function by sub-program */
15727#if SELECTTRACE_ENABLED
15728  int nSelect;         /* Number of SELECT statements seen */
15729  int nSelectIndent;   /* How far to indent SELECTTRACE() output */
15730#endif
15731#ifndef SQLITE_OMIT_SHARED_CACHE
15732  int nTableLock;        /* Number of locks in aTableLock */
15733  TableLock *aTableLock; /* Required table locks for shared-cache mode */
15734#endif
15735  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
15736  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
15737  Table *pTriggerTab;  /* Table triggers are being coded for */
15738  int addrCrTab;       /* Address of OP_CreateTable opcode on CREATE TABLE */
15739  u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
15740  u32 oldmask;         /* Mask of old.* columns referenced */
15741  u32 newmask;         /* Mask of new.* columns referenced */
15742  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
15743  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
15744  u8 disableTriggers;  /* True to disable triggers */
15745
15746  /**************************************************************************
15747  ** Fields above must be initialized to zero.  The fields that follow,
15748  ** down to the beginning of the recursive section, do not need to be
15749  ** initialized as they will be set before being used.  The boundary is
15750  ** determined by offsetof(Parse,aColCache).
15751  **************************************************************************/
15752
15753  struct yColCache {
15754    int iTable;           /* Table cursor number */
15755    i16 iColumn;          /* Table column number */
15756    u8 tempReg;           /* iReg is a temp register that needs to be freed */
15757    int iLevel;           /* Nesting level */
15758    int iReg;             /* Reg with value of this column. 0 means none. */
15759    int lru;              /* Least recently used entry has the smallest value */
15760  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
15761  int aTempReg[8];        /* Holding area for temporary registers */
15762  Token sNameToken;       /* Token with unqualified schema object name */
15763
15764  /************************************************************************
15765  ** Above is constant between recursions.  Below is reset before and after
15766  ** each recursion.  The boundary between these two regions is determined
15767  ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
15768  ** first field in the recursive region.
15769  ************************************************************************/
15770
15771  Token sLastToken;       /* The last token parsed */
15772  ynVar nVar;               /* Number of '?' variables seen in the SQL so far */
15773  u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
15774  u8 explain;               /* True if the EXPLAIN flag is found on the query */
15775#ifndef SQLITE_OMIT_VIRTUALTABLE
15776  u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
15777  int nVtabLock;            /* Number of virtual tables to lock */
15778#endif
15779  int nHeight;              /* Expression tree height of current sub-select */
15780#ifndef SQLITE_OMIT_EXPLAIN
15781  int iSelectId;            /* ID of current select for EXPLAIN output */
15782  int iNextSelectId;        /* Next available select ID for EXPLAIN output */
15783#endif
15784  VList *pVList;            /* Mapping between variable names and numbers */
15785  Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
15786  const char *zTail;        /* All SQL text past the last semicolon parsed */
15787  Table *pNewTable;         /* A table being constructed by CREATE TABLE */
15788  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
15789  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
15790#ifndef SQLITE_OMIT_VIRTUALTABLE
15791  Token sArg;               /* Complete text of a module argument */
15792  Table **apVtabLock;       /* Pointer to virtual tables needing locking */
15793#endif
15794  Table *pZombieTab;        /* List of Table objects to delete after code gen */
15795  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
15796  With *pWith;              /* Current WITH clause, or NULL */
15797  With *pWithToFree;        /* Free this WITH object at the end of the parse */
15798};
15799
15800/*
15801** Sizes and pointers of various parts of the Parse object.
15802*/
15803#define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/
15804#define PARSE_RECURSE_SZ offsetof(Parse,sLastToken)    /* Recursive part */
15805#define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
15806#define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ)  /* Pointer to tail */
15807
15808/*
15809** Return true if currently inside an sqlite3_declare_vtab() call.
15810*/
15811#ifdef SQLITE_OMIT_VIRTUALTABLE
15812  #define IN_DECLARE_VTAB 0
15813#else
15814  #define IN_DECLARE_VTAB (pParse->declareVtab)
15815#endif
15816
15817/*
15818** An instance of the following structure can be declared on a stack and used
15819** to save the Parse.zAuthContext value so that it can be restored later.
15820*/
15821struct AuthContext {
15822  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
15823  Parse *pParse;              /* The Parse structure */
15824};
15825
15826/*
15827** Bitfield flags for P5 value in various opcodes.
15828**
15829** Value constraints (enforced via assert()):
15830**    OPFLAG_LENGTHARG    == SQLITE_FUNC_LENGTH
15831**    OPFLAG_TYPEOFARG    == SQLITE_FUNC_TYPEOF
15832**    OPFLAG_BULKCSR      == BTREE_BULKLOAD
15833**    OPFLAG_SEEKEQ       == BTREE_SEEK_EQ
15834**    OPFLAG_FORDELETE    == BTREE_FORDELETE
15835**    OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
15836**    OPFLAG_AUXDELETE    == BTREE_AUXDELETE
15837*/
15838#define OPFLAG_NCHANGE       0x01    /* OP_Insert: Set to update db->nChange */
15839                                     /* Also used in P2 (not P5) of OP_Delete */
15840#define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
15841#define OPFLAG_LASTROWID     0x20    /* Set to update db->lastRowid */
15842#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
15843#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
15844#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
15845#define OPFLAG_ISNOOP        0x40    /* OP_Delete does pre-update-hook only */
15846#define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
15847#define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
15848#define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
15849#define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */
15850#define OPFLAG_FORDELETE     0x08    /* OP_Open should use BTREE_FORDELETE */
15851#define OPFLAG_P2ISREG       0x10    /* P2 to OP_Open** is a register number */
15852#define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
15853#define OPFLAG_SAVEPOSITION  0x02    /* OP_Delete/Insert: save cursor pos */
15854#define OPFLAG_AUXDELETE     0x04    /* OP_Delete: index in a DELETE op */
15855
15856/*
15857 * Each trigger present in the database schema is stored as an instance of
15858 * struct Trigger.
15859 *
15860 * Pointers to instances of struct Trigger are stored in two ways.
15861 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
15862 *    database). This allows Trigger structures to be retrieved by name.
15863 * 2. All triggers associated with a single table form a linked list, using the
15864 *    pNext member of struct Trigger. A pointer to the first element of the
15865 *    linked list is stored as the "pTrigger" member of the associated
15866 *    struct Table.
15867 *
15868 * The "step_list" member points to the first element of a linked list
15869 * containing the SQL statements specified as the trigger program.
15870 */
15871struct Trigger {
15872  char *zName;            /* The name of the trigger                        */
15873  char *table;            /* The table or view to which the trigger applies */
15874  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
15875  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
15876  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
15877  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
15878                             the <column-list> is stored here */
15879  Schema *pSchema;        /* Schema containing the trigger */
15880  Schema *pTabSchema;     /* Schema containing the table */
15881  TriggerStep *step_list; /* Link list of trigger program steps             */
15882  Trigger *pNext;         /* Next trigger associated with the table */
15883};
15884
15885/*
15886** A trigger is either a BEFORE or an AFTER trigger.  The following constants
15887** determine which.
15888**
15889** If there are multiple triggers, you might of some BEFORE and some AFTER.
15890** In that cases, the constants below can be ORed together.
15891*/
15892#define TRIGGER_BEFORE  1
15893#define TRIGGER_AFTER   2
15894
15895/*
15896 * An instance of struct TriggerStep is used to store a single SQL statement
15897 * that is a part of a trigger-program.
15898 *
15899 * Instances of struct TriggerStep are stored in a singly linked list (linked
15900 * using the "pNext" member) referenced by the "step_list" member of the
15901 * associated struct Trigger instance. The first element of the linked list is
15902 * the first step of the trigger-program.
15903 *
15904 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
15905 * "SELECT" statement. The meanings of the other members is determined by the
15906 * value of "op" as follows:
15907 *
15908 * (op == TK_INSERT)
15909 * orconf    -> stores the ON CONFLICT algorithm
15910 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
15911 *              this stores a pointer to the SELECT statement. Otherwise NULL.
15912 * zTarget   -> Dequoted name of the table to insert into.
15913 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
15914 *              this stores values to be inserted. Otherwise NULL.
15915 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
15916 *              statement, then this stores the column-names to be
15917 *              inserted into.
15918 *
15919 * (op == TK_DELETE)
15920 * zTarget   -> Dequoted name of the table to delete from.
15921 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
15922 *              Otherwise NULL.
15923 *
15924 * (op == TK_UPDATE)
15925 * zTarget   -> Dequoted name of the table to update.
15926 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
15927 *              Otherwise NULL.
15928 * pExprList -> A list of the columns to update and the expressions to update
15929 *              them to. See sqlite3Update() documentation of "pChanges"
15930 *              argument.
15931 *
15932 */
15933struct TriggerStep {
15934  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
15935  u8 orconf;           /* OE_Rollback etc. */
15936  Trigger *pTrig;      /* The trigger that this step is a part of */
15937  Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
15938  char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
15939  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
15940  ExprList *pExprList; /* SET clause for UPDATE. */
15941  IdList *pIdList;     /* Column names for INSERT */
15942  TriggerStep *pNext;  /* Next in the link-list */
15943  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
15944};
15945
15946/*
15947** The following structure contains information used by the sqliteFix...
15948** routines as they walk the parse tree to make database references
15949** explicit.
15950*/
15951typedef struct DbFixer DbFixer;
15952struct DbFixer {
15953  Parse *pParse;      /* The parsing context.  Error messages written here */
15954  Schema *pSchema;    /* Fix items to this schema */
15955  int bVarOnly;       /* Check for variable references only */
15956  const char *zDb;    /* Make sure all objects are contained in this database */
15957  const char *zType;  /* Type of the container - used for error messages */
15958  const Token *pName; /* Name of the container - used for error messages */
15959};
15960
15961/*
15962** An objected used to accumulate the text of a string where we
15963** do not necessarily know how big the string will be in the end.
15964*/
15965struct StrAccum {
15966  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
15967  char *zBase;         /* A base allocation.  Not from malloc. */
15968  char *zText;         /* The string collected so far */
15969  u32  nChar;          /* Length of the string so far */
15970  u32  nAlloc;         /* Amount of space allocated in zText */
15971  u32  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */
15972  u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
15973  u8   printfFlags;    /* SQLITE_PRINTF flags below */
15974};
15975#define STRACCUM_NOMEM   1
15976#define STRACCUM_TOOBIG  2
15977#define SQLITE_PRINTF_INTERNAL 0x01  /* Internal-use-only converters allowed */
15978#define SQLITE_PRINTF_SQLFUNC  0x02  /* SQL function arguments to VXPrintf */
15979#define SQLITE_PRINTF_MALLOCED 0x04  /* True if xText is allocated space */
15980
15981#define isMalloced(X)  (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
15982
15983
15984/*
15985** A pointer to this structure is used to communicate information
15986** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
15987*/
15988typedef struct {
15989  sqlite3 *db;        /* The database being initialized */
15990  char **pzErrMsg;    /* Error message stored here */
15991  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
15992  int rc;             /* Result code stored here */
15993} InitData;
15994
15995/*
15996** Structure containing global configuration data for the SQLite library.
15997**
15998** This structure also contains some state information.
15999*/
16000struct Sqlite3Config {
16001  int bMemstat;                     /* True to enable memory status */
16002  int bCoreMutex;                   /* True to enable core mutexing */
16003  int bFullMutex;                   /* True to enable full mutexing */
16004  int bOpenUri;                     /* True to interpret filenames as URIs */
16005  int bUseCis;                      /* Use covering indices for full-scans */
16006  int mxStrlen;                     /* Maximum string length */
16007  int neverCorrupt;                 /* Database is always well-formed */
16008  int szLookaside;                  /* Default lookaside buffer size */
16009  int nLookaside;                   /* Default lookaside buffer count */
16010  int nStmtSpill;                   /* Stmt-journal spill-to-disk threshold */
16011  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
16012  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
16013  sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
16014  void *pHeap;                      /* Heap storage space */
16015  int nHeap;                        /* Size of pHeap[] */
16016  int mnReq, mxReq;                 /* Min and max heap requests sizes */
16017  sqlite3_int64 szMmap;             /* mmap() space per open file */
16018  sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
16019  void *pScratch;                   /* Scratch memory */
16020  int szScratch;                    /* Size of each scratch buffer */
16021  int nScratch;                     /* Number of scratch buffers */
16022  void *pPage;                      /* Page cache memory */
16023  int szPage;                       /* Size of each page in pPage[] */
16024  int nPage;                        /* Number of pages in pPage[] */
16025  int mxParserStack;                /* maximum depth of the parser stack */
16026  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
16027  u32 szPma;                        /* Maximum Sorter PMA size */
16028  /* The above might be initialized to non-zero.  The following need to always
16029  ** initially be zero, however. */
16030  int isInit;                       /* True after initialization has finished */
16031  int inProgress;                   /* True while initialization in progress */
16032  int isMutexInit;                  /* True after mutexes are initialized */
16033  int isMallocInit;                 /* True after malloc is initialized */
16034  int isPCacheInit;                 /* True after malloc is initialized */
16035  int nRefInitMutex;                /* Number of users of pInitMutex */
16036  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
16037  void (*xLog)(void*,int,const char*); /* Function for logging */
16038  void *pLogArg;                       /* First argument to xLog() */
16039#ifdef SQLITE_ENABLE_SQLLOG
16040  void(*xSqllog)(void*,sqlite3*,const char*, int);
16041  void *pSqllogArg;
16042#endif
16043#ifdef SQLITE_VDBE_COVERAGE
16044  /* The following callback (if not NULL) is invoked on every VDBE branch
16045  ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
16046  */
16047  void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
16048  void *pVdbeBranchArg;                                     /* 1st argument */
16049#endif
16050#ifndef SQLITE_UNTESTABLE
16051  int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
16052#endif
16053  int bLocaltimeFault;              /* True to fail localtime() calls */
16054  int iOnceResetThreshold;          /* When to reset OP_Once counters */
16055};
16056
16057/*
16058** This macro is used inside of assert() statements to indicate that
16059** the assert is only valid on a well-formed database.  Instead of:
16060**
16061**     assert( X );
16062**
16063** One writes:
16064**
16065**     assert( X || CORRUPT_DB );
16066**
16067** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
16068** that the database is definitely corrupt, only that it might be corrupt.
16069** For most test cases, CORRUPT_DB is set to false using a special
16070** sqlite3_test_control().  This enables assert() statements to prove
16071** things that are always true for well-formed databases.
16072*/
16073#define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
16074
16075/*
16076** Context pointer passed down through the tree-walk.
16077*/
16078struct Walker {
16079  Parse *pParse;                            /* Parser context.  */
16080  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
16081  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
16082  void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
16083  int walkerDepth;                          /* Number of subqueries */
16084  u8 eCode;                                 /* A small processing code */
16085  union {                                   /* Extra data for callback */
16086    NameContext *pNC;                          /* Naming context */
16087    int n;                                     /* A counter */
16088    int iCur;                                  /* A cursor number */
16089    SrcList *pSrcList;                         /* FROM clause */
16090    struct SrcCount *pSrcCount;                /* Counting column references */
16091    struct CCurHint *pCCurHint;                /* Used by codeCursorHint() */
16092    int *aiCol;                                /* array of column indexes */
16093    struct IdxCover *pIdxCover;                /* Check for index coverage */
16094  } u;
16095};
16096
16097/* Forward declarations */
16098SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
16099SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
16100SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
16101SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
16102SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
16103SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
16104
16105/*
16106** Return code from the parse-tree walking primitives and their
16107** callbacks.
16108*/
16109#define WRC_Continue    0   /* Continue down into children */
16110#define WRC_Prune       1   /* Omit children but continue walking siblings */
16111#define WRC_Abort       2   /* Abandon the tree walk */
16112
16113/*
16114** An instance of this structure represents a set of one or more CTEs
16115** (common table expressions) created by a single WITH clause.
16116*/
16117struct With {
16118  int nCte;                       /* Number of CTEs in the WITH clause */
16119  With *pOuter;                   /* Containing WITH clause, or NULL */
16120  struct Cte {                    /* For each CTE in the WITH clause.... */
16121    char *zName;                    /* Name of this CTE */
16122    ExprList *pCols;                /* List of explicit column names, or NULL */
16123    Select *pSelect;                /* The definition of this CTE */
16124    const char *zCteErr;            /* Error message for circular references */
16125  } a[1];
16126};
16127
16128#ifdef SQLITE_DEBUG
16129/*
16130** An instance of the TreeView object is used for printing the content of
16131** data structures on sqlite3DebugPrintf() using a tree-like view.
16132*/
16133struct TreeView {
16134  int iLevel;             /* Which level of the tree we are on */
16135  u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */
16136};
16137#endif /* SQLITE_DEBUG */
16138
16139/*
16140** Assuming zIn points to the first byte of a UTF-8 character,
16141** advance zIn to point to the first byte of the next UTF-8 character.
16142*/
16143#define SQLITE_SKIP_UTF8(zIn) {                        \
16144  if( (*(zIn++))>=0xc0 ){                              \
16145    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
16146  }                                                    \
16147}
16148
16149/*
16150** The SQLITE_*_BKPT macros are substitutes for the error codes with
16151** the same name but without the _BKPT suffix.  These macros invoke
16152** routines that report the line-number on which the error originated
16153** using sqlite3_log().  The routines also provide a convenient place
16154** to set a debugger breakpoint.
16155*/
16156SQLITE_PRIVATE int sqlite3CorruptError(int);
16157SQLITE_PRIVATE int sqlite3MisuseError(int);
16158SQLITE_PRIVATE int sqlite3CantopenError(int);
16159#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
16160#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
16161#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
16162#ifdef SQLITE_DEBUG
16163SQLITE_PRIVATE   int sqlite3NomemError(int);
16164SQLITE_PRIVATE   int sqlite3IoerrnomemError(int);
16165# define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
16166# define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
16167#else
16168# define SQLITE_NOMEM_BKPT SQLITE_NOMEM
16169# define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
16170#endif
16171
16172/*
16173** FTS3 and FTS4 both require virtual table support
16174*/
16175#if defined(SQLITE_OMIT_VIRTUALTABLE)
16176# undef SQLITE_ENABLE_FTS3
16177# undef SQLITE_ENABLE_FTS4
16178#endif
16179
16180/*
16181** FTS4 is really an extension for FTS3.  It is enabled using the
16182** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
16183** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
16184*/
16185#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
16186# define SQLITE_ENABLE_FTS3 1
16187#endif
16188
16189/*
16190** The ctype.h header is needed for non-ASCII systems.  It is also
16191** needed by FTS3 when FTS3 is included in the amalgamation.
16192*/
16193#if !defined(SQLITE_ASCII) || \
16194    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
16195# include <ctype.h>
16196#endif
16197
16198/*
16199** The following macros mimic the standard library functions toupper(),
16200** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
16201** sqlite versions only work for ASCII characters, regardless of locale.
16202*/
16203#ifdef SQLITE_ASCII
16204# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
16205# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
16206# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
16207# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
16208# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
16209# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
16210# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
16211# define sqlite3Isquote(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
16212#else
16213# define sqlite3Toupper(x)   toupper((unsigned char)(x))
16214# define sqlite3Isspace(x)   isspace((unsigned char)(x))
16215# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
16216# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
16217# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
16218# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
16219# define sqlite3Tolower(x)   tolower((unsigned char)(x))
16220# define sqlite3Isquote(x)   ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
16221#endif
16222#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
16223SQLITE_PRIVATE int sqlite3IsIdChar(u8);
16224#endif
16225
16226/*
16227** Internal function prototypes
16228*/
16229SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
16230SQLITE_PRIVATE int sqlite3Strlen30(const char*);
16231SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
16232#define sqlite3StrNICmp sqlite3_strnicmp
16233
16234SQLITE_PRIVATE int sqlite3MallocInit(void);
16235SQLITE_PRIVATE void sqlite3MallocEnd(void);
16236SQLITE_PRIVATE void *sqlite3Malloc(u64);
16237SQLITE_PRIVATE void *sqlite3MallocZero(u64);
16238SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
16239SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
16240SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
16241SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
16242SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
16243SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
16244SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
16245SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
16246SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
16247SQLITE_PRIVATE int sqlite3MallocSize(void*);
16248SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
16249SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
16250SQLITE_PRIVATE void sqlite3ScratchFree(void*);
16251SQLITE_PRIVATE void *sqlite3PageMalloc(int);
16252SQLITE_PRIVATE void sqlite3PageFree(void*);
16253SQLITE_PRIVATE void sqlite3MemSetDefault(void);
16254#ifndef SQLITE_UNTESTABLE
16255SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
16256#endif
16257SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
16258
16259/*
16260** On systems with ample stack space and that support alloca(), make
16261** use of alloca() to obtain space for large automatic objects.  By default,
16262** obtain space from malloc().
16263**
16264** The alloca() routine never returns NULL.  This will cause code paths
16265** that deal with sqlite3StackAlloc() failures to be unreachable.
16266*/
16267#ifdef SQLITE_USE_ALLOCA
16268# define sqlite3StackAllocRaw(D,N)   alloca(N)
16269# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
16270# define sqlite3StackFree(D,P)
16271#else
16272# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
16273# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
16274# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
16275#endif
16276
16277/* Do not allow both MEMSYS5 and MEMSYS3 to be defined together.  If they
16278** are, disable MEMSYS3
16279*/
16280#ifdef SQLITE_ENABLE_MEMSYS5
16281SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
16282#undef SQLITE_ENABLE_MEMSYS3
16283#endif
16284#ifdef SQLITE_ENABLE_MEMSYS3
16285SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
16286#endif
16287
16288
16289#ifndef SQLITE_MUTEX_OMIT
16290SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
16291SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
16292SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
16293SQLITE_PRIVATE   int sqlite3MutexInit(void);
16294SQLITE_PRIVATE   int sqlite3MutexEnd(void);
16295#endif
16296#if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
16297SQLITE_PRIVATE   void sqlite3MemoryBarrier(void);
16298#else
16299# define sqlite3MemoryBarrier()
16300#endif
16301
16302SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
16303SQLITE_PRIVATE void sqlite3StatusUp(int, int);
16304SQLITE_PRIVATE void sqlite3StatusDown(int, int);
16305SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
16306
16307/* Access to mutexes used by sqlite3_status() */
16308SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
16309SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
16310
16311#ifndef SQLITE_OMIT_FLOATING_POINT
16312SQLITE_PRIVATE   int sqlite3IsNaN(double);
16313#else
16314# define sqlite3IsNaN(X)  0
16315#endif
16316
16317/*
16318** An instance of the following structure holds information about SQL
16319** functions arguments that are the parameters to the printf() function.
16320*/
16321struct PrintfArguments {
16322  int nArg;                /* Total number of arguments */
16323  int nUsed;               /* Number of arguments used so far */
16324  sqlite3_value **apArg;   /* The argument values */
16325};
16326
16327SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
16328SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
16329SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
16330SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
16331#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
16332SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
16333#endif
16334#if defined(SQLITE_TEST)
16335SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
16336#endif
16337
16338#if defined(SQLITE_DEBUG)
16339SQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
16340SQLITE_PRIVATE   void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
16341SQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
16342SQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
16343SQLITE_PRIVATE   void sqlite3TreeViewWith(TreeView*, const With*, u8);
16344#endif
16345
16346
16347SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
16348SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
16349SQLITE_PRIVATE void sqlite3Dequote(char*);
16350SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
16351SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
16352SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
16353SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
16354SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
16355SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
16356SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
16357SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
16358SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
16359#ifdef SQLITE_DEBUG
16360SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
16361#endif
16362SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
16363SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
16364SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
16365SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
16366SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
16367SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
16368SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
16369SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
16370SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
16371SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
16372SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
16373SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
16374SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
16375SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
16376SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
16377SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
16378SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
16379SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
16380SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
16381#ifndef SQLITE_OMIT_VIRTUALTABLE
16382SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
16383#endif
16384SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
16385SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
16386SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
16387SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
16388SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
16389SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
16390SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
16391SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
16392SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
16393SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
16394SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
16395SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
16396#if SQLITE_ENABLE_HIDDEN_COLUMNS
16397SQLITE_PRIVATE   void sqlite3ColumnPropertiesFromName(Table*, Column*);
16398#else
16399# define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
16400#endif
16401SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
16402SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
16403SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
16404SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
16405SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
16406SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
16407SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
16408SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
16409                    sqlite3_vfs**,char**,char **);
16410SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
16411
16412#ifdef SQLITE_UNTESTABLE
16413# define sqlite3FaultSim(X) SQLITE_OK
16414#else
16415SQLITE_PRIVATE   int sqlite3FaultSim(int);
16416#endif
16417
16418SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
16419SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
16420SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
16421SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
16422SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
16423SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
16424SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
16425#ifndef SQLITE_UNTESTABLE
16426SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
16427#endif
16428
16429SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
16430SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
16431SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
16432SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
16433SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
16434
16435SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
16436
16437#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
16438SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
16439#else
16440# define sqlite3ViewGetColumnNames(A,B) 0
16441#endif
16442
16443#if SQLITE_MAX_ATTACHED>30
16444SQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);
16445#endif
16446SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
16447SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
16448SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
16449#ifndef SQLITE_OMIT_AUTOINCREMENT
16450SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
16451SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
16452#else
16453# define sqlite3AutoincrementBegin(X)
16454# define sqlite3AutoincrementEnd(X)
16455#endif
16456SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
16457SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
16458SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
16459SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
16460SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
16461SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
16462SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
16463                                      Token*, Select*, Expr*, IdList*);
16464SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
16465SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
16466SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
16467SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
16468SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
16469SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
16470SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
16471SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
16472SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
16473                          Expr*, int, int, u8);
16474SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
16475SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
16476SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
16477                         Expr*,ExprList*,u32,Expr*,Expr*);
16478SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
16479SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
16480SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
16481SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
16482#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
16483SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
16484#endif
16485SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
16486SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
16487SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
16488SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
16489SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
16490SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
16491SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
16492SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*);
16493SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
16494SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
16495SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
16496SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
16497#define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */
16498#define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */
16499#define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */
16500SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
16501SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
16502SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
16503SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
16504SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
16505SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
16506SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
16507SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
16508SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
16509SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
16510SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
16511SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
16512SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
16513SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
16514SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
16515SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
16516SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
16517SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
16518SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
16519#define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
16520#define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
16521#define SQLITE_ECEL_REF      0x04  /* Use ExprList.u.x.iOrderByCol */
16522#define SQLITE_ECEL_OMITREF  0x08  /* Omit if ExprList.u.x.iOrderByCol */
16523SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
16524SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
16525SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
16526SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
16527#define LOCATE_VIEW    0x01
16528#define LOCATE_NOERR   0x02
16529SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
16530SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
16531SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
16532SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
16533SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
16534SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*);
16535SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int);
16536SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
16537SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
16538SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
16539SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
16540SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
16541SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
16542SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
16543SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
16544SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
16545SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
16546#ifndef SQLITE_UNTESTABLE
16547SQLITE_PRIVATE void sqlite3PrngSaveState(void);
16548SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
16549#endif
16550SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
16551SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
16552SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
16553SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
16554SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
16555SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
16556SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
16557SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
16558SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
16559SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
16560SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
16561SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
16562SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
16563#ifdef SQLITE_ENABLE_CURSOR_HINTS
16564SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
16565#endif
16566SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
16567SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
16568SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
16569SQLITE_PRIVATE int sqlite3IsRowid(const char*);
16570SQLITE_PRIVATE void sqlite3GenerateRowDelete(
16571    Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
16572SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
16573SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
16574SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
16575SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
16576                                     u8,u8,int,int*,int*);
16577#ifdef SQLITE_ENABLE_NULL_TRIM
16578SQLITE_PRIVATE   void sqlite3SetMakeRecordP5(Vdbe*,Table*);
16579#else
16580# define sqlite3SetMakeRecordP5(A,B)
16581#endif
16582SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
16583SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
16584SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
16585SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
16586SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
16587SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
16588SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
16589SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
16590SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
16591SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
16592SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
16593SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
16594SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
16595#if SELECTTRACE_ENABLED
16596SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
16597#else
16598# define sqlite3SelectSetName(A,B)
16599#endif
16600SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
16601SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
16602SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
16603SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
16604SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
16605SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
16606SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
16607SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
16608
16609#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
16610SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
16611#endif
16612
16613#ifndef SQLITE_OMIT_TRIGGER
16614SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
16615                           Expr*,int, int);
16616SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
16617SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
16618SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
16619SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
16620SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
16621SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
16622                            int, int, int);
16623SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
16624  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
16625SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
16626SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
16627SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
16628                                        Select*,u8);
16629SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
16630SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
16631SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
16632SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
16633SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
16634# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
16635# define sqlite3IsToplevel(p) ((p)->pToplevel==0)
16636#else
16637# define sqlite3TriggersExist(B,C,D,E,F) 0
16638# define sqlite3DeleteTrigger(A,B)
16639# define sqlite3DropTriggerPtr(A,B)
16640# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
16641# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
16642# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
16643# define sqlite3TriggerList(X, Y) 0
16644# define sqlite3ParseToplevel(p) p
16645# define sqlite3IsToplevel(p) 1
16646# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
16647#endif
16648
16649SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
16650SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
16651SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
16652#ifndef SQLITE_OMIT_AUTHORIZATION
16653SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
16654SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
16655SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
16656SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
16657SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
16658#else
16659# define sqlite3AuthRead(a,b,c,d)
16660# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
16661# define sqlite3AuthContextPush(a,b,c)
16662# define sqlite3AuthContextPop(a)  ((void)(a))
16663#endif
16664SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
16665SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
16666SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
16667SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
16668SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
16669SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
16670SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
16671SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
16672SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
16673SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
16674SQLITE_PRIVATE int sqlite3Atoi(const char*);
16675SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
16676SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
16677SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
16678SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
16679SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
16680#ifndef SQLITE_OMIT_VIRTUALTABLE
16681SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
16682#endif
16683#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
16684    defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
16685    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
16686SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
16687#endif
16688SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
16689SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
16690SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
16691
16692/*
16693** Routines to read and write variable-length integers.  These used to
16694** be defined locally, but now we use the varint routines in the util.c
16695** file.
16696*/
16697SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
16698SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
16699SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
16700SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
16701
16702/*
16703** The common case is for a varint to be a single byte.  They following
16704** macros handle the common case without a procedure call, but then call
16705** the procedure for larger varints.
16706*/
16707#define getVarint32(A,B)  \
16708  (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
16709#define putVarint32(A,B)  \
16710  (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
16711  sqlite3PutVarint((A),(B)))
16712#define getVarint    sqlite3GetVarint
16713#define putVarint    sqlite3PutVarint
16714
16715
16716SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
16717SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
16718SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
16719SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
16720SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
16721SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
16722SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
16723SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
16724SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
16725SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
16726SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
16727SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
16728SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
16729SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
16730
16731#if defined(SQLITE_NEED_ERR_NAME)
16732SQLITE_PRIVATE const char *sqlite3ErrName(int);
16733#endif
16734
16735SQLITE_PRIVATE const char *sqlite3ErrStr(int);
16736SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
16737SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
16738SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
16739SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
16740SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
16741SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
16742SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
16743SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
16744SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
16745SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
16746SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
16747SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
16748SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
16749SQLITE_PRIVATE int sqlite3AbsInt32(int);
16750#ifdef SQLITE_ENABLE_8_3_NAMES
16751SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
16752#else
16753# define sqlite3FileSuffix3(X,Y)
16754#endif
16755SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
16756
16757SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
16758SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
16759SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
16760                        void(*)(void*));
16761SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
16762SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
16763SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
16764SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
16765SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
16766SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
16767#ifndef SQLITE_AMALGAMATION
16768SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
16769SQLITE_PRIVATE const char sqlite3StrBINARY[];
16770SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
16771SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
16772SQLITE_PRIVATE const Token sqlite3IntTokens[];
16773SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
16774SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
16775#ifndef SQLITE_OMIT_WSD
16776SQLITE_PRIVATE int sqlite3PendingByte;
16777#endif
16778#endif
16779SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
16780SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
16781SQLITE_PRIVATE void sqlite3AlterFunctions(void);
16782SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
16783SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
16784SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
16785SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
16786SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int);
16787SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
16788SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
16789SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
16790SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
16791SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
16792SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
16793SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
16794SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
16795SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
16796SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
16797SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
16798SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
16799SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
16800SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
16801SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
16802SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
16803SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
16804SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
16805SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
16806SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
16807SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
16808SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
16809SQLITE_PRIVATE void sqlite3SchemaClear(void *);
16810SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
16811SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
16812SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
16813SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
16814SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
16815SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
16816#ifdef SQLITE_DEBUG
16817SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
16818#endif
16819SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
16820  void (*)(sqlite3_context*,int,sqlite3_value **),
16821  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
16822  FuncDestructor *pDestructor
16823);
16824SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
16825SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
16826SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
16827SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
16828
16829SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
16830SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
16831SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
16832SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
16833SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
16834SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
16835SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
16836SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
16837
16838SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
16839SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
16840
16841#ifndef SQLITE_OMIT_SUBQUERY
16842SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
16843#else
16844# define sqlite3ExprCheckIN(x,y) SQLITE_OK
16845#endif
16846
16847#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
16848SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
16849SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
16850    Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
16851SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
16852SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
16853SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
16854SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
16855#endif
16856
16857/*
16858** The interface to the LEMON-generated parser
16859*/
16860#ifndef SQLITE_AMALGAMATION
16861SQLITE_PRIVATE   void *sqlite3ParserAlloc(void*(*)(u64));
16862SQLITE_PRIVATE   void sqlite3ParserFree(void*, void(*)(void*));
16863#endif
16864SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
16865#ifdef YYTRACKMAXSTACKDEPTH
16866SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
16867#endif
16868
16869SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
16870#ifndef SQLITE_OMIT_LOAD_EXTENSION
16871SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
16872#else
16873# define sqlite3CloseExtensions(X)
16874#endif
16875
16876#ifndef SQLITE_OMIT_SHARED_CACHE
16877SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
16878#else
16879  #define sqlite3TableLock(v,w,x,y,z)
16880#endif
16881
16882#ifdef SQLITE_TEST
16883SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
16884#endif
16885
16886#ifdef SQLITE_OMIT_VIRTUALTABLE
16887#  define sqlite3VtabClear(Y)
16888#  define sqlite3VtabSync(X,Y) SQLITE_OK
16889#  define sqlite3VtabRollback(X)
16890#  define sqlite3VtabCommit(X)
16891#  define sqlite3VtabInSync(db) 0
16892#  define sqlite3VtabLock(X)
16893#  define sqlite3VtabUnlock(X)
16894#  define sqlite3VtabUnlockList(X)
16895#  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
16896#  define sqlite3GetVTable(X,Y)  ((VTable*)0)
16897#else
16898SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
16899SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
16900SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
16901SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
16902SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
16903SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
16904SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
16905SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
16906SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
16907SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
16908SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
16909SQLITE_PRIVATE    Module *sqlite3VtabCreateModule(
16910     sqlite3*,
16911     const char*,
16912     const sqlite3_module*,
16913     void*,
16914     void(*)(void*)
16915   );
16916#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
16917#endif
16918SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
16919SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
16920SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
16921SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
16922SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
16923SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
16924SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
16925SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
16926SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
16927SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
16928SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
16929SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
16930SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
16931SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
16932SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
16933SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
16934SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
16935SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
16936SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
16937SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
16938SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
16939SQLITE_PRIVATE const char *sqlite3JournalModename(int);
16940#ifndef SQLITE_OMIT_WAL
16941SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
16942SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
16943#endif
16944#ifndef SQLITE_OMIT_CTE
16945SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
16946SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
16947SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
16948#else
16949#define sqlite3WithPush(x,y,z)
16950#define sqlite3WithDelete(x,y)
16951#endif
16952
16953/* Declarations for functions in fkey.c. All of these are replaced by
16954** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
16955** key functionality is available. If OMIT_TRIGGER is defined but
16956** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
16957** this case foreign keys are parsed, but no other functionality is
16958** provided (enforcement of FK constraints requires the triggers sub-system).
16959*/
16960#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
16961SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
16962SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
16963SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
16964SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
16965SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
16966SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
16967#else
16968  #define sqlite3FkActions(a,b,c,d,e,f)
16969  #define sqlite3FkCheck(a,b,c,d,e,f)
16970  #define sqlite3FkDropTable(a,b,c)
16971  #define sqlite3FkOldmask(a,b)         0
16972  #define sqlite3FkRequired(a,b,c,d)    0
16973  #define sqlite3FkReferences(a)        0
16974#endif
16975#ifndef SQLITE_OMIT_FOREIGN_KEY
16976SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
16977SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
16978#else
16979  #define sqlite3FkDelete(a,b)
16980  #define sqlite3FkLocateIndex(a,b,c,d,e)
16981#endif
16982
16983
16984/*
16985** Available fault injectors.  Should be numbered beginning with 0.
16986*/
16987#define SQLITE_FAULTINJECTOR_MALLOC     0
16988#define SQLITE_FAULTINJECTOR_COUNT      1
16989
16990/*
16991** The interface to the code in fault.c used for identifying "benign"
16992** malloc failures. This is only present if SQLITE_UNTESTABLE
16993** is not defined.
16994*/
16995#ifndef SQLITE_UNTESTABLE
16996SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
16997SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
16998#else
16999  #define sqlite3BeginBenignMalloc()
17000  #define sqlite3EndBenignMalloc()
17001#endif
17002
17003/*
17004** Allowed return values from sqlite3FindInIndex()
17005*/
17006#define IN_INDEX_ROWID        1   /* Search the rowid of the table */
17007#define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
17008#define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
17009#define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
17010#define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
17011/*
17012** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
17013*/
17014#define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
17015#define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
17016#define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
17017SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*);
17018
17019SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
17020SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
17021#ifdef SQLITE_ENABLE_ATOMIC_WRITE
17022SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
17023#endif
17024
17025SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
17026SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
17027
17028SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
17029#if SQLITE_MAX_EXPR_DEPTH>0
17030SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
17031SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
17032#else
17033  #define sqlite3SelectExprHeight(x) 0
17034  #define sqlite3ExprCheckHeight(x,y)
17035#endif
17036
17037SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
17038SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
17039
17040#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
17041SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
17042SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
17043SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
17044#else
17045  #define sqlite3ConnectionBlocked(x,y)
17046  #define sqlite3ConnectionUnlocked(x)
17047  #define sqlite3ConnectionClosed(x)
17048#endif
17049
17050#ifdef SQLITE_DEBUG
17051SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
17052#endif
17053
17054/*
17055** If the SQLITE_ENABLE IOTRACE exists then the global variable
17056** sqlite3IoTrace is a pointer to a printf-like routine used to
17057** print I/O tracing messages.
17058*/
17059#ifdef SQLITE_ENABLE_IOTRACE
17060# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
17061SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
17062SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
17063#else
17064# define IOTRACE(A)
17065# define sqlite3VdbeIOTraceSql(X)
17066#endif
17067
17068/*
17069** These routines are available for the mem2.c debugging memory allocator
17070** only.  They are used to verify that different "types" of memory
17071** allocations are properly tracked by the system.
17072**
17073** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
17074** the MEMTYPE_* macros defined below.  The type must be a bitmask with
17075** a single bit set.
17076**
17077** sqlite3MemdebugHasType() returns true if any of the bits in its second
17078** argument match the type set by the previous sqlite3MemdebugSetType().
17079** sqlite3MemdebugHasType() is intended for use inside assert() statements.
17080**
17081** sqlite3MemdebugNoType() returns true if none of the bits in its second
17082** argument match the type set by the previous sqlite3MemdebugSetType().
17083**
17084** Perhaps the most important point is the difference between MEMTYPE_HEAP
17085** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
17086** it might have been allocated by lookaside, except the allocation was
17087** too large or lookaside was already full.  It is important to verify
17088** that allocations that might have been satisfied by lookaside are not
17089** passed back to non-lookaside free() routines.  Asserts such as the
17090** example above are placed on the non-lookaside free() routines to verify
17091** this constraint.
17092**
17093** All of this is no-op for a production build.  It only comes into
17094** play when the SQLITE_MEMDEBUG compile-time option is used.
17095*/
17096#ifdef SQLITE_MEMDEBUG
17097SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
17098SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
17099SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
17100#else
17101# define sqlite3MemdebugSetType(X,Y)  /* no-op */
17102# define sqlite3MemdebugHasType(X,Y)  1
17103# define sqlite3MemdebugNoType(X,Y)   1
17104#endif
17105#define MEMTYPE_HEAP       0x01  /* General heap allocations */
17106#define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */
17107#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
17108#define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
17109
17110/*
17111** Threading interface
17112*/
17113#if SQLITE_MAX_WORKER_THREADS>0
17114SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
17115SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
17116#endif
17117
17118#if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
17119SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
17120#endif
17121
17122SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
17123SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
17124SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
17125SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
17126SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
17127
17128#endif /* SQLITEINT_H */
17129
17130/************** End of sqliteInt.h *******************************************/
17131/************** Begin file global.c ******************************************/
17132/*
17133** 2008 June 13
17134**
17135** The author disclaims copyright to this source code.  In place of
17136** a legal notice, here is a blessing:
17137**
17138**    May you do good and not evil.
17139**    May you find forgiveness for yourself and forgive others.
17140**    May you share freely, never taking more than you give.
17141**
17142*************************************************************************
17143**
17144** This file contains definitions of global variables and constants.
17145*/
17146/* #include "sqliteInt.h" */
17147
17148/* An array to map all upper-case characters into their corresponding
17149** lower-case character.
17150**
17151** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
17152** handle case conversions for the UTF character set since the tables
17153** involved are nearly as big or bigger than SQLite itself.
17154*/
17155SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
17156#ifdef SQLITE_ASCII
17157      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
17158     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
17159     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
17160     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
17161    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
17162    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
17163    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
17164    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
17165    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
17166    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
17167    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
17168    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
17169    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
17170    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
17171    252,253,254,255
17172#endif
17173#ifdef SQLITE_EBCDIC
17174      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
17175     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
17176     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
17177     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
17178     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
17179     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
17180     96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
17181    112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
17182    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
17183    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
17184    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
17185    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
17186    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
17187    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
17188    224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
17189    240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
17190#endif
17191};
17192
17193/*
17194** The following 256 byte lookup table is used to support SQLites built-in
17195** equivalents to the following standard library functions:
17196**
17197**   isspace()                        0x01
17198**   isalpha()                        0x02
17199**   isdigit()                        0x04
17200**   isalnum()                        0x06
17201**   isxdigit()                       0x08
17202**   toupper()                        0x20
17203**   SQLite identifier character      0x40
17204**   Quote character                  0x80
17205**
17206** Bit 0x20 is set if the mapped character requires translation to upper
17207** case. i.e. if the character is a lower-case ASCII character.
17208** If x is a lower-case ASCII character, then its upper-case equivalent
17209** is (x - 0x20). Therefore toupper() can be implemented as:
17210**
17211**   (x & ~(map[x]&0x20))
17212**
17213** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
17214** array. tolower() is used more often than toupper() by SQLite.
17215**
17216** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
17217** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
17218** non-ASCII UTF character. Hence the test for whether or not a character is
17219** part of an identifier is 0x46.
17220*/
17221#ifdef SQLITE_ASCII
17222SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
17223  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
17224  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
17225  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
17226  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
17227  0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80,  /* 20..27     !"#$%&' */
17228  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
17229  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
17230  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
17231
17232  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
17233  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
17234  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
17235  0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
17236  0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
17237  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
17238  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
17239  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
17240
17241  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
17242  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
17243  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
17244  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
17245  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
17246  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
17247  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
17248  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
17249
17250  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
17251  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
17252  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
17253  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
17254  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
17255  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
17256  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
17257  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
17258};
17259#endif
17260
17261/* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
17262** compatibility for legacy applications, the URI filename capability is
17263** disabled by default.
17264**
17265** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
17266** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
17267**
17268** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
17269** disabled. The default value may be changed by compiling with the
17270** SQLITE_USE_URI symbol defined.
17271*/
17272#ifndef SQLITE_USE_URI
17273# define  SQLITE_USE_URI 0
17274#endif
17275
17276/* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
17277** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
17278** that compile-time option is omitted.
17279*/
17280#ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
17281# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
17282#endif
17283
17284/* The minimum PMA size is set to this value multiplied by the database
17285** page size in bytes.
17286*/
17287#ifndef SQLITE_SORTER_PMASZ
17288# define SQLITE_SORTER_PMASZ 250
17289#endif
17290
17291/* Statement journals spill to disk when their size exceeds the following
17292** threshold (in bytes). 0 means that statement journals are created and
17293** written to disk immediately (the default behavior for SQLite versions
17294** before 3.12.0).  -1 means always keep the entire statement journal in
17295** memory.  (The statement journal is also always held entirely in memory
17296** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
17297** setting.)
17298*/
17299#ifndef SQLITE_STMTJRNL_SPILL
17300# define SQLITE_STMTJRNL_SPILL (64*1024)
17301#endif
17302
17303/*
17304** The default lookaside-configuration, the format "SZ,N".  SZ is the
17305** number of bytes in each lookaside slot (should be a multiple of 8)
17306** and N is the number of slots.  The lookaside-configuration can be
17307** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
17308** or at run-time for an individual database connection using
17309** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
17310*/
17311#ifndef SQLITE_DEFAULT_LOOKASIDE
17312# define SQLITE_DEFAULT_LOOKASIDE 1200,100
17313#endif
17314
17315
17316/*
17317** The following singleton contains the global configuration for
17318** the SQLite library.
17319*/
17320SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
17321   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
17322   1,                         /* bCoreMutex */
17323   SQLITE_THREADSAFE==1,      /* bFullMutex */
17324   SQLITE_USE_URI,            /* bOpenUri */
17325   SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
17326   0x7ffffffe,                /* mxStrlen */
17327   0,                         /* neverCorrupt */
17328   SQLITE_DEFAULT_LOOKASIDE,  /* szLookaside, nLookaside */
17329   SQLITE_STMTJRNL_SPILL,     /* nStmtSpill */
17330   {0,0,0,0,0,0,0,0},         /* m */
17331   {0,0,0,0,0,0,0,0,0},       /* mutex */
17332   {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
17333   (void*)0,                  /* pHeap */
17334   0,                         /* nHeap */
17335   0, 0,                      /* mnHeap, mxHeap */
17336   SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
17337   SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
17338   (void*)0,                  /* pScratch */
17339   0,                         /* szScratch */
17340   0,                         /* nScratch */
17341   (void*)0,                  /* pPage */
17342   0,                         /* szPage */
17343   SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
17344   0,                         /* mxParserStack */
17345   0,                         /* sharedCacheEnabled */
17346   SQLITE_SORTER_PMASZ,       /* szPma */
17347   /* All the rest should always be initialized to zero */
17348   0,                         /* isInit */
17349   0,                         /* inProgress */
17350   0,                         /* isMutexInit */
17351   0,                         /* isMallocInit */
17352   0,                         /* isPCacheInit */
17353   0,                         /* nRefInitMutex */
17354   0,                         /* pInitMutex */
17355   0,                         /* xLog */
17356   0,                         /* pLogArg */
17357#ifdef SQLITE_ENABLE_SQLLOG
17358   0,                         /* xSqllog */
17359   0,                         /* pSqllogArg */
17360#endif
17361#ifdef SQLITE_VDBE_COVERAGE
17362   0,                         /* xVdbeBranch */
17363   0,                         /* pVbeBranchArg */
17364#endif
17365#ifndef SQLITE_UNTESTABLE
17366   0,                         /* xTestCallback */
17367#endif
17368   0,                         /* bLocaltimeFault */
17369   0x7ffffffe                 /* iOnceResetThreshold */
17370};
17371
17372/*
17373** Hash table for global functions - functions common to all
17374** database connections.  After initialization, this table is
17375** read-only.
17376*/
17377SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
17378
17379/*
17380** Constant tokens for values 0 and 1.
17381*/
17382SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
17383   { "0", 1 },
17384   { "1", 1 }
17385};
17386
17387
17388/*
17389** The value of the "pending" byte must be 0x40000000 (1 byte past the
17390** 1-gibabyte boundary) in a compatible database.  SQLite never uses
17391** the database page that contains the pending byte.  It never attempts
17392** to read or write that page.  The pending byte page is set aside
17393** for use by the VFS layers as space for managing file locks.
17394**
17395** During testing, it is often desirable to move the pending byte to
17396** a different position in the file.  This allows code that has to
17397** deal with the pending byte to run on files that are much smaller
17398** than 1 GiB.  The sqlite3_test_control() interface can be used to
17399** move the pending byte.
17400**
17401** IMPORTANT:  Changing the pending byte to any value other than
17402** 0x40000000 results in an incompatible database file format!
17403** Changing the pending byte during operation will result in undefined
17404** and incorrect behavior.
17405*/
17406#ifndef SQLITE_OMIT_WSD
17407SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
17408#endif
17409
17410/* #include "opcodes.h" */
17411/*
17412** Properties of opcodes.  The OPFLG_INITIALIZER macro is
17413** created by mkopcodeh.awk during compilation.  Data is obtained
17414** from the comments following the "case OP_xxxx:" statements in
17415** the vdbe.c file.
17416*/
17417SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
17418
17419/*
17420** Name of the default collating sequence
17421*/
17422SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
17423
17424/************** End of global.c **********************************************/
17425/************** Begin file ctime.c *******************************************/
17426/*
17427** 2010 February 23
17428**
17429** The author disclaims copyright to this source code.  In place of
17430** a legal notice, here is a blessing:
17431**
17432**    May you do good and not evil.
17433**    May you find forgiveness for yourself and forgive others.
17434**    May you share freely, never taking more than you give.
17435**
17436*************************************************************************
17437**
17438** This file implements routines used to report what compile-time options
17439** SQLite was built with.
17440*/
17441
17442#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
17443
17444/* #include "sqliteInt.h" */
17445
17446/*
17447** An array of names of all compile-time options.  This array should
17448** be sorted A-Z.
17449**
17450** This array looks large, but in a typical installation actually uses
17451** only a handful of compile-time options, so most times this array is usually
17452** rather short and uses little memory space.
17453*/
17454static const char * const azCompileOpt[] = {
17455
17456/* These macros are provided to "stringify" the value of the define
17457** for those options in which the value is meaningful. */
17458#define CTIMEOPT_VAL_(opt) #opt
17459#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
17460
17461#if SQLITE_32BIT_ROWID
17462  "32BIT_ROWID",
17463#endif
17464#if SQLITE_4_BYTE_ALIGNED_MALLOC
17465  "4_BYTE_ALIGNED_MALLOC",
17466#endif
17467#if SQLITE_CASE_SENSITIVE_LIKE
17468  "CASE_SENSITIVE_LIKE",
17469#endif
17470#if SQLITE_CHECK_PAGES
17471  "CHECK_PAGES",
17472#endif
17473#if defined(__clang__) && defined(__clang_major__)
17474  "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
17475                    CTIMEOPT_VAL(__clang_minor__) "."
17476                    CTIMEOPT_VAL(__clang_patchlevel__),
17477#elif defined(_MSC_VER)
17478  "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
17479#elif defined(__GNUC__) && defined(__VERSION__)
17480  "COMPILER=gcc-" __VERSION__,
17481#endif
17482#if SQLITE_COVERAGE_TEST
17483  "COVERAGE_TEST",
17484#endif
17485#ifdef SQLITE_DEBUG
17486  "DEBUG",
17487#endif
17488#if SQLITE_DEFAULT_LOCKING_MODE
17489  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
17490#endif
17491#if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
17492  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
17493#endif
17494#if SQLITE_DEFAULT_SYNCHRONOUS
17495  "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
17496#endif
17497#if SQLITE_DEFAULT_WAL_SYNCHRONOUS
17498  "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
17499#endif
17500#if SQLITE_DIRECT_OVERFLOW_READ
17501  "DIRECT_OVERFLOW_READ",
17502#endif
17503#if SQLITE_DISABLE_DIRSYNC
17504  "DISABLE_DIRSYNC",
17505#endif
17506#if SQLITE_DISABLE_LFS
17507  "DISABLE_LFS",
17508#endif
17509#if SQLITE_ENABLE_8_3_NAMES
17510  "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
17511#endif
17512#if SQLITE_ENABLE_API_ARMOR
17513  "ENABLE_API_ARMOR",
17514#endif
17515#if SQLITE_ENABLE_ATOMIC_WRITE
17516  "ENABLE_ATOMIC_WRITE",
17517#endif
17518#if SQLITE_ENABLE_CEROD
17519  "ENABLE_CEROD",
17520#endif
17521#if SQLITE_ENABLE_COLUMN_METADATA
17522  "ENABLE_COLUMN_METADATA",
17523#endif
17524#if SQLITE_ENABLE_DBSTAT_VTAB
17525  "ENABLE_DBSTAT_VTAB",
17526#endif
17527#if SQLITE_ENABLE_EXPENSIVE_ASSERT
17528  "ENABLE_EXPENSIVE_ASSERT",
17529#endif
17530#if SQLITE_ENABLE_FTS1
17531  "ENABLE_FTS1",
17532#endif
17533#if SQLITE_ENABLE_FTS2
17534  "ENABLE_FTS2",
17535#endif
17536#if SQLITE_ENABLE_FTS3
17537  "ENABLE_FTS3",
17538#endif
17539#if SQLITE_ENABLE_FTS3_PARENTHESIS
17540  "ENABLE_FTS3_PARENTHESIS",
17541#endif
17542#if SQLITE_ENABLE_FTS4
17543  "ENABLE_FTS4",
17544#endif
17545#if SQLITE_ENABLE_FTS5
17546  "ENABLE_FTS5",
17547#endif
17548#if SQLITE_ENABLE_ICU
17549  "ENABLE_ICU",
17550#endif
17551#if SQLITE_ENABLE_IOTRACE
17552  "ENABLE_IOTRACE",
17553#endif
17554#if SQLITE_ENABLE_JSON1
17555  "ENABLE_JSON1",
17556#endif
17557#if SQLITE_ENABLE_LOAD_EXTENSION
17558  "ENABLE_LOAD_EXTENSION",
17559#endif
17560#if SQLITE_ENABLE_LOCKING_STYLE
17561  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
17562#endif
17563#if SQLITE_ENABLE_MEMORY_MANAGEMENT
17564  "ENABLE_MEMORY_MANAGEMENT",
17565#endif
17566#if SQLITE_ENABLE_MEMSYS3
17567  "ENABLE_MEMSYS3",
17568#endif
17569#if SQLITE_ENABLE_MEMSYS5
17570  "ENABLE_MEMSYS5",
17571#endif
17572#if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
17573  "ENABLE_OVERSIZE_CELL_CHECK",
17574#endif
17575#if SQLITE_ENABLE_RTREE
17576  "ENABLE_RTREE",
17577#endif
17578#if defined(SQLITE_ENABLE_STAT4)
17579  "ENABLE_STAT4",
17580#elif defined(SQLITE_ENABLE_STAT3)
17581  "ENABLE_STAT3",
17582#endif
17583#if SQLITE_ENABLE_UNLOCK_NOTIFY
17584  "ENABLE_UNLOCK_NOTIFY",
17585#endif
17586#if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
17587  "ENABLE_UPDATE_DELETE_LIMIT",
17588#endif
17589#if defined(SQLITE_ENABLE_URI_00_ERROR)
17590  "ENABLE_URI_00_ERROR",
17591#endif
17592#if SQLITE_HAS_CODEC
17593  "HAS_CODEC",
17594#endif
17595#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
17596  "HAVE_ISNAN",
17597#endif
17598#if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17599  "HOMEGROWN_RECURSIVE_MUTEX",
17600#endif
17601#if SQLITE_IGNORE_AFP_LOCK_ERRORS
17602  "IGNORE_AFP_LOCK_ERRORS",
17603#endif
17604#if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
17605  "IGNORE_FLOCK_LOCK_ERRORS",
17606#endif
17607#ifdef SQLITE_INT64_TYPE
17608  "INT64_TYPE",
17609#endif
17610#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
17611  "LIKE_DOESNT_MATCH_BLOBS",
17612#endif
17613#if SQLITE_LOCK_TRACE
17614  "LOCK_TRACE",
17615#endif
17616#if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
17617  "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
17618#endif
17619#ifdef SQLITE_MAX_SCHEMA_RETRY
17620  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
17621#endif
17622#if SQLITE_MEMDEBUG
17623  "MEMDEBUG",
17624#endif
17625#if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
17626  "MIXED_ENDIAN_64BIT_FLOAT",
17627#endif
17628#if SQLITE_NO_SYNC
17629  "NO_SYNC",
17630#endif
17631#if SQLITE_OMIT_ALTERTABLE
17632  "OMIT_ALTERTABLE",
17633#endif
17634#if SQLITE_OMIT_ANALYZE
17635  "OMIT_ANALYZE",
17636#endif
17637#if SQLITE_OMIT_ATTACH
17638  "OMIT_ATTACH",
17639#endif
17640#if SQLITE_OMIT_AUTHORIZATION
17641  "OMIT_AUTHORIZATION",
17642#endif
17643#if SQLITE_OMIT_AUTOINCREMENT
17644  "OMIT_AUTOINCREMENT",
17645#endif
17646#if SQLITE_OMIT_AUTOINIT
17647  "OMIT_AUTOINIT",
17648#endif
17649#if SQLITE_OMIT_AUTOMATIC_INDEX
17650  "OMIT_AUTOMATIC_INDEX",
17651#endif
17652#if SQLITE_OMIT_AUTORESET
17653  "OMIT_AUTORESET",
17654#endif
17655#if SQLITE_OMIT_AUTOVACUUM
17656  "OMIT_AUTOVACUUM",
17657#endif
17658#if SQLITE_OMIT_BETWEEN_OPTIMIZATION
17659  "OMIT_BETWEEN_OPTIMIZATION",
17660#endif
17661#if SQLITE_OMIT_BLOB_LITERAL
17662  "OMIT_BLOB_LITERAL",
17663#endif
17664#if SQLITE_OMIT_BTREECOUNT
17665  "OMIT_BTREECOUNT",
17666#endif
17667#if SQLITE_OMIT_CAST
17668  "OMIT_CAST",
17669#endif
17670#if SQLITE_OMIT_CHECK
17671  "OMIT_CHECK",
17672#endif
17673#if SQLITE_OMIT_COMPLETE
17674  "OMIT_COMPLETE",
17675#endif
17676#if SQLITE_OMIT_COMPOUND_SELECT
17677  "OMIT_COMPOUND_SELECT",
17678#endif
17679#if SQLITE_OMIT_CTE
17680  "OMIT_CTE",
17681#endif
17682#if SQLITE_OMIT_DATETIME_FUNCS
17683  "OMIT_DATETIME_FUNCS",
17684#endif
17685#if SQLITE_OMIT_DECLTYPE
17686  "OMIT_DECLTYPE",
17687#endif
17688#if SQLITE_OMIT_DEPRECATED
17689  "OMIT_DEPRECATED",
17690#endif
17691#if SQLITE_OMIT_DISKIO
17692  "OMIT_DISKIO",
17693#endif
17694#if SQLITE_OMIT_EXPLAIN
17695  "OMIT_EXPLAIN",
17696#endif
17697#if SQLITE_OMIT_FLAG_PRAGMAS
17698  "OMIT_FLAG_PRAGMAS",
17699#endif
17700#if SQLITE_OMIT_FLOATING_POINT
17701  "OMIT_FLOATING_POINT",
17702#endif
17703#if SQLITE_OMIT_FOREIGN_KEY
17704  "OMIT_FOREIGN_KEY",
17705#endif
17706#if SQLITE_OMIT_GET_TABLE
17707  "OMIT_GET_TABLE",
17708#endif
17709#if SQLITE_OMIT_INCRBLOB
17710  "OMIT_INCRBLOB",
17711#endif
17712#if SQLITE_OMIT_INTEGRITY_CHECK
17713  "OMIT_INTEGRITY_CHECK",
17714#endif
17715#if SQLITE_OMIT_LIKE_OPTIMIZATION
17716  "OMIT_LIKE_OPTIMIZATION",
17717#endif
17718#if SQLITE_OMIT_LOAD_EXTENSION
17719  "OMIT_LOAD_EXTENSION",
17720#endif
17721#if SQLITE_OMIT_LOCALTIME
17722  "OMIT_LOCALTIME",
17723#endif
17724#if SQLITE_OMIT_LOOKASIDE
17725  "OMIT_LOOKASIDE",
17726#endif
17727#if SQLITE_OMIT_MEMORYDB
17728  "OMIT_MEMORYDB",
17729#endif
17730#if SQLITE_OMIT_OR_OPTIMIZATION
17731  "OMIT_OR_OPTIMIZATION",
17732#endif
17733#if SQLITE_OMIT_PAGER_PRAGMAS
17734  "OMIT_PAGER_PRAGMAS",
17735#endif
17736#if SQLITE_OMIT_PRAGMA
17737  "OMIT_PRAGMA",
17738#endif
17739#if SQLITE_OMIT_PROGRESS_CALLBACK
17740  "OMIT_PROGRESS_CALLBACK",
17741#endif
17742#if SQLITE_OMIT_QUICKBALANCE
17743  "OMIT_QUICKBALANCE",
17744#endif
17745#if SQLITE_OMIT_REINDEX
17746  "OMIT_REINDEX",
17747#endif
17748#if SQLITE_OMIT_SCHEMA_PRAGMAS
17749  "OMIT_SCHEMA_PRAGMAS",
17750#endif
17751#if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
17752  "OMIT_SCHEMA_VERSION_PRAGMAS",
17753#endif
17754#if SQLITE_OMIT_SHARED_CACHE
17755  "OMIT_SHARED_CACHE",
17756#endif
17757#if SQLITE_OMIT_SUBQUERY
17758  "OMIT_SUBQUERY",
17759#endif
17760#if SQLITE_OMIT_TCL_VARIABLE
17761  "OMIT_TCL_VARIABLE",
17762#endif
17763#if SQLITE_OMIT_TEMPDB
17764  "OMIT_TEMPDB",
17765#endif
17766#if SQLITE_OMIT_TRACE
17767  "OMIT_TRACE",
17768#endif
17769#if SQLITE_OMIT_TRIGGER
17770  "OMIT_TRIGGER",
17771#endif
17772#if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
17773  "OMIT_TRUNCATE_OPTIMIZATION",
17774#endif
17775#if SQLITE_OMIT_UTF16
17776  "OMIT_UTF16",
17777#endif
17778#if SQLITE_OMIT_VACUUM
17779  "OMIT_VACUUM",
17780#endif
17781#if SQLITE_OMIT_VIEW
17782  "OMIT_VIEW",
17783#endif
17784#if SQLITE_OMIT_VIRTUALTABLE
17785  "OMIT_VIRTUALTABLE",
17786#endif
17787#if SQLITE_OMIT_WAL
17788  "OMIT_WAL",
17789#endif
17790#if SQLITE_OMIT_WSD
17791  "OMIT_WSD",
17792#endif
17793#if SQLITE_OMIT_XFER_OPT
17794  "OMIT_XFER_OPT",
17795#endif
17796#if SQLITE_PERFORMANCE_TRACE
17797  "PERFORMANCE_TRACE",
17798#endif
17799#if SQLITE_PROXY_DEBUG
17800  "PROXY_DEBUG",
17801#endif
17802#if SQLITE_RTREE_INT_ONLY
17803  "RTREE_INT_ONLY",
17804#endif
17805#if SQLITE_SECURE_DELETE
17806  "SECURE_DELETE",
17807#endif
17808#if SQLITE_SMALL_STACK
17809  "SMALL_STACK",
17810#endif
17811#if SQLITE_SOUNDEX
17812  "SOUNDEX",
17813#endif
17814#if SQLITE_SYSTEM_MALLOC
17815  "SYSTEM_MALLOC",
17816#endif
17817#if SQLITE_TCL
17818  "TCL",
17819#endif
17820#if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
17821  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
17822#endif
17823#if SQLITE_TEST
17824  "TEST",
17825#endif
17826#if defined(SQLITE_THREADSAFE)
17827  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
17828#endif
17829#if SQLITE_UNTESTABLE
17830  "UNTESTABLE"
17831#endif
17832#if SQLITE_USE_ALLOCA
17833  "USE_ALLOCA",
17834#endif
17835#if SQLITE_USER_AUTHENTICATION
17836  "USER_AUTHENTICATION",
17837#endif
17838#if SQLITE_WIN32_MALLOC
17839  "WIN32_MALLOC",
17840#endif
17841#if SQLITE_ZERO_MALLOC
17842  "ZERO_MALLOC"
17843#endif
17844};
17845
17846/*
17847** Given the name of a compile-time option, return true if that option
17848** was used and false if not.
17849**
17850** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
17851** is not required for a match.
17852*/
17853SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
17854  int i, n;
17855
17856#if SQLITE_ENABLE_API_ARMOR
17857  if( zOptName==0 ){
17858    (void)SQLITE_MISUSE_BKPT;
17859    return 0;
17860  }
17861#endif
17862  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
17863  n = sqlite3Strlen30(zOptName);
17864
17865  /* Since ArraySize(azCompileOpt) is normally in single digits, a
17866  ** linear search is adequate.  No need for a binary search. */
17867  for(i=0; i<ArraySize(azCompileOpt); i++){
17868    if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
17869     && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
17870    ){
17871      return 1;
17872    }
17873  }
17874  return 0;
17875}
17876
17877/*
17878** Return the N-th compile-time option string.  If N is out of range,
17879** return a NULL pointer.
17880*/
17881SQLITE_API const char *sqlite3_compileoption_get(int N){
17882  if( N>=0 && N<ArraySize(azCompileOpt) ){
17883    return azCompileOpt[N];
17884  }
17885  return 0;
17886}
17887
17888#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
17889
17890/************** End of ctime.c ***********************************************/
17891/************** Begin file status.c ******************************************/
17892/*
17893** 2008 June 18
17894**
17895** The author disclaims copyright to this source code.  In place of
17896** a legal notice, here is a blessing:
17897**
17898**    May you do good and not evil.
17899**    May you find forgiveness for yourself and forgive others.
17900**    May you share freely, never taking more than you give.
17901**
17902*************************************************************************
17903**
17904** This module implements the sqlite3_status() interface and related
17905** functionality.
17906*/
17907/* #include "sqliteInt.h" */
17908/************** Include vdbeInt.h in the middle of status.c ******************/
17909/************** Begin file vdbeInt.h *****************************************/
17910/*
17911** 2003 September 6
17912**
17913** The author disclaims copyright to this source code.  In place of
17914** a legal notice, here is a blessing:
17915**
17916**    May you do good and not evil.
17917**    May you find forgiveness for yourself and forgive others.
17918**    May you share freely, never taking more than you give.
17919**
17920*************************************************************************
17921** This is the header file for information that is private to the
17922** VDBE.  This information used to all be at the top of the single
17923** source code file "vdbe.c".  When that file became too big (over
17924** 6000 lines long) it was split up into several smaller files and
17925** this header information was factored out.
17926*/
17927#ifndef SQLITE_VDBEINT_H
17928#define SQLITE_VDBEINT_H
17929
17930/*
17931** The maximum number of times that a statement will try to reparse
17932** itself before giving up and returning SQLITE_SCHEMA.
17933*/
17934#ifndef SQLITE_MAX_SCHEMA_RETRY
17935# define SQLITE_MAX_SCHEMA_RETRY 50
17936#endif
17937
17938/*
17939** VDBE_DISPLAY_P4 is true or false depending on whether or not the
17940** "explain" P4 display logic is enabled.
17941*/
17942#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
17943     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
17944# define VDBE_DISPLAY_P4 1
17945#else
17946# define VDBE_DISPLAY_P4 0
17947#endif
17948
17949/*
17950** SQL is translated into a sequence of instructions to be
17951** executed by a virtual machine.  Each instruction is an instance
17952** of the following structure.
17953*/
17954typedef struct VdbeOp Op;
17955
17956/*
17957** Boolean values
17958*/
17959typedef unsigned Bool;
17960
17961/* Opaque type used by code in vdbesort.c */
17962typedef struct VdbeSorter VdbeSorter;
17963
17964/* Elements of the linked list at Vdbe.pAuxData */
17965typedef struct AuxData AuxData;
17966
17967/* Types of VDBE cursors */
17968#define CURTYPE_BTREE       0
17969#define CURTYPE_SORTER      1
17970#define CURTYPE_VTAB        2
17971#define CURTYPE_PSEUDO      3
17972
17973/*
17974** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
17975**
17976**      * A b-tree cursor
17977**          -  In the main database or in an ephemeral database
17978**          -  On either an index or a table
17979**      * A sorter
17980**      * A virtual table
17981**      * A one-row "pseudotable" stored in a single register
17982*/
17983typedef struct VdbeCursor VdbeCursor;
17984struct VdbeCursor {
17985  u8 eCurType;            /* One of the CURTYPE_* values above */
17986  i8 iDb;                 /* Index of cursor database in db->aDb[] (or -1) */
17987  u8 nullRow;             /* True if pointing to a row with no data */
17988  u8 deferredMoveto;      /* A call to sqlite3BtreeMoveto() is needed */
17989  u8 isTable;             /* True for rowid tables.  False for indexes */
17990#ifdef SQLITE_DEBUG
17991  u8 seekOp;              /* Most recent seek operation on this cursor */
17992  u8 wrFlag;              /* The wrFlag argument to sqlite3BtreeCursor() */
17993#endif
17994  Bool isEphemeral:1;     /* True for an ephemeral table */
17995  Bool useRandomRowid:1;  /* Generate new record numbers semi-randomly */
17996  Bool isOrdered:1;       /* True if the table is not BTREE_UNORDERED */
17997  Btree *pBtx;            /* Separate file holding temporary table */
17998  i64 seqCount;           /* Sequence counter */
17999  int *aAltMap;           /* Mapping from table to index column numbers */
18000
18001  /* Cached OP_Column parse information is only valid if cacheStatus matches
18002  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
18003  ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
18004  ** the cache is out of date. */
18005  u32 cacheStatus;        /* Cache is valid if this matches Vdbe.cacheCtr */
18006  int seekResult;         /* Result of previous sqlite3BtreeMoveto() or 0
18007                          ** if there have been no prior seeks on the cursor. */
18008  /* NB: seekResult does not distinguish between "no seeks have ever occurred
18009  ** on this cursor" and "the most recent seek was an exact match". */
18010
18011  /* When a new VdbeCursor is allocated, only the fields above are zeroed.
18012  ** The fields that follow are uninitialized, and must be individually
18013  ** initialized prior to first use. */
18014  VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
18015  union {
18016    BtCursor *pCursor;          /* CURTYPE_BTREE.  Btree cursor */
18017    sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB.   Vtab cursor */
18018    int pseudoTableReg;         /* CURTYPE_PSEUDO. Reg holding content. */
18019    VdbeSorter *pSorter;        /* CURTYPE_SORTER. Sorter object */
18020  } uc;
18021  KeyInfo *pKeyInfo;      /* Info about index keys needed by index cursors */
18022  u32 iHdrOffset;         /* Offset to next unparsed byte of the header */
18023  Pgno pgnoRoot;          /* Root page of the open btree cursor */
18024  i16 nField;             /* Number of fields in the header */
18025  u16 nHdrParsed;         /* Number of header fields parsed so far */
18026  i64 movetoTarget;       /* Argument to the deferred sqlite3BtreeMoveto() */
18027  u32 *aOffset;           /* Pointer to aType[nField] */
18028  const u8 *aRow;         /* Data for the current row, if all on one page */
18029  u32 payloadSize;        /* Total number of bytes in the record */
18030  u32 szRow;              /* Byte available in aRow */
18031#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
18032  u64 maskUsed;           /* Mask of columns used by this cursor */
18033#endif
18034
18035  /* 2*nField extra array elements allocated for aType[], beyond the one
18036  ** static element declared in the structure.  nField total array slots for
18037  ** aType[] and nField+1 array slots for aOffset[] */
18038  u32 aType[1];           /* Type values record decode.  MUST BE LAST */
18039};
18040
18041
18042/*
18043** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
18044*/
18045#define CACHE_STALE 0
18046
18047/*
18048** When a sub-program is executed (OP_Program), a structure of this type
18049** is allocated to store the current value of the program counter, as
18050** well as the current memory cell array and various other frame specific
18051** values stored in the Vdbe struct. When the sub-program is finished,
18052** these values are copied back to the Vdbe from the VdbeFrame structure,
18053** restoring the state of the VM to as it was before the sub-program
18054** began executing.
18055**
18056** The memory for a VdbeFrame object is allocated and managed by a memory
18057** cell in the parent (calling) frame. When the memory cell is deleted or
18058** overwritten, the VdbeFrame object is not freed immediately. Instead, it
18059** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
18060** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
18061** this instead of deleting the VdbeFrame immediately is to avoid recursive
18062** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
18063** child frame are released.
18064**
18065** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
18066** set to NULL if the currently executing frame is the main program.
18067*/
18068typedef struct VdbeFrame VdbeFrame;
18069struct VdbeFrame {
18070  Vdbe *v;                /* VM this frame belongs to */
18071  VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
18072  Op *aOp;                /* Program instructions for parent frame */
18073  i64 *anExec;            /* Event counters from parent frame */
18074  Mem *aMem;              /* Array of memory cells for parent frame */
18075  VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
18076  u8 *aOnce;              /* Bitmask used by OP_Once */
18077  void *token;            /* Copy of SubProgram.token */
18078  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
18079  AuxData *pAuxData;      /* Linked list of auxdata allocations */
18080  int nCursor;            /* Number of entries in apCsr */
18081  int pc;                 /* Program Counter in parent (calling) frame */
18082  int nOp;                /* Size of aOp array */
18083  int nMem;               /* Number of entries in aMem */
18084  int nChildMem;          /* Number of memory cells for child frame */
18085  int nChildCsr;          /* Number of cursors for child frame */
18086  int nChange;            /* Statement changes (Vdbe.nChange)     */
18087  int nDbChange;          /* Value of db->nChange */
18088};
18089
18090#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
18091
18092/*
18093** Internally, the vdbe manipulates nearly all SQL values as Mem
18094** structures. Each Mem struct may cache multiple representations (string,
18095** integer etc.) of the same value.
18096*/
18097struct Mem {
18098  union MemValue {
18099    double r;           /* Real value used when MEM_Real is set in flags */
18100    i64 i;              /* Integer value used when MEM_Int is set in flags */
18101    int nZero;          /* Used when bit MEM_Zero is set in flags */
18102    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
18103    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
18104    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
18105  } u;
18106  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
18107  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
18108  u8  eSubtype;       /* Subtype for this value */
18109  int n;              /* Number of characters in string value, excluding '\0' */
18110  char *z;            /* String or BLOB value */
18111  /* ShallowCopy only needs to copy the information above */
18112  char *zMalloc;      /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
18113  int szMalloc;       /* Size of the zMalloc allocation */
18114  u32 uTemp;          /* Transient storage for serial_type in OP_MakeRecord */
18115  sqlite3 *db;        /* The associated database connection */
18116  void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
18117#ifdef SQLITE_DEBUG
18118  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
18119  void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
18120#endif
18121};
18122
18123/*
18124** Size of struct Mem not including the Mem.zMalloc member or anything that
18125** follows.
18126*/
18127#define MEMCELLSIZE offsetof(Mem,zMalloc)
18128
18129/* One or more of the following flags are set to indicate the validOK
18130** representations of the value stored in the Mem struct.
18131**
18132** If the MEM_Null flag is set, then the value is an SQL NULL value.
18133** No other flags may be set in this case.
18134**
18135** If the MEM_Str flag is set then Mem.z points at a string representation.
18136** Usually this is encoded in the same unicode encoding as the main
18137** database (see below for exceptions). If the MEM_Term flag is also
18138** set, then the string is nul terminated. The MEM_Int and MEM_Real
18139** flags may coexist with the MEM_Str flag.
18140*/
18141#define MEM_Null      0x0001   /* Value is NULL */
18142#define MEM_Str       0x0002   /* Value is a string */
18143#define MEM_Int       0x0004   /* Value is an integer */
18144#define MEM_Real      0x0008   /* Value is a real number */
18145#define MEM_Blob      0x0010   /* Value is a BLOB */
18146#define MEM_AffMask   0x001f   /* Mask of affinity bits */
18147#define MEM_RowSet    0x0020   /* Value is a RowSet object */
18148#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
18149#define MEM_Undefined 0x0080   /* Value is undefined */
18150#define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
18151#define MEM_TypeMask  0x81ff   /* Mask of type bits */
18152
18153
18154/* Whenever Mem contains a valid string or blob representation, one of
18155** the following flags must be set to determine the memory management
18156** policy for Mem.z.  The MEM_Term flag tells us whether or not the
18157** string is \000 or \u0000 terminated
18158*/
18159#define MEM_Term      0x0200   /* String rep is nul terminated */
18160#define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
18161#define MEM_Static    0x0800   /* Mem.z points to a static string */
18162#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
18163#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
18164#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
18165#define MEM_Subtype   0x8000   /* Mem.eSubtype is valid */
18166#ifdef SQLITE_OMIT_INCRBLOB
18167  #undef MEM_Zero
18168  #define MEM_Zero 0x0000
18169#endif
18170
18171/* Return TRUE if Mem X contains dynamically allocated content - anything
18172** that needs to be deallocated to avoid a leak.
18173*/
18174#define VdbeMemDynamic(X)  \
18175  (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
18176
18177/*
18178** Clear any existing type flags from a Mem and replace them with f
18179*/
18180#define MemSetTypeFlag(p, f) \
18181   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
18182
18183/*
18184** Return true if a memory cell is not marked as invalid.  This macro
18185** is for use inside assert() statements only.
18186*/
18187#ifdef SQLITE_DEBUG
18188#define memIsValid(M)  ((M)->flags & MEM_Undefined)==0
18189#endif
18190
18191/*
18192** Each auxiliary data pointer stored by a user defined function
18193** implementation calling sqlite3_set_auxdata() is stored in an instance
18194** of this structure. All such structures associated with a single VM
18195** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
18196** when the VM is halted (if not before).
18197*/
18198struct AuxData {
18199  int iOp;                        /* Instruction number of OP_Function opcode */
18200  int iArg;                       /* Index of function argument. */
18201  void *pAux;                     /* Aux data pointer */
18202  void (*xDelete)(void *);        /* Destructor for the aux data */
18203  AuxData *pNext;                 /* Next element in list */
18204};
18205
18206/*
18207** The "context" argument for an installable function.  A pointer to an
18208** instance of this structure is the first argument to the routines used
18209** implement the SQL functions.
18210**
18211** There is a typedef for this structure in sqlite.h.  So all routines,
18212** even the public interface to SQLite, can use a pointer to this structure.
18213** But this file is the only place where the internal details of this
18214** structure are known.
18215**
18216** This structure is defined inside of vdbeInt.h because it uses substructures
18217** (Mem) which are only defined there.
18218*/
18219struct sqlite3_context {
18220  Mem *pOut;              /* The return value is stored here */
18221  FuncDef *pFunc;         /* Pointer to function information */
18222  Mem *pMem;              /* Memory cell used to store aggregate context */
18223  Vdbe *pVdbe;            /* The VM that owns this context */
18224  int iOp;                /* Instruction number of OP_Function */
18225  int isError;            /* Error code returned by the function. */
18226  u8 skipFlag;            /* Skip accumulator loading if true */
18227  u8 fErrorOrAux;         /* isError!=0 or pVdbe->pAuxData modified */
18228  u8 argc;                /* Number of arguments */
18229  sqlite3_value *argv[1]; /* Argument set */
18230};
18231
18232/* A bitfield type for use inside of structures.  Always follow with :N where
18233** N is the number of bits.
18234*/
18235typedef unsigned bft;  /* Bit Field Type */
18236
18237typedef struct ScanStatus ScanStatus;
18238struct ScanStatus {
18239  int addrExplain;                /* OP_Explain for loop */
18240  int addrLoop;                   /* Address of "loops" counter */
18241  int addrVisit;                  /* Address of "rows visited" counter */
18242  int iSelectID;                  /* The "Select-ID" for this loop */
18243  LogEst nEst;                    /* Estimated output rows per loop */
18244  char *zName;                    /* Name of table or index */
18245};
18246
18247/*
18248** An instance of the virtual machine.  This structure contains the complete
18249** state of the virtual machine.
18250**
18251** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
18252** is really a pointer to an instance of this structure.
18253*/
18254struct Vdbe {
18255  sqlite3 *db;            /* The database connection that owns this statement */
18256  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
18257  Parse *pParse;          /* Parsing context used to create this Vdbe */
18258  ynVar nVar;             /* Number of entries in aVar[] */
18259  u32 magic;              /* Magic number for sanity checking */
18260  int nMem;               /* Number of memory locations currently allocated */
18261  int nCursor;            /* Number of slots in apCsr[] */
18262  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
18263  int pc;                 /* The program counter */
18264  int rc;                 /* Value to return */
18265  int nChange;            /* Number of db changes made since last reset */
18266  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
18267  i64 iCurrentTime;       /* Value of julianday('now') for this statement */
18268  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
18269  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
18270  i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
18271
18272  /* When allocating a new Vdbe object, all of the fields below should be
18273  ** initialized to zero or NULL */
18274
18275  Op *aOp;                /* Space to hold the virtual machine's program */
18276  Mem *aMem;              /* The memory locations */
18277  Mem **apArg;            /* Arguments to currently executing user function */
18278  Mem *aColName;          /* Column names to return */
18279  Mem *pResultSet;        /* Pointer to an array of results */
18280  char *zErrMsg;          /* Error message written here */
18281  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
18282  Mem *aVar;              /* Values for the OP_Variable opcode. */
18283  VList *pVList;          /* Name of variables */
18284#ifndef SQLITE_OMIT_TRACE
18285  i64 startTime;          /* Time when query started - used for profiling */
18286#endif
18287  int nOp;                /* Number of instructions in the program */
18288#ifdef SQLITE_DEBUG
18289  int rcApp;              /* errcode set by sqlite3_result_error_code() */
18290#endif
18291  u16 nResColumn;         /* Number of columns in one row of the result set */
18292  u8 errorAction;         /* Recovery action to do in case of an error */
18293  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
18294  bft expired:1;          /* True if the VM needs to be recompiled */
18295  bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
18296  bft explain:2;          /* True if EXPLAIN present on SQL command */
18297  bft changeCntOn:1;      /* True to update the change-counter */
18298  bft runOnlyOnce:1;      /* Automatically expire on reset */
18299  bft usesStmtJournal:1;  /* True if uses a statement journal */
18300  bft readOnly:1;         /* True for statements that do not write */
18301  bft bIsReader:1;        /* True for statements that read */
18302  bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
18303  yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
18304  yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
18305  u32 aCounter[5];        /* Counters used by sqlite3_stmt_status() */
18306  char *zSql;             /* Text of the SQL statement that generated this */
18307  void *pFree;            /* Free this when deleting the vdbe */
18308  VdbeFrame *pFrame;      /* Parent frame */
18309  VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
18310  int nFrame;             /* Number of frames in pFrame list */
18311  u32 expmask;            /* Binding to these vars invalidates VM */
18312  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
18313  AuxData *pAuxData;      /* Linked list of auxdata allocations */
18314#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
18315  i64 *anExec;            /* Number of times each op has been executed */
18316  int nScan;              /* Entries in aScan[] */
18317  ScanStatus *aScan;      /* Scan definitions for sqlite3_stmt_scanstatus() */
18318#endif
18319};
18320
18321/*
18322** The following are allowed values for Vdbe.magic
18323*/
18324#define VDBE_MAGIC_INIT     0x16bceaa5    /* Building a VDBE program */
18325#define VDBE_MAGIC_RUN      0x2df20da3    /* VDBE is ready to execute */
18326#define VDBE_MAGIC_HALT     0x319c2973    /* VDBE has completed execution */
18327#define VDBE_MAGIC_RESET    0x48fa9f76    /* Reset and ready to run again */
18328#define VDBE_MAGIC_DEAD     0x5606c3c8    /* The VDBE has been deallocated */
18329
18330/*
18331** Structure used to store the context required by the
18332** sqlite3_preupdate_*() API functions.
18333*/
18334struct PreUpdate {
18335  Vdbe *v;
18336  VdbeCursor *pCsr;               /* Cursor to read old values from */
18337  int op;                         /* One of SQLITE_INSERT, UPDATE, DELETE */
18338  u8 *aRecord;                    /* old.* database record */
18339  KeyInfo keyinfo;
18340  UnpackedRecord *pUnpacked;      /* Unpacked version of aRecord[] */
18341  UnpackedRecord *pNewUnpacked;   /* Unpacked version of new.* record */
18342  int iNewReg;                    /* Register for new.* values */
18343  i64 iKey1;                      /* First key value passed to hook */
18344  i64 iKey2;                      /* Second key value passed to hook */
18345  Mem *aNew;                      /* Array of new.* values */
18346  Table *pTab;                    /* Schema object being upated */
18347  Index *pPk;                     /* PK index if pTab is WITHOUT ROWID */
18348};
18349
18350/*
18351** Function prototypes
18352*/
18353SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
18354SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
18355void sqliteVdbePopStack(Vdbe*,int);
18356SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
18357SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
18358#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18359SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18360#endif
18361SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
18362SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
18363SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
18364SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
18365SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18366SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
18367
18368int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18369SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
18370SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
18371SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18372SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18373SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18374SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18375SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18376SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18377SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18378SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18379SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18380SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18381SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18382#ifdef SQLITE_OMIT_FLOATING_POINT
18383# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
18384#else
18385SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
18386#endif
18387SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
18388SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
18389SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
18390SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
18391SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
18392SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
18393SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
18394SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
18395SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
18396SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
18397SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
18398SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
18399SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
18400SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
18401SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
18402SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
18403SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18404SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18405SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
18406SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
18407SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
18408SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
18409#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
18410SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
18411#endif
18412SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
18413
18414SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
18415SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
18416SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
18417SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
18418SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
18419SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
18420SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
18421SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
18422
18423#if !defined(SQLITE_OMIT_SHARED_CACHE)
18424SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
18425#else
18426# define sqlite3VdbeEnter(X)
18427#endif
18428
18429#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
18430SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
18431#else
18432# define sqlite3VdbeLeave(X)
18433#endif
18434
18435#ifdef SQLITE_DEBUG
18436SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
18437SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
18438#endif
18439
18440#ifndef SQLITE_OMIT_FOREIGN_KEY
18441SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
18442#else
18443# define sqlite3VdbeCheckFk(p,i) 0
18444#endif
18445
18446SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
18447#ifdef SQLITE_DEBUG
18448SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
18449SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
18450#endif
18451SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
18452
18453#ifndef SQLITE_OMIT_INCRBLOB
18454SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
18455  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
18456#else
18457  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
18458  #define ExpandBlob(P) SQLITE_OK
18459#endif
18460
18461#endif /* !defined(SQLITE_VDBEINT_H) */
18462
18463/************** End of vdbeInt.h *********************************************/
18464/************** Continuing where we left off in status.c *********************/
18465
18466/*
18467** Variables in which to record status information.
18468*/
18469#if SQLITE_PTRSIZE>4
18470typedef sqlite3_int64 sqlite3StatValueType;
18471#else
18472typedef u32 sqlite3StatValueType;
18473#endif
18474typedef struct sqlite3StatType sqlite3StatType;
18475static SQLITE_WSD struct sqlite3StatType {
18476  sqlite3StatValueType nowValue[10];  /* Current value */
18477  sqlite3StatValueType mxValue[10];   /* Maximum value */
18478} sqlite3Stat = { {0,}, {0,} };
18479
18480/*
18481** Elements of sqlite3Stat[] are protected by either the memory allocator
18482** mutex, or by the pcache1 mutex.  The following array determines which.
18483*/
18484static const char statMutex[] = {
18485  0,  /* SQLITE_STATUS_MEMORY_USED */
18486  1,  /* SQLITE_STATUS_PAGECACHE_USED */
18487  1,  /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
18488  0,  /* SQLITE_STATUS_SCRATCH_USED */
18489  0,  /* SQLITE_STATUS_SCRATCH_OVERFLOW */
18490  0,  /* SQLITE_STATUS_MALLOC_SIZE */
18491  0,  /* SQLITE_STATUS_PARSER_STACK */
18492  1,  /* SQLITE_STATUS_PAGECACHE_SIZE */
18493  0,  /* SQLITE_STATUS_SCRATCH_SIZE */
18494  0,  /* SQLITE_STATUS_MALLOC_COUNT */
18495};
18496
18497
18498/* The "wsdStat" macro will resolve to the status information
18499** state vector.  If writable static data is unsupported on the target,
18500** we have to locate the state vector at run-time.  In the more common
18501** case where writable static data is supported, wsdStat can refer directly
18502** to the "sqlite3Stat" state vector declared above.
18503*/
18504#ifdef SQLITE_OMIT_WSD
18505# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
18506# define wsdStat x[0]
18507#else
18508# define wsdStatInit
18509# define wsdStat sqlite3Stat
18510#endif
18511
18512/*
18513** Return the current value of a status parameter.  The caller must
18514** be holding the appropriate mutex.
18515*/
18516SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
18517  wsdStatInit;
18518  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18519  assert( op>=0 && op<ArraySize(statMutex) );
18520  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18521                                           : sqlite3MallocMutex()) );
18522  return wsdStat.nowValue[op];
18523}
18524
18525/*
18526** Add N to the value of a status record.  The caller must hold the
18527** appropriate mutex.  (Locking is checked by assert()).
18528**
18529** The StatusUp() routine can accept positive or negative values for N.
18530** The value of N is added to the current status value and the high-water
18531** mark is adjusted if necessary.
18532**
18533** The StatusDown() routine lowers the current value by N.  The highwater
18534** mark is unchanged.  N must be non-negative for StatusDown().
18535*/
18536SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
18537  wsdStatInit;
18538  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18539  assert( op>=0 && op<ArraySize(statMutex) );
18540  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18541                                           : sqlite3MallocMutex()) );
18542  wsdStat.nowValue[op] += N;
18543  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
18544    wsdStat.mxValue[op] = wsdStat.nowValue[op];
18545  }
18546}
18547SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
18548  wsdStatInit;
18549  assert( N>=0 );
18550  assert( op>=0 && op<ArraySize(statMutex) );
18551  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18552                                           : sqlite3MallocMutex()) );
18553  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18554  wsdStat.nowValue[op] -= N;
18555}
18556
18557/*
18558** Adjust the highwater mark if necessary.
18559** The caller must hold the appropriate mutex.
18560*/
18561SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
18562  sqlite3StatValueType newValue;
18563  wsdStatInit;
18564  assert( X>=0 );
18565  newValue = (sqlite3StatValueType)X;
18566  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18567  assert( op>=0 && op<ArraySize(statMutex) );
18568  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18569                                           : sqlite3MallocMutex()) );
18570  assert( op==SQLITE_STATUS_MALLOC_SIZE
18571          || op==SQLITE_STATUS_PAGECACHE_SIZE
18572          || op==SQLITE_STATUS_SCRATCH_SIZE
18573          || op==SQLITE_STATUS_PARSER_STACK );
18574  if( newValue>wsdStat.mxValue[op] ){
18575    wsdStat.mxValue[op] = newValue;
18576  }
18577}
18578
18579/*
18580** Query status information.
18581*/
18582SQLITE_API int sqlite3_status64(
18583  int op,
18584  sqlite3_int64 *pCurrent,
18585  sqlite3_int64 *pHighwater,
18586  int resetFlag
18587){
18588  sqlite3_mutex *pMutex;
18589  wsdStatInit;
18590  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
18591    return SQLITE_MISUSE_BKPT;
18592  }
18593#ifdef SQLITE_ENABLE_API_ARMOR
18594  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
18595#endif
18596  pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
18597  sqlite3_mutex_enter(pMutex);
18598  *pCurrent = wsdStat.nowValue[op];
18599  *pHighwater = wsdStat.mxValue[op];
18600  if( resetFlag ){
18601    wsdStat.mxValue[op] = wsdStat.nowValue[op];
18602  }
18603  sqlite3_mutex_leave(pMutex);
18604  (void)pMutex;  /* Prevent warning when SQLITE_THREADSAFE=0 */
18605  return SQLITE_OK;
18606}
18607SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
18608  sqlite3_int64 iCur = 0, iHwtr = 0;
18609  int rc;
18610#ifdef SQLITE_ENABLE_API_ARMOR
18611  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
18612#endif
18613  rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
18614  if( rc==0 ){
18615    *pCurrent = (int)iCur;
18616    *pHighwater = (int)iHwtr;
18617  }
18618  return rc;
18619}
18620
18621/*
18622** Query status information for a single database connection
18623*/
18624SQLITE_API int sqlite3_db_status(
18625  sqlite3 *db,          /* The database connection whose status is desired */
18626  int op,               /* Status verb */
18627  int *pCurrent,        /* Write current value here */
18628  int *pHighwater,      /* Write high-water mark here */
18629  int resetFlag         /* Reset high-water mark if true */
18630){
18631  int rc = SQLITE_OK;   /* Return code */
18632#ifdef SQLITE_ENABLE_API_ARMOR
18633  if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
18634    return SQLITE_MISUSE_BKPT;
18635  }
18636#endif
18637  sqlite3_mutex_enter(db->mutex);
18638  switch( op ){
18639    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
18640      *pCurrent = db->lookaside.nOut;
18641      *pHighwater = db->lookaside.mxOut;
18642      if( resetFlag ){
18643        db->lookaside.mxOut = db->lookaside.nOut;
18644      }
18645      break;
18646    }
18647
18648    case SQLITE_DBSTATUS_LOOKASIDE_HIT:
18649    case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
18650    case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
18651      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
18652      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
18653      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
18654      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
18655      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
18656      *pCurrent = 0;
18657      *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
18658      if( resetFlag ){
18659        db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
18660      }
18661      break;
18662    }
18663
18664    /*
18665    ** Return an approximation for the amount of memory currently used
18666    ** by all pagers associated with the given database connection.  The
18667    ** highwater mark is meaningless and is returned as zero.
18668    */
18669    case SQLITE_DBSTATUS_CACHE_USED_SHARED:
18670    case SQLITE_DBSTATUS_CACHE_USED: {
18671      int totalUsed = 0;
18672      int i;
18673      sqlite3BtreeEnterAll(db);
18674      for(i=0; i<db->nDb; i++){
18675        Btree *pBt = db->aDb[i].pBt;
18676        if( pBt ){
18677          Pager *pPager = sqlite3BtreePager(pBt);
18678          int nByte = sqlite3PagerMemUsed(pPager);
18679          if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
18680            nByte = nByte / sqlite3BtreeConnectionCount(pBt);
18681          }
18682          totalUsed += nByte;
18683        }
18684      }
18685      sqlite3BtreeLeaveAll(db);
18686      *pCurrent = totalUsed;
18687      *pHighwater = 0;
18688      break;
18689    }
18690
18691    /*
18692    ** *pCurrent gets an accurate estimate of the amount of memory used
18693    ** to store the schema for all databases (main, temp, and any ATTACHed
18694    ** databases.  *pHighwater is set to zero.
18695    */
18696    case SQLITE_DBSTATUS_SCHEMA_USED: {
18697      int i;                      /* Used to iterate through schemas */
18698      int nByte = 0;              /* Used to accumulate return value */
18699
18700      sqlite3BtreeEnterAll(db);
18701      db->pnBytesFreed = &nByte;
18702      for(i=0; i<db->nDb; i++){
18703        Schema *pSchema = db->aDb[i].pSchema;
18704        if( ALWAYS(pSchema!=0) ){
18705          HashElem *p;
18706
18707          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
18708              pSchema->tblHash.count
18709            + pSchema->trigHash.count
18710            + pSchema->idxHash.count
18711            + pSchema->fkeyHash.count
18712          );
18713          nByte += sqlite3_msize(pSchema->tblHash.ht);
18714          nByte += sqlite3_msize(pSchema->trigHash.ht);
18715          nByte += sqlite3_msize(pSchema->idxHash.ht);
18716          nByte += sqlite3_msize(pSchema->fkeyHash.ht);
18717
18718          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
18719            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
18720          }
18721          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
18722            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
18723          }
18724        }
18725      }
18726      db->pnBytesFreed = 0;
18727      sqlite3BtreeLeaveAll(db);
18728
18729      *pHighwater = 0;
18730      *pCurrent = nByte;
18731      break;
18732    }
18733
18734    /*
18735    ** *pCurrent gets an accurate estimate of the amount of memory used
18736    ** to store all prepared statements.
18737    ** *pHighwater is set to zero.
18738    */
18739    case SQLITE_DBSTATUS_STMT_USED: {
18740      struct Vdbe *pVdbe;         /* Used to iterate through VMs */
18741      int nByte = 0;              /* Used to accumulate return value */
18742
18743      db->pnBytesFreed = &nByte;
18744      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
18745        sqlite3VdbeClearObject(db, pVdbe);
18746        sqlite3DbFree(db, pVdbe);
18747      }
18748      db->pnBytesFreed = 0;
18749
18750      *pHighwater = 0;  /* IMP: R-64479-57858 */
18751      *pCurrent = nByte;
18752
18753      break;
18754    }
18755
18756    /*
18757    ** Set *pCurrent to the total cache hits or misses encountered by all
18758    ** pagers the database handle is connected to. *pHighwater is always set
18759    ** to zero.
18760    */
18761    case SQLITE_DBSTATUS_CACHE_HIT:
18762    case SQLITE_DBSTATUS_CACHE_MISS:
18763    case SQLITE_DBSTATUS_CACHE_WRITE:{
18764      int i;
18765      int nRet = 0;
18766      assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
18767      assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
18768
18769      for(i=0; i<db->nDb; i++){
18770        if( db->aDb[i].pBt ){
18771          Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
18772          sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
18773        }
18774      }
18775      *pHighwater = 0; /* IMP: R-42420-56072 */
18776                       /* IMP: R-54100-20147 */
18777                       /* IMP: R-29431-39229 */
18778      *pCurrent = nRet;
18779      break;
18780    }
18781
18782    /* Set *pCurrent to non-zero if there are unresolved deferred foreign
18783    ** key constraints.  Set *pCurrent to zero if all foreign key constraints
18784    ** have been satisfied.  The *pHighwater is always set to zero.
18785    */
18786    case SQLITE_DBSTATUS_DEFERRED_FKS: {
18787      *pHighwater = 0;  /* IMP: R-11967-56545 */
18788      *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
18789      break;
18790    }
18791
18792    default: {
18793      rc = SQLITE_ERROR;
18794    }
18795  }
18796  sqlite3_mutex_leave(db->mutex);
18797  return rc;
18798}
18799
18800/************** End of status.c **********************************************/
18801/************** Begin file date.c ********************************************/
18802/*
18803** 2003 October 31
18804**
18805** The author disclaims copyright to this source code.  In place of
18806** a legal notice, here is a blessing:
18807**
18808**    May you do good and not evil.
18809**    May you find forgiveness for yourself and forgive others.
18810**    May you share freely, never taking more than you give.
18811**
18812*************************************************************************
18813** This file contains the C functions that implement date and time
18814** functions for SQLite.
18815**
18816** There is only one exported symbol in this file - the function
18817** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
18818** All other code has file scope.
18819**
18820** SQLite processes all times and dates as julian day numbers.  The
18821** dates and times are stored as the number of days since noon
18822** in Greenwich on November 24, 4714 B.C. according to the Gregorian
18823** calendar system.
18824**
18825** 1970-01-01 00:00:00 is JD 2440587.5
18826** 2000-01-01 00:00:00 is JD 2451544.5
18827**
18828** This implementation requires years to be expressed as a 4-digit number
18829** which means that only dates between 0000-01-01 and 9999-12-31 can
18830** be represented, even though julian day numbers allow a much wider
18831** range of dates.
18832**
18833** The Gregorian calendar system is used for all dates and times,
18834** even those that predate the Gregorian calendar.  Historians usually
18835** use the julian calendar for dates prior to 1582-10-15 and for some
18836** dates afterwards, depending on locale.  Beware of this difference.
18837**
18838** The conversion algorithms are implemented based on descriptions
18839** in the following text:
18840**
18841**      Jean Meeus
18842**      Astronomical Algorithms, 2nd Edition, 1998
18843**      ISBM 0-943396-61-1
18844**      Willmann-Bell, Inc
18845**      Richmond, Virginia (USA)
18846*/
18847/* #include "sqliteInt.h" */
18848/* #include <stdlib.h> */
18849/* #include <assert.h> */
18850#include <time.h>
18851
18852#ifndef SQLITE_OMIT_DATETIME_FUNCS
18853
18854/*
18855** The MSVC CRT on Windows CE may not have a localtime() function.
18856** So declare a substitute.  The substitute function itself is
18857** defined in "os_win.c".
18858*/
18859#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
18860    (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
18861struct tm *__cdecl localtime(const time_t *);
18862#endif
18863
18864/*
18865** A structure for holding a single date and time.
18866*/
18867typedef struct DateTime DateTime;
18868struct DateTime {
18869  sqlite3_int64 iJD;  /* The julian day number times 86400000 */
18870  int Y, M, D;        /* Year, month, and day */
18871  int h, m;           /* Hour and minutes */
18872  int tz;             /* Timezone offset in minutes */
18873  double s;           /* Seconds */
18874  char validJD;       /* True (1) if iJD is valid */
18875  char rawS;          /* Raw numeric value stored in s */
18876  char validYMD;      /* True (1) if Y,M,D are valid */
18877  char validHMS;      /* True (1) if h,m,s are valid */
18878  char validTZ;       /* True (1) if tz is valid */
18879  char tzSet;         /* Timezone was set explicitly */
18880  char isError;       /* An overflow has occurred */
18881};
18882
18883
18884/*
18885** Convert zDate into one or more integers according to the conversion
18886** specifier zFormat.
18887**
18888** zFormat[] contains 4 characters for each integer converted, except for
18889** the last integer which is specified by three characters.  The meaning
18890** of a four-character format specifiers ABCD is:
18891**
18892**    A:   number of digits to convert.  Always "2" or "4".
18893**    B:   minimum value.  Always "0" or "1".
18894**    C:   maximum value, decoded as:
18895**           a:  12
18896**           b:  14
18897**           c:  24
18898**           d:  31
18899**           e:  59
18900**           f:  9999
18901**    D:   the separator character, or \000 to indicate this is the
18902**         last number to convert.
18903**
18904** Example:  To translate an ISO-8601 date YYYY-MM-DD, the format would
18905** be "40f-21a-20c".  The "40f-" indicates the 4-digit year followed by "-".
18906** The "21a-" indicates the 2-digit month followed by "-".  The "20c" indicates
18907** the 2-digit day which is the last integer in the set.
18908**
18909** The function returns the number of successful conversions.
18910*/
18911static int getDigits(const char *zDate, const char *zFormat, ...){
18912  /* The aMx[] array translates the 3rd character of each format
18913  ** spec into a max size:    a   b   c   d   e     f */
18914  static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
18915  va_list ap;
18916  int cnt = 0;
18917  char nextC;
18918  va_start(ap, zFormat);
18919  do{
18920    char N = zFormat[0] - '0';
18921    char min = zFormat[1] - '0';
18922    int val = 0;
18923    u16 max;
18924
18925    assert( zFormat[2]>='a' && zFormat[2]<='f' );
18926    max = aMx[zFormat[2] - 'a'];
18927    nextC = zFormat[3];
18928    val = 0;
18929    while( N-- ){
18930      if( !sqlite3Isdigit(*zDate) ){
18931        goto end_getDigits;
18932      }
18933      val = val*10 + *zDate - '0';
18934      zDate++;
18935    }
18936    if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
18937      goto end_getDigits;
18938    }
18939    *va_arg(ap,int*) = val;
18940    zDate++;
18941    cnt++;
18942    zFormat += 4;
18943  }while( nextC );
18944end_getDigits:
18945  va_end(ap);
18946  return cnt;
18947}
18948
18949/*
18950** Parse a timezone extension on the end of a date-time.
18951** The extension is of the form:
18952**
18953**        (+/-)HH:MM
18954**
18955** Or the "zulu" notation:
18956**
18957**        Z
18958**
18959** If the parse is successful, write the number of minutes
18960** of change in p->tz and return 0.  If a parser error occurs,
18961** return non-zero.
18962**
18963** A missing specifier is not considered an error.
18964*/
18965static int parseTimezone(const char *zDate, DateTime *p){
18966  int sgn = 0;
18967  int nHr, nMn;
18968  int c;
18969  while( sqlite3Isspace(*zDate) ){ zDate++; }
18970  p->tz = 0;
18971  c = *zDate;
18972  if( c=='-' ){
18973    sgn = -1;
18974  }else if( c=='+' ){
18975    sgn = +1;
18976  }else if( c=='Z' || c=='z' ){
18977    zDate++;
18978    goto zulu_time;
18979  }else{
18980    return c!=0;
18981  }
18982  zDate++;
18983  if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
18984    return 1;
18985  }
18986  zDate += 5;
18987  p->tz = sgn*(nMn + nHr*60);
18988zulu_time:
18989  while( sqlite3Isspace(*zDate) ){ zDate++; }
18990  p->tzSet = 1;
18991  return *zDate!=0;
18992}
18993
18994/*
18995** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
18996** The HH, MM, and SS must each be exactly 2 digits.  The
18997** fractional seconds FFFF can be one or more digits.
18998**
18999** Return 1 if there is a parsing error and 0 on success.
19000*/
19001static int parseHhMmSs(const char *zDate, DateTime *p){
19002  int h, m, s;
19003  double ms = 0.0;
19004  if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
19005    return 1;
19006  }
19007  zDate += 5;
19008  if( *zDate==':' ){
19009    zDate++;
19010    if( getDigits(zDate, "20e", &s)!=1 ){
19011      return 1;
19012    }
19013    zDate += 2;
19014    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
19015      double rScale = 1.0;
19016      zDate++;
19017      while( sqlite3Isdigit(*zDate) ){
19018        ms = ms*10.0 + *zDate - '0';
19019        rScale *= 10.0;
19020        zDate++;
19021      }
19022      ms /= rScale;
19023    }
19024  }else{
19025    s = 0;
19026  }
19027  p->validJD = 0;
19028  p->rawS = 0;
19029  p->validHMS = 1;
19030  p->h = h;
19031  p->m = m;
19032  p->s = s + ms;
19033  if( parseTimezone(zDate, p) ) return 1;
19034  p->validTZ = (p->tz!=0)?1:0;
19035  return 0;
19036}
19037
19038/*
19039** Put the DateTime object into its error state.
19040*/
19041static void datetimeError(DateTime *p){
19042  memset(p, 0, sizeof(*p));
19043  p->isError = 1;
19044}
19045
19046/*
19047** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
19048** that the YYYY-MM-DD is according to the Gregorian calendar.
19049**
19050** Reference:  Meeus page 61
19051*/
19052static void computeJD(DateTime *p){
19053  int Y, M, D, A, B, X1, X2;
19054
19055  if( p->validJD ) return;
19056  if( p->validYMD ){
19057    Y = p->Y;
19058    M = p->M;
19059    D = p->D;
19060  }else{
19061    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
19062    M = 1;
19063    D = 1;
19064  }
19065  if( Y<-4713 || Y>9999 || p->rawS ){
19066    datetimeError(p);
19067    return;
19068  }
19069  if( M<=2 ){
19070    Y--;
19071    M += 12;
19072  }
19073  A = Y/100;
19074  B = 2 - A + (A/4);
19075  X1 = 36525*(Y+4716)/100;
19076  X2 = 306001*(M+1)/10000;
19077  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
19078  p->validJD = 1;
19079  if( p->validHMS ){
19080    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
19081    if( p->validTZ ){
19082      p->iJD -= p->tz*60000;
19083      p->validYMD = 0;
19084      p->validHMS = 0;
19085      p->validTZ = 0;
19086    }
19087  }
19088}
19089
19090/*
19091** Parse dates of the form
19092**
19093**     YYYY-MM-DD HH:MM:SS.FFF
19094**     YYYY-MM-DD HH:MM:SS
19095**     YYYY-MM-DD HH:MM
19096**     YYYY-MM-DD
19097**
19098** Write the result into the DateTime structure and return 0
19099** on success and 1 if the input string is not a well-formed
19100** date.
19101*/
19102static int parseYyyyMmDd(const char *zDate, DateTime *p){
19103  int Y, M, D, neg;
19104
19105  if( zDate[0]=='-' ){
19106    zDate++;
19107    neg = 1;
19108  }else{
19109    neg = 0;
19110  }
19111  if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
19112    return 1;
19113  }
19114  zDate += 10;
19115  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
19116  if( parseHhMmSs(zDate, p)==0 ){
19117    /* We got the time */
19118  }else if( *zDate==0 ){
19119    p->validHMS = 0;
19120  }else{
19121    return 1;
19122  }
19123  p->validJD = 0;
19124  p->validYMD = 1;
19125  p->Y = neg ? -Y : Y;
19126  p->M = M;
19127  p->D = D;
19128  if( p->validTZ ){
19129    computeJD(p);
19130  }
19131  return 0;
19132}
19133
19134/*
19135** Set the time to the current time reported by the VFS.
19136**
19137** Return the number of errors.
19138*/
19139static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
19140  p->iJD = sqlite3StmtCurrentTime(context);
19141  if( p->iJD>0 ){
19142    p->validJD = 1;
19143    return 0;
19144  }else{
19145    return 1;
19146  }
19147}
19148
19149/*
19150** Input "r" is a numeric quantity which might be a julian day number,
19151** or the number of seconds since 1970.  If the value if r is within
19152** range of a julian day number, install it as such and set validJD.
19153** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
19154*/
19155static void setRawDateNumber(DateTime *p, double r){
19156  p->s = r;
19157  p->rawS = 1;
19158  if( r>=0.0 && r<5373484.5 ){
19159    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
19160    p->validJD = 1;
19161  }
19162}
19163
19164/*
19165** Attempt to parse the given string into a julian day number.  Return
19166** the number of errors.
19167**
19168** The following are acceptable forms for the input string:
19169**
19170**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
19171**      DDDD.DD
19172**      now
19173**
19174** In the first form, the +/-HH:MM is always optional.  The fractional
19175** seconds extension (the ".FFF") is optional.  The seconds portion
19176** (":SS.FFF") is option.  The year and date can be omitted as long
19177** as there is a time string.  The time string can be omitted as long
19178** as there is a year and date.
19179*/
19180static int parseDateOrTime(
19181  sqlite3_context *context,
19182  const char *zDate,
19183  DateTime *p
19184){
19185  double r;
19186  if( parseYyyyMmDd(zDate,p)==0 ){
19187    return 0;
19188  }else if( parseHhMmSs(zDate, p)==0 ){
19189    return 0;
19190  }else if( sqlite3StrICmp(zDate,"now")==0){
19191    return setDateTimeToCurrent(context, p);
19192  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
19193    setRawDateNumber(p, r);
19194    return 0;
19195  }
19196  return 1;
19197}
19198
19199/* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
19200** Multiplying this by 86400000 gives 464269060799999 as the maximum value
19201** for DateTime.iJD.
19202**
19203** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
19204** such a large integer literal, so we have to encode it.
19205*/
19206#define INT_464269060799999  ((((i64)0x1a640)<<32)|0x1072fdff)
19207
19208/*
19209** Return TRUE if the given julian day number is within range.
19210**
19211** The input is the JulianDay times 86400000.
19212*/
19213static int validJulianDay(sqlite3_int64 iJD){
19214  return iJD>=0 && iJD<=INT_464269060799999;
19215}
19216
19217/*
19218** Compute the Year, Month, and Day from the julian day number.
19219*/
19220static void computeYMD(DateTime *p){
19221  int Z, A, B, C, D, E, X1;
19222  if( p->validYMD ) return;
19223  if( !p->validJD ){
19224    p->Y = 2000;
19225    p->M = 1;
19226    p->D = 1;
19227  }else{
19228    assert( validJulianDay(p->iJD) );
19229    Z = (int)((p->iJD + 43200000)/86400000);
19230    A = (int)((Z - 1867216.25)/36524.25);
19231    A = Z + 1 + A - (A/4);
19232    B = A + 1524;
19233    C = (int)((B - 122.1)/365.25);
19234    D = (36525*(C&32767))/100;
19235    E = (int)((B-D)/30.6001);
19236    X1 = (int)(30.6001*E);
19237    p->D = B - D - X1;
19238    p->M = E<14 ? E-1 : E-13;
19239    p->Y = p->M>2 ? C - 4716 : C - 4715;
19240  }
19241  p->validYMD = 1;
19242}
19243
19244/*
19245** Compute the Hour, Minute, and Seconds from the julian day number.
19246*/
19247static void computeHMS(DateTime *p){
19248  int s;
19249  if( p->validHMS ) return;
19250  computeJD(p);
19251  s = (int)((p->iJD + 43200000) % 86400000);
19252  p->s = s/1000.0;
19253  s = (int)p->s;
19254  p->s -= s;
19255  p->h = s/3600;
19256  s -= p->h*3600;
19257  p->m = s/60;
19258  p->s += s - p->m*60;
19259  p->rawS = 0;
19260  p->validHMS = 1;
19261}
19262
19263/*
19264** Compute both YMD and HMS
19265*/
19266static void computeYMD_HMS(DateTime *p){
19267  computeYMD(p);
19268  computeHMS(p);
19269}
19270
19271/*
19272** Clear the YMD and HMS and the TZ
19273*/
19274static void clearYMD_HMS_TZ(DateTime *p){
19275  p->validYMD = 0;
19276  p->validHMS = 0;
19277  p->validTZ = 0;
19278}
19279
19280#ifndef SQLITE_OMIT_LOCALTIME
19281/*
19282** On recent Windows platforms, the localtime_s() function is available
19283** as part of the "Secure CRT". It is essentially equivalent to
19284** localtime_r() available under most POSIX platforms, except that the
19285** order of the parameters is reversed.
19286**
19287** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
19288**
19289** If the user has not indicated to use localtime_r() or localtime_s()
19290** already, check for an MSVC build environment that provides
19291** localtime_s().
19292*/
19293#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
19294    && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
19295#undef  HAVE_LOCALTIME_S
19296#define HAVE_LOCALTIME_S 1
19297#endif
19298
19299/*
19300** The following routine implements the rough equivalent of localtime_r()
19301** using whatever operating-system specific localtime facility that
19302** is available.  This routine returns 0 on success and
19303** non-zero on any kind of error.
19304**
19305** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
19306** routine will always fail.
19307**
19308** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
19309** library function localtime_r() is used to assist in the calculation of
19310** local time.
19311*/
19312static int osLocaltime(time_t *t, struct tm *pTm){
19313  int rc;
19314#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
19315  struct tm *pX;
19316#if SQLITE_THREADSAFE>0
19317  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
19318#endif
19319  sqlite3_mutex_enter(mutex);
19320  pX = localtime(t);
19321#ifndef SQLITE_UNTESTABLE
19322  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
19323#endif
19324  if( pX ) *pTm = *pX;
19325  sqlite3_mutex_leave(mutex);
19326  rc = pX==0;
19327#else
19328#ifndef SQLITE_UNTESTABLE
19329  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
19330#endif
19331#if HAVE_LOCALTIME_R
19332  rc = localtime_r(t, pTm)==0;
19333#else
19334  rc = localtime_s(pTm, t);
19335#endif /* HAVE_LOCALTIME_R */
19336#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
19337  return rc;
19338}
19339#endif /* SQLITE_OMIT_LOCALTIME */
19340
19341
19342#ifndef SQLITE_OMIT_LOCALTIME
19343/*
19344** Compute the difference (in milliseconds) between localtime and UTC
19345** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
19346** return this value and set *pRc to SQLITE_OK.
19347**
19348** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
19349** is undefined in this case.
19350*/
19351static sqlite3_int64 localtimeOffset(
19352  DateTime *p,                    /* Date at which to calculate offset */
19353  sqlite3_context *pCtx,          /* Write error here if one occurs */
19354  int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
19355){
19356  DateTime x, y;
19357  time_t t;
19358  struct tm sLocal;
19359
19360  /* Initialize the contents of sLocal to avoid a compiler warning. */
19361  memset(&sLocal, 0, sizeof(sLocal));
19362
19363  x = *p;
19364  computeYMD_HMS(&x);
19365  if( x.Y<1971 || x.Y>=2038 ){
19366    /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
19367    ** works for years between 1970 and 2037. For dates outside this range,
19368    ** SQLite attempts to map the year into an equivalent year within this
19369    ** range, do the calculation, then map the year back.
19370    */
19371    x.Y = 2000;
19372    x.M = 1;
19373    x.D = 1;
19374    x.h = 0;
19375    x.m = 0;
19376    x.s = 0.0;
19377  } else {
19378    int s = (int)(x.s + 0.5);
19379    x.s = s;
19380  }
19381  x.tz = 0;
19382  x.validJD = 0;
19383  computeJD(&x);
19384  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
19385  if( osLocaltime(&t, &sLocal) ){
19386    sqlite3_result_error(pCtx, "local time unavailable", -1);
19387    *pRc = SQLITE_ERROR;
19388    return 0;
19389  }
19390  y.Y = sLocal.tm_year + 1900;
19391  y.M = sLocal.tm_mon + 1;
19392  y.D = sLocal.tm_mday;
19393  y.h = sLocal.tm_hour;
19394  y.m = sLocal.tm_min;
19395  y.s = sLocal.tm_sec;
19396  y.validYMD = 1;
19397  y.validHMS = 1;
19398  y.validJD = 0;
19399  y.rawS = 0;
19400  y.validTZ = 0;
19401  y.isError = 0;
19402  computeJD(&y);
19403  *pRc = SQLITE_OK;
19404  return y.iJD - x.iJD;
19405}
19406#endif /* SQLITE_OMIT_LOCALTIME */
19407
19408/*
19409** The following table defines various date transformations of the form
19410**
19411**            'NNN days'
19412**
19413** Where NNN is an arbitrary floating-point number and "days" can be one
19414** of several units of time.
19415*/
19416static const struct {
19417  u8 eType;           /* Transformation type code */
19418  u8 nName;           /* Length of th name */
19419  char *zName;        /* Name of the transformation */
19420  double rLimit;      /* Maximum NNN value for this transform */
19421  double rXform;      /* Constant used for this transform */
19422} aXformType[] = {
19423  { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
19424  { 0, 6, "minute", 7737817680.0,   86400000.0/(24.0*60.0)      },
19425  { 0, 4, "hour",   128963628.0,    86400000.0/24.0             },
19426  { 0, 3, "day",    5373485.0,      86400000.0                  },
19427  { 1, 5, "month",  176546.0,       30.0*86400000.0             },
19428  { 2, 4, "year",   14713.0,        365.0*86400000.0            },
19429};
19430
19431/*
19432** Process a modifier to a date-time stamp.  The modifiers are
19433** as follows:
19434**
19435**     NNN days
19436**     NNN hours
19437**     NNN minutes
19438**     NNN.NNNN seconds
19439**     NNN months
19440**     NNN years
19441**     start of month
19442**     start of year
19443**     start of week
19444**     start of day
19445**     weekday N
19446**     unixepoch
19447**     localtime
19448**     utc
19449**
19450** Return 0 on success and 1 if there is any kind of error. If the error
19451** is in a system call (i.e. localtime()), then an error message is written
19452** to context pCtx. If the error is an unrecognized modifier, no error is
19453** written to pCtx.
19454*/
19455static int parseModifier(
19456  sqlite3_context *pCtx,      /* Function context */
19457  const char *z,              /* The text of the modifier */
19458  int n,                      /* Length of zMod in bytes */
19459  DateTime *p                 /* The date/time value to be modified */
19460){
19461  int rc = 1;
19462  double r;
19463  switch(sqlite3UpperToLower[(u8)z[0]] ){
19464#ifndef SQLITE_OMIT_LOCALTIME
19465    case 'l': {
19466      /*    localtime
19467      **
19468      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
19469      ** show local time.
19470      */
19471      if( sqlite3_stricmp(z, "localtime")==0 ){
19472        computeJD(p);
19473        p->iJD += localtimeOffset(p, pCtx, &rc);
19474        clearYMD_HMS_TZ(p);
19475      }
19476      break;
19477    }
19478#endif
19479    case 'u': {
19480      /*
19481      **    unixepoch
19482      **
19483      ** Treat the current value of p->s as the number of
19484      ** seconds since 1970.  Convert to a real julian day number.
19485      */
19486      if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
19487        r = p->s*1000.0 + 210866760000000.0;
19488        if( r>=0.0 && r<464269060800000.0 ){
19489          clearYMD_HMS_TZ(p);
19490          p->iJD = (sqlite3_int64)r;
19491          p->validJD = 1;
19492          p->rawS = 0;
19493          rc = 0;
19494        }
19495      }
19496#ifndef SQLITE_OMIT_LOCALTIME
19497      else if( sqlite3_stricmp(z, "utc")==0 ){
19498        if( p->tzSet==0 ){
19499          sqlite3_int64 c1;
19500          computeJD(p);
19501          c1 = localtimeOffset(p, pCtx, &rc);
19502          if( rc==SQLITE_OK ){
19503            p->iJD -= c1;
19504            clearYMD_HMS_TZ(p);
19505            p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
19506          }
19507          p->tzSet = 1;
19508        }else{
19509          rc = SQLITE_OK;
19510        }
19511      }
19512#endif
19513      break;
19514    }
19515    case 'w': {
19516      /*
19517      **    weekday N
19518      **
19519      ** Move the date to the same time on the next occurrence of
19520      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
19521      ** date is already on the appropriate weekday, this is a no-op.
19522      */
19523      if( sqlite3_strnicmp(z, "weekday ", 8)==0
19524               && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
19525               && (n=(int)r)==r && n>=0 && r<7 ){
19526        sqlite3_int64 Z;
19527        computeYMD_HMS(p);
19528        p->validTZ = 0;
19529        p->validJD = 0;
19530        computeJD(p);
19531        Z = ((p->iJD + 129600000)/86400000) % 7;
19532        if( Z>n ) Z -= 7;
19533        p->iJD += (n - Z)*86400000;
19534        clearYMD_HMS_TZ(p);
19535        rc = 0;
19536      }
19537      break;
19538    }
19539    case 's': {
19540      /*
19541      **    start of TTTTT
19542      **
19543      ** Move the date backwards to the beginning of the current day,
19544      ** or month or year.
19545      */
19546      if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
19547      if( !p->validJD && !p->validYMD && !p->validHMS ) break;
19548      z += 9;
19549      computeYMD(p);
19550      p->validHMS = 1;
19551      p->h = p->m = 0;
19552      p->s = 0.0;
19553      p->rawS = 0;
19554      p->validTZ = 0;
19555      p->validJD = 0;
19556      if( sqlite3_stricmp(z,"month")==0 ){
19557        p->D = 1;
19558        rc = 0;
19559      }else if( sqlite3_stricmp(z,"year")==0 ){
19560        p->M = 1;
19561        p->D = 1;
19562        rc = 0;
19563      }else if( sqlite3_stricmp(z,"day")==0 ){
19564        rc = 0;
19565      }
19566      break;
19567    }
19568    case '+':
19569    case '-':
19570    case '0':
19571    case '1':
19572    case '2':
19573    case '3':
19574    case '4':
19575    case '5':
19576    case '6':
19577    case '7':
19578    case '8':
19579    case '9': {
19580      double rRounder;
19581      int i;
19582      for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
19583      if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
19584        rc = 1;
19585        break;
19586      }
19587      if( z[n]==':' ){
19588        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
19589        ** specified number of hours, minutes, seconds, and fractional seconds
19590        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
19591        ** omitted.
19592        */
19593        const char *z2 = z;
19594        DateTime tx;
19595        sqlite3_int64 day;
19596        if( !sqlite3Isdigit(*z2) ) z2++;
19597        memset(&tx, 0, sizeof(tx));
19598        if( parseHhMmSs(z2, &tx) ) break;
19599        computeJD(&tx);
19600        tx.iJD -= 43200000;
19601        day = tx.iJD/86400000;
19602        tx.iJD -= day*86400000;
19603        if( z[0]=='-' ) tx.iJD = -tx.iJD;
19604        computeJD(p);
19605        clearYMD_HMS_TZ(p);
19606        p->iJD += tx.iJD;
19607        rc = 0;
19608        break;
19609      }
19610
19611      /* If control reaches this point, it means the transformation is
19612      ** one of the forms like "+NNN days".  */
19613      z += n;
19614      while( sqlite3Isspace(*z) ) z++;
19615      n = sqlite3Strlen30(z);
19616      if( n>10 || n<3 ) break;
19617      if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
19618      computeJD(p);
19619      rc = 1;
19620      rRounder = r<0 ? -0.5 : +0.5;
19621      for(i=0; i<ArraySize(aXformType); i++){
19622        if( aXformType[i].nName==n
19623         && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
19624         && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
19625        ){
19626          switch( aXformType[i].eType ){
19627            case 1: { /* Special processing to add months */
19628              int x;
19629              computeYMD_HMS(p);
19630              p->M += (int)r;
19631              x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
19632              p->Y += x;
19633              p->M -= x*12;
19634              p->validJD = 0;
19635              r -= (int)r;
19636              break;
19637            }
19638            case 2: { /* Special processing to add years */
19639              int y = (int)r;
19640              computeYMD_HMS(p);
19641              p->Y += y;
19642              p->validJD = 0;
19643              r -= (int)r;
19644              break;
19645            }
19646          }
19647          computeJD(p);
19648          p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
19649          rc = 0;
19650          break;
19651        }
19652      }
19653      clearYMD_HMS_TZ(p);
19654      break;
19655    }
19656    default: {
19657      break;
19658    }
19659  }
19660  return rc;
19661}
19662
19663/*
19664** Process time function arguments.  argv[0] is a date-time stamp.
19665** argv[1] and following are modifiers.  Parse them all and write
19666** the resulting time into the DateTime structure p.  Return 0
19667** on success and 1 if there are any errors.
19668**
19669** If there are zero parameters (if even argv[0] is undefined)
19670** then assume a default value of "now" for argv[0].
19671*/
19672static int isDate(
19673  sqlite3_context *context,
19674  int argc,
19675  sqlite3_value **argv,
19676  DateTime *p
19677){
19678  int i, n;
19679  const unsigned char *z;
19680  int eType;
19681  memset(p, 0, sizeof(*p));
19682  if( argc==0 ){
19683    return setDateTimeToCurrent(context, p);
19684  }
19685  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
19686                   || eType==SQLITE_INTEGER ){
19687    setRawDateNumber(p, sqlite3_value_double(argv[0]));
19688  }else{
19689    z = sqlite3_value_text(argv[0]);
19690    if( !z || parseDateOrTime(context, (char*)z, p) ){
19691      return 1;
19692    }
19693  }
19694  for(i=1; i<argc; i++){
19695    z = sqlite3_value_text(argv[i]);
19696    n = sqlite3_value_bytes(argv[i]);
19697    if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
19698  }
19699  computeJD(p);
19700  if( p->isError || !validJulianDay(p->iJD) ) return 1;
19701  return 0;
19702}
19703
19704
19705/*
19706** The following routines implement the various date and time functions
19707** of SQLite.
19708*/
19709
19710/*
19711**    julianday( TIMESTRING, MOD, MOD, ...)
19712**
19713** Return the julian day number of the date specified in the arguments
19714*/
19715static void juliandayFunc(
19716  sqlite3_context *context,
19717  int argc,
19718  sqlite3_value **argv
19719){
19720  DateTime x;
19721  if( isDate(context, argc, argv, &x)==0 ){
19722    computeJD(&x);
19723    sqlite3_result_double(context, x.iJD/86400000.0);
19724  }
19725}
19726
19727/*
19728**    datetime( TIMESTRING, MOD, MOD, ...)
19729**
19730** Return YYYY-MM-DD HH:MM:SS
19731*/
19732static void datetimeFunc(
19733  sqlite3_context *context,
19734  int argc,
19735  sqlite3_value **argv
19736){
19737  DateTime x;
19738  if( isDate(context, argc, argv, &x)==0 ){
19739    char zBuf[100];
19740    computeYMD_HMS(&x);
19741    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
19742                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
19743    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19744  }
19745}
19746
19747/*
19748**    time( TIMESTRING, MOD, MOD, ...)
19749**
19750** Return HH:MM:SS
19751*/
19752static void timeFunc(
19753  sqlite3_context *context,
19754  int argc,
19755  sqlite3_value **argv
19756){
19757  DateTime x;
19758  if( isDate(context, argc, argv, &x)==0 ){
19759    char zBuf[100];
19760    computeHMS(&x);
19761    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
19762    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19763  }
19764}
19765
19766/*
19767**    date( TIMESTRING, MOD, MOD, ...)
19768**
19769** Return YYYY-MM-DD
19770*/
19771static void dateFunc(
19772  sqlite3_context *context,
19773  int argc,
19774  sqlite3_value **argv
19775){
19776  DateTime x;
19777  if( isDate(context, argc, argv, &x)==0 ){
19778    char zBuf[100];
19779    computeYMD(&x);
19780    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
19781    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19782  }
19783}
19784
19785/*
19786**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
19787**
19788** Return a string described by FORMAT.  Conversions as follows:
19789**
19790**   %d  day of month
19791**   %f  ** fractional seconds  SS.SSS
19792**   %H  hour 00-24
19793**   %j  day of year 000-366
19794**   %J  ** julian day number
19795**   %m  month 01-12
19796**   %M  minute 00-59
19797**   %s  seconds since 1970-01-01
19798**   %S  seconds 00-59
19799**   %w  day of week 0-6  sunday==0
19800**   %W  week of year 00-53
19801**   %Y  year 0000-9999
19802**   %%  %
19803*/
19804static void strftimeFunc(
19805  sqlite3_context *context,
19806  int argc,
19807  sqlite3_value **argv
19808){
19809  DateTime x;
19810  u64 n;
19811  size_t i,j;
19812  char *z;
19813  sqlite3 *db;
19814  const char *zFmt;
19815  char zBuf[100];
19816  if( argc==0 ) return;
19817  zFmt = (const char*)sqlite3_value_text(argv[0]);
19818  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
19819  db = sqlite3_context_db_handle(context);
19820  for(i=0, n=1; zFmt[i]; i++, n++){
19821    if( zFmt[i]=='%' ){
19822      switch( zFmt[i+1] ){
19823        case 'd':
19824        case 'H':
19825        case 'm':
19826        case 'M':
19827        case 'S':
19828        case 'W':
19829          n++;
19830          /* fall thru */
19831        case 'w':
19832        case '%':
19833          break;
19834        case 'f':
19835          n += 8;
19836          break;
19837        case 'j':
19838          n += 3;
19839          break;
19840        case 'Y':
19841          n += 8;
19842          break;
19843        case 's':
19844        case 'J':
19845          n += 50;
19846          break;
19847        default:
19848          return;  /* ERROR.  return a NULL */
19849      }
19850      i++;
19851    }
19852  }
19853  testcase( n==sizeof(zBuf)-1 );
19854  testcase( n==sizeof(zBuf) );
19855  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
19856  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
19857  if( n<sizeof(zBuf) ){
19858    z = zBuf;
19859  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
19860    sqlite3_result_error_toobig(context);
19861    return;
19862  }else{
19863    z = sqlite3DbMallocRawNN(db, (int)n);
19864    if( z==0 ){
19865      sqlite3_result_error_nomem(context);
19866      return;
19867    }
19868  }
19869  computeJD(&x);
19870  computeYMD_HMS(&x);
19871  for(i=j=0; zFmt[i]; i++){
19872    if( zFmt[i]!='%' ){
19873      z[j++] = zFmt[i];
19874    }else{
19875      i++;
19876      switch( zFmt[i] ){
19877        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
19878        case 'f': {
19879          double s = x.s;
19880          if( s>59.999 ) s = 59.999;
19881          sqlite3_snprintf(7, &z[j],"%06.3f", s);
19882          j += sqlite3Strlen30(&z[j]);
19883          break;
19884        }
19885        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
19886        case 'W': /* Fall thru */
19887        case 'j': {
19888          int nDay;             /* Number of days since 1st day of year */
19889          DateTime y = x;
19890          y.validJD = 0;
19891          y.M = 1;
19892          y.D = 1;
19893          computeJD(&y);
19894          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
19895          if( zFmt[i]=='W' ){
19896            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
19897            wd = (int)(((x.iJD+43200000)/86400000)%7);
19898            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
19899            j += 2;
19900          }else{
19901            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
19902            j += 3;
19903          }
19904          break;
19905        }
19906        case 'J': {
19907          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
19908          j+=sqlite3Strlen30(&z[j]);
19909          break;
19910        }
19911        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
19912        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
19913        case 's': {
19914          sqlite3_snprintf(30,&z[j],"%lld",
19915                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
19916          j += sqlite3Strlen30(&z[j]);
19917          break;
19918        }
19919        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
19920        case 'w': {
19921          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
19922          break;
19923        }
19924        case 'Y': {
19925          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
19926          break;
19927        }
19928        default:   z[j++] = '%'; break;
19929      }
19930    }
19931  }
19932  z[j] = 0;
19933  sqlite3_result_text(context, z, -1,
19934                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
19935}
19936
19937/*
19938** current_time()
19939**
19940** This function returns the same value as time('now').
19941*/
19942static void ctimeFunc(
19943  sqlite3_context *context,
19944  int NotUsed,
19945  sqlite3_value **NotUsed2
19946){
19947  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19948  timeFunc(context, 0, 0);
19949}
19950
19951/*
19952** current_date()
19953**
19954** This function returns the same value as date('now').
19955*/
19956static void cdateFunc(
19957  sqlite3_context *context,
19958  int NotUsed,
19959  sqlite3_value **NotUsed2
19960){
19961  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19962  dateFunc(context, 0, 0);
19963}
19964
19965/*
19966** current_timestamp()
19967**
19968** This function returns the same value as datetime('now').
19969*/
19970static void ctimestampFunc(
19971  sqlite3_context *context,
19972  int NotUsed,
19973  sqlite3_value **NotUsed2
19974){
19975  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19976  datetimeFunc(context, 0, 0);
19977}
19978#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
19979
19980#ifdef SQLITE_OMIT_DATETIME_FUNCS
19981/*
19982** If the library is compiled to omit the full-scale date and time
19983** handling (to get a smaller binary), the following minimal version
19984** of the functions current_time(), current_date() and current_timestamp()
19985** are included instead. This is to support column declarations that
19986** include "DEFAULT CURRENT_TIME" etc.
19987**
19988** This function uses the C-library functions time(), gmtime()
19989** and strftime(). The format string to pass to strftime() is supplied
19990** as the user-data for the function.
19991*/
19992static void currentTimeFunc(
19993  sqlite3_context *context,
19994  int argc,
19995  sqlite3_value **argv
19996){
19997  time_t t;
19998  char *zFormat = (char *)sqlite3_user_data(context);
19999  sqlite3_int64 iT;
20000  struct tm *pTm;
20001  struct tm sNow;
20002  char zBuf[20];
20003
20004  UNUSED_PARAMETER(argc);
20005  UNUSED_PARAMETER(argv);
20006
20007  iT = sqlite3StmtCurrentTime(context);
20008  if( iT<=0 ) return;
20009  t = iT/1000 - 10000*(sqlite3_int64)21086676;
20010#if HAVE_GMTIME_R
20011  pTm = gmtime_r(&t, &sNow);
20012#else
20013  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
20014  pTm = gmtime(&t);
20015  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
20016  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
20017#endif
20018  if( pTm ){
20019    strftime(zBuf, 20, zFormat, &sNow);
20020    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
20021  }
20022}
20023#endif
20024
20025/*
20026** This function registered all of the above C functions as SQL
20027** functions.  This should be the only routine in this file with
20028** external linkage.
20029*/
20030SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
20031  static FuncDef aDateTimeFuncs[] = {
20032#ifndef SQLITE_OMIT_DATETIME_FUNCS
20033    DFUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
20034    DFUNCTION(date,             -1, 0, 0, dateFunc      ),
20035    DFUNCTION(time,             -1, 0, 0, timeFunc      ),
20036    DFUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
20037    DFUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
20038    DFUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
20039    DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
20040    DFUNCTION(current_date,      0, 0, 0, cdateFunc     ),
20041#else
20042    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
20043    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
20044    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
20045#endif
20046  };
20047  sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
20048}
20049
20050/************** End of date.c ************************************************/
20051/************** Begin file os.c **********************************************/
20052/*
20053** 2005 November 29
20054**
20055** The author disclaims copyright to this source code.  In place of
20056** a legal notice, here is a blessing:
20057**
20058**    May you do good and not evil.
20059**    May you find forgiveness for yourself and forgive others.
20060**    May you share freely, never taking more than you give.
20061**
20062******************************************************************************
20063**
20064** This file contains OS interface code that is common to all
20065** architectures.
20066*/
20067/* #include "sqliteInt.h" */
20068
20069/*
20070** If we compile with the SQLITE_TEST macro set, then the following block
20071** of code will give us the ability to simulate a disk I/O error.  This
20072** is used for testing the I/O recovery logic.
20073*/
20074#if defined(SQLITE_TEST)
20075SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
20076SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
20077SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
20078SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
20079SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
20080SQLITE_API int sqlite3_diskfull_pending = 0;
20081SQLITE_API int sqlite3_diskfull = 0;
20082#endif /* defined(SQLITE_TEST) */
20083
20084/*
20085** When testing, also keep a count of the number of open files.
20086*/
20087#if defined(SQLITE_TEST)
20088SQLITE_API int sqlite3_open_file_count = 0;
20089#endif /* defined(SQLITE_TEST) */
20090
20091/*
20092** The default SQLite sqlite3_vfs implementations do not allocate
20093** memory (actually, os_unix.c allocates a small amount of memory
20094** from within OsOpen()), but some third-party implementations may.
20095** So we test the effects of a malloc() failing and the sqlite3OsXXX()
20096** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
20097**
20098** The following functions are instrumented for malloc() failure
20099** testing:
20100**
20101**     sqlite3OsRead()
20102**     sqlite3OsWrite()
20103**     sqlite3OsSync()
20104**     sqlite3OsFileSize()
20105**     sqlite3OsLock()
20106**     sqlite3OsCheckReservedLock()
20107**     sqlite3OsFileControl()
20108**     sqlite3OsShmMap()
20109**     sqlite3OsOpen()
20110**     sqlite3OsDelete()
20111**     sqlite3OsAccess()
20112**     sqlite3OsFullPathname()
20113**
20114*/
20115#if defined(SQLITE_TEST)
20116SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
20117  #define DO_OS_MALLOC_TEST(x)                                       \
20118  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
20119    void *pTstAlloc = sqlite3Malloc(10);                             \
20120    if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT;                  \
20121    sqlite3_free(pTstAlloc);                                         \
20122  }
20123#else
20124  #define DO_OS_MALLOC_TEST(x)
20125#endif
20126
20127/*
20128** The following routines are convenience wrappers around methods
20129** of the sqlite3_file object.  This is mostly just syntactic sugar. All
20130** of this would be completely automatic if SQLite were coded using
20131** C++ instead of plain old C.
20132*/
20133SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
20134  if( pId->pMethods ){
20135    pId->pMethods->xClose(pId);
20136    pId->pMethods = 0;
20137  }
20138}
20139SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
20140  DO_OS_MALLOC_TEST(id);
20141  return id->pMethods->xRead(id, pBuf, amt, offset);
20142}
20143SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
20144  DO_OS_MALLOC_TEST(id);
20145  return id->pMethods->xWrite(id, pBuf, amt, offset);
20146}
20147SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
20148  return id->pMethods->xTruncate(id, size);
20149}
20150SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
20151  DO_OS_MALLOC_TEST(id);
20152  return id->pMethods->xSync(id, flags);
20153}
20154SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
20155  DO_OS_MALLOC_TEST(id);
20156  return id->pMethods->xFileSize(id, pSize);
20157}
20158SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
20159  DO_OS_MALLOC_TEST(id);
20160  return id->pMethods->xLock(id, lockType);
20161}
20162SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
20163  return id->pMethods->xUnlock(id, lockType);
20164}
20165SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
20166  DO_OS_MALLOC_TEST(id);
20167  return id->pMethods->xCheckReservedLock(id, pResOut);
20168}
20169
20170/*
20171** Use sqlite3OsFileControl() when we are doing something that might fail
20172** and we need to know about the failures.  Use sqlite3OsFileControlHint()
20173** when simply tossing information over the wall to the VFS and we do not
20174** really care if the VFS receives and understands the information since it
20175** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
20176** routine has no return value since the return value would be meaningless.
20177*/
20178SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
20179#ifdef SQLITE_TEST
20180  if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
20181    /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
20182    ** is using a regular VFS, it is called after the corresponding
20183    ** transaction has been committed. Injecting a fault at this point
20184    ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
20185    ** but the transaction is committed anyway.
20186    **
20187    ** The core must call OsFileControl() though, not OsFileControlHint(),
20188    ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
20189    ** means the commit really has failed and an error should be returned
20190    ** to the user.  */
20191    DO_OS_MALLOC_TEST(id);
20192  }
20193#endif
20194  return id->pMethods->xFileControl(id, op, pArg);
20195}
20196SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
20197  (void)id->pMethods->xFileControl(id, op, pArg);
20198}
20199
20200SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
20201  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
20202  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
20203}
20204SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
20205  return id->pMethods->xDeviceCharacteristics(id);
20206}
20207SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
20208  return id->pMethods->xShmLock(id, offset, n, flags);
20209}
20210SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
20211  id->pMethods->xShmBarrier(id);
20212}
20213SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
20214  return id->pMethods->xShmUnmap(id, deleteFlag);
20215}
20216SQLITE_PRIVATE int sqlite3OsShmMap(
20217  sqlite3_file *id,               /* Database file handle */
20218  int iPage,
20219  int pgsz,
20220  int bExtend,                    /* True to extend file if necessary */
20221  void volatile **pp              /* OUT: Pointer to mapping */
20222){
20223  DO_OS_MALLOC_TEST(id);
20224  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
20225}
20226
20227#if SQLITE_MAX_MMAP_SIZE>0
20228/* The real implementation of xFetch and xUnfetch */
20229SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
20230  DO_OS_MALLOC_TEST(id);
20231  return id->pMethods->xFetch(id, iOff, iAmt, pp);
20232}
20233SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
20234  return id->pMethods->xUnfetch(id, iOff, p);
20235}
20236#else
20237/* No-op stubs to use when memory-mapped I/O is disabled */
20238SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
20239  *pp = 0;
20240  return SQLITE_OK;
20241}
20242SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
20243  return SQLITE_OK;
20244}
20245#endif
20246
20247/*
20248** The next group of routines are convenience wrappers around the
20249** VFS methods.
20250*/
20251SQLITE_PRIVATE int sqlite3OsOpen(
20252  sqlite3_vfs *pVfs,
20253  const char *zPath,
20254  sqlite3_file *pFile,
20255  int flags,
20256  int *pFlagsOut
20257){
20258  int rc;
20259  DO_OS_MALLOC_TEST(0);
20260  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
20261  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
20262  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
20263  ** reaching the VFS. */
20264  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
20265  assert( rc==SQLITE_OK || pFile->pMethods==0 );
20266  return rc;
20267}
20268SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
20269  DO_OS_MALLOC_TEST(0);
20270  assert( dirSync==0 || dirSync==1 );
20271  return pVfs->xDelete(pVfs, zPath, dirSync);
20272}
20273SQLITE_PRIVATE int sqlite3OsAccess(
20274  sqlite3_vfs *pVfs,
20275  const char *zPath,
20276  int flags,
20277  int *pResOut
20278){
20279  DO_OS_MALLOC_TEST(0);
20280  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
20281}
20282SQLITE_PRIVATE int sqlite3OsFullPathname(
20283  sqlite3_vfs *pVfs,
20284  const char *zPath,
20285  int nPathOut,
20286  char *zPathOut
20287){
20288  DO_OS_MALLOC_TEST(0);
20289  zPathOut[0] = 0;
20290  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
20291}
20292#ifndef SQLITE_OMIT_LOAD_EXTENSION
20293SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
20294  return pVfs->xDlOpen(pVfs, zPath);
20295}
20296SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
20297  pVfs->xDlError(pVfs, nByte, zBufOut);
20298}
20299SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
20300  return pVfs->xDlSym(pVfs, pHdle, zSym);
20301}
20302SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
20303  pVfs->xDlClose(pVfs, pHandle);
20304}
20305#endif /* SQLITE_OMIT_LOAD_EXTENSION */
20306SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
20307  return pVfs->xRandomness(pVfs, nByte, zBufOut);
20308}
20309SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
20310  return pVfs->xSleep(pVfs, nMicro);
20311}
20312SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
20313  return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
20314}
20315SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
20316  int rc;
20317  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
20318  ** method to get the current date and time if that method is available
20319  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
20320  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
20321  ** unavailable.
20322  */
20323  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
20324    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
20325  }else{
20326    double r;
20327    rc = pVfs->xCurrentTime(pVfs, &r);
20328    *pTimeOut = (sqlite3_int64)(r*86400000.0);
20329  }
20330  return rc;
20331}
20332
20333SQLITE_PRIVATE int sqlite3OsOpenMalloc(
20334  sqlite3_vfs *pVfs,
20335  const char *zFile,
20336  sqlite3_file **ppFile,
20337  int flags,
20338  int *pOutFlags
20339){
20340  int rc;
20341  sqlite3_file *pFile;
20342  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
20343  if( pFile ){
20344    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
20345    if( rc!=SQLITE_OK ){
20346      sqlite3_free(pFile);
20347    }else{
20348      *ppFile = pFile;
20349    }
20350  }else{
20351    rc = SQLITE_NOMEM_BKPT;
20352  }
20353  return rc;
20354}
20355SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
20356  assert( pFile );
20357  sqlite3OsClose(pFile);
20358  sqlite3_free(pFile);
20359}
20360
20361/*
20362** This function is a wrapper around the OS specific implementation of
20363** sqlite3_os_init(). The purpose of the wrapper is to provide the
20364** ability to simulate a malloc failure, so that the handling of an
20365** error in sqlite3_os_init() by the upper layers can be tested.
20366*/
20367SQLITE_PRIVATE int sqlite3OsInit(void){
20368  void *p = sqlite3_malloc(10);
20369  if( p==0 ) return SQLITE_NOMEM_BKPT;
20370  sqlite3_free(p);
20371  return sqlite3_os_init();
20372}
20373
20374/*
20375** The list of all registered VFS implementations.
20376*/
20377static sqlite3_vfs * SQLITE_WSD vfsList = 0;
20378#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
20379
20380/*
20381** Locate a VFS by name.  If no name is given, simply return the
20382** first VFS on the list.
20383*/
20384SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
20385  sqlite3_vfs *pVfs = 0;
20386#if SQLITE_THREADSAFE
20387  sqlite3_mutex *mutex;
20388#endif
20389#ifndef SQLITE_OMIT_AUTOINIT
20390  int rc = sqlite3_initialize();
20391  if( rc ) return 0;
20392#endif
20393#if SQLITE_THREADSAFE
20394  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
20395#endif
20396  sqlite3_mutex_enter(mutex);
20397  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
20398    if( zVfs==0 ) break;
20399    if( strcmp(zVfs, pVfs->zName)==0 ) break;
20400  }
20401  sqlite3_mutex_leave(mutex);
20402  return pVfs;
20403}
20404
20405/*
20406** Unlink a VFS from the linked list
20407*/
20408static void vfsUnlink(sqlite3_vfs *pVfs){
20409  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
20410  if( pVfs==0 ){
20411    /* No-op */
20412  }else if( vfsList==pVfs ){
20413    vfsList = pVfs->pNext;
20414  }else if( vfsList ){
20415    sqlite3_vfs *p = vfsList;
20416    while( p->pNext && p->pNext!=pVfs ){
20417      p = p->pNext;
20418    }
20419    if( p->pNext==pVfs ){
20420      p->pNext = pVfs->pNext;
20421    }
20422  }
20423}
20424
20425/*
20426** Register a VFS with the system.  It is harmless to register the same
20427** VFS multiple times.  The new VFS becomes the default if makeDflt is
20428** true.
20429*/
20430SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
20431  MUTEX_LOGIC(sqlite3_mutex *mutex;)
20432#ifndef SQLITE_OMIT_AUTOINIT
20433  int rc = sqlite3_initialize();
20434  if( rc ) return rc;
20435#endif
20436#ifdef SQLITE_ENABLE_API_ARMOR
20437  if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
20438#endif
20439
20440  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
20441  sqlite3_mutex_enter(mutex);
20442  vfsUnlink(pVfs);
20443  if( makeDflt || vfsList==0 ){
20444    pVfs->pNext = vfsList;
20445    vfsList = pVfs;
20446  }else{
20447    pVfs->pNext = vfsList->pNext;
20448    vfsList->pNext = pVfs;
20449  }
20450  assert(vfsList);
20451  sqlite3_mutex_leave(mutex);
20452  return SQLITE_OK;
20453}
20454
20455/*
20456** Unregister a VFS so that it is no longer accessible.
20457*/
20458SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
20459#if SQLITE_THREADSAFE
20460  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
20461#endif
20462  sqlite3_mutex_enter(mutex);
20463  vfsUnlink(pVfs);
20464  sqlite3_mutex_leave(mutex);
20465  return SQLITE_OK;
20466}
20467
20468/************** End of os.c **************************************************/
20469/************** Begin file fault.c *******************************************/
20470/*
20471** 2008 Jan 22
20472**
20473** The author disclaims copyright to this source code.  In place of
20474** a legal notice, here is a blessing:
20475**
20476**    May you do good and not evil.
20477**    May you find forgiveness for yourself and forgive others.
20478**    May you share freely, never taking more than you give.
20479**
20480*************************************************************************
20481**
20482** This file contains code to support the concept of "benign"
20483** malloc failures (when the xMalloc() or xRealloc() method of the
20484** sqlite3_mem_methods structure fails to allocate a block of memory
20485** and returns 0).
20486**
20487** Most malloc failures are non-benign. After they occur, SQLite
20488** abandons the current operation and returns an error code (usually
20489** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
20490** fatal. For example, if a malloc fails while resizing a hash table, this
20491** is completely recoverable simply by not carrying out the resize. The
20492** hash table will continue to function normally.  So a malloc failure
20493** during a hash table resize is a benign fault.
20494*/
20495
20496/* #include "sqliteInt.h" */
20497
20498#ifndef SQLITE_UNTESTABLE
20499
20500/*
20501** Global variables.
20502*/
20503typedef struct BenignMallocHooks BenignMallocHooks;
20504static SQLITE_WSD struct BenignMallocHooks {
20505  void (*xBenignBegin)(void);
20506  void (*xBenignEnd)(void);
20507} sqlite3Hooks = { 0, 0 };
20508
20509/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
20510** structure.  If writable static data is unsupported on the target,
20511** we have to locate the state vector at run-time.  In the more common
20512** case where writable static data is supported, wsdHooks can refer directly
20513** to the "sqlite3Hooks" state vector declared above.
20514*/
20515#ifdef SQLITE_OMIT_WSD
20516# define wsdHooksInit \
20517  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
20518# define wsdHooks x[0]
20519#else
20520# define wsdHooksInit
20521# define wsdHooks sqlite3Hooks
20522#endif
20523
20524
20525/*
20526** Register hooks to call when sqlite3BeginBenignMalloc() and
20527** sqlite3EndBenignMalloc() are called, respectively.
20528*/
20529SQLITE_PRIVATE void sqlite3BenignMallocHooks(
20530  void (*xBenignBegin)(void),
20531  void (*xBenignEnd)(void)
20532){
20533  wsdHooksInit;
20534  wsdHooks.xBenignBegin = xBenignBegin;
20535  wsdHooks.xBenignEnd = xBenignEnd;
20536}
20537
20538/*
20539** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
20540** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
20541** indicates that subsequent malloc failures are non-benign.
20542*/
20543SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
20544  wsdHooksInit;
20545  if( wsdHooks.xBenignBegin ){
20546    wsdHooks.xBenignBegin();
20547  }
20548}
20549SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
20550  wsdHooksInit;
20551  if( wsdHooks.xBenignEnd ){
20552    wsdHooks.xBenignEnd();
20553  }
20554}
20555
20556#endif   /* #ifndef SQLITE_UNTESTABLE */
20557
20558/************** End of fault.c ***********************************************/
20559/************** Begin file mem0.c ********************************************/
20560/*
20561** 2008 October 28
20562**
20563** The author disclaims copyright to this source code.  In place of
20564** a legal notice, here is a blessing:
20565**
20566**    May you do good and not evil.
20567**    May you find forgiveness for yourself and forgive others.
20568**    May you share freely, never taking more than you give.
20569**
20570*************************************************************************
20571**
20572** This file contains a no-op memory allocation drivers for use when
20573** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
20574** here always fail.  SQLite will not operate with these drivers.  These
20575** are merely placeholders.  Real drivers must be substituted using
20576** sqlite3_config() before SQLite will operate.
20577*/
20578/* #include "sqliteInt.h" */
20579
20580/*
20581** This version of the memory allocator is the default.  It is
20582** used when no other memory allocator is specified using compile-time
20583** macros.
20584*/
20585#ifdef SQLITE_ZERO_MALLOC
20586
20587/*
20588** No-op versions of all memory allocation routines
20589*/
20590static void *sqlite3MemMalloc(int nByte){ return 0; }
20591static void sqlite3MemFree(void *pPrior){ return; }
20592static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
20593static int sqlite3MemSize(void *pPrior){ return 0; }
20594static int sqlite3MemRoundup(int n){ return n; }
20595static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
20596static void sqlite3MemShutdown(void *NotUsed){ return; }
20597
20598/*
20599** This routine is the only routine in this file with external linkage.
20600**
20601** Populate the low-level memory allocation function pointers in
20602** sqlite3GlobalConfig.m with pointers to the routines in this file.
20603*/
20604SQLITE_PRIVATE void sqlite3MemSetDefault(void){
20605  static const sqlite3_mem_methods defaultMethods = {
20606     sqlite3MemMalloc,
20607     sqlite3MemFree,
20608     sqlite3MemRealloc,
20609     sqlite3MemSize,
20610     sqlite3MemRoundup,
20611     sqlite3MemInit,
20612     sqlite3MemShutdown,
20613     0
20614  };
20615  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20616}
20617
20618#endif /* SQLITE_ZERO_MALLOC */
20619
20620/************** End of mem0.c ************************************************/
20621/************** Begin file mem1.c ********************************************/
20622/*
20623** 2007 August 14
20624**
20625** The author disclaims copyright to this source code.  In place of
20626** a legal notice, here is a blessing:
20627**
20628**    May you do good and not evil.
20629**    May you find forgiveness for yourself and forgive others.
20630**    May you share freely, never taking more than you give.
20631**
20632*************************************************************************
20633**
20634** This file contains low-level memory allocation drivers for when
20635** SQLite will use the standard C-library malloc/realloc/free interface
20636** to obtain the memory it needs.
20637**
20638** This file contains implementations of the low-level memory allocation
20639** routines specified in the sqlite3_mem_methods object.  The content of
20640** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
20641** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
20642** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
20643** default configuration is to use memory allocation routines in this
20644** file.
20645**
20646** C-preprocessor macro summary:
20647**
20648**    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
20649**                                the malloc_usable_size() interface exists
20650**                                on the target platform.  Or, this symbol
20651**                                can be set manually, if desired.
20652**                                If an equivalent interface exists by
20653**                                a different name, using a separate -D
20654**                                option to rename it.
20655**
20656**    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
20657**                                memory allocator.  Set this symbol to enable
20658**                                building on older macs.
20659**
20660**    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
20661**                                _msize() on windows systems.  This might
20662**                                be necessary when compiling for Delphi,
20663**                                for example.
20664*/
20665/* #include "sqliteInt.h" */
20666
20667/*
20668** This version of the memory allocator is the default.  It is
20669** used when no other memory allocator is specified using compile-time
20670** macros.
20671*/
20672#ifdef SQLITE_SYSTEM_MALLOC
20673#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
20674
20675/*
20676** Use the zone allocator available on apple products unless the
20677** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
20678*/
20679#include <sys/sysctl.h>
20680#include <malloc/malloc.h>
20681#ifdef SQLITE_MIGHT_BE_SINGLE_CORE
20682#include <libkern/OSAtomic.h>
20683#endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
20684static malloc_zone_t* _sqliteZone_;
20685#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
20686#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
20687#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
20688#define SQLITE_MALLOCSIZE(x) \
20689        (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
20690
20691#else /* if not __APPLE__ */
20692
20693/*
20694** Use standard C library malloc and free on non-Apple systems.
20695** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
20696*/
20697#define SQLITE_MALLOC(x)             malloc(x)
20698#define SQLITE_FREE(x)               free(x)
20699#define SQLITE_REALLOC(x,y)          realloc((x),(y))
20700
20701/*
20702** The malloc.h header file is needed for malloc_usable_size() function
20703** on some systems (e.g. Linux).
20704*/
20705#if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
20706#  define SQLITE_USE_MALLOC_H 1
20707#  define SQLITE_USE_MALLOC_USABLE_SIZE 1
20708/*
20709** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
20710** use of _msize() is automatic, but can be disabled by compiling with
20711** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
20712** the malloc.h header file.
20713*/
20714#elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
20715#  define SQLITE_USE_MALLOC_H
20716#  define SQLITE_USE_MSIZE
20717#endif
20718
20719/*
20720** Include the malloc.h header file, if necessary.  Also set define macro
20721** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
20722** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
20723** The memory size function can always be overridden manually by defining
20724** the macro SQLITE_MALLOCSIZE to the desired function name.
20725*/
20726#if defined(SQLITE_USE_MALLOC_H)
20727#  include <malloc.h>
20728#  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
20729#    if !defined(SQLITE_MALLOCSIZE)
20730#      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
20731#    endif
20732#  elif defined(SQLITE_USE_MSIZE)
20733#    if !defined(SQLITE_MALLOCSIZE)
20734#      define SQLITE_MALLOCSIZE      _msize
20735#    endif
20736#  endif
20737#endif /* defined(SQLITE_USE_MALLOC_H) */
20738
20739#endif /* __APPLE__ or not __APPLE__ */
20740
20741/*
20742** Like malloc(), but remember the size of the allocation
20743** so that we can find it later using sqlite3MemSize().
20744**
20745** For this low-level routine, we are guaranteed that nByte>0 because
20746** cases of nByte<=0 will be intercepted and dealt with by higher level
20747** routines.
20748*/
20749static void *sqlite3MemMalloc(int nByte){
20750#ifdef SQLITE_MALLOCSIZE
20751  void *p;
20752  testcase( ROUND8(nByte)==nByte );
20753  p = SQLITE_MALLOC( nByte );
20754  if( p==0 ){
20755    testcase( sqlite3GlobalConfig.xLog!=0 );
20756    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
20757  }
20758  return p;
20759#else
20760  sqlite3_int64 *p;
20761  assert( nByte>0 );
20762  testcase( ROUND8(nByte)!=nByte );
20763  p = SQLITE_MALLOC( nByte+8 );
20764  if( p ){
20765    p[0] = nByte;
20766    p++;
20767  }else{
20768    testcase( sqlite3GlobalConfig.xLog!=0 );
20769    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
20770  }
20771  return (void *)p;
20772#endif
20773}
20774
20775/*
20776** Like free() but works for allocations obtained from sqlite3MemMalloc()
20777** or sqlite3MemRealloc().
20778**
20779** For this low-level routine, we already know that pPrior!=0 since
20780** cases where pPrior==0 will have been intecepted and dealt with
20781** by higher-level routines.
20782*/
20783static void sqlite3MemFree(void *pPrior){
20784#ifdef SQLITE_MALLOCSIZE
20785  SQLITE_FREE(pPrior);
20786#else
20787  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
20788  assert( pPrior!=0 );
20789  p--;
20790  SQLITE_FREE(p);
20791#endif
20792}
20793
20794/*
20795** Report the allocated size of a prior return from xMalloc()
20796** or xRealloc().
20797*/
20798static int sqlite3MemSize(void *pPrior){
20799#ifdef SQLITE_MALLOCSIZE
20800  assert( pPrior!=0 );
20801  return (int)SQLITE_MALLOCSIZE(pPrior);
20802#else
20803  sqlite3_int64 *p;
20804  assert( pPrior!=0 );
20805  p = (sqlite3_int64*)pPrior;
20806  p--;
20807  return (int)p[0];
20808#endif
20809}
20810
20811/*
20812** Like realloc().  Resize an allocation previously obtained from
20813** sqlite3MemMalloc().
20814**
20815** For this low-level interface, we know that pPrior!=0.  Cases where
20816** pPrior==0 while have been intercepted by higher-level routine and
20817** redirected to xMalloc.  Similarly, we know that nByte>0 because
20818** cases where nByte<=0 will have been intercepted by higher-level
20819** routines and redirected to xFree.
20820*/
20821static void *sqlite3MemRealloc(void *pPrior, int nByte){
20822#ifdef SQLITE_MALLOCSIZE
20823  void *p = SQLITE_REALLOC(pPrior, nByte);
20824  if( p==0 ){
20825    testcase( sqlite3GlobalConfig.xLog!=0 );
20826    sqlite3_log(SQLITE_NOMEM,
20827      "failed memory resize %u to %u bytes",
20828      SQLITE_MALLOCSIZE(pPrior), nByte);
20829  }
20830  return p;
20831#else
20832  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
20833  assert( pPrior!=0 && nByte>0 );
20834  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
20835  p--;
20836  p = SQLITE_REALLOC(p, nByte+8 );
20837  if( p ){
20838    p[0] = nByte;
20839    p++;
20840  }else{
20841    testcase( sqlite3GlobalConfig.xLog!=0 );
20842    sqlite3_log(SQLITE_NOMEM,
20843      "failed memory resize %u to %u bytes",
20844      sqlite3MemSize(pPrior), nByte);
20845  }
20846  return (void*)p;
20847#endif
20848}
20849
20850/*
20851** Round up a request size to the next valid allocation size.
20852*/
20853static int sqlite3MemRoundup(int n){
20854  return ROUND8(n);
20855}
20856
20857/*
20858** Initialize this module.
20859*/
20860static int sqlite3MemInit(void *NotUsed){
20861#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
20862  int cpuCount;
20863  size_t len;
20864  if( _sqliteZone_ ){
20865    return SQLITE_OK;
20866  }
20867  len = sizeof(cpuCount);
20868  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
20869  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
20870  if( cpuCount>1 ){
20871    /* defer MT decisions to system malloc */
20872    _sqliteZone_ = malloc_default_zone();
20873  }else{
20874    /* only 1 core, use our own zone to contention over global locks,
20875    ** e.g. we have our own dedicated locks */
20876    _sqliteZone_ = malloc_create_zone(4096, 0);
20877    malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
20878  }
20879#endif /*  defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
20880  UNUSED_PARAMETER(NotUsed);
20881  return SQLITE_OK;
20882}
20883
20884/*
20885** Deinitialize this module.
20886*/
20887static void sqlite3MemShutdown(void *NotUsed){
20888  UNUSED_PARAMETER(NotUsed);
20889  return;
20890}
20891
20892/*
20893** This routine is the only routine in this file with external linkage.
20894**
20895** Populate the low-level memory allocation function pointers in
20896** sqlite3GlobalConfig.m with pointers to the routines in this file.
20897*/
20898SQLITE_PRIVATE void sqlite3MemSetDefault(void){
20899  static const sqlite3_mem_methods defaultMethods = {
20900     sqlite3MemMalloc,
20901     sqlite3MemFree,
20902     sqlite3MemRealloc,
20903     sqlite3MemSize,
20904     sqlite3MemRoundup,
20905     sqlite3MemInit,
20906     sqlite3MemShutdown,
20907     0
20908  };
20909  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20910}
20911
20912#endif /* SQLITE_SYSTEM_MALLOC */
20913
20914/************** End of mem1.c ************************************************/
20915/************** Begin file mem2.c ********************************************/
20916/*
20917** 2007 August 15
20918**
20919** The author disclaims copyright to this source code.  In place of
20920** a legal notice, here is a blessing:
20921**
20922**    May you do good and not evil.
20923**    May you find forgiveness for yourself and forgive others.
20924**    May you share freely, never taking more than you give.
20925**
20926*************************************************************************
20927**
20928** This file contains low-level memory allocation drivers for when
20929** SQLite will use the standard C-library malloc/realloc/free interface
20930** to obtain the memory it needs while adding lots of additional debugging
20931** information to each allocation in order to help detect and fix memory
20932** leaks and memory usage errors.
20933**
20934** This file contains implementations of the low-level memory allocation
20935** routines specified in the sqlite3_mem_methods object.
20936*/
20937/* #include "sqliteInt.h" */
20938
20939/*
20940** This version of the memory allocator is used only if the
20941** SQLITE_MEMDEBUG macro is defined
20942*/
20943#ifdef SQLITE_MEMDEBUG
20944
20945/*
20946** The backtrace functionality is only available with GLIBC
20947*/
20948#ifdef __GLIBC__
20949  extern int backtrace(void**,int);
20950  extern void backtrace_symbols_fd(void*const*,int,int);
20951#else
20952# define backtrace(A,B) 1
20953# define backtrace_symbols_fd(A,B,C)
20954#endif
20955/* #include <stdio.h> */
20956
20957/*
20958** Each memory allocation looks like this:
20959**
20960**  ------------------------------------------------------------------------
20961**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
20962**  ------------------------------------------------------------------------
20963**
20964** The application code sees only a pointer to the allocation.  We have
20965** to back up from the allocation pointer to find the MemBlockHdr.  The
20966** MemBlockHdr tells us the size of the allocation and the number of
20967** backtrace pointers.  There is also a guard word at the end of the
20968** MemBlockHdr.
20969*/
20970struct MemBlockHdr {
20971  i64 iSize;                          /* Size of this allocation */
20972  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
20973  char nBacktrace;                    /* Number of backtraces on this alloc */
20974  char nBacktraceSlots;               /* Available backtrace slots */
20975  u8 nTitle;                          /* Bytes of title; includes '\0' */
20976  u8 eType;                           /* Allocation type code */
20977  int iForeGuard;                     /* Guard word for sanity */
20978};
20979
20980/*
20981** Guard words
20982*/
20983#define FOREGUARD 0x80F5E153
20984#define REARGUARD 0xE4676B53
20985
20986/*
20987** Number of malloc size increments to track.
20988*/
20989#define NCSIZE  1000
20990
20991/*
20992** All of the static variables used by this module are collected
20993** into a single structure named "mem".  This is to keep the
20994** static variables organized and to reduce namespace pollution
20995** when this module is combined with other in the amalgamation.
20996*/
20997static struct {
20998
20999  /*
21000  ** Mutex to control access to the memory allocation subsystem.
21001  */
21002  sqlite3_mutex *mutex;
21003
21004  /*
21005  ** Head and tail of a linked list of all outstanding allocations
21006  */
21007  struct MemBlockHdr *pFirst;
21008  struct MemBlockHdr *pLast;
21009
21010  /*
21011  ** The number of levels of backtrace to save in new allocations.
21012  */
21013  int nBacktrace;
21014  void (*xBacktrace)(int, int, void **);
21015
21016  /*
21017  ** Title text to insert in front of each block
21018  */
21019  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
21020  char zTitle[100];  /* The title text */
21021
21022  /*
21023  ** sqlite3MallocDisallow() increments the following counter.
21024  ** sqlite3MallocAllow() decrements it.
21025  */
21026  int disallow; /* Do not allow memory allocation */
21027
21028  /*
21029  ** Gather statistics on the sizes of memory allocations.
21030  ** nAlloc[i] is the number of allocation attempts of i*8
21031  ** bytes.  i==NCSIZE is the number of allocation attempts for
21032  ** sizes more than NCSIZE*8 bytes.
21033  */
21034  int nAlloc[NCSIZE];      /* Total number of allocations */
21035  int nCurrent[NCSIZE];    /* Current number of allocations */
21036  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
21037
21038} mem;
21039
21040
21041/*
21042** Adjust memory usage statistics
21043*/
21044static void adjustStats(int iSize, int increment){
21045  int i = ROUND8(iSize)/8;
21046  if( i>NCSIZE-1 ){
21047    i = NCSIZE - 1;
21048  }
21049  if( increment>0 ){
21050    mem.nAlloc[i]++;
21051    mem.nCurrent[i]++;
21052    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
21053      mem.mxCurrent[i] = mem.nCurrent[i];
21054    }
21055  }else{
21056    mem.nCurrent[i]--;
21057    assert( mem.nCurrent[i]>=0 );
21058  }
21059}
21060
21061/*
21062** Given an allocation, find the MemBlockHdr for that allocation.
21063**
21064** This routine checks the guards at either end of the allocation and
21065** if they are incorrect it asserts.
21066*/
21067static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
21068  struct MemBlockHdr *p;
21069  int *pInt;
21070  u8 *pU8;
21071  int nReserve;
21072
21073  p = (struct MemBlockHdr*)pAllocation;
21074  p--;
21075  assert( p->iForeGuard==(int)FOREGUARD );
21076  nReserve = ROUND8(p->iSize);
21077  pInt = (int*)pAllocation;
21078  pU8 = (u8*)pAllocation;
21079  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
21080  /* This checks any of the "extra" bytes allocated due
21081  ** to rounding up to an 8 byte boundary to ensure
21082  ** they haven't been overwritten.
21083  */
21084  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
21085  return p;
21086}
21087
21088/*
21089** Return the number of bytes currently allocated at address p.
21090*/
21091static int sqlite3MemSize(void *p){
21092  struct MemBlockHdr *pHdr;
21093  if( !p ){
21094    return 0;
21095  }
21096  pHdr = sqlite3MemsysGetHeader(p);
21097  return (int)pHdr->iSize;
21098}
21099
21100/*
21101** Initialize the memory allocation subsystem.
21102*/
21103static int sqlite3MemInit(void *NotUsed){
21104  UNUSED_PARAMETER(NotUsed);
21105  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
21106  if( !sqlite3GlobalConfig.bMemstat ){
21107    /* If memory status is enabled, then the malloc.c wrapper will already
21108    ** hold the STATIC_MEM mutex when the routines here are invoked. */
21109    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
21110  }
21111  return SQLITE_OK;
21112}
21113
21114/*
21115** Deinitialize the memory allocation subsystem.
21116*/
21117static void sqlite3MemShutdown(void *NotUsed){
21118  UNUSED_PARAMETER(NotUsed);
21119  mem.mutex = 0;
21120}
21121
21122/*
21123** Round up a request size to the next valid allocation size.
21124*/
21125static int sqlite3MemRoundup(int n){
21126  return ROUND8(n);
21127}
21128
21129/*
21130** Fill a buffer with pseudo-random bytes.  This is used to preset
21131** the content of a new memory allocation to unpredictable values and
21132** to clear the content of a freed allocation to unpredictable values.
21133*/
21134static void randomFill(char *pBuf, int nByte){
21135  unsigned int x, y, r;
21136  x = SQLITE_PTR_TO_INT(pBuf);
21137  y = nByte | 1;
21138  while( nByte >= 4 ){
21139    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
21140    y = y*1103515245 + 12345;
21141    r = x ^ y;
21142    *(int*)pBuf = r;
21143    pBuf += 4;
21144    nByte -= 4;
21145  }
21146  while( nByte-- > 0 ){
21147    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
21148    y = y*1103515245 + 12345;
21149    r = x ^ y;
21150    *(pBuf++) = r & 0xff;
21151  }
21152}
21153
21154/*
21155** Allocate nByte bytes of memory.
21156*/
21157static void *sqlite3MemMalloc(int nByte){
21158  struct MemBlockHdr *pHdr;
21159  void **pBt;
21160  char *z;
21161  int *pInt;
21162  void *p = 0;
21163  int totalSize;
21164  int nReserve;
21165  sqlite3_mutex_enter(mem.mutex);
21166  assert( mem.disallow==0 );
21167  nReserve = ROUND8(nByte);
21168  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
21169               mem.nBacktrace*sizeof(void*) + mem.nTitle;
21170  p = malloc(totalSize);
21171  if( p ){
21172    z = p;
21173    pBt = (void**)&z[mem.nTitle];
21174    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
21175    pHdr->pNext = 0;
21176    pHdr->pPrev = mem.pLast;
21177    if( mem.pLast ){
21178      mem.pLast->pNext = pHdr;
21179    }else{
21180      mem.pFirst = pHdr;
21181    }
21182    mem.pLast = pHdr;
21183    pHdr->iForeGuard = FOREGUARD;
21184    pHdr->eType = MEMTYPE_HEAP;
21185    pHdr->nBacktraceSlots = mem.nBacktrace;
21186    pHdr->nTitle = mem.nTitle;
21187    if( mem.nBacktrace ){
21188      void *aAddr[40];
21189      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
21190      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
21191      assert(pBt[0]);
21192      if( mem.xBacktrace ){
21193        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
21194      }
21195    }else{
21196      pHdr->nBacktrace = 0;
21197    }
21198    if( mem.nTitle ){
21199      memcpy(z, mem.zTitle, mem.nTitle);
21200    }
21201    pHdr->iSize = nByte;
21202    adjustStats(nByte, +1);
21203    pInt = (int*)&pHdr[1];
21204    pInt[nReserve/sizeof(int)] = REARGUARD;
21205    randomFill((char*)pInt, nByte);
21206    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
21207    p = (void*)pInt;
21208  }
21209  sqlite3_mutex_leave(mem.mutex);
21210  return p;
21211}
21212
21213/*
21214** Free memory.
21215*/
21216static void sqlite3MemFree(void *pPrior){
21217  struct MemBlockHdr *pHdr;
21218  void **pBt;
21219  char *z;
21220  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
21221       || mem.mutex!=0 );
21222  pHdr = sqlite3MemsysGetHeader(pPrior);
21223  pBt = (void**)pHdr;
21224  pBt -= pHdr->nBacktraceSlots;
21225  sqlite3_mutex_enter(mem.mutex);
21226  if( pHdr->pPrev ){
21227    assert( pHdr->pPrev->pNext==pHdr );
21228    pHdr->pPrev->pNext = pHdr->pNext;
21229  }else{
21230    assert( mem.pFirst==pHdr );
21231    mem.pFirst = pHdr->pNext;
21232  }
21233  if( pHdr->pNext ){
21234    assert( pHdr->pNext->pPrev==pHdr );
21235    pHdr->pNext->pPrev = pHdr->pPrev;
21236  }else{
21237    assert( mem.pLast==pHdr );
21238    mem.pLast = pHdr->pPrev;
21239  }
21240  z = (char*)pBt;
21241  z -= pHdr->nTitle;
21242  adjustStats((int)pHdr->iSize, -1);
21243  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
21244                (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
21245  free(z);
21246  sqlite3_mutex_leave(mem.mutex);
21247}
21248
21249/*
21250** Change the size of an existing memory allocation.
21251**
21252** For this debugging implementation, we *always* make a copy of the
21253** allocation into a new place in memory.  In this way, if the
21254** higher level code is using pointer to the old allocation, it is
21255** much more likely to break and we are much more liking to find
21256** the error.
21257*/
21258static void *sqlite3MemRealloc(void *pPrior, int nByte){
21259  struct MemBlockHdr *pOldHdr;
21260  void *pNew;
21261  assert( mem.disallow==0 );
21262  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
21263  pOldHdr = sqlite3MemsysGetHeader(pPrior);
21264  pNew = sqlite3MemMalloc(nByte);
21265  if( pNew ){
21266    memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
21267    if( nByte>pOldHdr->iSize ){
21268      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
21269    }
21270    sqlite3MemFree(pPrior);
21271  }
21272  return pNew;
21273}
21274
21275/*
21276** Populate the low-level memory allocation function pointers in
21277** sqlite3GlobalConfig.m with pointers to the routines in this file.
21278*/
21279SQLITE_PRIVATE void sqlite3MemSetDefault(void){
21280  static const sqlite3_mem_methods defaultMethods = {
21281     sqlite3MemMalloc,
21282     sqlite3MemFree,
21283     sqlite3MemRealloc,
21284     sqlite3MemSize,
21285     sqlite3MemRoundup,
21286     sqlite3MemInit,
21287     sqlite3MemShutdown,
21288     0
21289  };
21290  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
21291}
21292
21293/*
21294** Set the "type" of an allocation.
21295*/
21296SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
21297  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
21298    struct MemBlockHdr *pHdr;
21299    pHdr = sqlite3MemsysGetHeader(p);
21300    assert( pHdr->iForeGuard==FOREGUARD );
21301    pHdr->eType = eType;
21302  }
21303}
21304
21305/*
21306** Return TRUE if the mask of type in eType matches the type of the
21307** allocation p.  Also return true if p==NULL.
21308**
21309** This routine is designed for use within an assert() statement, to
21310** verify the type of an allocation.  For example:
21311**
21312**     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
21313*/
21314SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
21315  int rc = 1;
21316  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
21317    struct MemBlockHdr *pHdr;
21318    pHdr = sqlite3MemsysGetHeader(p);
21319    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
21320    if( (pHdr->eType&eType)==0 ){
21321      rc = 0;
21322    }
21323  }
21324  return rc;
21325}
21326
21327/*
21328** Return TRUE if the mask of type in eType matches no bits of the type of the
21329** allocation p.  Also return true if p==NULL.
21330**
21331** This routine is designed for use within an assert() statement, to
21332** verify the type of an allocation.  For example:
21333**
21334**     assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
21335*/
21336SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
21337  int rc = 1;
21338  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
21339    struct MemBlockHdr *pHdr;
21340    pHdr = sqlite3MemsysGetHeader(p);
21341    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
21342    if( (pHdr->eType&eType)!=0 ){
21343      rc = 0;
21344    }
21345  }
21346  return rc;
21347}
21348
21349/*
21350** Set the number of backtrace levels kept for each allocation.
21351** A value of zero turns off backtracing.  The number is always rounded
21352** up to a multiple of 2.
21353*/
21354SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
21355  if( depth<0 ){ depth = 0; }
21356  if( depth>20 ){ depth = 20; }
21357  depth = (depth+1)&0xfe;
21358  mem.nBacktrace = depth;
21359}
21360
21361SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
21362  mem.xBacktrace = xBacktrace;
21363}
21364
21365/*
21366** Set the title string for subsequent allocations.
21367*/
21368SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
21369  unsigned int n = sqlite3Strlen30(zTitle) + 1;
21370  sqlite3_mutex_enter(mem.mutex);
21371  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
21372  memcpy(mem.zTitle, zTitle, n);
21373  mem.zTitle[n] = 0;
21374  mem.nTitle = ROUND8(n);
21375  sqlite3_mutex_leave(mem.mutex);
21376}
21377
21378SQLITE_PRIVATE void sqlite3MemdebugSync(){
21379  struct MemBlockHdr *pHdr;
21380  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
21381    void **pBt = (void**)pHdr;
21382    pBt -= pHdr->nBacktraceSlots;
21383    mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
21384  }
21385}
21386
21387/*
21388** Open the file indicated and write a log of all unfreed memory
21389** allocations into that log.
21390*/
21391SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
21392  FILE *out;
21393  struct MemBlockHdr *pHdr;
21394  void **pBt;
21395  int i;
21396  out = fopen(zFilename, "w");
21397  if( out==0 ){
21398    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
21399                    zFilename);
21400    return;
21401  }
21402  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
21403    char *z = (char*)pHdr;
21404    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
21405    fprintf(out, "**** %lld bytes at %p from %s ****\n",
21406            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
21407    if( pHdr->nBacktrace ){
21408      fflush(out);
21409      pBt = (void**)pHdr;
21410      pBt -= pHdr->nBacktraceSlots;
21411      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
21412      fprintf(out, "\n");
21413    }
21414  }
21415  fprintf(out, "COUNTS:\n");
21416  for(i=0; i<NCSIZE-1; i++){
21417    if( mem.nAlloc[i] ){
21418      fprintf(out, "   %5d: %10d %10d %10d\n",
21419            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
21420    }
21421  }
21422  if( mem.nAlloc[NCSIZE-1] ){
21423    fprintf(out, "   %5d: %10d %10d %10d\n",
21424             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
21425             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
21426  }
21427  fclose(out);
21428}
21429
21430/*
21431** Return the number of times sqlite3MemMalloc() has been called.
21432*/
21433SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
21434  int i;
21435  int nTotal = 0;
21436  for(i=0; i<NCSIZE; i++){
21437    nTotal += mem.nAlloc[i];
21438  }
21439  return nTotal;
21440}
21441
21442
21443#endif /* SQLITE_MEMDEBUG */
21444
21445/************** End of mem2.c ************************************************/
21446/************** Begin file mem3.c ********************************************/
21447/*
21448** 2007 October 14
21449**
21450** The author disclaims copyright to this source code.  In place of
21451** a legal notice, here is a blessing:
21452**
21453**    May you do good and not evil.
21454**    May you find forgiveness for yourself and forgive others.
21455**    May you share freely, never taking more than you give.
21456**
21457*************************************************************************
21458** This file contains the C functions that implement a memory
21459** allocation subsystem for use by SQLite.
21460**
21461** This version of the memory allocation subsystem omits all
21462** use of malloc(). The SQLite user supplies a block of memory
21463** before calling sqlite3_initialize() from which allocations
21464** are made and returned by the xMalloc() and xRealloc()
21465** implementations. Once sqlite3_initialize() has been called,
21466** the amount of memory available to SQLite is fixed and cannot
21467** be changed.
21468**
21469** This version of the memory allocation subsystem is included
21470** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
21471*/
21472/* #include "sqliteInt.h" */
21473
21474/*
21475** This version of the memory allocator is only built into the library
21476** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
21477** mean that the library will use a memory-pool by default, just that
21478** it is available. The mempool allocator is activated by calling
21479** sqlite3_config().
21480*/
21481#ifdef SQLITE_ENABLE_MEMSYS3
21482
21483/*
21484** Maximum size (in Mem3Blocks) of a "small" chunk.
21485*/
21486#define MX_SMALL 10
21487
21488
21489/*
21490** Number of freelist hash slots
21491*/
21492#define N_HASH  61
21493
21494/*
21495** A memory allocation (also called a "chunk") consists of two or
21496** more blocks where each block is 8 bytes.  The first 8 bytes are
21497** a header that is not returned to the user.
21498**
21499** A chunk is two or more blocks that is either checked out or
21500** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
21501** size of the allocation in blocks if the allocation is free.
21502** The u.hdr.size4x&1 bit is true if the chunk is checked out and
21503** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
21504** is true if the previous chunk is checked out and false if the
21505** previous chunk is free.  The u.hdr.prevSize field is the size of
21506** the previous chunk in blocks if the previous chunk is on the
21507** freelist. If the previous chunk is checked out, then
21508** u.hdr.prevSize can be part of the data for that chunk and should
21509** not be read or written.
21510**
21511** We often identify a chunk by its index in mem3.aPool[].  When
21512** this is done, the chunk index refers to the second block of
21513** the chunk.  In this way, the first chunk has an index of 1.
21514** A chunk index of 0 means "no such chunk" and is the equivalent
21515** of a NULL pointer.
21516**
21517** The second block of free chunks is of the form u.list.  The
21518** two fields form a double-linked list of chunks of related sizes.
21519** Pointers to the head of the list are stored in mem3.aiSmall[]
21520** for smaller chunks and mem3.aiHash[] for larger chunks.
21521**
21522** The second block of a chunk is user data if the chunk is checked
21523** out.  If a chunk is checked out, the user data may extend into
21524** the u.hdr.prevSize value of the following chunk.
21525*/
21526typedef struct Mem3Block Mem3Block;
21527struct Mem3Block {
21528  union {
21529    struct {
21530      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
21531      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
21532    } hdr;
21533    struct {
21534      u32 next;       /* Index in mem3.aPool[] of next free chunk */
21535      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
21536    } list;
21537  } u;
21538};
21539
21540/*
21541** All of the static variables used by this module are collected
21542** into a single structure named "mem3".  This is to keep the
21543** static variables organized and to reduce namespace pollution
21544** when this module is combined with other in the amalgamation.
21545*/
21546static SQLITE_WSD struct Mem3Global {
21547  /*
21548  ** Memory available for allocation. nPool is the size of the array
21549  ** (in Mem3Blocks) pointed to by aPool less 2.
21550  */
21551  u32 nPool;
21552  Mem3Block *aPool;
21553
21554  /*
21555  ** True if we are evaluating an out-of-memory callback.
21556  */
21557  int alarmBusy;
21558
21559  /*
21560  ** Mutex to control access to the memory allocation subsystem.
21561  */
21562  sqlite3_mutex *mutex;
21563
21564  /*
21565  ** The minimum amount of free space that we have seen.
21566  */
21567  u32 mnMaster;
21568
21569  /*
21570  ** iMaster is the index of the master chunk.  Most new allocations
21571  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
21572  ** of the current master.  iMaster is 0 if there is not master chunk.
21573  ** The master chunk is not in either the aiHash[] or aiSmall[].
21574  */
21575  u32 iMaster;
21576  u32 szMaster;
21577
21578  /*
21579  ** Array of lists of free blocks according to the block size
21580  ** for smaller chunks, or a hash on the block size for larger
21581  ** chunks.
21582  */
21583  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
21584  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
21585} mem3 = { 97535575 };
21586
21587#define mem3 GLOBAL(struct Mem3Global, mem3)
21588
21589/*
21590** Unlink the chunk at mem3.aPool[i] from list it is currently
21591** on.  *pRoot is the list that i is a member of.
21592*/
21593static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
21594  u32 next = mem3.aPool[i].u.list.next;
21595  u32 prev = mem3.aPool[i].u.list.prev;
21596  assert( sqlite3_mutex_held(mem3.mutex) );
21597  if( prev==0 ){
21598    *pRoot = next;
21599  }else{
21600    mem3.aPool[prev].u.list.next = next;
21601  }
21602  if( next ){
21603    mem3.aPool[next].u.list.prev = prev;
21604  }
21605  mem3.aPool[i].u.list.next = 0;
21606  mem3.aPool[i].u.list.prev = 0;
21607}
21608
21609/*
21610** Unlink the chunk at index i from
21611** whatever list is currently a member of.
21612*/
21613static void memsys3Unlink(u32 i){
21614  u32 size, hash;
21615  assert( sqlite3_mutex_held(mem3.mutex) );
21616  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
21617  assert( i>=1 );
21618  size = mem3.aPool[i-1].u.hdr.size4x/4;
21619  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
21620  assert( size>=2 );
21621  if( size <= MX_SMALL ){
21622    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
21623  }else{
21624    hash = size % N_HASH;
21625    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
21626  }
21627}
21628
21629/*
21630** Link the chunk at mem3.aPool[i] so that is on the list rooted
21631** at *pRoot.
21632*/
21633static void memsys3LinkIntoList(u32 i, u32 *pRoot){
21634  assert( sqlite3_mutex_held(mem3.mutex) );
21635  mem3.aPool[i].u.list.next = *pRoot;
21636  mem3.aPool[i].u.list.prev = 0;
21637  if( *pRoot ){
21638    mem3.aPool[*pRoot].u.list.prev = i;
21639  }
21640  *pRoot = i;
21641}
21642
21643/*
21644** Link the chunk at index i into either the appropriate
21645** small chunk list, or into the large chunk hash table.
21646*/
21647static void memsys3Link(u32 i){
21648  u32 size, hash;
21649  assert( sqlite3_mutex_held(mem3.mutex) );
21650  assert( i>=1 );
21651  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
21652  size = mem3.aPool[i-1].u.hdr.size4x/4;
21653  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
21654  assert( size>=2 );
21655  if( size <= MX_SMALL ){
21656    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
21657  }else{
21658    hash = size % N_HASH;
21659    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
21660  }
21661}
21662
21663/*
21664** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
21665** will already be held (obtained by code in malloc.c) if
21666** sqlite3GlobalConfig.bMemStat is true.
21667*/
21668static void memsys3Enter(void){
21669  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
21670    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
21671  }
21672  sqlite3_mutex_enter(mem3.mutex);
21673}
21674static void memsys3Leave(void){
21675  sqlite3_mutex_leave(mem3.mutex);
21676}
21677
21678/*
21679** Called when we are unable to satisfy an allocation of nBytes.
21680*/
21681static void memsys3OutOfMemory(int nByte){
21682  if( !mem3.alarmBusy ){
21683    mem3.alarmBusy = 1;
21684    assert( sqlite3_mutex_held(mem3.mutex) );
21685    sqlite3_mutex_leave(mem3.mutex);
21686    sqlite3_release_memory(nByte);
21687    sqlite3_mutex_enter(mem3.mutex);
21688    mem3.alarmBusy = 0;
21689  }
21690}
21691
21692
21693/*
21694** Chunk i is a free chunk that has been unlinked.  Adjust its
21695** size parameters for check-out and return a pointer to the
21696** user portion of the chunk.
21697*/
21698static void *memsys3Checkout(u32 i, u32 nBlock){
21699  u32 x;
21700  assert( sqlite3_mutex_held(mem3.mutex) );
21701  assert( i>=1 );
21702  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
21703  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
21704  x = mem3.aPool[i-1].u.hdr.size4x;
21705  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
21706  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
21707  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
21708  return &mem3.aPool[i];
21709}
21710
21711/*
21712** Carve a piece off of the end of the mem3.iMaster free chunk.
21713** Return a pointer to the new allocation.  Or, if the master chunk
21714** is not large enough, return 0.
21715*/
21716static void *memsys3FromMaster(u32 nBlock){
21717  assert( sqlite3_mutex_held(mem3.mutex) );
21718  assert( mem3.szMaster>=nBlock );
21719  if( nBlock>=mem3.szMaster-1 ){
21720    /* Use the entire master */
21721    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
21722    mem3.iMaster = 0;
21723    mem3.szMaster = 0;
21724    mem3.mnMaster = 0;
21725    return p;
21726  }else{
21727    /* Split the master block.  Return the tail. */
21728    u32 newi, x;
21729    newi = mem3.iMaster + mem3.szMaster - nBlock;
21730    assert( newi > mem3.iMaster+1 );
21731    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
21732    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
21733    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
21734    mem3.szMaster -= nBlock;
21735    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
21736    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21737    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21738    if( mem3.szMaster < mem3.mnMaster ){
21739      mem3.mnMaster = mem3.szMaster;
21740    }
21741    return (void*)&mem3.aPool[newi];
21742  }
21743}
21744
21745/*
21746** *pRoot is the head of a list of free chunks of the same size
21747** or same size hash.  In other words, *pRoot is an entry in either
21748** mem3.aiSmall[] or mem3.aiHash[].
21749**
21750** This routine examines all entries on the given list and tries
21751** to coalesce each entries with adjacent free chunks.
21752**
21753** If it sees a chunk that is larger than mem3.iMaster, it replaces
21754** the current mem3.iMaster with the new larger chunk.  In order for
21755** this mem3.iMaster replacement to work, the master chunk must be
21756** linked into the hash tables.  That is not the normal state of
21757** affairs, of course.  The calling routine must link the master
21758** chunk before invoking this routine, then must unlink the (possibly
21759** changed) master chunk once this routine has finished.
21760*/
21761static void memsys3Merge(u32 *pRoot){
21762  u32 iNext, prev, size, i, x;
21763
21764  assert( sqlite3_mutex_held(mem3.mutex) );
21765  for(i=*pRoot; i>0; i=iNext){
21766    iNext = mem3.aPool[i].u.list.next;
21767    size = mem3.aPool[i-1].u.hdr.size4x;
21768    assert( (size&1)==0 );
21769    if( (size&2)==0 ){
21770      memsys3UnlinkFromList(i, pRoot);
21771      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
21772      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
21773      if( prev==iNext ){
21774        iNext = mem3.aPool[prev].u.list.next;
21775      }
21776      memsys3Unlink(prev);
21777      size = i + size/4 - prev;
21778      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
21779      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
21780      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
21781      memsys3Link(prev);
21782      i = prev;
21783    }else{
21784      size /= 4;
21785    }
21786    if( size>mem3.szMaster ){
21787      mem3.iMaster = i;
21788      mem3.szMaster = size;
21789    }
21790  }
21791}
21792
21793/*
21794** Return a block of memory of at least nBytes in size.
21795** Return NULL if unable.
21796**
21797** This function assumes that the necessary mutexes, if any, are
21798** already held by the caller. Hence "Unsafe".
21799*/
21800static void *memsys3MallocUnsafe(int nByte){
21801  u32 i;
21802  u32 nBlock;
21803  u32 toFree;
21804
21805  assert( sqlite3_mutex_held(mem3.mutex) );
21806  assert( sizeof(Mem3Block)==8 );
21807  if( nByte<=12 ){
21808    nBlock = 2;
21809  }else{
21810    nBlock = (nByte + 11)/8;
21811  }
21812  assert( nBlock>=2 );
21813
21814  /* STEP 1:
21815  ** Look for an entry of the correct size in either the small
21816  ** chunk table or in the large chunk hash table.  This is
21817  ** successful most of the time (about 9 times out of 10).
21818  */
21819  if( nBlock <= MX_SMALL ){
21820    i = mem3.aiSmall[nBlock-2];
21821    if( i>0 ){
21822      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
21823      return memsys3Checkout(i, nBlock);
21824    }
21825  }else{
21826    int hash = nBlock % N_HASH;
21827    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
21828      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
21829        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
21830        return memsys3Checkout(i, nBlock);
21831      }
21832    }
21833  }
21834
21835  /* STEP 2:
21836  ** Try to satisfy the allocation by carving a piece off of the end
21837  ** of the master chunk.  This step usually works if step 1 fails.
21838  */
21839  if( mem3.szMaster>=nBlock ){
21840    return memsys3FromMaster(nBlock);
21841  }
21842
21843
21844  /* STEP 3:
21845  ** Loop through the entire memory pool.  Coalesce adjacent free
21846  ** chunks.  Recompute the master chunk as the largest free chunk.
21847  ** Then try again to satisfy the allocation by carving a piece off
21848  ** of the end of the master chunk.  This step happens very
21849  ** rarely (we hope!)
21850  */
21851  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
21852    memsys3OutOfMemory(toFree);
21853    if( mem3.iMaster ){
21854      memsys3Link(mem3.iMaster);
21855      mem3.iMaster = 0;
21856      mem3.szMaster = 0;
21857    }
21858    for(i=0; i<N_HASH; i++){
21859      memsys3Merge(&mem3.aiHash[i]);
21860    }
21861    for(i=0; i<MX_SMALL-1; i++){
21862      memsys3Merge(&mem3.aiSmall[i]);
21863    }
21864    if( mem3.szMaster ){
21865      memsys3Unlink(mem3.iMaster);
21866      if( mem3.szMaster>=nBlock ){
21867        return memsys3FromMaster(nBlock);
21868      }
21869    }
21870  }
21871
21872  /* If none of the above worked, then we fail. */
21873  return 0;
21874}
21875
21876/*
21877** Free an outstanding memory allocation.
21878**
21879** This function assumes that the necessary mutexes, if any, are
21880** already held by the caller. Hence "Unsafe".
21881*/
21882static void memsys3FreeUnsafe(void *pOld){
21883  Mem3Block *p = (Mem3Block*)pOld;
21884  int i;
21885  u32 size, x;
21886  assert( sqlite3_mutex_held(mem3.mutex) );
21887  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
21888  i = p - mem3.aPool;
21889  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
21890  size = mem3.aPool[i-1].u.hdr.size4x/4;
21891  assert( i+size<=mem3.nPool+1 );
21892  mem3.aPool[i-1].u.hdr.size4x &= ~1;
21893  mem3.aPool[i+size-1].u.hdr.prevSize = size;
21894  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
21895  memsys3Link(i);
21896
21897  /* Try to expand the master using the newly freed chunk */
21898  if( mem3.iMaster ){
21899    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
21900      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
21901      mem3.iMaster -= size;
21902      mem3.szMaster += size;
21903      memsys3Unlink(mem3.iMaster);
21904      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21905      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21906      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
21907    }
21908    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21909    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
21910      memsys3Unlink(mem3.iMaster+mem3.szMaster);
21911      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
21912      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21913      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
21914    }
21915  }
21916}
21917
21918/*
21919** Return the size of an outstanding allocation, in bytes.  The
21920** size returned omits the 8-byte header overhead.  This only
21921** works for chunks that are currently checked out.
21922*/
21923static int memsys3Size(void *p){
21924  Mem3Block *pBlock;
21925  assert( p!=0 );
21926  pBlock = (Mem3Block*)p;
21927  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
21928  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
21929}
21930
21931/*
21932** Round up a request size to the next valid allocation size.
21933*/
21934static int memsys3Roundup(int n){
21935  if( n<=12 ){
21936    return 12;
21937  }else{
21938    return ((n+11)&~7) - 4;
21939  }
21940}
21941
21942/*
21943** Allocate nBytes of memory.
21944*/
21945static void *memsys3Malloc(int nBytes){
21946  sqlite3_int64 *p;
21947  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
21948  memsys3Enter();
21949  p = memsys3MallocUnsafe(nBytes);
21950  memsys3Leave();
21951  return (void*)p;
21952}
21953
21954/*
21955** Free memory.
21956*/
21957static void memsys3Free(void *pPrior){
21958  assert( pPrior );
21959  memsys3Enter();
21960  memsys3FreeUnsafe(pPrior);
21961  memsys3Leave();
21962}
21963
21964/*
21965** Change the size of an existing memory allocation
21966*/
21967static void *memsys3Realloc(void *pPrior, int nBytes){
21968  int nOld;
21969  void *p;
21970  if( pPrior==0 ){
21971    return sqlite3_malloc(nBytes);
21972  }
21973  if( nBytes<=0 ){
21974    sqlite3_free(pPrior);
21975    return 0;
21976  }
21977  nOld = memsys3Size(pPrior);
21978  if( nBytes<=nOld && nBytes>=nOld-128 ){
21979    return pPrior;
21980  }
21981  memsys3Enter();
21982  p = memsys3MallocUnsafe(nBytes);
21983  if( p ){
21984    if( nOld<nBytes ){
21985      memcpy(p, pPrior, nOld);
21986    }else{
21987      memcpy(p, pPrior, nBytes);
21988    }
21989    memsys3FreeUnsafe(pPrior);
21990  }
21991  memsys3Leave();
21992  return p;
21993}
21994
21995/*
21996** Initialize this module.
21997*/
21998static int memsys3Init(void *NotUsed){
21999  UNUSED_PARAMETER(NotUsed);
22000  if( !sqlite3GlobalConfig.pHeap ){
22001    return SQLITE_ERROR;
22002  }
22003
22004  /* Store a pointer to the memory block in global structure mem3. */
22005  assert( sizeof(Mem3Block)==8 );
22006  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
22007  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
22008
22009  /* Initialize the master block. */
22010  mem3.szMaster = mem3.nPool;
22011  mem3.mnMaster = mem3.szMaster;
22012  mem3.iMaster = 1;
22013  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
22014  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
22015  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
22016
22017  return SQLITE_OK;
22018}
22019
22020/*
22021** Deinitialize this module.
22022*/
22023static void memsys3Shutdown(void *NotUsed){
22024  UNUSED_PARAMETER(NotUsed);
22025  mem3.mutex = 0;
22026  return;
22027}
22028
22029
22030
22031/*
22032** Open the file indicated and write a log of all unfreed memory
22033** allocations into that log.
22034*/
22035SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
22036#ifdef SQLITE_DEBUG
22037  FILE *out;
22038  u32 i, j;
22039  u32 size;
22040  if( zFilename==0 || zFilename[0]==0 ){
22041    out = stdout;
22042  }else{
22043    out = fopen(zFilename, "w");
22044    if( out==0 ){
22045      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
22046                      zFilename);
22047      return;
22048    }
22049  }
22050  memsys3Enter();
22051  fprintf(out, "CHUNKS:\n");
22052  for(i=1; i<=mem3.nPool; i+=size/4){
22053    size = mem3.aPool[i-1].u.hdr.size4x;
22054    if( size/4<=1 ){
22055      fprintf(out, "%p size error\n", &mem3.aPool[i]);
22056      assert( 0 );
22057      break;
22058    }
22059    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
22060      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
22061      assert( 0 );
22062      break;
22063    }
22064    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
22065      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
22066      assert( 0 );
22067      break;
22068    }
22069    if( size&1 ){
22070      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
22071    }else{
22072      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
22073                  i==mem3.iMaster ? " **master**" : "");
22074    }
22075  }
22076  for(i=0; i<MX_SMALL-1; i++){
22077    if( mem3.aiSmall[i]==0 ) continue;
22078    fprintf(out, "small(%2d):", i);
22079    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
22080      fprintf(out, " %p(%d)", &mem3.aPool[j],
22081              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
22082    }
22083    fprintf(out, "\n");
22084  }
22085  for(i=0; i<N_HASH; i++){
22086    if( mem3.aiHash[i]==0 ) continue;
22087    fprintf(out, "hash(%2d):", i);
22088    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
22089      fprintf(out, " %p(%d)", &mem3.aPool[j],
22090              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
22091    }
22092    fprintf(out, "\n");
22093  }
22094  fprintf(out, "master=%d\n", mem3.iMaster);
22095  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
22096  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
22097  sqlite3_mutex_leave(mem3.mutex);
22098  if( out==stdout ){
22099    fflush(stdout);
22100  }else{
22101    fclose(out);
22102  }
22103#else
22104  UNUSED_PARAMETER(zFilename);
22105#endif
22106}
22107
22108/*
22109** This routine is the only routine in this file with external
22110** linkage.
22111**
22112** Populate the low-level memory allocation function pointers in
22113** sqlite3GlobalConfig.m with pointers to the routines in this file. The
22114** arguments specify the block of memory to manage.
22115**
22116** This routine is only called by sqlite3_config(), and therefore
22117** is not required to be threadsafe (it is not).
22118*/
22119SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
22120  static const sqlite3_mem_methods mempoolMethods = {
22121     memsys3Malloc,
22122     memsys3Free,
22123     memsys3Realloc,
22124     memsys3Size,
22125     memsys3Roundup,
22126     memsys3Init,
22127     memsys3Shutdown,
22128     0
22129  };
22130  return &mempoolMethods;
22131}
22132
22133#endif /* SQLITE_ENABLE_MEMSYS3 */
22134
22135/************** End of mem3.c ************************************************/
22136/************** Begin file mem5.c ********************************************/
22137/*
22138** 2007 October 14
22139**
22140** The author disclaims copyright to this source code.  In place of
22141** a legal notice, here is a blessing:
22142**
22143**    May you do good and not evil.
22144**    May you find forgiveness for yourself and forgive others.
22145**    May you share freely, never taking more than you give.
22146**
22147*************************************************************************
22148** This file contains the C functions that implement a memory
22149** allocation subsystem for use by SQLite.
22150**
22151** This version of the memory allocation subsystem omits all
22152** use of malloc(). The application gives SQLite a block of memory
22153** before calling sqlite3_initialize() from which allocations
22154** are made and returned by the xMalloc() and xRealloc()
22155** implementations. Once sqlite3_initialize() has been called,
22156** the amount of memory available to SQLite is fixed and cannot
22157** be changed.
22158**
22159** This version of the memory allocation subsystem is included
22160** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
22161**
22162** This memory allocator uses the following algorithm:
22163**
22164**   1.  All memory allocation sizes are rounded up to a power of 2.
22165**
22166**   2.  If two adjacent free blocks are the halves of a larger block,
22167**       then the two blocks are coalesced into the single larger block.
22168**
22169**   3.  New memory is allocated from the first available free block.
22170**
22171** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
22172** Concerning Dynamic Storage Allocation". Journal of the Association for
22173** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
22174**
22175** Let n be the size of the largest allocation divided by the minimum
22176** allocation size (after rounding all sizes up to a power of 2.)  Let M
22177** be the maximum amount of memory ever outstanding at one time.  Let
22178** N be the total amount of memory available for allocation.  Robson
22179** proved that this memory allocator will never breakdown due to
22180** fragmentation as long as the following constraint holds:
22181**
22182**      N >=  M*(1 + log2(n)/2) - n + 1
22183**
22184** The sqlite3_status() logic tracks the maximum values of n and M so
22185** that an application can, at any time, verify this constraint.
22186*/
22187/* #include "sqliteInt.h" */
22188
22189/*
22190** This version of the memory allocator is used only when
22191** SQLITE_ENABLE_MEMSYS5 is defined.
22192*/
22193#ifdef SQLITE_ENABLE_MEMSYS5
22194
22195/*
22196** A minimum allocation is an instance of the following structure.
22197** Larger allocations are an array of these structures where the
22198** size of the array is a power of 2.
22199**
22200** The size of this object must be a power of two.  That fact is
22201** verified in memsys5Init().
22202*/
22203typedef struct Mem5Link Mem5Link;
22204struct Mem5Link {
22205  int next;       /* Index of next free chunk */
22206  int prev;       /* Index of previous free chunk */
22207};
22208
22209/*
22210** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
22211** mem5.szAtom is always at least 8 and 32-bit integers are used,
22212** it is not actually possible to reach this limit.
22213*/
22214#define LOGMAX 30
22215
22216/*
22217** Masks used for mem5.aCtrl[] elements.
22218*/
22219#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
22220#define CTRL_FREE     0x20    /* True if not checked out */
22221
22222/*
22223** All of the static variables used by this module are collected
22224** into a single structure named "mem5".  This is to keep the
22225** static variables organized and to reduce namespace pollution
22226** when this module is combined with other in the amalgamation.
22227*/
22228static SQLITE_WSD struct Mem5Global {
22229  /*
22230  ** Memory available for allocation
22231  */
22232  int szAtom;      /* Smallest possible allocation in bytes */
22233  int nBlock;      /* Number of szAtom sized blocks in zPool */
22234  u8 *zPool;       /* Memory available to be allocated */
22235
22236  /*
22237  ** Mutex to control access to the memory allocation subsystem.
22238  */
22239  sqlite3_mutex *mutex;
22240
22241#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22242  /*
22243  ** Performance statistics
22244  */
22245  u64 nAlloc;         /* Total number of calls to malloc */
22246  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
22247  u64 totalExcess;    /* Total internal fragmentation */
22248  u32 currentOut;     /* Current checkout, including internal fragmentation */
22249  u32 currentCount;   /* Current number of distinct checkouts */
22250  u32 maxOut;         /* Maximum instantaneous currentOut */
22251  u32 maxCount;       /* Maximum instantaneous currentCount */
22252  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
22253#endif
22254
22255  /*
22256  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
22257  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
22258  ** aiFreelist[2] holds free blocks of size szAtom*4.  And so forth.
22259  */
22260  int aiFreelist[LOGMAX+1];
22261
22262  /*
22263  ** Space for tracking which blocks are checked out and the size
22264  ** of each block.  One byte per block.
22265  */
22266  u8 *aCtrl;
22267
22268} mem5;
22269
22270/*
22271** Access the static variable through a macro for SQLITE_OMIT_WSD.
22272*/
22273#define mem5 GLOBAL(struct Mem5Global, mem5)
22274
22275/*
22276** Assuming mem5.zPool is divided up into an array of Mem5Link
22277** structures, return a pointer to the idx-th such link.
22278*/
22279#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
22280
22281/*
22282** Unlink the chunk at mem5.aPool[i] from list it is currently
22283** on.  It should be found on mem5.aiFreelist[iLogsize].
22284*/
22285static void memsys5Unlink(int i, int iLogsize){
22286  int next, prev;
22287  assert( i>=0 && i<mem5.nBlock );
22288  assert( iLogsize>=0 && iLogsize<=LOGMAX );
22289  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
22290
22291  next = MEM5LINK(i)->next;
22292  prev = MEM5LINK(i)->prev;
22293  if( prev<0 ){
22294    mem5.aiFreelist[iLogsize] = next;
22295  }else{
22296    MEM5LINK(prev)->next = next;
22297  }
22298  if( next>=0 ){
22299    MEM5LINK(next)->prev = prev;
22300  }
22301}
22302
22303/*
22304** Link the chunk at mem5.aPool[i] so that is on the iLogsize
22305** free list.
22306*/
22307static void memsys5Link(int i, int iLogsize){
22308  int x;
22309  assert( sqlite3_mutex_held(mem5.mutex) );
22310  assert( i>=0 && i<mem5.nBlock );
22311  assert( iLogsize>=0 && iLogsize<=LOGMAX );
22312  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
22313
22314  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
22315  MEM5LINK(i)->prev = -1;
22316  if( x>=0 ){
22317    assert( x<mem5.nBlock );
22318    MEM5LINK(x)->prev = i;
22319  }
22320  mem5.aiFreelist[iLogsize] = i;
22321}
22322
22323/*
22324** Obtain or release the mutex needed to access global data structures.
22325*/
22326static void memsys5Enter(void){
22327  sqlite3_mutex_enter(mem5.mutex);
22328}
22329static void memsys5Leave(void){
22330  sqlite3_mutex_leave(mem5.mutex);
22331}
22332
22333/*
22334** Return the size of an outstanding allocation, in bytes.
22335** This only works for chunks that are currently checked out.
22336*/
22337static int memsys5Size(void *p){
22338  int iSize, i;
22339  assert( p!=0 );
22340  i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
22341  assert( i>=0 && i<mem5.nBlock );
22342  iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
22343  return iSize;
22344}
22345
22346/*
22347** Return a block of memory of at least nBytes in size.
22348** Return NULL if unable.  Return NULL if nBytes==0.
22349**
22350** The caller guarantees that nByte is positive.
22351**
22352** The caller has obtained a mutex prior to invoking this
22353** routine so there is never any chance that two or more
22354** threads can be in this routine at the same time.
22355*/
22356static void *memsys5MallocUnsafe(int nByte){
22357  int i;           /* Index of a mem5.aPool[] slot */
22358  int iBin;        /* Index into mem5.aiFreelist[] */
22359  int iFullSz;     /* Size of allocation rounded up to power of 2 */
22360  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
22361
22362  /* nByte must be a positive */
22363  assert( nByte>0 );
22364
22365  /* No more than 1GiB per allocation */
22366  if( nByte > 0x40000000 ) return 0;
22367
22368#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22369  /* Keep track of the maximum allocation request.  Even unfulfilled
22370  ** requests are counted */
22371  if( (u32)nByte>mem5.maxRequest ){
22372    mem5.maxRequest = nByte;
22373  }
22374#endif
22375
22376
22377  /* Round nByte up to the next valid power of two */
22378  for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
22379
22380  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
22381  ** block.  If not, then split a block of the next larger power of
22382  ** two in order to create a new free block of size iLogsize.
22383  */
22384  for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
22385  if( iBin>LOGMAX ){
22386    testcase( sqlite3GlobalConfig.xLog!=0 );
22387    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
22388    return 0;
22389  }
22390  i = mem5.aiFreelist[iBin];
22391  memsys5Unlink(i, iBin);
22392  while( iBin>iLogsize ){
22393    int newSize;
22394
22395    iBin--;
22396    newSize = 1 << iBin;
22397    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
22398    memsys5Link(i+newSize, iBin);
22399  }
22400  mem5.aCtrl[i] = iLogsize;
22401
22402#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22403  /* Update allocator performance statistics. */
22404  mem5.nAlloc++;
22405  mem5.totalAlloc += iFullSz;
22406  mem5.totalExcess += iFullSz - nByte;
22407  mem5.currentCount++;
22408  mem5.currentOut += iFullSz;
22409  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
22410  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
22411#endif
22412
22413#ifdef SQLITE_DEBUG
22414  /* Make sure the allocated memory does not assume that it is set to zero
22415  ** or retains a value from a previous allocation */
22416  memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
22417#endif
22418
22419  /* Return a pointer to the allocated memory. */
22420  return (void*)&mem5.zPool[i*mem5.szAtom];
22421}
22422
22423/*
22424** Free an outstanding memory allocation.
22425*/
22426static void memsys5FreeUnsafe(void *pOld){
22427  u32 size, iLogsize;
22428  int iBlock;
22429
22430  /* Set iBlock to the index of the block pointed to by pOld in
22431  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
22432  */
22433  iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
22434
22435  /* Check that the pointer pOld points to a valid, non-free block. */
22436  assert( iBlock>=0 && iBlock<mem5.nBlock );
22437  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
22438  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
22439
22440  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
22441  size = 1<<iLogsize;
22442  assert( iBlock+size-1<(u32)mem5.nBlock );
22443
22444  mem5.aCtrl[iBlock] |= CTRL_FREE;
22445  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
22446
22447#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22448  assert( mem5.currentCount>0 );
22449  assert( mem5.currentOut>=(size*mem5.szAtom) );
22450  mem5.currentCount--;
22451  mem5.currentOut -= size*mem5.szAtom;
22452  assert( mem5.currentOut>0 || mem5.currentCount==0 );
22453  assert( mem5.currentCount>0 || mem5.currentOut==0 );
22454#endif
22455
22456  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
22457  while( ALWAYS(iLogsize<LOGMAX) ){
22458    int iBuddy;
22459    if( (iBlock>>iLogsize) & 1 ){
22460      iBuddy = iBlock - size;
22461      assert( iBuddy>=0 );
22462    }else{
22463      iBuddy = iBlock + size;
22464      if( iBuddy>=mem5.nBlock ) break;
22465    }
22466    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
22467    memsys5Unlink(iBuddy, iLogsize);
22468    iLogsize++;
22469    if( iBuddy<iBlock ){
22470      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
22471      mem5.aCtrl[iBlock] = 0;
22472      iBlock = iBuddy;
22473    }else{
22474      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
22475      mem5.aCtrl[iBuddy] = 0;
22476    }
22477    size *= 2;
22478  }
22479
22480#ifdef SQLITE_DEBUG
22481  /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
22482  ** not used after being freed */
22483  memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
22484#endif
22485
22486  memsys5Link(iBlock, iLogsize);
22487}
22488
22489/*
22490** Allocate nBytes of memory.
22491*/
22492static void *memsys5Malloc(int nBytes){
22493  sqlite3_int64 *p = 0;
22494  if( nBytes>0 ){
22495    memsys5Enter();
22496    p = memsys5MallocUnsafe(nBytes);
22497    memsys5Leave();
22498  }
22499  return (void*)p;
22500}
22501
22502/*
22503** Free memory.
22504**
22505** The outer layer memory allocator prevents this routine from
22506** being called with pPrior==0.
22507*/
22508static void memsys5Free(void *pPrior){
22509  assert( pPrior!=0 );
22510  memsys5Enter();
22511  memsys5FreeUnsafe(pPrior);
22512  memsys5Leave();
22513}
22514
22515/*
22516** Change the size of an existing memory allocation.
22517**
22518** The outer layer memory allocator prevents this routine from
22519** being called with pPrior==0.
22520**
22521** nBytes is always a value obtained from a prior call to
22522** memsys5Round().  Hence nBytes is always a non-negative power
22523** of two.  If nBytes==0 that means that an oversize allocation
22524** (an allocation larger than 0x40000000) was requested and this
22525** routine should return 0 without freeing pPrior.
22526*/
22527static void *memsys5Realloc(void *pPrior, int nBytes){
22528  int nOld;
22529  void *p;
22530  assert( pPrior!=0 );
22531  assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
22532  assert( nBytes>=0 );
22533  if( nBytes==0 ){
22534    return 0;
22535  }
22536  nOld = memsys5Size(pPrior);
22537  if( nBytes<=nOld ){
22538    return pPrior;
22539  }
22540  p = memsys5Malloc(nBytes);
22541  if( p ){
22542    memcpy(p, pPrior, nOld);
22543    memsys5Free(pPrior);
22544  }
22545  return p;
22546}
22547
22548/*
22549** Round up a request size to the next valid allocation size.  If
22550** the allocation is too large to be handled by this allocation system,
22551** return 0.
22552**
22553** All allocations must be a power of two and must be expressed by a
22554** 32-bit signed integer.  Hence the largest allocation is 0x40000000
22555** or 1073741824 bytes.
22556*/
22557static int memsys5Roundup(int n){
22558  int iFullSz;
22559  if( n > 0x40000000 ) return 0;
22560  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
22561  return iFullSz;
22562}
22563
22564/*
22565** Return the ceiling of the logarithm base 2 of iValue.
22566**
22567** Examples:   memsys5Log(1) -> 0
22568**             memsys5Log(2) -> 1
22569**             memsys5Log(4) -> 2
22570**             memsys5Log(5) -> 3
22571**             memsys5Log(8) -> 3
22572**             memsys5Log(9) -> 4
22573*/
22574static int memsys5Log(int iValue){
22575  int iLog;
22576  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
22577  return iLog;
22578}
22579
22580/*
22581** Initialize the memory allocator.
22582**
22583** This routine is not threadsafe.  The caller must be holding a mutex
22584** to prevent multiple threads from entering at the same time.
22585*/
22586static int memsys5Init(void *NotUsed){
22587  int ii;            /* Loop counter */
22588  int nByte;         /* Number of bytes of memory available to this allocator */
22589  u8 *zByte;         /* Memory usable by this allocator */
22590  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
22591  int iOffset;       /* An offset into mem5.aCtrl[] */
22592
22593  UNUSED_PARAMETER(NotUsed);
22594
22595  /* For the purposes of this routine, disable the mutex */
22596  mem5.mutex = 0;
22597
22598  /* The size of a Mem5Link object must be a power of two.  Verify that
22599  ** this is case.
22600  */
22601  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
22602
22603  nByte = sqlite3GlobalConfig.nHeap;
22604  zByte = (u8*)sqlite3GlobalConfig.pHeap;
22605  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
22606
22607  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
22608  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
22609  mem5.szAtom = (1<<nMinLog);
22610  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
22611    mem5.szAtom = mem5.szAtom << 1;
22612  }
22613
22614  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
22615  mem5.zPool = zByte;
22616  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
22617
22618  for(ii=0; ii<=LOGMAX; ii++){
22619    mem5.aiFreelist[ii] = -1;
22620  }
22621
22622  iOffset = 0;
22623  for(ii=LOGMAX; ii>=0; ii--){
22624    int nAlloc = (1<<ii);
22625    if( (iOffset+nAlloc)<=mem5.nBlock ){
22626      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
22627      memsys5Link(iOffset, ii);
22628      iOffset += nAlloc;
22629    }
22630    assert((iOffset+nAlloc)>mem5.nBlock);
22631  }
22632
22633  /* If a mutex is required for normal operation, allocate one */
22634  if( sqlite3GlobalConfig.bMemstat==0 ){
22635    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
22636  }
22637
22638  return SQLITE_OK;
22639}
22640
22641/*
22642** Deinitialize this module.
22643*/
22644static void memsys5Shutdown(void *NotUsed){
22645  UNUSED_PARAMETER(NotUsed);
22646  mem5.mutex = 0;
22647  return;
22648}
22649
22650#ifdef SQLITE_TEST
22651/*
22652** Open the file indicated and write a log of all unfreed memory
22653** allocations into that log.
22654*/
22655SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
22656  FILE *out;
22657  int i, j, n;
22658  int nMinLog;
22659
22660  if( zFilename==0 || zFilename[0]==0 ){
22661    out = stdout;
22662  }else{
22663    out = fopen(zFilename, "w");
22664    if( out==0 ){
22665      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
22666                      zFilename);
22667      return;
22668    }
22669  }
22670  memsys5Enter();
22671  nMinLog = memsys5Log(mem5.szAtom);
22672  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
22673    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
22674    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
22675  }
22676  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
22677  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
22678  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
22679  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
22680  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
22681  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
22682  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
22683  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
22684  memsys5Leave();
22685  if( out==stdout ){
22686    fflush(stdout);
22687  }else{
22688    fclose(out);
22689  }
22690}
22691#endif
22692
22693/*
22694** This routine is the only routine in this file with external
22695** linkage. It returns a pointer to a static sqlite3_mem_methods
22696** struct populated with the memsys5 methods.
22697*/
22698SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
22699  static const sqlite3_mem_methods memsys5Methods = {
22700     memsys5Malloc,
22701     memsys5Free,
22702     memsys5Realloc,
22703     memsys5Size,
22704     memsys5Roundup,
22705     memsys5Init,
22706     memsys5Shutdown,
22707     0
22708  };
22709  return &memsys5Methods;
22710}
22711
22712#endif /* SQLITE_ENABLE_MEMSYS5 */
22713
22714/************** End of mem5.c ************************************************/
22715/************** Begin file mutex.c *******************************************/
22716/*
22717** 2007 August 14
22718**
22719** The author disclaims copyright to this source code.  In place of
22720** a legal notice, here is a blessing:
22721**
22722**    May you do good and not evil.
22723**    May you find forgiveness for yourself and forgive others.
22724**    May you share freely, never taking more than you give.
22725**
22726*************************************************************************
22727** This file contains the C functions that implement mutexes.
22728**
22729** This file contains code that is common across all mutex implementations.
22730*/
22731/* #include "sqliteInt.h" */
22732
22733#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
22734/*
22735** For debugging purposes, record when the mutex subsystem is initialized
22736** and uninitialized so that we can assert() if there is an attempt to
22737** allocate a mutex while the system is uninitialized.
22738*/
22739static SQLITE_WSD int mutexIsInit = 0;
22740#endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
22741
22742
22743#ifndef SQLITE_MUTEX_OMIT
22744/*
22745** Initialize the mutex system.
22746*/
22747SQLITE_PRIVATE int sqlite3MutexInit(void){
22748  int rc = SQLITE_OK;
22749  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
22750    /* If the xMutexAlloc method has not been set, then the user did not
22751    ** install a mutex implementation via sqlite3_config() prior to
22752    ** sqlite3_initialize() being called. This block copies pointers to
22753    ** the default implementation into the sqlite3GlobalConfig structure.
22754    */
22755    sqlite3_mutex_methods const *pFrom;
22756    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
22757
22758    if( sqlite3GlobalConfig.bCoreMutex ){
22759      pFrom = sqlite3DefaultMutex();
22760    }else{
22761      pFrom = sqlite3NoopMutex();
22762    }
22763    pTo->xMutexInit = pFrom->xMutexInit;
22764    pTo->xMutexEnd = pFrom->xMutexEnd;
22765    pTo->xMutexFree = pFrom->xMutexFree;
22766    pTo->xMutexEnter = pFrom->xMutexEnter;
22767    pTo->xMutexTry = pFrom->xMutexTry;
22768    pTo->xMutexLeave = pFrom->xMutexLeave;
22769    pTo->xMutexHeld = pFrom->xMutexHeld;
22770    pTo->xMutexNotheld = pFrom->xMutexNotheld;
22771    sqlite3MemoryBarrier();
22772    pTo->xMutexAlloc = pFrom->xMutexAlloc;
22773  }
22774  assert( sqlite3GlobalConfig.mutex.xMutexInit );
22775  rc = sqlite3GlobalConfig.mutex.xMutexInit();
22776
22777#ifdef SQLITE_DEBUG
22778  GLOBAL(int, mutexIsInit) = 1;
22779#endif
22780
22781  return rc;
22782}
22783
22784/*
22785** Shutdown the mutex system. This call frees resources allocated by
22786** sqlite3MutexInit().
22787*/
22788SQLITE_PRIVATE int sqlite3MutexEnd(void){
22789  int rc = SQLITE_OK;
22790  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
22791    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
22792  }
22793
22794#ifdef SQLITE_DEBUG
22795  GLOBAL(int, mutexIsInit) = 0;
22796#endif
22797
22798  return rc;
22799}
22800
22801/*
22802** Retrieve a pointer to a static mutex or allocate a new dynamic one.
22803*/
22804SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
22805#ifndef SQLITE_OMIT_AUTOINIT
22806  if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
22807  if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
22808#endif
22809  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
22810  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
22811}
22812
22813SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
22814  if( !sqlite3GlobalConfig.bCoreMutex ){
22815    return 0;
22816  }
22817  assert( GLOBAL(int, mutexIsInit) );
22818  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
22819  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
22820}
22821
22822/*
22823** Free a dynamic mutex.
22824*/
22825SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
22826  if( p ){
22827    assert( sqlite3GlobalConfig.mutex.xMutexFree );
22828    sqlite3GlobalConfig.mutex.xMutexFree(p);
22829  }
22830}
22831
22832/*
22833** Obtain the mutex p. If some other thread already has the mutex, block
22834** until it can be obtained.
22835*/
22836SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
22837  if( p ){
22838    assert( sqlite3GlobalConfig.mutex.xMutexEnter );
22839    sqlite3GlobalConfig.mutex.xMutexEnter(p);
22840  }
22841}
22842
22843/*
22844** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
22845** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
22846*/
22847SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
22848  int rc = SQLITE_OK;
22849  if( p ){
22850    assert( sqlite3GlobalConfig.mutex.xMutexTry );
22851    return sqlite3GlobalConfig.mutex.xMutexTry(p);
22852  }
22853  return rc;
22854}
22855
22856/*
22857** The sqlite3_mutex_leave() routine exits a mutex that was previously
22858** entered by the same thread.  The behavior is undefined if the mutex
22859** is not currently entered. If a NULL pointer is passed as an argument
22860** this function is a no-op.
22861*/
22862SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
22863  if( p ){
22864    assert( sqlite3GlobalConfig.mutex.xMutexLeave );
22865    sqlite3GlobalConfig.mutex.xMutexLeave(p);
22866  }
22867}
22868
22869#ifndef NDEBUG
22870/*
22871** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22872** intended for use inside assert() statements.
22873*/
22874SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
22875  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
22876  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
22877}
22878SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
22879  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
22880  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
22881}
22882#endif
22883
22884#endif /* !defined(SQLITE_MUTEX_OMIT) */
22885
22886/************** End of mutex.c ***********************************************/
22887/************** Begin file mutex_noop.c **************************************/
22888/*
22889** 2008 October 07
22890**
22891** The author disclaims copyright to this source code.  In place of
22892** a legal notice, here is a blessing:
22893**
22894**    May you do good and not evil.
22895**    May you find forgiveness for yourself and forgive others.
22896**    May you share freely, never taking more than you give.
22897**
22898*************************************************************************
22899** This file contains the C functions that implement mutexes.
22900**
22901** This implementation in this file does not provide any mutual
22902** exclusion and is thus suitable for use only in applications
22903** that use SQLite in a single thread.  The routines defined
22904** here are place-holders.  Applications can substitute working
22905** mutex routines at start-time using the
22906**
22907**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
22908**
22909** interface.
22910**
22911** If compiled with SQLITE_DEBUG, then additional logic is inserted
22912** that does error checking on mutexes to make sure they are being
22913** called correctly.
22914*/
22915/* #include "sqliteInt.h" */
22916
22917#ifndef SQLITE_MUTEX_OMIT
22918
22919#ifndef SQLITE_DEBUG
22920/*
22921** Stub routines for all mutex methods.
22922**
22923** This routines provide no mutual exclusion or error checking.
22924*/
22925static int noopMutexInit(void){ return SQLITE_OK; }
22926static int noopMutexEnd(void){ return SQLITE_OK; }
22927static sqlite3_mutex *noopMutexAlloc(int id){
22928  UNUSED_PARAMETER(id);
22929  return (sqlite3_mutex*)8;
22930}
22931static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22932static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22933static int noopMutexTry(sqlite3_mutex *p){
22934  UNUSED_PARAMETER(p);
22935  return SQLITE_OK;
22936}
22937static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22938
22939SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
22940  static const sqlite3_mutex_methods sMutex = {
22941    noopMutexInit,
22942    noopMutexEnd,
22943    noopMutexAlloc,
22944    noopMutexFree,
22945    noopMutexEnter,
22946    noopMutexTry,
22947    noopMutexLeave,
22948
22949    0,
22950    0,
22951  };
22952
22953  return &sMutex;
22954}
22955#endif /* !SQLITE_DEBUG */
22956
22957#ifdef SQLITE_DEBUG
22958/*
22959** In this implementation, error checking is provided for testing
22960** and debugging purposes.  The mutexes still do not provide any
22961** mutual exclusion.
22962*/
22963
22964/*
22965** The mutex object
22966*/
22967typedef struct sqlite3_debug_mutex {
22968  int id;     /* The mutex type */
22969  int cnt;    /* Number of entries without a matching leave */
22970} sqlite3_debug_mutex;
22971
22972/*
22973** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22974** intended for use inside assert() statements.
22975*/
22976static int debugMutexHeld(sqlite3_mutex *pX){
22977  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22978  return p==0 || p->cnt>0;
22979}
22980static int debugMutexNotheld(sqlite3_mutex *pX){
22981  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22982  return p==0 || p->cnt==0;
22983}
22984
22985/*
22986** Initialize and deinitialize the mutex subsystem.
22987*/
22988static int debugMutexInit(void){ return SQLITE_OK; }
22989static int debugMutexEnd(void){ return SQLITE_OK; }
22990
22991/*
22992** The sqlite3_mutex_alloc() routine allocates a new
22993** mutex and returns a pointer to it.  If it returns NULL
22994** that means that a mutex could not be allocated.
22995*/
22996static sqlite3_mutex *debugMutexAlloc(int id){
22997  static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
22998  sqlite3_debug_mutex *pNew = 0;
22999  switch( id ){
23000    case SQLITE_MUTEX_FAST:
23001    case SQLITE_MUTEX_RECURSIVE: {
23002      pNew = sqlite3Malloc(sizeof(*pNew));
23003      if( pNew ){
23004        pNew->id = id;
23005        pNew->cnt = 0;
23006      }
23007      break;
23008    }
23009    default: {
23010#ifdef SQLITE_ENABLE_API_ARMOR
23011      if( id-2<0 || id-2>=ArraySize(aStatic) ){
23012        (void)SQLITE_MISUSE_BKPT;
23013        return 0;
23014      }
23015#endif
23016      pNew = &aStatic[id-2];
23017      pNew->id = id;
23018      break;
23019    }
23020  }
23021  return (sqlite3_mutex*)pNew;
23022}
23023
23024/*
23025** This routine deallocates a previously allocated mutex.
23026*/
23027static void debugMutexFree(sqlite3_mutex *pX){
23028  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23029  assert( p->cnt==0 );
23030  if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
23031    sqlite3_free(p);
23032  }else{
23033#ifdef SQLITE_ENABLE_API_ARMOR
23034    (void)SQLITE_MISUSE_BKPT;
23035#endif
23036  }
23037}
23038
23039/*
23040** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
23041** to enter a mutex.  If another thread is already within the mutex,
23042** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
23043** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
23044** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
23045** be entered multiple times by the same thread.  In such cases the,
23046** mutex must be exited an equal number of times before another thread
23047** can enter.  If the same thread tries to enter any other kind of mutex
23048** more than once, the behavior is undefined.
23049*/
23050static void debugMutexEnter(sqlite3_mutex *pX){
23051  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23052  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
23053  p->cnt++;
23054}
23055static int debugMutexTry(sqlite3_mutex *pX){
23056  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23057  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
23058  p->cnt++;
23059  return SQLITE_OK;
23060}
23061
23062/*
23063** The sqlite3_mutex_leave() routine exits a mutex that was
23064** previously entered by the same thread.  The behavior
23065** is undefined if the mutex is not currently entered or
23066** is not currently allocated.  SQLite will never do either.
23067*/
23068static void debugMutexLeave(sqlite3_mutex *pX){
23069  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23070  assert( debugMutexHeld(pX) );
23071  p->cnt--;
23072  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
23073}
23074
23075SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
23076  static const sqlite3_mutex_methods sMutex = {
23077    debugMutexInit,
23078    debugMutexEnd,
23079    debugMutexAlloc,
23080    debugMutexFree,
23081    debugMutexEnter,
23082    debugMutexTry,
23083    debugMutexLeave,
23084
23085    debugMutexHeld,
23086    debugMutexNotheld
23087  };
23088
23089  return &sMutex;
23090}
23091#endif /* SQLITE_DEBUG */
23092
23093/*
23094** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
23095** is used regardless of the run-time threadsafety setting.
23096*/
23097#ifdef SQLITE_MUTEX_NOOP
23098SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
23099  return sqlite3NoopMutex();
23100}
23101#endif /* defined(SQLITE_MUTEX_NOOP) */
23102#endif /* !defined(SQLITE_MUTEX_OMIT) */
23103
23104/************** End of mutex_noop.c ******************************************/
23105/************** Begin file mutex_unix.c **************************************/
23106/*
23107** 2007 August 28
23108**
23109** The author disclaims copyright to this source code.  In place of
23110** a legal notice, here is a blessing:
23111**
23112**    May you do good and not evil.
23113**    May you find forgiveness for yourself and forgive others.
23114**    May you share freely, never taking more than you give.
23115**
23116*************************************************************************
23117** This file contains the C functions that implement mutexes for pthreads
23118*/
23119/* #include "sqliteInt.h" */
23120
23121/*
23122** The code in this file is only used if we are compiling threadsafe
23123** under unix with pthreads.
23124**
23125** Note that this implementation requires a version of pthreads that
23126** supports recursive mutexes.
23127*/
23128#ifdef SQLITE_MUTEX_PTHREADS
23129
23130#include <pthread.h>
23131
23132/*
23133** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
23134** are necessary under two condidtions:  (1) Debug builds and (2) using
23135** home-grown mutexes.  Encapsulate these conditions into a single #define.
23136*/
23137#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
23138# define SQLITE_MUTEX_NREF 1
23139#else
23140# define SQLITE_MUTEX_NREF 0
23141#endif
23142
23143/*
23144** Each recursive mutex is an instance of the following structure.
23145*/
23146struct sqlite3_mutex {
23147  pthread_mutex_t mutex;     /* Mutex controlling the lock */
23148#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
23149  int id;                    /* Mutex type */
23150#endif
23151#if SQLITE_MUTEX_NREF
23152  volatile int nRef;         /* Number of entrances */
23153  volatile pthread_t owner;  /* Thread that is within this mutex */
23154  int trace;                 /* True to trace changes */
23155#endif
23156};
23157#if SQLITE_MUTEX_NREF
23158#define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
23159#elif defined(SQLITE_ENABLE_API_ARMOR)
23160#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
23161#else
23162#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
23163#endif
23164
23165/*
23166** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
23167** intended for use only inside assert() statements.  On some platforms,
23168** there might be race conditions that can cause these routines to
23169** deliver incorrect results.  In particular, if pthread_equal() is
23170** not an atomic operation, then these routines might delivery
23171** incorrect results.  On most platforms, pthread_equal() is a
23172** comparison of two integers and is therefore atomic.  But we are
23173** told that HPUX is not such a platform.  If so, then these routines
23174** will not always work correctly on HPUX.
23175**
23176** On those platforms where pthread_equal() is not atomic, SQLite
23177** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
23178** make sure no assert() statements are evaluated and hence these
23179** routines are never called.
23180*/
23181#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
23182static int pthreadMutexHeld(sqlite3_mutex *p){
23183  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
23184}
23185static int pthreadMutexNotheld(sqlite3_mutex *p){
23186  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
23187}
23188#endif
23189
23190/*
23191** Try to provide a memory barrier operation, needed for initialization
23192** and also for the implementation of xShmBarrier in the VFS in cases
23193** where SQLite is compiled without mutexes.
23194*/
23195SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
23196#if defined(SQLITE_MEMORY_BARRIER)
23197  SQLITE_MEMORY_BARRIER;
23198#elif defined(__GNUC__) && GCC_VERSION>=4001000
23199  __sync_synchronize();
23200#endif
23201}
23202
23203/*
23204** Initialize and deinitialize the mutex subsystem.
23205*/
23206static int pthreadMutexInit(void){ return SQLITE_OK; }
23207static int pthreadMutexEnd(void){ return SQLITE_OK; }
23208
23209/*
23210** The sqlite3_mutex_alloc() routine allocates a new
23211** mutex and returns a pointer to it.  If it returns NULL
23212** that means that a mutex could not be allocated.  SQLite
23213** will unwind its stack and return an error.  The argument
23214** to sqlite3_mutex_alloc() is one of these integer constants:
23215**
23216** <ul>
23217** <li>  SQLITE_MUTEX_FAST
23218** <li>  SQLITE_MUTEX_RECURSIVE
23219** <li>  SQLITE_MUTEX_STATIC_MASTER
23220** <li>  SQLITE_MUTEX_STATIC_MEM
23221** <li>  SQLITE_MUTEX_STATIC_OPEN
23222** <li>  SQLITE_MUTEX_STATIC_PRNG
23223** <li>  SQLITE_MUTEX_STATIC_LRU
23224** <li>  SQLITE_MUTEX_STATIC_PMEM
23225** <li>  SQLITE_MUTEX_STATIC_APP1
23226** <li>  SQLITE_MUTEX_STATIC_APP2
23227** <li>  SQLITE_MUTEX_STATIC_APP3
23228** <li>  SQLITE_MUTEX_STATIC_VFS1
23229** <li>  SQLITE_MUTEX_STATIC_VFS2
23230** <li>  SQLITE_MUTEX_STATIC_VFS3
23231** </ul>
23232**
23233** The first two constants cause sqlite3_mutex_alloc() to create
23234** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
23235** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
23236** The mutex implementation does not need to make a distinction
23237** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
23238** not want to.  But SQLite will only request a recursive mutex in
23239** cases where it really needs one.  If a faster non-recursive mutex
23240** implementation is available on the host platform, the mutex subsystem
23241** might return such a mutex in response to SQLITE_MUTEX_FAST.
23242**
23243** The other allowed parameters to sqlite3_mutex_alloc() each return
23244** a pointer to a static preexisting mutex.  Six static mutexes are
23245** used by the current version of SQLite.  Future versions of SQLite
23246** may add additional static mutexes.  Static mutexes are for internal
23247** use by SQLite only.  Applications that use SQLite mutexes should
23248** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
23249** SQLITE_MUTEX_RECURSIVE.
23250**
23251** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
23252** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
23253** returns a different mutex on every call.  But for the static
23254** mutex types, the same mutex is returned on every call that has
23255** the same type number.
23256*/
23257static sqlite3_mutex *pthreadMutexAlloc(int iType){
23258  static sqlite3_mutex staticMutexes[] = {
23259    SQLITE3_MUTEX_INITIALIZER,
23260    SQLITE3_MUTEX_INITIALIZER,
23261    SQLITE3_MUTEX_INITIALIZER,
23262    SQLITE3_MUTEX_INITIALIZER,
23263    SQLITE3_MUTEX_INITIALIZER,
23264    SQLITE3_MUTEX_INITIALIZER,
23265    SQLITE3_MUTEX_INITIALIZER,
23266    SQLITE3_MUTEX_INITIALIZER,
23267    SQLITE3_MUTEX_INITIALIZER,
23268    SQLITE3_MUTEX_INITIALIZER,
23269    SQLITE3_MUTEX_INITIALIZER,
23270    SQLITE3_MUTEX_INITIALIZER
23271  };
23272  sqlite3_mutex *p;
23273  switch( iType ){
23274    case SQLITE_MUTEX_RECURSIVE: {
23275      p = sqlite3MallocZero( sizeof(*p) );
23276      if( p ){
23277#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23278        /* If recursive mutexes are not available, we will have to
23279        ** build our own.  See below. */
23280        pthread_mutex_init(&p->mutex, 0);
23281#else
23282        /* Use a recursive mutex if it is available */
23283        pthread_mutexattr_t recursiveAttr;
23284        pthread_mutexattr_init(&recursiveAttr);
23285        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
23286        pthread_mutex_init(&p->mutex, &recursiveAttr);
23287        pthread_mutexattr_destroy(&recursiveAttr);
23288#endif
23289      }
23290      break;
23291    }
23292    case SQLITE_MUTEX_FAST: {
23293      p = sqlite3MallocZero( sizeof(*p) );
23294      if( p ){
23295        pthread_mutex_init(&p->mutex, 0);
23296      }
23297      break;
23298    }
23299    default: {
23300#ifdef SQLITE_ENABLE_API_ARMOR
23301      if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
23302        (void)SQLITE_MISUSE_BKPT;
23303        return 0;
23304      }
23305#endif
23306      p = &staticMutexes[iType-2];
23307      break;
23308    }
23309  }
23310#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
23311  if( p ) p->id = iType;
23312#endif
23313  return p;
23314}
23315
23316
23317/*
23318** This routine deallocates a previously
23319** allocated mutex.  SQLite is careful to deallocate every
23320** mutex that it allocates.
23321*/
23322static void pthreadMutexFree(sqlite3_mutex *p){
23323  assert( p->nRef==0 );
23324#if SQLITE_ENABLE_API_ARMOR
23325  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
23326#endif
23327  {
23328    pthread_mutex_destroy(&p->mutex);
23329    sqlite3_free(p);
23330  }
23331#ifdef SQLITE_ENABLE_API_ARMOR
23332  else{
23333    (void)SQLITE_MISUSE_BKPT;
23334  }
23335#endif
23336}
23337
23338/*
23339** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
23340** to enter a mutex.  If another thread is already within the mutex,
23341** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
23342** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
23343** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
23344** be entered multiple times by the same thread.  In such cases the,
23345** mutex must be exited an equal number of times before another thread
23346** can enter.  If the same thread tries to enter any other kind of mutex
23347** more than once, the behavior is undefined.
23348*/
23349static void pthreadMutexEnter(sqlite3_mutex *p){
23350  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
23351
23352#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23353  /* If recursive mutexes are not available, then we have to grow
23354  ** our own.  This implementation assumes that pthread_equal()
23355  ** is atomic - that it cannot be deceived into thinking self
23356  ** and p->owner are equal if p->owner changes between two values
23357  ** that are not equal to self while the comparison is taking place.
23358  ** This implementation also assumes a coherent cache - that
23359  ** separate processes cannot read different values from the same
23360  ** address at the same time.  If either of these two conditions
23361  ** are not met, then the mutexes will fail and problems will result.
23362  */
23363  {
23364    pthread_t self = pthread_self();
23365    if( p->nRef>0 && pthread_equal(p->owner, self) ){
23366      p->nRef++;
23367    }else{
23368      pthread_mutex_lock(&p->mutex);
23369      assert( p->nRef==0 );
23370      p->owner = self;
23371      p->nRef = 1;
23372    }
23373  }
23374#else
23375  /* Use the built-in recursive mutexes if they are available.
23376  */
23377  pthread_mutex_lock(&p->mutex);
23378#if SQLITE_MUTEX_NREF
23379  assert( p->nRef>0 || p->owner==0 );
23380  p->owner = pthread_self();
23381  p->nRef++;
23382#endif
23383#endif
23384
23385#ifdef SQLITE_DEBUG
23386  if( p->trace ){
23387    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23388  }
23389#endif
23390}
23391static int pthreadMutexTry(sqlite3_mutex *p){
23392  int rc;
23393  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
23394
23395#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23396  /* If recursive mutexes are not available, then we have to grow
23397  ** our own.  This implementation assumes that pthread_equal()
23398  ** is atomic - that it cannot be deceived into thinking self
23399  ** and p->owner are equal if p->owner changes between two values
23400  ** that are not equal to self while the comparison is taking place.
23401  ** This implementation also assumes a coherent cache - that
23402  ** separate processes cannot read different values from the same
23403  ** address at the same time.  If either of these two conditions
23404  ** are not met, then the mutexes will fail and problems will result.
23405  */
23406  {
23407    pthread_t self = pthread_self();
23408    if( p->nRef>0 && pthread_equal(p->owner, self) ){
23409      p->nRef++;
23410      rc = SQLITE_OK;
23411    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
23412      assert( p->nRef==0 );
23413      p->owner = self;
23414      p->nRef = 1;
23415      rc = SQLITE_OK;
23416    }else{
23417      rc = SQLITE_BUSY;
23418    }
23419  }
23420#else
23421  /* Use the built-in recursive mutexes if they are available.
23422  */
23423  if( pthread_mutex_trylock(&p->mutex)==0 ){
23424#if SQLITE_MUTEX_NREF
23425    p->owner = pthread_self();
23426    p->nRef++;
23427#endif
23428    rc = SQLITE_OK;
23429  }else{
23430    rc = SQLITE_BUSY;
23431  }
23432#endif
23433
23434#ifdef SQLITE_DEBUG
23435  if( rc==SQLITE_OK && p->trace ){
23436    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23437  }
23438#endif
23439  return rc;
23440}
23441
23442/*
23443** The sqlite3_mutex_leave() routine exits a mutex that was
23444** previously entered by the same thread.  The behavior
23445** is undefined if the mutex is not currently entered or
23446** is not currently allocated.  SQLite will never do either.
23447*/
23448static void pthreadMutexLeave(sqlite3_mutex *p){
23449  assert( pthreadMutexHeld(p) );
23450#if SQLITE_MUTEX_NREF
23451  p->nRef--;
23452  if( p->nRef==0 ) p->owner = 0;
23453#endif
23454  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
23455
23456#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23457  if( p->nRef==0 ){
23458    pthread_mutex_unlock(&p->mutex);
23459  }
23460#else
23461  pthread_mutex_unlock(&p->mutex);
23462#endif
23463
23464#ifdef SQLITE_DEBUG
23465  if( p->trace ){
23466    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23467  }
23468#endif
23469}
23470
23471SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
23472  static const sqlite3_mutex_methods sMutex = {
23473    pthreadMutexInit,
23474    pthreadMutexEnd,
23475    pthreadMutexAlloc,
23476    pthreadMutexFree,
23477    pthreadMutexEnter,
23478    pthreadMutexTry,
23479    pthreadMutexLeave,
23480#ifdef SQLITE_DEBUG
23481    pthreadMutexHeld,
23482    pthreadMutexNotheld
23483#else
23484    0,
23485    0
23486#endif
23487  };
23488
23489  return &sMutex;
23490}
23491
23492#endif /* SQLITE_MUTEX_PTHREADS */
23493
23494/************** End of mutex_unix.c ******************************************/
23495/************** Begin file mutex_w32.c ***************************************/
23496/*
23497** 2007 August 14
23498**
23499** The author disclaims copyright to this source code.  In place of
23500** a legal notice, here is a blessing:
23501**
23502**    May you do good and not evil.
23503**    May you find forgiveness for yourself and forgive others.
23504**    May you share freely, never taking more than you give.
23505**
23506*************************************************************************
23507** This file contains the C functions that implement mutexes for Win32.
23508*/
23509/* #include "sqliteInt.h" */
23510
23511#if SQLITE_OS_WIN
23512/*
23513** Include code that is common to all os_*.c files
23514*/
23515/************** Include os_common.h in the middle of mutex_w32.c *************/
23516/************** Begin file os_common.h ***************************************/
23517/*
23518** 2004 May 22
23519**
23520** The author disclaims copyright to this source code.  In place of
23521** a legal notice, here is a blessing:
23522**
23523**    May you do good and not evil.
23524**    May you find forgiveness for yourself and forgive others.
23525**    May you share freely, never taking more than you give.
23526**
23527******************************************************************************
23528**
23529** This file contains macros and a little bit of code that is common to
23530** all of the platform-specific files (os_*.c) and is #included into those
23531** files.
23532**
23533** This file should be #included by the os_*.c files only.  It is not a
23534** general purpose header file.
23535*/
23536#ifndef _OS_COMMON_H_
23537#define _OS_COMMON_H_
23538
23539/*
23540** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23541** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23542** switch.  The following code should catch this problem at compile-time.
23543*/
23544#ifdef MEMORY_DEBUG
23545# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
23546#endif
23547
23548/*
23549** Macros for performance tracing.  Normally turned off.  Only works
23550** on i486 hardware.
23551*/
23552#ifdef SQLITE_PERFORMANCE_TRACE
23553
23554/*
23555** hwtime.h contains inline assembler code for implementing
23556** high-performance timing routines.
23557*/
23558/************** Include hwtime.h in the middle of os_common.h ****************/
23559/************** Begin file hwtime.h ******************************************/
23560/*
23561** 2008 May 27
23562**
23563** The author disclaims copyright to this source code.  In place of
23564** a legal notice, here is a blessing:
23565**
23566**    May you do good and not evil.
23567**    May you find forgiveness for yourself and forgive others.
23568**    May you share freely, never taking more than you give.
23569**
23570******************************************************************************
23571**
23572** This file contains inline asm code for retrieving "high-performance"
23573** counters for x86 class CPUs.
23574*/
23575#ifndef SQLITE_HWTIME_H
23576#define SQLITE_HWTIME_H
23577
23578/*
23579** The following routine only works on pentium-class (or newer) processors.
23580** It uses the RDTSC opcode to read the cycle count value out of the
23581** processor and returns that value.  This can be used for high-res
23582** profiling.
23583*/
23584#if (defined(__GNUC__) || defined(_MSC_VER)) && \
23585      (defined(i386) || defined(__i386__) || defined(_M_IX86))
23586
23587  #if defined(__GNUC__)
23588
23589  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23590     unsigned int lo, hi;
23591     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23592     return (sqlite_uint64)hi << 32 | lo;
23593  }
23594
23595  #elif defined(_MSC_VER)
23596
23597  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23598     __asm {
23599        rdtsc
23600        ret       ; return value at EDX:EAX
23601     }
23602  }
23603
23604  #endif
23605
23606#elif (defined(__GNUC__) && defined(__x86_64__))
23607
23608  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23609      unsigned long val;
23610      __asm__ __volatile__ ("rdtsc" : "=A" (val));
23611      return val;
23612  }
23613
23614#elif (defined(__GNUC__) && defined(__ppc__))
23615
23616  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23617      unsigned long long retval;
23618      unsigned long junk;
23619      __asm__ __volatile__ ("\n\
23620          1:      mftbu   %1\n\
23621                  mftb    %L0\n\
23622                  mftbu   %0\n\
23623                  cmpw    %0,%1\n\
23624                  bne     1b"
23625                  : "=r" (retval), "=r" (junk));
23626      return retval;
23627  }
23628
23629#else
23630
23631  #error Need implementation of sqlite3Hwtime() for your platform.
23632
23633  /*
23634  ** To compile without implementing sqlite3Hwtime() for your platform,
23635  ** you can remove the above #error and use the following
23636  ** stub function.  You will lose timing support for many
23637  ** of the debugging and testing utilities, but it should at
23638  ** least compile and run.
23639  */
23640SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23641
23642#endif
23643
23644#endif /* !defined(SQLITE_HWTIME_H) */
23645
23646/************** End of hwtime.h **********************************************/
23647/************** Continuing where we left off in os_common.h ******************/
23648
23649static sqlite_uint64 g_start;
23650static sqlite_uint64 g_elapsed;
23651#define TIMER_START       g_start=sqlite3Hwtime()
23652#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
23653#define TIMER_ELAPSED     g_elapsed
23654#else
23655#define TIMER_START
23656#define TIMER_END
23657#define TIMER_ELAPSED     ((sqlite_uint64)0)
23658#endif
23659
23660/*
23661** If we compile with the SQLITE_TEST macro set, then the following block
23662** of code will give us the ability to simulate a disk I/O error.  This
23663** is used for testing the I/O recovery logic.
23664*/
23665#if defined(SQLITE_TEST)
23666SQLITE_API extern int sqlite3_io_error_hit;
23667SQLITE_API extern int sqlite3_io_error_hardhit;
23668SQLITE_API extern int sqlite3_io_error_pending;
23669SQLITE_API extern int sqlite3_io_error_persist;
23670SQLITE_API extern int sqlite3_io_error_benign;
23671SQLITE_API extern int sqlite3_diskfull_pending;
23672SQLITE_API extern int sqlite3_diskfull;
23673#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23674#define SimulateIOError(CODE)  \
23675  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23676       || sqlite3_io_error_pending-- == 1 )  \
23677              { local_ioerr(); CODE; }
23678static void local_ioerr(){
23679  IOTRACE(("IOERR\n"));
23680  sqlite3_io_error_hit++;
23681  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23682}
23683#define SimulateDiskfullError(CODE) \
23684   if( sqlite3_diskfull_pending ){ \
23685     if( sqlite3_diskfull_pending == 1 ){ \
23686       local_ioerr(); \
23687       sqlite3_diskfull = 1; \
23688       sqlite3_io_error_hit = 1; \
23689       CODE; \
23690     }else{ \
23691       sqlite3_diskfull_pending--; \
23692     } \
23693   }
23694#else
23695#define SimulateIOErrorBenign(X)
23696#define SimulateIOError(A)
23697#define SimulateDiskfullError(A)
23698#endif /* defined(SQLITE_TEST) */
23699
23700/*
23701** When testing, keep a count of the number of open files.
23702*/
23703#if defined(SQLITE_TEST)
23704SQLITE_API extern int sqlite3_open_file_count;
23705#define OpenCounter(X)  sqlite3_open_file_count+=(X)
23706#else
23707#define OpenCounter(X)
23708#endif /* defined(SQLITE_TEST) */
23709
23710#endif /* !defined(_OS_COMMON_H_) */
23711
23712/************** End of os_common.h *******************************************/
23713/************** Continuing where we left off in mutex_w32.c ******************/
23714
23715/*
23716** Include the header file for the Windows VFS.
23717*/
23718/************** Include os_win.h in the middle of mutex_w32.c ****************/
23719/************** Begin file os_win.h ******************************************/
23720/*
23721** 2013 November 25
23722**
23723** The author disclaims copyright to this source code.  In place of
23724** a legal notice, here is a blessing:
23725**
23726**    May you do good and not evil.
23727**    May you find forgiveness for yourself and forgive others.
23728**    May you share freely, never taking more than you give.
23729**
23730******************************************************************************
23731**
23732** This file contains code that is specific to Windows.
23733*/
23734#ifndef SQLITE_OS_WIN_H
23735#define SQLITE_OS_WIN_H
23736
23737/*
23738** Include the primary Windows SDK header file.
23739*/
23740#include "windows.h"
23741
23742#ifdef __CYGWIN__
23743# include <sys/cygwin.h>
23744# include <errno.h> /* amalgamator: dontcache */
23745#endif
23746
23747/*
23748** Determine if we are dealing with Windows NT.
23749**
23750** We ought to be able to determine if we are compiling for Windows 9x or
23751** Windows NT using the _WIN32_WINNT macro as follows:
23752**
23753** #if defined(_WIN32_WINNT)
23754** # define SQLITE_OS_WINNT 1
23755** #else
23756** # define SQLITE_OS_WINNT 0
23757** #endif
23758**
23759** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
23760** it ought to, so the above test does not work.  We'll just assume that
23761** everything is Windows NT unless the programmer explicitly says otherwise
23762** by setting SQLITE_OS_WINNT to 0.
23763*/
23764#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
23765# define SQLITE_OS_WINNT 1
23766#endif
23767
23768/*
23769** Determine if we are dealing with Windows CE - which has a much reduced
23770** API.
23771*/
23772#if defined(_WIN32_WCE)
23773# define SQLITE_OS_WINCE 1
23774#else
23775# define SQLITE_OS_WINCE 0
23776#endif
23777
23778/*
23779** Determine if we are dealing with WinRT, which provides only a subset of
23780** the full Win32 API.
23781*/
23782#if !defined(SQLITE_OS_WINRT)
23783# define SQLITE_OS_WINRT 0
23784#endif
23785
23786/*
23787** For WinCE, some API function parameters do not appear to be declared as
23788** volatile.
23789*/
23790#if SQLITE_OS_WINCE
23791# define SQLITE_WIN32_VOLATILE
23792#else
23793# define SQLITE_WIN32_VOLATILE volatile
23794#endif
23795
23796/*
23797** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
23798** functions are not available (e.g. those not using MSVC, Cygwin, etc).
23799*/
23800#if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
23801    SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
23802# define SQLITE_OS_WIN_THREADS 1
23803#else
23804# define SQLITE_OS_WIN_THREADS 0
23805#endif
23806
23807#endif /* SQLITE_OS_WIN_H */
23808
23809/************** End of os_win.h **********************************************/
23810/************** Continuing where we left off in mutex_w32.c ******************/
23811#endif
23812
23813/*
23814** The code in this file is only used if we are compiling multithreaded
23815** on a Win32 system.
23816*/
23817#ifdef SQLITE_MUTEX_W32
23818
23819/*
23820** Each recursive mutex is an instance of the following structure.
23821*/
23822struct sqlite3_mutex {
23823  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
23824  int id;                    /* Mutex type */
23825#ifdef SQLITE_DEBUG
23826  volatile int nRef;         /* Number of enterances */
23827  volatile DWORD owner;      /* Thread holding this mutex */
23828  volatile int trace;        /* True to trace changes */
23829#endif
23830};
23831
23832/*
23833** These are the initializer values used when declaring a "static" mutex
23834** on Win32.  It should be noted that all mutexes require initialization
23835** on the Win32 platform.
23836*/
23837#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
23838
23839#ifdef SQLITE_DEBUG
23840#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
23841                                    0L, (DWORD)0, 0 }
23842#else
23843#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
23844#endif
23845
23846#ifdef SQLITE_DEBUG
23847/*
23848** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
23849** intended for use only inside assert() statements.
23850*/
23851static int winMutexHeld(sqlite3_mutex *p){
23852  return p->nRef!=0 && p->owner==GetCurrentThreadId();
23853}
23854
23855static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
23856  return p->nRef==0 || p->owner!=tid;
23857}
23858
23859static int winMutexNotheld(sqlite3_mutex *p){
23860  DWORD tid = GetCurrentThreadId();
23861  return winMutexNotheld2(p, tid);
23862}
23863#endif
23864
23865/*
23866** Try to provide a memory barrier operation, needed for initialization
23867** and also for the xShmBarrier method of the VFS in cases when SQLite is
23868** compiled without mutexes (SQLITE_THREADSAFE=0).
23869*/
23870SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
23871#if defined(SQLITE_MEMORY_BARRIER)
23872  SQLITE_MEMORY_BARRIER;
23873#elif defined(__GNUC__)
23874  __sync_synchronize();
23875#elif MSVC_VERSION>=1300
23876  _ReadWriteBarrier();
23877#elif defined(MemoryBarrier)
23878  MemoryBarrier();
23879#endif
23880}
23881
23882/*
23883** Initialize and deinitialize the mutex subsystem.
23884*/
23885static sqlite3_mutex winMutex_staticMutexes[] = {
23886  SQLITE3_MUTEX_INITIALIZER,
23887  SQLITE3_MUTEX_INITIALIZER,
23888  SQLITE3_MUTEX_INITIALIZER,
23889  SQLITE3_MUTEX_INITIALIZER,
23890  SQLITE3_MUTEX_INITIALIZER,
23891  SQLITE3_MUTEX_INITIALIZER,
23892  SQLITE3_MUTEX_INITIALIZER,
23893  SQLITE3_MUTEX_INITIALIZER,
23894  SQLITE3_MUTEX_INITIALIZER,
23895  SQLITE3_MUTEX_INITIALIZER,
23896  SQLITE3_MUTEX_INITIALIZER,
23897  SQLITE3_MUTEX_INITIALIZER
23898};
23899
23900static int winMutex_isInit = 0;
23901static int winMutex_isNt = -1; /* <0 means "need to query" */
23902
23903/* As the winMutexInit() and winMutexEnd() functions are called as part
23904** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
23905** "interlocked" magic used here is probably not strictly necessary.
23906*/
23907static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
23908
23909SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
23910SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
23911
23912static int winMutexInit(void){
23913  /* The first to increment to 1 does actual initialization */
23914  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
23915    int i;
23916    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
23917#if SQLITE_OS_WINRT
23918      InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
23919#else
23920      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
23921#endif
23922    }
23923    winMutex_isInit = 1;
23924  }else{
23925    /* Another thread is (in the process of) initializing the static
23926    ** mutexes */
23927    while( !winMutex_isInit ){
23928      sqlite3_win32_sleep(1);
23929    }
23930  }
23931  return SQLITE_OK;
23932}
23933
23934static int winMutexEnd(void){
23935  /* The first to decrement to 0 does actual shutdown
23936  ** (which should be the last to shutdown.) */
23937  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
23938    if( winMutex_isInit==1 ){
23939      int i;
23940      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
23941        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
23942      }
23943      winMutex_isInit = 0;
23944    }
23945  }
23946  return SQLITE_OK;
23947}
23948
23949/*
23950** The sqlite3_mutex_alloc() routine allocates a new
23951** mutex and returns a pointer to it.  If it returns NULL
23952** that means that a mutex could not be allocated.  SQLite
23953** will unwind its stack and return an error.  The argument
23954** to sqlite3_mutex_alloc() is one of these integer constants:
23955**
23956** <ul>
23957** <li>  SQLITE_MUTEX_FAST
23958** <li>  SQLITE_MUTEX_RECURSIVE
23959** <li>  SQLITE_MUTEX_STATIC_MASTER
23960** <li>  SQLITE_MUTEX_STATIC_MEM
23961** <li>  SQLITE_MUTEX_STATIC_OPEN
23962** <li>  SQLITE_MUTEX_STATIC_PRNG
23963** <li>  SQLITE_MUTEX_STATIC_LRU
23964** <li>  SQLITE_MUTEX_STATIC_PMEM
23965** <li>  SQLITE_MUTEX_STATIC_APP1
23966** <li>  SQLITE_MUTEX_STATIC_APP2
23967** <li>  SQLITE_MUTEX_STATIC_APP3
23968** <li>  SQLITE_MUTEX_STATIC_VFS1
23969** <li>  SQLITE_MUTEX_STATIC_VFS2
23970** <li>  SQLITE_MUTEX_STATIC_VFS3
23971** </ul>
23972**
23973** The first two constants cause sqlite3_mutex_alloc() to create
23974** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
23975** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
23976** The mutex implementation does not need to make a distinction
23977** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
23978** not want to.  But SQLite will only request a recursive mutex in
23979** cases where it really needs one.  If a faster non-recursive mutex
23980** implementation is available on the host platform, the mutex subsystem
23981** might return such a mutex in response to SQLITE_MUTEX_FAST.
23982**
23983** The other allowed parameters to sqlite3_mutex_alloc() each return
23984** a pointer to a static preexisting mutex.  Six static mutexes are
23985** used by the current version of SQLite.  Future versions of SQLite
23986** may add additional static mutexes.  Static mutexes are for internal
23987** use by SQLite only.  Applications that use SQLite mutexes should
23988** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
23989** SQLITE_MUTEX_RECURSIVE.
23990**
23991** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
23992** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
23993** returns a different mutex on every call.  But for the static
23994** mutex types, the same mutex is returned on every call that has
23995** the same type number.
23996*/
23997static sqlite3_mutex *winMutexAlloc(int iType){
23998  sqlite3_mutex *p;
23999
24000  switch( iType ){
24001    case SQLITE_MUTEX_FAST:
24002    case SQLITE_MUTEX_RECURSIVE: {
24003      p = sqlite3MallocZero( sizeof(*p) );
24004      if( p ){
24005        p->id = iType;
24006#ifdef SQLITE_DEBUG
24007#ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
24008        p->trace = 1;
24009#endif
24010#endif
24011#if SQLITE_OS_WINRT
24012        InitializeCriticalSectionEx(&p->mutex, 0, 0);
24013#else
24014        InitializeCriticalSection(&p->mutex);
24015#endif
24016      }
24017      break;
24018    }
24019    default: {
24020#ifdef SQLITE_ENABLE_API_ARMOR
24021      if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
24022        (void)SQLITE_MISUSE_BKPT;
24023        return 0;
24024      }
24025#endif
24026      p = &winMutex_staticMutexes[iType-2];
24027      p->id = iType;
24028#ifdef SQLITE_DEBUG
24029#ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
24030      p->trace = 1;
24031#endif
24032#endif
24033      break;
24034    }
24035  }
24036  return p;
24037}
24038
24039
24040/*
24041** This routine deallocates a previously
24042** allocated mutex.  SQLite is careful to deallocate every
24043** mutex that it allocates.
24044*/
24045static void winMutexFree(sqlite3_mutex *p){
24046  assert( p );
24047  assert( p->nRef==0 && p->owner==0 );
24048  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
24049    DeleteCriticalSection(&p->mutex);
24050    sqlite3_free(p);
24051  }else{
24052#ifdef SQLITE_ENABLE_API_ARMOR
24053    (void)SQLITE_MISUSE_BKPT;
24054#endif
24055  }
24056}
24057
24058/*
24059** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
24060** to enter a mutex.  If another thread is already within the mutex,
24061** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
24062** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
24063** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
24064** be entered multiple times by the same thread.  In such cases the,
24065** mutex must be exited an equal number of times before another thread
24066** can enter.  If the same thread tries to enter any other kind of mutex
24067** more than once, the behavior is undefined.
24068*/
24069static void winMutexEnter(sqlite3_mutex *p){
24070#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
24071  DWORD tid = GetCurrentThreadId();
24072#endif
24073#ifdef SQLITE_DEBUG
24074  assert( p );
24075  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
24076#else
24077  assert( p );
24078#endif
24079  assert( winMutex_isInit==1 );
24080  EnterCriticalSection(&p->mutex);
24081#ifdef SQLITE_DEBUG
24082  assert( p->nRef>0 || p->owner==0 );
24083  p->owner = tid;
24084  p->nRef++;
24085  if( p->trace ){
24086    OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
24087             tid, p->id, p, p->trace, p->nRef));
24088  }
24089#endif
24090}
24091
24092static int winMutexTry(sqlite3_mutex *p){
24093#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
24094  DWORD tid = GetCurrentThreadId();
24095#endif
24096  int rc = SQLITE_BUSY;
24097  assert( p );
24098  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
24099  /*
24100  ** The sqlite3_mutex_try() routine is very rarely used, and when it
24101  ** is used it is merely an optimization.  So it is OK for it to always
24102  ** fail.
24103  **
24104  ** The TryEnterCriticalSection() interface is only available on WinNT.
24105  ** And some windows compilers complain if you try to use it without
24106  ** first doing some #defines that prevent SQLite from building on Win98.
24107  ** For that reason, we will omit this optimization for now.  See
24108  ** ticket #2685.
24109  */
24110#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
24111  assert( winMutex_isInit==1 );
24112  assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
24113  if( winMutex_isNt<0 ){
24114    winMutex_isNt = sqlite3_win32_is_nt();
24115  }
24116  assert( winMutex_isNt==0 || winMutex_isNt==1 );
24117  if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
24118#ifdef SQLITE_DEBUG
24119    p->owner = tid;
24120    p->nRef++;
24121#endif
24122    rc = SQLITE_OK;
24123  }
24124#else
24125  UNUSED_PARAMETER(p);
24126#endif
24127#ifdef SQLITE_DEBUG
24128  if( p->trace ){
24129    OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
24130             tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
24131  }
24132#endif
24133  return rc;
24134}
24135
24136/*
24137** The sqlite3_mutex_leave() routine exits a mutex that was
24138** previously entered by the same thread.  The behavior
24139** is undefined if the mutex is not currently entered or
24140** is not currently allocated.  SQLite will never do either.
24141*/
24142static void winMutexLeave(sqlite3_mutex *p){
24143#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
24144  DWORD tid = GetCurrentThreadId();
24145#endif
24146  assert( p );
24147#ifdef SQLITE_DEBUG
24148  assert( p->nRef>0 );
24149  assert( p->owner==tid );
24150  p->nRef--;
24151  if( p->nRef==0 ) p->owner = 0;
24152  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
24153#endif
24154  assert( winMutex_isInit==1 );
24155  LeaveCriticalSection(&p->mutex);
24156#ifdef SQLITE_DEBUG
24157  if( p->trace ){
24158    OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
24159             tid, p->id, p, p->trace, p->nRef));
24160  }
24161#endif
24162}
24163
24164SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
24165  static const sqlite3_mutex_methods sMutex = {
24166    winMutexInit,
24167    winMutexEnd,
24168    winMutexAlloc,
24169    winMutexFree,
24170    winMutexEnter,
24171    winMutexTry,
24172    winMutexLeave,
24173#ifdef SQLITE_DEBUG
24174    winMutexHeld,
24175    winMutexNotheld
24176#else
24177    0,
24178    0
24179#endif
24180  };
24181  return &sMutex;
24182}
24183
24184#endif /* SQLITE_MUTEX_W32 */
24185
24186/************** End of mutex_w32.c *******************************************/
24187/************** Begin file malloc.c ******************************************/
24188/*
24189** 2001 September 15
24190**
24191** The author disclaims copyright to this source code.  In place of
24192** a legal notice, here is a blessing:
24193**
24194**    May you do good and not evil.
24195**    May you find forgiveness for yourself and forgive others.
24196**    May you share freely, never taking more than you give.
24197**
24198*************************************************************************
24199**
24200** Memory allocation functions used throughout sqlite.
24201*/
24202/* #include "sqliteInt.h" */
24203/* #include <stdarg.h> */
24204
24205/*
24206** Attempt to release up to n bytes of non-essential memory currently
24207** held by SQLite. An example of non-essential memory is memory used to
24208** cache database pages that are not currently in use.
24209*/
24210SQLITE_API int sqlite3_release_memory(int n){
24211#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24212  return sqlite3PcacheReleaseMemory(n);
24213#else
24214  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
24215  ** is a no-op returning zero if SQLite is not compiled with
24216  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
24217  UNUSED_PARAMETER(n);
24218  return 0;
24219#endif
24220}
24221
24222/*
24223** An instance of the following object records the location of
24224** each unused scratch buffer.
24225*/
24226typedef struct ScratchFreeslot {
24227  struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
24228} ScratchFreeslot;
24229
24230/*
24231** State information local to the memory allocation subsystem.
24232*/
24233static SQLITE_WSD struct Mem0Global {
24234  sqlite3_mutex *mutex;         /* Mutex to serialize access */
24235  sqlite3_int64 alarmThreshold; /* The soft heap limit */
24236
24237  /*
24238  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
24239  ** (so that a range test can be used to determine if an allocation
24240  ** being freed came from pScratch) and a pointer to the list of
24241  ** unused scratch allocations.
24242  */
24243  void *pScratchEnd;
24244  ScratchFreeslot *pScratchFree;
24245  u32 nScratchFree;
24246
24247  /*
24248  ** True if heap is nearly "full" where "full" is defined by the
24249  ** sqlite3_soft_heap_limit() setting.
24250  */
24251  int nearlyFull;
24252} mem0 = { 0, 0, 0, 0, 0, 0 };
24253
24254#define mem0 GLOBAL(struct Mem0Global, mem0)
24255
24256/*
24257** Return the memory allocator mutex. sqlite3_status() needs it.
24258*/
24259SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
24260  return mem0.mutex;
24261}
24262
24263#ifndef SQLITE_OMIT_DEPRECATED
24264/*
24265** Deprecated external interface.  It used to set an alarm callback
24266** that was invoked when memory usage grew too large.  Now it is a
24267** no-op.
24268*/
24269SQLITE_API int sqlite3_memory_alarm(
24270  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
24271  void *pArg,
24272  sqlite3_int64 iThreshold
24273){
24274  (void)xCallback;
24275  (void)pArg;
24276  (void)iThreshold;
24277  return SQLITE_OK;
24278}
24279#endif
24280
24281/*
24282** Set the soft heap-size limit for the library. Passing a zero or
24283** negative value indicates no limit.
24284*/
24285SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
24286  sqlite3_int64 priorLimit;
24287  sqlite3_int64 excess;
24288  sqlite3_int64 nUsed;
24289#ifndef SQLITE_OMIT_AUTOINIT
24290  int rc = sqlite3_initialize();
24291  if( rc ) return -1;
24292#endif
24293  sqlite3_mutex_enter(mem0.mutex);
24294  priorLimit = mem0.alarmThreshold;
24295  if( n<0 ){
24296    sqlite3_mutex_leave(mem0.mutex);
24297    return priorLimit;
24298  }
24299  mem0.alarmThreshold = n;
24300  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
24301  mem0.nearlyFull = (n>0 && n<=nUsed);
24302  sqlite3_mutex_leave(mem0.mutex);
24303  excess = sqlite3_memory_used() - n;
24304  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
24305  return priorLimit;
24306}
24307SQLITE_API void sqlite3_soft_heap_limit(int n){
24308  if( n<0 ) n = 0;
24309  sqlite3_soft_heap_limit64(n);
24310}
24311
24312/*
24313** Initialize the memory allocation subsystem.
24314*/
24315SQLITE_PRIVATE int sqlite3MallocInit(void){
24316  int rc;
24317  if( sqlite3GlobalConfig.m.xMalloc==0 ){
24318    sqlite3MemSetDefault();
24319  }
24320  memset(&mem0, 0, sizeof(mem0));
24321  mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
24322  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
24323      && sqlite3GlobalConfig.nScratch>0 ){
24324    int i, n, sz;
24325    ScratchFreeslot *pSlot;
24326    sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
24327    sqlite3GlobalConfig.szScratch = sz;
24328    pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
24329    n = sqlite3GlobalConfig.nScratch;
24330    mem0.pScratchFree = pSlot;
24331    mem0.nScratchFree = n;
24332    for(i=0; i<n-1; i++){
24333      pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
24334      pSlot = pSlot->pNext;
24335    }
24336    pSlot->pNext = 0;
24337    mem0.pScratchEnd = (void*)&pSlot[1];
24338  }else{
24339    mem0.pScratchEnd = 0;
24340    sqlite3GlobalConfig.pScratch = 0;
24341    sqlite3GlobalConfig.szScratch = 0;
24342    sqlite3GlobalConfig.nScratch = 0;
24343  }
24344  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
24345      || sqlite3GlobalConfig.nPage<=0 ){
24346    sqlite3GlobalConfig.pPage = 0;
24347    sqlite3GlobalConfig.szPage = 0;
24348  }
24349  rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
24350  if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
24351  return rc;
24352}
24353
24354/*
24355** Return true if the heap is currently under memory pressure - in other
24356** words if the amount of heap used is close to the limit set by
24357** sqlite3_soft_heap_limit().
24358*/
24359SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
24360  return mem0.nearlyFull;
24361}
24362
24363/*
24364** Deinitialize the memory allocation subsystem.
24365*/
24366SQLITE_PRIVATE void sqlite3MallocEnd(void){
24367  if( sqlite3GlobalConfig.m.xShutdown ){
24368    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
24369  }
24370  memset(&mem0, 0, sizeof(mem0));
24371}
24372
24373/*
24374** Return the amount of memory currently checked out.
24375*/
24376SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
24377  sqlite3_int64 res, mx;
24378  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
24379  return res;
24380}
24381
24382/*
24383** Return the maximum amount of memory that has ever been
24384** checked out since either the beginning of this process
24385** or since the most recent reset.
24386*/
24387SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
24388  sqlite3_int64 res, mx;
24389  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
24390  return mx;
24391}
24392
24393/*
24394** Trigger the alarm
24395*/
24396static void sqlite3MallocAlarm(int nByte){
24397  if( mem0.alarmThreshold<=0 ) return;
24398  sqlite3_mutex_leave(mem0.mutex);
24399  sqlite3_release_memory(nByte);
24400  sqlite3_mutex_enter(mem0.mutex);
24401}
24402
24403/*
24404** Do a memory allocation with statistics and alarms.  Assume the
24405** lock is already held.
24406*/
24407static void mallocWithAlarm(int n, void **pp){
24408  void *p;
24409  int nFull;
24410  assert( sqlite3_mutex_held(mem0.mutex) );
24411  assert( n>0 );
24412
24413  /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
24414  ** implementation of malloc_good_size(), which must be called in debug
24415  ** mode and specifically when the DMD "Dark Matter Detector" is enabled
24416  ** or else a crash results.  Hence, do not attempt to optimize out the
24417  ** following xRoundup() call. */
24418  nFull = sqlite3GlobalConfig.m.xRoundup(n);
24419
24420#ifdef SQLITE_MAX_MEMORY
24421  if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
24422    *pp = 0;
24423    return;
24424  }
24425#endif
24426
24427  sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
24428  if( mem0.alarmThreshold>0 ){
24429    sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
24430    if( nUsed >= mem0.alarmThreshold - nFull ){
24431      mem0.nearlyFull = 1;
24432      sqlite3MallocAlarm(nFull);
24433    }else{
24434      mem0.nearlyFull = 0;
24435    }
24436  }
24437  p = sqlite3GlobalConfig.m.xMalloc(nFull);
24438#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24439  if( p==0 && mem0.alarmThreshold>0 ){
24440    sqlite3MallocAlarm(nFull);
24441    p = sqlite3GlobalConfig.m.xMalloc(nFull);
24442  }
24443#endif
24444  if( p ){
24445    nFull = sqlite3MallocSize(p);
24446    sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
24447    sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
24448  }
24449  *pp = p;
24450}
24451
24452/*
24453** Allocate memory.  This routine is like sqlite3_malloc() except that it
24454** assumes the memory subsystem has already been initialized.
24455*/
24456SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
24457  void *p;
24458  if( n==0 || n>=0x7fffff00 ){
24459    /* A memory allocation of a number of bytes which is near the maximum
24460    ** signed integer value might cause an integer overflow inside of the
24461    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
24462    ** 255 bytes of overhead.  SQLite itself will never use anything near
24463    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
24464    p = 0;
24465  }else if( sqlite3GlobalConfig.bMemstat ){
24466    sqlite3_mutex_enter(mem0.mutex);
24467    mallocWithAlarm((int)n, &p);
24468    sqlite3_mutex_leave(mem0.mutex);
24469  }else{
24470    p = sqlite3GlobalConfig.m.xMalloc((int)n);
24471  }
24472  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
24473  return p;
24474}
24475
24476/*
24477** This version of the memory allocation is for use by the application.
24478** First make sure the memory subsystem is initialized, then do the
24479** allocation.
24480*/
24481SQLITE_API void *sqlite3_malloc(int n){
24482#ifndef SQLITE_OMIT_AUTOINIT
24483  if( sqlite3_initialize() ) return 0;
24484#endif
24485  return n<=0 ? 0 : sqlite3Malloc(n);
24486}
24487SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
24488#ifndef SQLITE_OMIT_AUTOINIT
24489  if( sqlite3_initialize() ) return 0;
24490#endif
24491  return sqlite3Malloc(n);
24492}
24493
24494/*
24495** Each thread may only have a single outstanding allocation from
24496** xScratchMalloc().  We verify this constraint in the single-threaded
24497** case by setting scratchAllocOut to 1 when an allocation
24498** is outstanding clearing it when the allocation is freed.
24499*/
24500#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24501static int scratchAllocOut = 0;
24502#endif
24503
24504
24505/*
24506** Allocate memory that is to be used and released right away.
24507** This routine is similar to alloca() in that it is not intended
24508** for situations where the memory might be held long-term.  This
24509** routine is intended to get memory to old large transient data
24510** structures that would not normally fit on the stack of an
24511** embedded processor.
24512*/
24513SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
24514  void *p;
24515  assert( n>0 );
24516
24517  sqlite3_mutex_enter(mem0.mutex);
24518  sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n);
24519  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
24520    p = mem0.pScratchFree;
24521    mem0.pScratchFree = mem0.pScratchFree->pNext;
24522    mem0.nScratchFree--;
24523    sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
24524    sqlite3_mutex_leave(mem0.mutex);
24525  }else{
24526    sqlite3_mutex_leave(mem0.mutex);
24527    p = sqlite3Malloc(n);
24528    if( sqlite3GlobalConfig.bMemstat && p ){
24529      sqlite3_mutex_enter(mem0.mutex);
24530      sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
24531      sqlite3_mutex_leave(mem0.mutex);
24532    }
24533    sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
24534  }
24535  assert( sqlite3_mutex_notheld(mem0.mutex) );
24536
24537
24538#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24539  /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
24540  ** buffers per thread.
24541  **
24542  ** This can only be checked in single-threaded mode.
24543  */
24544  assert( scratchAllocOut==0 );
24545  if( p ) scratchAllocOut++;
24546#endif
24547
24548  return p;
24549}
24550SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
24551  if( p ){
24552
24553#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24554    /* Verify that no more than two scratch allocation per thread
24555    ** is outstanding at one time.  (This is only checked in the
24556    ** single-threaded case since checking in the multi-threaded case
24557    ** would be much more complicated.) */
24558    assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
24559    scratchAllocOut--;
24560#endif
24561
24562    if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){
24563      /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
24564      ScratchFreeslot *pSlot;
24565      pSlot = (ScratchFreeslot*)p;
24566      sqlite3_mutex_enter(mem0.mutex);
24567      pSlot->pNext = mem0.pScratchFree;
24568      mem0.pScratchFree = pSlot;
24569      mem0.nScratchFree++;
24570      assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
24571      sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
24572      sqlite3_mutex_leave(mem0.mutex);
24573    }else{
24574      /* Release memory back to the heap */
24575      assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
24576      assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
24577      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24578      if( sqlite3GlobalConfig.bMemstat ){
24579        int iSize = sqlite3MallocSize(p);
24580        sqlite3_mutex_enter(mem0.mutex);
24581        sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
24582        sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
24583        sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
24584        sqlite3GlobalConfig.m.xFree(p);
24585        sqlite3_mutex_leave(mem0.mutex);
24586      }else{
24587        sqlite3GlobalConfig.m.xFree(p);
24588      }
24589    }
24590  }
24591}
24592
24593/*
24594** TRUE if p is a lookaside memory allocation from db
24595*/
24596#ifndef SQLITE_OMIT_LOOKASIDE
24597static int isLookaside(sqlite3 *db, void *p){
24598  return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
24599}
24600#else
24601#define isLookaside(A,B) 0
24602#endif
24603
24604/*
24605** Return the size of a memory allocation previously obtained from
24606** sqlite3Malloc() or sqlite3_malloc().
24607*/
24608SQLITE_PRIVATE int sqlite3MallocSize(void *p){
24609  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24610  return sqlite3GlobalConfig.m.xSize(p);
24611}
24612SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
24613  assert( p!=0 );
24614  if( db==0 || !isLookaside(db,p) ){
24615#ifdef SQLITE_DEBUG
24616    if( db==0 ){
24617      assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24618      assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24619    }else{
24620      assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24621      assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24622    }
24623#endif
24624    return sqlite3GlobalConfig.m.xSize(p);
24625  }else{
24626    assert( sqlite3_mutex_held(db->mutex) );
24627    return db->lookaside.sz;
24628  }
24629}
24630SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
24631  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24632  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24633  return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
24634}
24635
24636/*
24637** Free memory previously obtained from sqlite3Malloc().
24638*/
24639SQLITE_API void sqlite3_free(void *p){
24640  if( p==0 ) return;  /* IMP: R-49053-54554 */
24641  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24642  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24643  if( sqlite3GlobalConfig.bMemstat ){
24644    sqlite3_mutex_enter(mem0.mutex);
24645    sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
24646    sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
24647    sqlite3GlobalConfig.m.xFree(p);
24648    sqlite3_mutex_leave(mem0.mutex);
24649  }else{
24650    sqlite3GlobalConfig.m.xFree(p);
24651  }
24652}
24653
24654/*
24655** Add the size of memory allocation "p" to the count in
24656** *db->pnBytesFreed.
24657*/
24658static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
24659  *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
24660}
24661
24662/*
24663** Free memory that might be associated with a particular database
24664** connection.
24665*/
24666SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
24667  assert( db==0 || sqlite3_mutex_held(db->mutex) );
24668  if( p==0 ) return;
24669  if( db ){
24670    if( db->pnBytesFreed ){
24671      measureAllocationSize(db, p);
24672      return;
24673    }
24674    if( isLookaside(db, p) ){
24675      LookasideSlot *pBuf = (LookasideSlot*)p;
24676#ifdef SQLITE_DEBUG
24677      /* Trash all content in the buffer being freed */
24678      memset(p, 0xaa, db->lookaside.sz);
24679#endif
24680      pBuf->pNext = db->lookaside.pFree;
24681      db->lookaside.pFree = pBuf;
24682      db->lookaside.nOut--;
24683      return;
24684    }
24685  }
24686  assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24687  assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24688  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
24689  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24690  sqlite3_free(p);
24691}
24692
24693/*
24694** Change the size of an existing memory allocation
24695*/
24696SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
24697  int nOld, nNew, nDiff;
24698  void *pNew;
24699  assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
24700  assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
24701  if( pOld==0 ){
24702    return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
24703  }
24704  if( nBytes==0 ){
24705    sqlite3_free(pOld); /* IMP: R-26507-47431 */
24706    return 0;
24707  }
24708  if( nBytes>=0x7fffff00 ){
24709    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
24710    return 0;
24711  }
24712  nOld = sqlite3MallocSize(pOld);
24713  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
24714  ** argument to xRealloc is always a value returned by a prior call to
24715  ** xRoundup. */
24716  nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
24717  if( nOld==nNew ){
24718    pNew = pOld;
24719  }else if( sqlite3GlobalConfig.bMemstat ){
24720    sqlite3_mutex_enter(mem0.mutex);
24721    sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
24722    nDiff = nNew - nOld;
24723    if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
24724          mem0.alarmThreshold-nDiff ){
24725      sqlite3MallocAlarm(nDiff);
24726    }
24727    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24728    if( pNew==0 && mem0.alarmThreshold>0 ){
24729      sqlite3MallocAlarm((int)nBytes);
24730      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24731    }
24732    if( pNew ){
24733      nNew = sqlite3MallocSize(pNew);
24734      sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
24735    }
24736    sqlite3_mutex_leave(mem0.mutex);
24737  }else{
24738    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24739  }
24740  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
24741  return pNew;
24742}
24743
24744/*
24745** The public interface to sqlite3Realloc.  Make sure that the memory
24746** subsystem is initialized prior to invoking sqliteRealloc.
24747*/
24748SQLITE_API void *sqlite3_realloc(void *pOld, int n){
24749#ifndef SQLITE_OMIT_AUTOINIT
24750  if( sqlite3_initialize() ) return 0;
24751#endif
24752  if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
24753  return sqlite3Realloc(pOld, n);
24754}
24755SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
24756#ifndef SQLITE_OMIT_AUTOINIT
24757  if( sqlite3_initialize() ) return 0;
24758#endif
24759  return sqlite3Realloc(pOld, n);
24760}
24761
24762
24763/*
24764** Allocate and zero memory.
24765*/
24766SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
24767  void *p = sqlite3Malloc(n);
24768  if( p ){
24769    memset(p, 0, (size_t)n);
24770  }
24771  return p;
24772}
24773
24774/*
24775** Allocate and zero memory.  If the allocation fails, make
24776** the mallocFailed flag in the connection pointer.
24777*/
24778SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
24779  void *p;
24780  testcase( db==0 );
24781  p = sqlite3DbMallocRaw(db, n);
24782  if( p ) memset(p, 0, (size_t)n);
24783  return p;
24784}
24785
24786
24787/* Finish the work of sqlite3DbMallocRawNN for the unusual and
24788** slower case when the allocation cannot be fulfilled using lookaside.
24789*/
24790static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
24791  void *p;
24792  assert( db!=0 );
24793  p = sqlite3Malloc(n);
24794  if( !p ) sqlite3OomFault(db);
24795  sqlite3MemdebugSetType(p,
24796         (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
24797  return p;
24798}
24799
24800/*
24801** Allocate memory, either lookaside (if possible) or heap.
24802** If the allocation fails, set the mallocFailed flag in
24803** the connection pointer.
24804**
24805** If db!=0 and db->mallocFailed is true (indicating a prior malloc
24806** failure on the same database connection) then always return 0.
24807** Hence for a particular database connection, once malloc starts
24808** failing, it fails consistently until mallocFailed is reset.
24809** This is an important assumption.  There are many places in the
24810** code that do things like this:
24811**
24812**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
24813**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
24814**         if( b ) a[10] = 9;
24815**
24816** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
24817** that all prior mallocs (ex: "a") worked too.
24818**
24819** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
24820** not a NULL pointer.
24821*/
24822SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
24823  void *p;
24824  if( db ) return sqlite3DbMallocRawNN(db, n);
24825  p = sqlite3Malloc(n);
24826  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24827  return p;
24828}
24829SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
24830#ifndef SQLITE_OMIT_LOOKASIDE
24831  LookasideSlot *pBuf;
24832  assert( db!=0 );
24833  assert( sqlite3_mutex_held(db->mutex) );
24834  assert( db->pnBytesFreed==0 );
24835  if( db->lookaside.bDisable==0 ){
24836    assert( db->mallocFailed==0 );
24837    if( n>db->lookaside.sz ){
24838      db->lookaside.anStat[1]++;
24839    }else if( (pBuf = db->lookaside.pFree)==0 ){
24840      db->lookaside.anStat[2]++;
24841    }else{
24842      db->lookaside.pFree = pBuf->pNext;
24843      db->lookaside.nOut++;
24844      db->lookaside.anStat[0]++;
24845      if( db->lookaside.nOut>db->lookaside.mxOut ){
24846        db->lookaside.mxOut = db->lookaside.nOut;
24847      }
24848      return (void*)pBuf;
24849    }
24850  }else if( db->mallocFailed ){
24851    return 0;
24852  }
24853#else
24854  assert( db!=0 );
24855  assert( sqlite3_mutex_held(db->mutex) );
24856  assert( db->pnBytesFreed==0 );
24857  if( db->mallocFailed ){
24858    return 0;
24859  }
24860#endif
24861  return dbMallocRawFinish(db, n);
24862}
24863
24864/* Forward declaration */
24865static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
24866
24867/*
24868** Resize the block of memory pointed to by p to n bytes. If the
24869** resize fails, set the mallocFailed flag in the connection object.
24870*/
24871SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
24872  assert( db!=0 );
24873  if( p==0 ) return sqlite3DbMallocRawNN(db, n);
24874  assert( sqlite3_mutex_held(db->mutex) );
24875  if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
24876  return dbReallocFinish(db, p, n);
24877}
24878static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
24879  void *pNew = 0;
24880  assert( db!=0 );
24881  assert( p!=0 );
24882  if( db->mallocFailed==0 ){
24883    if( isLookaside(db, p) ){
24884      pNew = sqlite3DbMallocRawNN(db, n);
24885      if( pNew ){
24886        memcpy(pNew, p, db->lookaside.sz);
24887        sqlite3DbFree(db, p);
24888      }
24889    }else{
24890      assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24891      assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24892      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24893      pNew = sqlite3_realloc64(p, n);
24894      if( !pNew ){
24895        sqlite3OomFault(db);
24896      }
24897      sqlite3MemdebugSetType(pNew,
24898            (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
24899    }
24900  }
24901  return pNew;
24902}
24903
24904/*
24905** Attempt to reallocate p.  If the reallocation fails, then free p
24906** and set the mallocFailed flag in the database connection.
24907*/
24908SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
24909  void *pNew;
24910  pNew = sqlite3DbRealloc(db, p, n);
24911  if( !pNew ){
24912    sqlite3DbFree(db, p);
24913  }
24914  return pNew;
24915}
24916
24917/*
24918** Make a copy of a string in memory obtained from sqliteMalloc(). These
24919** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
24920** is because when memory debugging is turned on, these two functions are
24921** called via macros that record the current file and line number in the
24922** ThreadData structure.
24923*/
24924SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
24925  char *zNew;
24926  size_t n;
24927  if( z==0 ){
24928    return 0;
24929  }
24930  n = strlen(z) + 1;
24931  zNew = sqlite3DbMallocRaw(db, n);
24932  if( zNew ){
24933    memcpy(zNew, z, n);
24934  }
24935  return zNew;
24936}
24937SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
24938  char *zNew;
24939  assert( db!=0 );
24940  if( z==0 ){
24941    return 0;
24942  }
24943  assert( (n&0x7fffffff)==n );
24944  zNew = sqlite3DbMallocRawNN(db, n+1);
24945  if( zNew ){
24946    memcpy(zNew, z, (size_t)n);
24947    zNew[n] = 0;
24948  }
24949  return zNew;
24950}
24951
24952/*
24953** Free any prior content in *pz and replace it with a copy of zNew.
24954*/
24955SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
24956  sqlite3DbFree(db, *pz);
24957  *pz = sqlite3DbStrDup(db, zNew);
24958}
24959
24960/*
24961** Call this routine to record the fact that an OOM (out-of-memory) error
24962** has happened.  This routine will set db->mallocFailed, and also
24963** temporarily disable the lookaside memory allocator and interrupt
24964** any running VDBEs.
24965*/
24966SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
24967  if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
24968    db->mallocFailed = 1;
24969    if( db->nVdbeExec>0 ){
24970      db->u1.isInterrupted = 1;
24971    }
24972    db->lookaside.bDisable++;
24973  }
24974}
24975
24976/*
24977** This routine reactivates the memory allocator and clears the
24978** db->mallocFailed flag as necessary.
24979**
24980** The memory allocator is not restarted if there are running
24981** VDBEs.
24982*/
24983SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
24984  if( db->mallocFailed && db->nVdbeExec==0 ){
24985    db->mallocFailed = 0;
24986    db->u1.isInterrupted = 0;
24987    assert( db->lookaside.bDisable>0 );
24988    db->lookaside.bDisable--;
24989  }
24990}
24991
24992/*
24993** Take actions at the end of an API call to indicate an OOM error
24994*/
24995static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
24996  sqlite3OomClear(db);
24997  sqlite3Error(db, SQLITE_NOMEM);
24998  return SQLITE_NOMEM_BKPT;
24999}
25000
25001/*
25002** This function must be called before exiting any API function (i.e.
25003** returning control to the user) that has called sqlite3_malloc or
25004** sqlite3_realloc.
25005**
25006** The returned value is normally a copy of the second argument to this
25007** function. However, if a malloc() failure has occurred since the previous
25008** invocation SQLITE_NOMEM is returned instead.
25009**
25010** If an OOM as occurred, then the connection error-code (the value
25011** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
25012*/
25013SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
25014  /* If the db handle must hold the connection handle mutex here.
25015  ** Otherwise the read (and possible write) of db->mallocFailed
25016  ** is unsafe, as is the call to sqlite3Error().
25017  */
25018  assert( db!=0 );
25019  assert( sqlite3_mutex_held(db->mutex) );
25020  if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
25021    return apiOomError(db);
25022  }
25023  return rc & db->errMask;
25024}
25025
25026/************** End of malloc.c **********************************************/
25027/************** Begin file printf.c ******************************************/
25028/*
25029** The "printf" code that follows dates from the 1980's.  It is in
25030** the public domain.
25031**
25032**************************************************************************
25033**
25034** This file contains code for a set of "printf"-like routines.  These
25035** routines format strings much like the printf() from the standard C
25036** library, though the implementation here has enhancements to support
25037** SQLite.
25038*/
25039/* #include "sqliteInt.h" */
25040
25041/*
25042** Conversion types fall into various categories as defined by the
25043** following enumeration.
25044*/
25045#define etRADIX       0 /* non-decimal integer types.  %x %o */
25046#define etFLOAT       1 /* Floating point.  %f */
25047#define etEXP         2 /* Exponentional notation. %e and %E */
25048#define etGENERIC     3 /* Floating or exponential, depending on exponent. %g */
25049#define etSIZE        4 /* Return number of characters processed so far. %n */
25050#define etSTRING      5 /* Strings. %s */
25051#define etDYNSTRING   6 /* Dynamically allocated strings. %z */
25052#define etPERCENT     7 /* Percent symbol. %% */
25053#define etCHARX       8 /* Characters. %c */
25054/* The rest are extensions, not normally found in printf() */
25055#define etSQLESCAPE   9 /* Strings with '\'' doubled.  %q */
25056#define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
25057                          NULL pointers replaced by SQL NULL.  %Q */
25058#define etTOKEN      11 /* a pointer to a Token structure */
25059#define etSRCLIST    12 /* a pointer to a SrcList */
25060#define etPOINTER    13 /* The %p conversion */
25061#define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
25062#define etORDINAL    15 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
25063#define etDECIMAL    16 /* %d or %u, but not %x, %o */
25064
25065#define etINVALID    17 /* Any unrecognized conversion type */
25066
25067
25068/*
25069** An "etByte" is an 8-bit unsigned value.
25070*/
25071typedef unsigned char etByte;
25072
25073/*
25074** Each builtin conversion character (ex: the 'd' in "%d") is described
25075** by an instance of the following structure
25076*/
25077typedef struct et_info {   /* Information about each format field */
25078  char fmttype;            /* The format field code letter */
25079  etByte base;             /* The base for radix conversion */
25080  etByte flags;            /* One or more of FLAG_ constants below */
25081  etByte type;             /* Conversion paradigm */
25082  etByte charset;          /* Offset into aDigits[] of the digits string */
25083  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
25084} et_info;
25085
25086/*
25087** Allowed values for et_info.flags
25088*/
25089#define FLAG_SIGNED    1     /* True if the value to convert is signed */
25090#define FLAG_STRING    4     /* Allow infinite precision */
25091
25092
25093/*
25094** The following table is searched linearly, so it is good to put the
25095** most frequently used conversion types first.
25096*/
25097static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
25098static const char aPrefix[] = "-x0\000X0";
25099static const et_info fmtinfo[] = {
25100  {  'd', 10, 1, etDECIMAL,    0,  0 },
25101  {  's',  0, 4, etSTRING,     0,  0 },
25102  {  'g',  0, 1, etGENERIC,    30, 0 },
25103  {  'z',  0, 4, etDYNSTRING,  0,  0 },
25104  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
25105  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
25106  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
25107  {  'c',  0, 0, etCHARX,      0,  0 },
25108  {  'o',  8, 0, etRADIX,      0,  2 },
25109  {  'u', 10, 0, etDECIMAL,    0,  0 },
25110  {  'x', 16, 0, etRADIX,      16, 1 },
25111  {  'X', 16, 0, etRADIX,      0,  4 },
25112#ifndef SQLITE_OMIT_FLOATING_POINT
25113  {  'f',  0, 1, etFLOAT,      0,  0 },
25114  {  'e',  0, 1, etEXP,        30, 0 },
25115  {  'E',  0, 1, etEXP,        14, 0 },
25116  {  'G',  0, 1, etGENERIC,    14, 0 },
25117#endif
25118  {  'i', 10, 1, etDECIMAL,    0,  0 },
25119  {  'n',  0, 0, etSIZE,       0,  0 },
25120  {  '%',  0, 0, etPERCENT,    0,  0 },
25121  {  'p', 16, 0, etPOINTER,    0,  1 },
25122
25123  /* All the rest are undocumented and are for internal use only */
25124  {  'T',  0, 0, etTOKEN,      0,  0 },
25125  {  'S',  0, 0, etSRCLIST,    0,  0 },
25126  {  'r', 10, 1, etORDINAL,    0,  0 },
25127};
25128
25129/*
25130** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
25131** conversions will work.
25132*/
25133#ifndef SQLITE_OMIT_FLOATING_POINT
25134/*
25135** "*val" is a double such that 0.1 <= *val < 10.0
25136** Return the ascii code for the leading digit of *val, then
25137** multiply "*val" by 10.0 to renormalize.
25138**
25139** Example:
25140**     input:     *val = 3.14159
25141**     output:    *val = 1.4159    function return = '3'
25142**
25143** The counter *cnt is incremented each time.  After counter exceeds
25144** 16 (the number of significant digits in a 64-bit float) '0' is
25145** always returned.
25146*/
25147static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
25148  int digit;
25149  LONGDOUBLE_TYPE d;
25150  if( (*cnt)<=0 ) return '0';
25151  (*cnt)--;
25152  digit = (int)*val;
25153  d = digit;
25154  digit += '0';
25155  *val = (*val - d)*10.0;
25156  return (char)digit;
25157}
25158#endif /* SQLITE_OMIT_FLOATING_POINT */
25159
25160/*
25161** Set the StrAccum object to an error mode.
25162*/
25163static void setStrAccumError(StrAccum *p, u8 eError){
25164  assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
25165  p->accError = eError;
25166  p->nAlloc = 0;
25167}
25168
25169/*
25170** Extra argument values from a PrintfArguments object
25171*/
25172static sqlite3_int64 getIntArg(PrintfArguments *p){
25173  if( p->nArg<=p->nUsed ) return 0;
25174  return sqlite3_value_int64(p->apArg[p->nUsed++]);
25175}
25176static double getDoubleArg(PrintfArguments *p){
25177  if( p->nArg<=p->nUsed ) return 0.0;
25178  return sqlite3_value_double(p->apArg[p->nUsed++]);
25179}
25180static char *getTextArg(PrintfArguments *p){
25181  if( p->nArg<=p->nUsed ) return 0;
25182  return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
25183}
25184
25185
25186/*
25187** On machines with a small stack size, you can redefine the
25188** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
25189*/
25190#ifndef SQLITE_PRINT_BUF_SIZE
25191# define SQLITE_PRINT_BUF_SIZE 70
25192#endif
25193#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
25194
25195/*
25196** Render a string given by "fmt" into the StrAccum object.
25197*/
25198SQLITE_PRIVATE void sqlite3VXPrintf(
25199  StrAccum *pAccum,          /* Accumulate results here */
25200  const char *fmt,           /* Format string */
25201  va_list ap                 /* arguments */
25202){
25203  int c;                     /* Next character in the format string */
25204  char *bufpt;               /* Pointer to the conversion buffer */
25205  int precision;             /* Precision of the current field */
25206  int length;                /* Length of the field */
25207  int idx;                   /* A general purpose loop counter */
25208  int width;                 /* Width of the current field */
25209  etByte flag_leftjustify;   /* True if "-" flag is present */
25210  etByte flag_prefix;        /* '+' or ' ' or 0 for prefix */
25211  etByte flag_alternateform; /* True if "#" flag is present */
25212  etByte flag_altform2;      /* True if "!" flag is present */
25213  etByte flag_zeropad;       /* True if field width constant starts with zero */
25214  etByte flag_long;          /* 1 for the "l" flag, 2 for "ll", 0 by default */
25215  etByte done;               /* Loop termination flag */
25216  etByte cThousand;          /* Thousands separator for %d and %u */
25217  etByte xtype = etINVALID;  /* Conversion paradigm */
25218  u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
25219  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
25220  sqlite_uint64 longvalue;   /* Value for integer types */
25221  LONGDOUBLE_TYPE realvalue; /* Value for real types */
25222  const et_info *infop;      /* Pointer to the appropriate info structure */
25223  char *zOut;                /* Rendering buffer */
25224  int nOut;                  /* Size of the rendering buffer */
25225  char *zExtra = 0;          /* Malloced memory used by some conversion */
25226#ifndef SQLITE_OMIT_FLOATING_POINT
25227  int  exp, e2;              /* exponent of real numbers */
25228  int nsd;                   /* Number of significant digits returned */
25229  double rounder;            /* Used for rounding floating point values */
25230  etByte flag_dp;            /* True if decimal point should be shown */
25231  etByte flag_rtz;           /* True if trailing zeros should be removed */
25232#endif
25233  PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
25234  char buf[etBUFSIZE];       /* Conversion buffer */
25235
25236  bufpt = 0;
25237  if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
25238    pArgList = va_arg(ap, PrintfArguments*);
25239    bArgList = 1;
25240  }else{
25241    bArgList = 0;
25242  }
25243  for(; (c=(*fmt))!=0; ++fmt){
25244    if( c!='%' ){
25245      bufpt = (char *)fmt;
25246#if HAVE_STRCHRNUL
25247      fmt = strchrnul(fmt, '%');
25248#else
25249      do{ fmt++; }while( *fmt && *fmt != '%' );
25250#endif
25251      sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
25252      if( *fmt==0 ) break;
25253    }
25254    if( (c=(*++fmt))==0 ){
25255      sqlite3StrAccumAppend(pAccum, "%", 1);
25256      break;
25257    }
25258    /* Find out what flags are present */
25259    flag_leftjustify = flag_prefix = cThousand =
25260     flag_alternateform = flag_altform2 = flag_zeropad = 0;
25261    done = 0;
25262    do{
25263      switch( c ){
25264        case '-':   flag_leftjustify = 1;     break;
25265        case '+':   flag_prefix = '+';        break;
25266        case ' ':   flag_prefix = ' ';        break;
25267        case '#':   flag_alternateform = 1;   break;
25268        case '!':   flag_altform2 = 1;        break;
25269        case '0':   flag_zeropad = 1;         break;
25270        case ',':   cThousand = ',';          break;
25271        default:    done = 1;                 break;
25272      }
25273    }while( !done && (c=(*++fmt))!=0 );
25274    /* Get the field width */
25275    if( c=='*' ){
25276      if( bArgList ){
25277        width = (int)getIntArg(pArgList);
25278      }else{
25279        width = va_arg(ap,int);
25280      }
25281      if( width<0 ){
25282        flag_leftjustify = 1;
25283        width = width >= -2147483647 ? -width : 0;
25284      }
25285      c = *++fmt;
25286    }else{
25287      unsigned wx = 0;
25288      while( c>='0' && c<='9' ){
25289        wx = wx*10 + c - '0';
25290        c = *++fmt;
25291      }
25292      testcase( wx>0x7fffffff );
25293      width = wx & 0x7fffffff;
25294    }
25295    assert( width>=0 );
25296#ifdef SQLITE_PRINTF_PRECISION_LIMIT
25297    if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
25298      width = SQLITE_PRINTF_PRECISION_LIMIT;
25299    }
25300#endif
25301
25302    /* Get the precision */
25303    if( c=='.' ){
25304      c = *++fmt;
25305      if( c=='*' ){
25306        if( bArgList ){
25307          precision = (int)getIntArg(pArgList);
25308        }else{
25309          precision = va_arg(ap,int);
25310        }
25311        c = *++fmt;
25312        if( precision<0 ){
25313          precision = precision >= -2147483647 ? -precision : -1;
25314        }
25315      }else{
25316        unsigned px = 0;
25317        while( c>='0' && c<='9' ){
25318          px = px*10 + c - '0';
25319          c = *++fmt;
25320        }
25321        testcase( px>0x7fffffff );
25322        precision = px & 0x7fffffff;
25323      }
25324    }else{
25325      precision = -1;
25326    }
25327    assert( precision>=(-1) );
25328#ifdef SQLITE_PRINTF_PRECISION_LIMIT
25329    if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
25330      precision = SQLITE_PRINTF_PRECISION_LIMIT;
25331    }
25332#endif
25333
25334
25335    /* Get the conversion type modifier */
25336    if( c=='l' ){
25337      flag_long = 1;
25338      c = *++fmt;
25339      if( c=='l' ){
25340        flag_long = 2;
25341        c = *++fmt;
25342      }
25343    }else{
25344      flag_long = 0;
25345    }
25346    /* Fetch the info entry for the field */
25347    infop = &fmtinfo[0];
25348    xtype = etINVALID;
25349    for(idx=0; idx<ArraySize(fmtinfo); idx++){
25350      if( c==fmtinfo[idx].fmttype ){
25351        infop = &fmtinfo[idx];
25352        xtype = infop->type;
25353        break;
25354      }
25355    }
25356
25357    /*
25358    ** At this point, variables are initialized as follows:
25359    **
25360    **   flag_alternateform          TRUE if a '#' is present.
25361    **   flag_altform2               TRUE if a '!' is present.
25362    **   flag_prefix                 '+' or ' ' or zero
25363    **   flag_leftjustify            TRUE if a '-' is present or if the
25364    **                               field width was negative.
25365    **   flag_zeropad                TRUE if the width began with 0.
25366    **   flag_long                   1 for "l", 2 for "ll"
25367    **   width                       The specified field width.  This is
25368    **                               always non-negative.  Zero is the default.
25369    **   precision                   The specified precision.  The default
25370    **                               is -1.
25371    **   xtype                       The class of the conversion.
25372    **   infop                       Pointer to the appropriate info struct.
25373    */
25374    switch( xtype ){
25375      case etPOINTER:
25376        flag_long = sizeof(char*)==sizeof(i64) ? 2 :
25377                     sizeof(char*)==sizeof(long int) ? 1 : 0;
25378        /* Fall through into the next case */
25379      case etORDINAL:
25380      case etRADIX:
25381        cThousand = 0;
25382        /* Fall through into the next case */
25383      case etDECIMAL:
25384        if( infop->flags & FLAG_SIGNED ){
25385          i64 v;
25386          if( bArgList ){
25387            v = getIntArg(pArgList);
25388          }else if( flag_long ){
25389            if( flag_long==2 ){
25390              v = va_arg(ap,i64) ;
25391            }else{
25392              v = va_arg(ap,long int);
25393            }
25394          }else{
25395            v = va_arg(ap,int);
25396          }
25397          if( v<0 ){
25398            if( v==SMALLEST_INT64 ){
25399              longvalue = ((u64)1)<<63;
25400            }else{
25401              longvalue = -v;
25402            }
25403            prefix = '-';
25404          }else{
25405            longvalue = v;
25406            prefix = flag_prefix;
25407          }
25408        }else{
25409          if( bArgList ){
25410            longvalue = (u64)getIntArg(pArgList);
25411          }else if( flag_long ){
25412            if( flag_long==2 ){
25413              longvalue = va_arg(ap,u64);
25414            }else{
25415              longvalue = va_arg(ap,unsigned long int);
25416            }
25417          }else{
25418            longvalue = va_arg(ap,unsigned int);
25419          }
25420          prefix = 0;
25421        }
25422        if( longvalue==0 ) flag_alternateform = 0;
25423        if( flag_zeropad && precision<width-(prefix!=0) ){
25424          precision = width-(prefix!=0);
25425        }
25426        if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
25427          nOut = etBUFSIZE;
25428          zOut = buf;
25429        }else{
25430          u64 n = (u64)precision + 10 + precision/3;
25431          zOut = zExtra = sqlite3Malloc( n );
25432          if( zOut==0 ){
25433            setStrAccumError(pAccum, STRACCUM_NOMEM);
25434            return;
25435          }
25436          nOut = (int)n;
25437        }
25438        bufpt = &zOut[nOut-1];
25439        if( xtype==etORDINAL ){
25440          static const char zOrd[] = "thstndrd";
25441          int x = (int)(longvalue % 10);
25442          if( x>=4 || (longvalue/10)%10==1 ){
25443            x = 0;
25444          }
25445          *(--bufpt) = zOrd[x*2+1];
25446          *(--bufpt) = zOrd[x*2];
25447        }
25448        {
25449          const char *cset = &aDigits[infop->charset];
25450          u8 base = infop->base;
25451          do{                                           /* Convert to ascii */
25452            *(--bufpt) = cset[longvalue%base];
25453            longvalue = longvalue/base;
25454          }while( longvalue>0 );
25455        }
25456        length = (int)(&zOut[nOut-1]-bufpt);
25457        while( precision>length ){
25458          *(--bufpt) = '0';                             /* Zero pad */
25459          length++;
25460        }
25461        if( cThousand ){
25462          int nn = (length - 1)/3;  /* Number of "," to insert */
25463          int ix = (length - 1)%3 + 1;
25464          bufpt -= nn;
25465          for(idx=0; nn>0; idx++){
25466            bufpt[idx] = bufpt[idx+nn];
25467            ix--;
25468            if( ix==0 ){
25469              bufpt[++idx] = cThousand;
25470              nn--;
25471              ix = 3;
25472            }
25473          }
25474        }
25475        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
25476        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
25477          const char *pre;
25478          char x;
25479          pre = &aPrefix[infop->prefix];
25480          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
25481        }
25482        length = (int)(&zOut[nOut-1]-bufpt);
25483        break;
25484      case etFLOAT:
25485      case etEXP:
25486      case etGENERIC:
25487        if( bArgList ){
25488          realvalue = getDoubleArg(pArgList);
25489        }else{
25490          realvalue = va_arg(ap,double);
25491        }
25492#ifdef SQLITE_OMIT_FLOATING_POINT
25493        length = 0;
25494#else
25495        if( precision<0 ) precision = 6;         /* Set default precision */
25496        if( realvalue<0.0 ){
25497          realvalue = -realvalue;
25498          prefix = '-';
25499        }else{
25500          prefix = flag_prefix;
25501        }
25502        if( xtype==etGENERIC && precision>0 ) precision--;
25503        testcase( precision>0xfff );
25504        for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
25505        if( xtype==etFLOAT ) realvalue += rounder;
25506        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
25507        exp = 0;
25508        if( sqlite3IsNaN((double)realvalue) ){
25509          bufpt = "NaN";
25510          length = 3;
25511          break;
25512        }
25513        if( realvalue>0.0 ){
25514          LONGDOUBLE_TYPE scale = 1.0;
25515          while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
25516          while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
25517          while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
25518          realvalue /= scale;
25519          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
25520          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
25521          if( exp>350 ){
25522            bufpt = buf;
25523            buf[0] = prefix;
25524            memcpy(buf+(prefix!=0),"Inf",4);
25525            length = 3+(prefix!=0);
25526            break;
25527          }
25528        }
25529        bufpt = buf;
25530        /*
25531        ** If the field type is etGENERIC, then convert to either etEXP
25532        ** or etFLOAT, as appropriate.
25533        */
25534        if( xtype!=etFLOAT ){
25535          realvalue += rounder;
25536          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
25537        }
25538        if( xtype==etGENERIC ){
25539          flag_rtz = !flag_alternateform;
25540          if( exp<-4 || exp>precision ){
25541            xtype = etEXP;
25542          }else{
25543            precision = precision - exp;
25544            xtype = etFLOAT;
25545          }
25546        }else{
25547          flag_rtz = flag_altform2;
25548        }
25549        if( xtype==etEXP ){
25550          e2 = 0;
25551        }else{
25552          e2 = exp;
25553        }
25554        if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
25555          bufpt = zExtra
25556              = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
25557          if( bufpt==0 ){
25558            setStrAccumError(pAccum, STRACCUM_NOMEM);
25559            return;
25560          }
25561        }
25562        zOut = bufpt;
25563        nsd = 16 + flag_altform2*10;
25564        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
25565        /* The sign in front of the number */
25566        if( prefix ){
25567          *(bufpt++) = prefix;
25568        }
25569        /* Digits prior to the decimal point */
25570        if( e2<0 ){
25571          *(bufpt++) = '0';
25572        }else{
25573          for(; e2>=0; e2--){
25574            *(bufpt++) = et_getdigit(&realvalue,&nsd);
25575          }
25576        }
25577        /* The decimal point */
25578        if( flag_dp ){
25579          *(bufpt++) = '.';
25580        }
25581        /* "0" digits after the decimal point but before the first
25582        ** significant digit of the number */
25583        for(e2++; e2<0; precision--, e2++){
25584          assert( precision>0 );
25585          *(bufpt++) = '0';
25586        }
25587        /* Significant digits after the decimal point */
25588        while( (precision--)>0 ){
25589          *(bufpt++) = et_getdigit(&realvalue,&nsd);
25590        }
25591        /* Remove trailing zeros and the "." if no digits follow the "." */
25592        if( flag_rtz && flag_dp ){
25593          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
25594          assert( bufpt>zOut );
25595          if( bufpt[-1]=='.' ){
25596            if( flag_altform2 ){
25597              *(bufpt++) = '0';
25598            }else{
25599              *(--bufpt) = 0;
25600            }
25601          }
25602        }
25603        /* Add the "eNNN" suffix */
25604        if( xtype==etEXP ){
25605          *(bufpt++) = aDigits[infop->charset];
25606          if( exp<0 ){
25607            *(bufpt++) = '-'; exp = -exp;
25608          }else{
25609            *(bufpt++) = '+';
25610          }
25611          if( exp>=100 ){
25612            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
25613            exp %= 100;
25614          }
25615          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
25616          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
25617        }
25618        *bufpt = 0;
25619
25620        /* The converted number is in buf[] and zero terminated. Output it.
25621        ** Note that the number is in the usual order, not reversed as with
25622        ** integer conversions. */
25623        length = (int)(bufpt-zOut);
25624        bufpt = zOut;
25625
25626        /* Special case:  Add leading zeros if the flag_zeropad flag is
25627        ** set and we are not left justified */
25628        if( flag_zeropad && !flag_leftjustify && length < width){
25629          int i;
25630          int nPad = width - length;
25631          for(i=width; i>=nPad; i--){
25632            bufpt[i] = bufpt[i-nPad];
25633          }
25634          i = prefix!=0;
25635          while( nPad-- ) bufpt[i++] = '0';
25636          length = width;
25637        }
25638#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
25639        break;
25640      case etSIZE:
25641        if( !bArgList ){
25642          *(va_arg(ap,int*)) = pAccum->nChar;
25643        }
25644        length = width = 0;
25645        break;
25646      case etPERCENT:
25647        buf[0] = '%';
25648        bufpt = buf;
25649        length = 1;
25650        break;
25651      case etCHARX:
25652        if( bArgList ){
25653          bufpt = getTextArg(pArgList);
25654          c = bufpt ? bufpt[0] : 0;
25655        }else{
25656          c = va_arg(ap,int);
25657        }
25658        if( precision>1 ){
25659          width -= precision-1;
25660          if( width>1 && !flag_leftjustify ){
25661            sqlite3AppendChar(pAccum, width-1, ' ');
25662            width = 0;
25663          }
25664          sqlite3AppendChar(pAccum, precision-1, c);
25665        }
25666        length = 1;
25667        buf[0] = c;
25668        bufpt = buf;
25669        break;
25670      case etSTRING:
25671      case etDYNSTRING:
25672        if( bArgList ){
25673          bufpt = getTextArg(pArgList);
25674          xtype = etSTRING;
25675        }else{
25676          bufpt = va_arg(ap,char*);
25677        }
25678        if( bufpt==0 ){
25679          bufpt = "";
25680        }else if( xtype==etDYNSTRING ){
25681          zExtra = bufpt;
25682        }
25683        if( precision>=0 ){
25684          for(length=0; length<precision && bufpt[length]; length++){}
25685        }else{
25686          length = sqlite3Strlen30(bufpt);
25687        }
25688        break;
25689      case etSQLESCAPE:           /* Escape ' characters */
25690      case etSQLESCAPE2:          /* Escape ' and enclose in '...' */
25691      case etSQLESCAPE3: {        /* Escape " characters */
25692        int i, j, k, n, isnull;
25693        int needQuote;
25694        char ch;
25695        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
25696        char *escarg;
25697
25698        if( bArgList ){
25699          escarg = getTextArg(pArgList);
25700        }else{
25701          escarg = va_arg(ap,char*);
25702        }
25703        isnull = escarg==0;
25704        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
25705        k = precision;
25706        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
25707          if( ch==q )  n++;
25708        }
25709        needQuote = !isnull && xtype==etSQLESCAPE2;
25710        n += i + 3;
25711        if( n>etBUFSIZE ){
25712          bufpt = zExtra = sqlite3Malloc( n );
25713          if( bufpt==0 ){
25714            setStrAccumError(pAccum, STRACCUM_NOMEM);
25715            return;
25716          }
25717        }else{
25718          bufpt = buf;
25719        }
25720        j = 0;
25721        if( needQuote ) bufpt[j++] = q;
25722        k = i;
25723        for(i=0; i<k; i++){
25724          bufpt[j++] = ch = escarg[i];
25725          if( ch==q ) bufpt[j++] = ch;
25726        }
25727        if( needQuote ) bufpt[j++] = q;
25728        bufpt[j] = 0;
25729        length = j;
25730        /* The precision in %q and %Q means how many input characters to
25731        ** consume, not the length of the output...
25732        ** if( precision>=0 && precision<length ) length = precision; */
25733        break;
25734      }
25735      case etTOKEN: {
25736        Token *pToken;
25737        if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
25738        pToken = va_arg(ap, Token*);
25739        assert( bArgList==0 );
25740        if( pToken && pToken->n ){
25741          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
25742        }
25743        length = width = 0;
25744        break;
25745      }
25746      case etSRCLIST: {
25747        SrcList *pSrc;
25748        int k;
25749        struct SrcList_item *pItem;
25750        if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
25751        pSrc = va_arg(ap, SrcList*);
25752        k = va_arg(ap, int);
25753        pItem = &pSrc->a[k];
25754        assert( bArgList==0 );
25755        assert( k>=0 && k<pSrc->nSrc );
25756        if( pItem->zDatabase ){
25757          sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
25758          sqlite3StrAccumAppend(pAccum, ".", 1);
25759        }
25760        sqlite3StrAccumAppendAll(pAccum, pItem->zName);
25761        length = width = 0;
25762        break;
25763      }
25764      default: {
25765        assert( xtype==etINVALID );
25766        return;
25767      }
25768    }/* End switch over the format type */
25769    /*
25770    ** The text of the conversion is pointed to by "bufpt" and is
25771    ** "length" characters long.  The field width is "width".  Do
25772    ** the output.
25773    */
25774    width -= length;
25775    if( width>0 ){
25776      if( !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
25777      sqlite3StrAccumAppend(pAccum, bufpt, length);
25778      if( flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
25779    }else{
25780      sqlite3StrAccumAppend(pAccum, bufpt, length);
25781    }
25782
25783    if( zExtra ){
25784      sqlite3DbFree(pAccum->db, zExtra);
25785      zExtra = 0;
25786    }
25787  }/* End for loop over the format string */
25788} /* End of function */
25789
25790/*
25791** Enlarge the memory allocation on a StrAccum object so that it is
25792** able to accept at least N more bytes of text.
25793**
25794** Return the number of bytes of text that StrAccum is able to accept
25795** after the attempted enlargement.  The value returned might be zero.
25796*/
25797static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
25798  char *zNew;
25799  assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
25800  if( p->accError ){
25801    testcase(p->accError==STRACCUM_TOOBIG);
25802    testcase(p->accError==STRACCUM_NOMEM);
25803    return 0;
25804  }
25805  if( p->mxAlloc==0 ){
25806    N = p->nAlloc - p->nChar - 1;
25807    setStrAccumError(p, STRACCUM_TOOBIG);
25808    return N;
25809  }else{
25810    char *zOld = isMalloced(p) ? p->zText : 0;
25811    i64 szNew = p->nChar;
25812    assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25813    szNew += N + 1;
25814    if( szNew+p->nChar<=p->mxAlloc ){
25815      /* Force exponential buffer size growth as long as it does not overflow,
25816      ** to avoid having to call this routine too often */
25817      szNew += p->nChar;
25818    }
25819    if( szNew > p->mxAlloc ){
25820      sqlite3StrAccumReset(p);
25821      setStrAccumError(p, STRACCUM_TOOBIG);
25822      return 0;
25823    }else{
25824      p->nAlloc = (int)szNew;
25825    }
25826    if( p->db ){
25827      zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
25828    }else{
25829      zNew = sqlite3_realloc64(zOld, p->nAlloc);
25830    }
25831    if( zNew ){
25832      assert( p->zText!=0 || p->nChar==0 );
25833      if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
25834      p->zText = zNew;
25835      p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
25836      p->printfFlags |= SQLITE_PRINTF_MALLOCED;
25837    }else{
25838      sqlite3StrAccumReset(p);
25839      setStrAccumError(p, STRACCUM_NOMEM);
25840      return 0;
25841    }
25842  }
25843  return N;
25844}
25845
25846/*
25847** Append N copies of character c to the given string buffer.
25848*/
25849SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
25850  testcase( p->nChar + (i64)N > 0x7fffffff );
25851  if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
25852    return;
25853  }
25854  assert( (p->zText==p->zBase)==!isMalloced(p) );
25855  while( (N--)>0 ) p->zText[p->nChar++] = c;
25856}
25857
25858/*
25859** The StrAccum "p" is not large enough to accept N new bytes of z[].
25860** So enlarge if first, then do the append.
25861**
25862** This is a helper routine to sqlite3StrAccumAppend() that does special-case
25863** work (enlarging the buffer) using tail recursion, so that the
25864** sqlite3StrAccumAppend() routine can use fast calling semantics.
25865*/
25866static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
25867  N = sqlite3StrAccumEnlarge(p, N);
25868  if( N>0 ){
25869    memcpy(&p->zText[p->nChar], z, N);
25870    p->nChar += N;
25871  }
25872  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25873}
25874
25875/*
25876** Append N bytes of text from z to the StrAccum object.  Increase the
25877** size of the memory allocation for StrAccum if necessary.
25878*/
25879SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
25880  assert( z!=0 || N==0 );
25881  assert( p->zText!=0 || p->nChar==0 || p->accError );
25882  assert( N>=0 );
25883  assert( p->accError==0 || p->nAlloc==0 );
25884  if( p->nChar+N >= p->nAlloc ){
25885    enlargeAndAppend(p,z,N);
25886  }else if( N ){
25887    assert( p->zText );
25888    p->nChar += N;
25889    memcpy(&p->zText[p->nChar-N], z, N);
25890  }
25891}
25892
25893/*
25894** Append the complete text of zero-terminated string z[] to the p string.
25895*/
25896SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
25897  sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
25898}
25899
25900
25901/*
25902** Finish off a string by making sure it is zero-terminated.
25903** Return a pointer to the resulting string.  Return a NULL
25904** pointer if any kind of error was encountered.
25905*/
25906static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
25907  assert( p->mxAlloc>0 && !isMalloced(p) );
25908  p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
25909  if( p->zText ){
25910    memcpy(p->zText, p->zBase, p->nChar+1);
25911    p->printfFlags |= SQLITE_PRINTF_MALLOCED;
25912  }else{
25913    setStrAccumError(p, STRACCUM_NOMEM);
25914  }
25915  return p->zText;
25916}
25917SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
25918  if( p->zText ){
25919    assert( (p->zText==p->zBase)==!isMalloced(p) );
25920    p->zText[p->nChar] = 0;
25921    if( p->mxAlloc>0 && !isMalloced(p) ){
25922      return strAccumFinishRealloc(p);
25923    }
25924  }
25925  return p->zText;
25926}
25927
25928/*
25929** Reset an StrAccum string.  Reclaim all malloced memory.
25930*/
25931SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
25932  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25933  if( isMalloced(p) ){
25934    sqlite3DbFree(p->db, p->zText);
25935    p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
25936  }
25937  p->zText = 0;
25938}
25939
25940/*
25941** Initialize a string accumulator.
25942**
25943** p:     The accumulator to be initialized.
25944** db:    Pointer to a database connection.  May be NULL.  Lookaside
25945**        memory is used if not NULL. db->mallocFailed is set appropriately
25946**        when not NULL.
25947** zBase: An initial buffer.  May be NULL in which case the initial buffer
25948**        is malloced.
25949** n:     Size of zBase in bytes.  If total space requirements never exceed
25950**        n then no memory allocations ever occur.
25951** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
25952**        allocations will ever occur.
25953*/
25954SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
25955  p->zText = p->zBase = zBase;
25956  p->db = db;
25957  p->nChar = 0;
25958  p->nAlloc = n;
25959  p->mxAlloc = mx;
25960  p->accError = 0;
25961  p->printfFlags = 0;
25962}
25963
25964/*
25965** Print into memory obtained from sqliteMalloc().  Use the internal
25966** %-conversion extensions.
25967*/
25968SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
25969  char *z;
25970  char zBase[SQLITE_PRINT_BUF_SIZE];
25971  StrAccum acc;
25972  assert( db!=0 );
25973  sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
25974                      db->aLimit[SQLITE_LIMIT_LENGTH]);
25975  acc.printfFlags = SQLITE_PRINTF_INTERNAL;
25976  sqlite3VXPrintf(&acc, zFormat, ap);
25977  z = sqlite3StrAccumFinish(&acc);
25978  if( acc.accError==STRACCUM_NOMEM ){
25979    sqlite3OomFault(db);
25980  }
25981  return z;
25982}
25983
25984/*
25985** Print into memory obtained from sqliteMalloc().  Use the internal
25986** %-conversion extensions.
25987*/
25988SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
25989  va_list ap;
25990  char *z;
25991  va_start(ap, zFormat);
25992  z = sqlite3VMPrintf(db, zFormat, ap);
25993  va_end(ap);
25994  return z;
25995}
25996
25997/*
25998** Print into memory obtained from sqlite3_malloc().  Omit the internal
25999** %-conversion extensions.
26000*/
26001SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
26002  char *z;
26003  char zBase[SQLITE_PRINT_BUF_SIZE];
26004  StrAccum acc;
26005
26006#ifdef SQLITE_ENABLE_API_ARMOR
26007  if( zFormat==0 ){
26008    (void)SQLITE_MISUSE_BKPT;
26009    return 0;
26010  }
26011#endif
26012#ifndef SQLITE_OMIT_AUTOINIT
26013  if( sqlite3_initialize() ) return 0;
26014#endif
26015  sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
26016  sqlite3VXPrintf(&acc, zFormat, ap);
26017  z = sqlite3StrAccumFinish(&acc);
26018  return z;
26019}
26020
26021/*
26022** Print into memory obtained from sqlite3_malloc()().  Omit the internal
26023** %-conversion extensions.
26024*/
26025SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
26026  va_list ap;
26027  char *z;
26028#ifndef SQLITE_OMIT_AUTOINIT
26029  if( sqlite3_initialize() ) return 0;
26030#endif
26031  va_start(ap, zFormat);
26032  z = sqlite3_vmprintf(zFormat, ap);
26033  va_end(ap);
26034  return z;
26035}
26036
26037/*
26038** sqlite3_snprintf() works like snprintf() except that it ignores the
26039** current locale settings.  This is important for SQLite because we
26040** are not able to use a "," as the decimal point in place of "." as
26041** specified by some locales.
26042**
26043** Oops:  The first two arguments of sqlite3_snprintf() are backwards
26044** from the snprintf() standard.  Unfortunately, it is too late to change
26045** this without breaking compatibility, so we just have to live with the
26046** mistake.
26047**
26048** sqlite3_vsnprintf() is the varargs version.
26049*/
26050SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
26051  StrAccum acc;
26052  if( n<=0 ) return zBuf;
26053#ifdef SQLITE_ENABLE_API_ARMOR
26054  if( zBuf==0 || zFormat==0 ) {
26055    (void)SQLITE_MISUSE_BKPT;
26056    if( zBuf ) zBuf[0] = 0;
26057    return zBuf;
26058  }
26059#endif
26060  sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
26061  sqlite3VXPrintf(&acc, zFormat, ap);
26062  zBuf[acc.nChar] = 0;
26063  return zBuf;
26064}
26065SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
26066  char *z;
26067  va_list ap;
26068  va_start(ap,zFormat);
26069  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
26070  va_end(ap);
26071  return z;
26072}
26073
26074/*
26075** This is the routine that actually formats the sqlite3_log() message.
26076** We house it in a separate routine from sqlite3_log() to avoid using
26077** stack space on small-stack systems when logging is disabled.
26078**
26079** sqlite3_log() must render into a static buffer.  It cannot dynamically
26080** allocate memory because it might be called while the memory allocator
26081** mutex is held.
26082**
26083** sqlite3VXPrintf() might ask for *temporary* memory allocations for
26084** certain format characters (%q) or for very large precisions or widths.
26085** Care must be taken that any sqlite3_log() calls that occur while the
26086** memory mutex is held do not use these mechanisms.
26087*/
26088static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
26089  StrAccum acc;                          /* String accumulator */
26090  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
26091
26092  sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
26093  sqlite3VXPrintf(&acc, zFormat, ap);
26094  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
26095                           sqlite3StrAccumFinish(&acc));
26096}
26097
26098/*
26099** Format and write a message to the log if logging is enabled.
26100*/
26101SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
26102  va_list ap;                             /* Vararg list */
26103  if( sqlite3GlobalConfig.xLog ){
26104    va_start(ap, zFormat);
26105    renderLogMsg(iErrCode, zFormat, ap);
26106    va_end(ap);
26107  }
26108}
26109
26110#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
26111/*
26112** A version of printf() that understands %lld.  Used for debugging.
26113** The printf() built into some versions of windows does not understand %lld
26114** and segfaults if you give it a long long int.
26115*/
26116SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
26117  va_list ap;
26118  StrAccum acc;
26119  char zBuf[500];
26120  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
26121  va_start(ap,zFormat);
26122  sqlite3VXPrintf(&acc, zFormat, ap);
26123  va_end(ap);
26124  sqlite3StrAccumFinish(&acc);
26125  fprintf(stdout,"%s", zBuf);
26126  fflush(stdout);
26127}
26128#endif
26129
26130
26131/*
26132** variable-argument wrapper around sqlite3VXPrintf().  The bFlags argument
26133** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
26134*/
26135SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
26136  va_list ap;
26137  va_start(ap,zFormat);
26138  sqlite3VXPrintf(p, zFormat, ap);
26139  va_end(ap);
26140}
26141
26142/************** End of printf.c **********************************************/
26143/************** Begin file treeview.c ****************************************/
26144/*
26145** 2015-06-08
26146**
26147** The author disclaims copyright to this source code.  In place of
26148** a legal notice, here is a blessing:
26149**
26150**    May you do good and not evil.
26151**    May you find forgiveness for yourself and forgive others.
26152**    May you share freely, never taking more than you give.
26153**
26154*************************************************************************
26155**
26156** This file contains C code to implement the TreeView debugging routines.
26157** These routines print a parse tree to standard output for debugging and
26158** analysis.
26159**
26160** The interfaces in this file is only available when compiling
26161** with SQLITE_DEBUG.
26162*/
26163/* #include "sqliteInt.h" */
26164#ifdef SQLITE_DEBUG
26165
26166/*
26167** Add a new subitem to the tree.  The moreToFollow flag indicates that this
26168** is not the last item in the tree.
26169*/
26170static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
26171  if( p==0 ){
26172    p = sqlite3_malloc64( sizeof(*p) );
26173    if( p==0 ) return 0;
26174    memset(p, 0, sizeof(*p));
26175  }else{
26176    p->iLevel++;
26177  }
26178  assert( moreToFollow==0 || moreToFollow==1 );
26179  if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
26180  return p;
26181}
26182
26183/*
26184** Finished with one layer of the tree
26185*/
26186static void sqlite3TreeViewPop(TreeView *p){
26187  if( p==0 ) return;
26188  p->iLevel--;
26189  if( p->iLevel<0 ) sqlite3_free(p);
26190}
26191
26192/*
26193** Generate a single line of output for the tree, with a prefix that contains
26194** all the appropriate tree lines
26195*/
26196static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
26197  va_list ap;
26198  int i;
26199  StrAccum acc;
26200  char zBuf[500];
26201  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
26202  if( p ){
26203    for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
26204      sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|   " : "    ", 4);
26205    }
26206    sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
26207  }
26208  va_start(ap, zFormat);
26209  sqlite3VXPrintf(&acc, zFormat, ap);
26210  va_end(ap);
26211  assert( acc.nChar>0 );
26212  if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
26213  sqlite3StrAccumFinish(&acc);
26214  fprintf(stdout,"%s", zBuf);
26215  fflush(stdout);
26216}
26217
26218/*
26219** Shorthand for starting a new tree item that consists of a single label
26220*/
26221static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
26222  p = sqlite3TreeViewPush(p, moreFollows);
26223  sqlite3TreeViewLine(p, "%s", zLabel);
26224}
26225
26226/*
26227** Generate a human-readable description of a WITH clause.
26228*/
26229SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
26230  int i;
26231  if( pWith==0 ) return;
26232  if( pWith->nCte==0 ) return;
26233  if( pWith->pOuter ){
26234    sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
26235  }else{
26236    sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
26237  }
26238  if( pWith->nCte>0 ){
26239    pView = sqlite3TreeViewPush(pView, 1);
26240    for(i=0; i<pWith->nCte; i++){
26241      StrAccum x;
26242      char zLine[1000];
26243      const struct Cte *pCte = &pWith->a[i];
26244      sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
26245      sqlite3XPrintf(&x, "%s", pCte->zName);
26246      if( pCte->pCols && pCte->pCols->nExpr>0 ){
26247        char cSep = '(';
26248        int j;
26249        for(j=0; j<pCte->pCols->nExpr; j++){
26250          sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
26251          cSep = ',';
26252        }
26253        sqlite3XPrintf(&x, ")");
26254      }
26255      sqlite3XPrintf(&x, " AS");
26256      sqlite3StrAccumFinish(&x);
26257      sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
26258      sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
26259      sqlite3TreeViewPop(pView);
26260    }
26261    sqlite3TreeViewPop(pView);
26262  }
26263}
26264
26265
26266/*
26267** Generate a human-readable description of a Select object.
26268*/
26269SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
26270  int n = 0;
26271  int cnt = 0;
26272  if( p==0 ){
26273    sqlite3TreeViewLine(pView, "nil-SELECT");
26274    return;
26275  }
26276  pView = sqlite3TreeViewPush(pView, moreToFollow);
26277  if( p->pWith ){
26278    sqlite3TreeViewWith(pView, p->pWith, 1);
26279    cnt = 1;
26280    sqlite3TreeViewPush(pView, 1);
26281  }
26282  do{
26283    sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
26284      ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
26285      ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
26286      (int)p->nSelectRow
26287    );
26288    if( cnt++ ) sqlite3TreeViewPop(pView);
26289    if( p->pPrior ){
26290      n = 1000;
26291    }else{
26292      n = 0;
26293      if( p->pSrc && p->pSrc->nSrc ) n++;
26294      if( p->pWhere ) n++;
26295      if( p->pGroupBy ) n++;
26296      if( p->pHaving ) n++;
26297      if( p->pOrderBy ) n++;
26298      if( p->pLimit ) n++;
26299      if( p->pOffset ) n++;
26300    }
26301    sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
26302    if( p->pSrc && p->pSrc->nSrc ){
26303      int i;
26304      pView = sqlite3TreeViewPush(pView, (n--)>0);
26305      sqlite3TreeViewLine(pView, "FROM");
26306      for(i=0; i<p->pSrc->nSrc; i++){
26307        struct SrcList_item *pItem = &p->pSrc->a[i];
26308        StrAccum x;
26309        char zLine[100];
26310        sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
26311        sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
26312        if( pItem->zDatabase ){
26313          sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
26314        }else if( pItem->zName ){
26315          sqlite3XPrintf(&x, " %s", pItem->zName);
26316        }
26317        if( pItem->pTab ){
26318          sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
26319        }
26320        if( pItem->zAlias ){
26321          sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
26322        }
26323        if( pItem->fg.jointype & JT_LEFT ){
26324          sqlite3XPrintf(&x, " LEFT-JOIN");
26325        }
26326        sqlite3StrAccumFinish(&x);
26327        sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
26328        if( pItem->pSelect ){
26329          sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
26330        }
26331        if( pItem->fg.isTabFunc ){
26332          sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
26333        }
26334        sqlite3TreeViewPop(pView);
26335      }
26336      sqlite3TreeViewPop(pView);
26337    }
26338    if( p->pWhere ){
26339      sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
26340      sqlite3TreeViewExpr(pView, p->pWhere, 0);
26341      sqlite3TreeViewPop(pView);
26342    }
26343    if( p->pGroupBy ){
26344      sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
26345    }
26346    if( p->pHaving ){
26347      sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
26348      sqlite3TreeViewExpr(pView, p->pHaving, 0);
26349      sqlite3TreeViewPop(pView);
26350    }
26351    if( p->pOrderBy ){
26352      sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
26353    }
26354    if( p->pLimit ){
26355      sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
26356      sqlite3TreeViewExpr(pView, p->pLimit, 0);
26357      sqlite3TreeViewPop(pView);
26358    }
26359    if( p->pOffset ){
26360      sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
26361      sqlite3TreeViewExpr(pView, p->pOffset, 0);
26362      sqlite3TreeViewPop(pView);
26363    }
26364    if( p->pPrior ){
26365      const char *zOp = "UNION";
26366      switch( p->op ){
26367        case TK_ALL:         zOp = "UNION ALL";  break;
26368        case TK_INTERSECT:   zOp = "INTERSECT";  break;
26369        case TK_EXCEPT:      zOp = "EXCEPT";     break;
26370      }
26371      sqlite3TreeViewItem(pView, zOp, 1);
26372    }
26373    p = p->pPrior;
26374  }while( p!=0 );
26375  sqlite3TreeViewPop(pView);
26376}
26377
26378/*
26379** Generate a human-readable explanation of an expression tree.
26380*/
26381SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
26382  const char *zBinOp = 0;   /* Binary operator */
26383  const char *zUniOp = 0;   /* Unary operator */
26384  char zFlgs[30];
26385  pView = sqlite3TreeViewPush(pView, moreToFollow);
26386  if( pExpr==0 ){
26387    sqlite3TreeViewLine(pView, "nil");
26388    sqlite3TreeViewPop(pView);
26389    return;
26390  }
26391  if( pExpr->flags ){
26392    sqlite3_snprintf(sizeof(zFlgs),zFlgs,"  flags=0x%x",pExpr->flags);
26393  }else{
26394    zFlgs[0] = 0;
26395  }
26396  switch( pExpr->op ){
26397    case TK_AGG_COLUMN: {
26398      sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
26399            pExpr->iTable, pExpr->iColumn, zFlgs);
26400      break;
26401    }
26402    case TK_COLUMN: {
26403      if( pExpr->iTable<0 ){
26404        /* This only happens when coding check constraints */
26405        sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
26406      }else{
26407        sqlite3TreeViewLine(pView, "{%d:%d}%s",
26408                             pExpr->iTable, pExpr->iColumn, zFlgs);
26409      }
26410      break;
26411    }
26412    case TK_INTEGER: {
26413      if( pExpr->flags & EP_IntValue ){
26414        sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
26415      }else{
26416        sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
26417      }
26418      break;
26419    }
26420#ifndef SQLITE_OMIT_FLOATING_POINT
26421    case TK_FLOAT: {
26422      sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26423      break;
26424    }
26425#endif
26426    case TK_STRING: {
26427      sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
26428      break;
26429    }
26430    case TK_NULL: {
26431      sqlite3TreeViewLine(pView,"NULL");
26432      break;
26433    }
26434#ifndef SQLITE_OMIT_BLOB_LITERAL
26435    case TK_BLOB: {
26436      sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26437      break;
26438    }
26439#endif
26440    case TK_VARIABLE: {
26441      sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
26442                          pExpr->u.zToken, pExpr->iColumn);
26443      break;
26444    }
26445    case TK_REGISTER: {
26446      sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
26447      break;
26448    }
26449    case TK_ID: {
26450      sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
26451      break;
26452    }
26453#ifndef SQLITE_OMIT_CAST
26454    case TK_CAST: {
26455      /* Expressions of the form:   CAST(pLeft AS token) */
26456      sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
26457      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26458      break;
26459    }
26460#endif /* SQLITE_OMIT_CAST */
26461    case TK_LT:      zBinOp = "LT";     break;
26462    case TK_LE:      zBinOp = "LE";     break;
26463    case TK_GT:      zBinOp = "GT";     break;
26464    case TK_GE:      zBinOp = "GE";     break;
26465    case TK_NE:      zBinOp = "NE";     break;
26466    case TK_EQ:      zBinOp = "EQ";     break;
26467    case TK_IS:      zBinOp = "IS";     break;
26468    case TK_ISNOT:   zBinOp = "ISNOT";  break;
26469    case TK_AND:     zBinOp = "AND";    break;
26470    case TK_OR:      zBinOp = "OR";     break;
26471    case TK_PLUS:    zBinOp = "ADD";    break;
26472    case TK_STAR:    zBinOp = "MUL";    break;
26473    case TK_MINUS:   zBinOp = "SUB";    break;
26474    case TK_REM:     zBinOp = "REM";    break;
26475    case TK_BITAND:  zBinOp = "BITAND"; break;
26476    case TK_BITOR:   zBinOp = "BITOR";  break;
26477    case TK_SLASH:   zBinOp = "DIV";    break;
26478    case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
26479    case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
26480    case TK_CONCAT:  zBinOp = "CONCAT"; break;
26481    case TK_DOT:     zBinOp = "DOT";    break;
26482
26483    case TK_UMINUS:  zUniOp = "UMINUS"; break;
26484    case TK_UPLUS:   zUniOp = "UPLUS";  break;
26485    case TK_BITNOT:  zUniOp = "BITNOT"; break;
26486    case TK_NOT:     zUniOp = "NOT";    break;
26487    case TK_ISNULL:  zUniOp = "ISNULL"; break;
26488    case TK_NOTNULL: zUniOp = "NOTNULL"; break;
26489
26490    case TK_SPAN: {
26491      sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
26492      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26493      break;
26494    }
26495
26496    case TK_COLLATE: {
26497      sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
26498      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26499      break;
26500    }
26501
26502    case TK_AGG_FUNCTION:
26503    case TK_FUNCTION: {
26504      ExprList *pFarg;       /* List of function arguments */
26505      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
26506        pFarg = 0;
26507      }else{
26508        pFarg = pExpr->x.pList;
26509      }
26510      if( pExpr->op==TK_AGG_FUNCTION ){
26511        sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
26512                             pExpr->op2, pExpr->u.zToken);
26513      }else{
26514        sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
26515      }
26516      if( pFarg ){
26517        sqlite3TreeViewExprList(pView, pFarg, 0, 0);
26518      }
26519      break;
26520    }
26521#ifndef SQLITE_OMIT_SUBQUERY
26522    case TK_EXISTS: {
26523      sqlite3TreeViewLine(pView, "EXISTS-expr");
26524      sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26525      break;
26526    }
26527    case TK_SELECT: {
26528      sqlite3TreeViewLine(pView, "SELECT-expr");
26529      sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26530      break;
26531    }
26532    case TK_IN: {
26533      sqlite3TreeViewLine(pView, "IN");
26534      sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26535      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
26536        sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26537      }else{
26538        sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
26539      }
26540      break;
26541    }
26542#endif /* SQLITE_OMIT_SUBQUERY */
26543
26544    /*
26545    **    x BETWEEN y AND z
26546    **
26547    ** This is equivalent to
26548    **
26549    **    x>=y AND x<=z
26550    **
26551    ** X is stored in pExpr->pLeft.
26552    ** Y is stored in pExpr->pList->a[0].pExpr.
26553    ** Z is stored in pExpr->pList->a[1].pExpr.
26554    */
26555    case TK_BETWEEN: {
26556      Expr *pX = pExpr->pLeft;
26557      Expr *pY = pExpr->x.pList->a[0].pExpr;
26558      Expr *pZ = pExpr->x.pList->a[1].pExpr;
26559      sqlite3TreeViewLine(pView, "BETWEEN");
26560      sqlite3TreeViewExpr(pView, pX, 1);
26561      sqlite3TreeViewExpr(pView, pY, 1);
26562      sqlite3TreeViewExpr(pView, pZ, 0);
26563      break;
26564    }
26565    case TK_TRIGGER: {
26566      /* If the opcode is TK_TRIGGER, then the expression is a reference
26567      ** to a column in the new.* or old.* pseudo-tables available to
26568      ** trigger programs. In this case Expr.iTable is set to 1 for the
26569      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
26570      ** is set to the column of the pseudo-table to read, or to -1 to
26571      ** read the rowid field.
26572      */
26573      sqlite3TreeViewLine(pView, "%s(%d)",
26574          pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
26575      break;
26576    }
26577    case TK_CASE: {
26578      sqlite3TreeViewLine(pView, "CASE");
26579      sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26580      sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
26581      break;
26582    }
26583#ifndef SQLITE_OMIT_TRIGGER
26584    case TK_RAISE: {
26585      const char *zType = "unk";
26586      switch( pExpr->affinity ){
26587        case OE_Rollback:   zType = "rollback";  break;
26588        case OE_Abort:      zType = "abort";     break;
26589        case OE_Fail:       zType = "fail";      break;
26590        case OE_Ignore:     zType = "ignore";    break;
26591      }
26592      sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
26593      break;
26594    }
26595#endif
26596    case TK_MATCH: {
26597      sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
26598                          pExpr->iTable, pExpr->iColumn, zFlgs);
26599      sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
26600      break;
26601    }
26602    case TK_VECTOR: {
26603      sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
26604      break;
26605    }
26606    case TK_SELECT_COLUMN: {
26607      sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
26608      sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
26609      break;
26610    }
26611    default: {
26612      sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
26613      break;
26614    }
26615  }
26616  if( zBinOp ){
26617    sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
26618    sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26619    sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
26620  }else if( zUniOp ){
26621    sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
26622    sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26623  }
26624  sqlite3TreeViewPop(pView);
26625}
26626
26627
26628/*
26629** Generate a human-readable explanation of an expression list.
26630*/
26631SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
26632  TreeView *pView,
26633  const ExprList *pList,
26634  const char *zLabel
26635){
26636  if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
26637  if( pList==0 ){
26638    sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
26639  }else{
26640    int i;
26641    sqlite3TreeViewLine(pView, "%s", zLabel);
26642    for(i=0; i<pList->nExpr; i++){
26643      int j = pList->a[i].u.x.iOrderByCol;
26644      if( j ){
26645        sqlite3TreeViewPush(pView, 0);
26646        sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
26647      }
26648      sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
26649      if( j ) sqlite3TreeViewPop(pView);
26650    }
26651  }
26652}
26653SQLITE_PRIVATE void sqlite3TreeViewExprList(
26654  TreeView *pView,
26655  const ExprList *pList,
26656  u8 moreToFollow,
26657  const char *zLabel
26658){
26659  pView = sqlite3TreeViewPush(pView, moreToFollow);
26660  sqlite3TreeViewBareExprList(pView, pList, zLabel);
26661  sqlite3TreeViewPop(pView);
26662}
26663
26664#endif /* SQLITE_DEBUG */
26665
26666/************** End of treeview.c ********************************************/
26667/************** Begin file random.c ******************************************/
26668/*
26669** 2001 September 15
26670**
26671** The author disclaims copyright to this source code.  In place of
26672** a legal notice, here is a blessing:
26673**
26674**    May you do good and not evil.
26675**    May you find forgiveness for yourself and forgive others.
26676**    May you share freely, never taking more than you give.
26677**
26678*************************************************************************
26679** This file contains code to implement a pseudo-random number
26680** generator (PRNG) for SQLite.
26681**
26682** Random numbers are used by some of the database backends in order
26683** to generate random integer keys for tables or random filenames.
26684*/
26685/* #include "sqliteInt.h" */
26686
26687
26688/* All threads share a single random number generator.
26689** This structure is the current state of the generator.
26690*/
26691static SQLITE_WSD struct sqlite3PrngType {
26692  unsigned char isInit;          /* True if initialized */
26693  unsigned char i, j;            /* State variables */
26694  unsigned char s[256];          /* State variables */
26695} sqlite3Prng;
26696
26697/*
26698** Return N random bytes.
26699*/
26700SQLITE_API void sqlite3_randomness(int N, void *pBuf){
26701  unsigned char t;
26702  unsigned char *zBuf = pBuf;
26703
26704  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
26705  ** state vector.  If writable static data is unsupported on the target,
26706  ** we have to locate the state vector at run-time.  In the more common
26707  ** case where writable static data is supported, wsdPrng can refer directly
26708  ** to the "sqlite3Prng" state vector declared above.
26709  */
26710#ifdef SQLITE_OMIT_WSD
26711  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
26712# define wsdPrng p[0]
26713#else
26714# define wsdPrng sqlite3Prng
26715#endif
26716
26717#if SQLITE_THREADSAFE
26718  sqlite3_mutex *mutex;
26719#endif
26720
26721#ifndef SQLITE_OMIT_AUTOINIT
26722  if( sqlite3_initialize() ) return;
26723#endif
26724
26725#if SQLITE_THREADSAFE
26726  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
26727#endif
26728
26729  sqlite3_mutex_enter(mutex);
26730  if( N<=0 || pBuf==0 ){
26731    wsdPrng.isInit = 0;
26732    sqlite3_mutex_leave(mutex);
26733    return;
26734  }
26735
26736  /* Initialize the state of the random number generator once,
26737  ** the first time this routine is called.  The seed value does
26738  ** not need to contain a lot of randomness since we are not
26739  ** trying to do secure encryption or anything like that...
26740  **
26741  ** Nothing in this file or anywhere else in SQLite does any kind of
26742  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
26743  ** number generator) not as an encryption device.
26744  */
26745  if( !wsdPrng.isInit ){
26746    int i;
26747    char k[256];
26748    wsdPrng.j = 0;
26749    wsdPrng.i = 0;
26750    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
26751    for(i=0; i<256; i++){
26752      wsdPrng.s[i] = (u8)i;
26753    }
26754    for(i=0; i<256; i++){
26755      wsdPrng.j += wsdPrng.s[i] + k[i];
26756      t = wsdPrng.s[wsdPrng.j];
26757      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
26758      wsdPrng.s[i] = t;
26759    }
26760    wsdPrng.isInit = 1;
26761  }
26762
26763  assert( N>0 );
26764  do{
26765    wsdPrng.i++;
26766    t = wsdPrng.s[wsdPrng.i];
26767    wsdPrng.j += t;
26768    wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
26769    wsdPrng.s[wsdPrng.j] = t;
26770    t += wsdPrng.s[wsdPrng.i];
26771    *(zBuf++) = wsdPrng.s[t];
26772  }while( --N );
26773  sqlite3_mutex_leave(mutex);
26774}
26775
26776#ifndef SQLITE_UNTESTABLE
26777/*
26778** For testing purposes, we sometimes want to preserve the state of
26779** PRNG and restore the PRNG to its saved state at a later time, or
26780** to reset the PRNG to its initial state.  These routines accomplish
26781** those tasks.
26782**
26783** The sqlite3_test_control() interface calls these routines to
26784** control the PRNG.
26785*/
26786static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
26787SQLITE_PRIVATE void sqlite3PrngSaveState(void){
26788  memcpy(
26789    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
26790    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
26791    sizeof(sqlite3Prng)
26792  );
26793}
26794SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
26795  memcpy(
26796    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
26797    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
26798    sizeof(sqlite3Prng)
26799  );
26800}
26801#endif /* SQLITE_UNTESTABLE */
26802
26803/************** End of random.c **********************************************/
26804/************** Begin file threads.c *****************************************/
26805/*
26806** 2012 July 21
26807**
26808** The author disclaims copyright to this source code.  In place of
26809** a legal notice, here is a blessing:
26810**
26811**    May you do good and not evil.
26812**    May you find forgiveness for yourself and forgive others.
26813**    May you share freely, never taking more than you give.
26814**
26815******************************************************************************
26816**
26817** This file presents a simple cross-platform threading interface for
26818** use internally by SQLite.
26819**
26820** A "thread" can be created using sqlite3ThreadCreate().  This thread
26821** runs independently of its creator until it is joined using
26822** sqlite3ThreadJoin(), at which point it terminates.
26823**
26824** Threads do not have to be real.  It could be that the work of the
26825** "thread" is done by the main thread at either the sqlite3ThreadCreate()
26826** or sqlite3ThreadJoin() call.  This is, in fact, what happens in
26827** single threaded systems.  Nothing in SQLite requires multiple threads.
26828** This interface exists so that applications that want to take advantage
26829** of multiple cores can do so, while also allowing applications to stay
26830** single-threaded if desired.
26831*/
26832/* #include "sqliteInt.h" */
26833#if SQLITE_OS_WIN
26834/* #  include "os_win.h" */
26835#endif
26836
26837#if SQLITE_MAX_WORKER_THREADS>0
26838
26839/********************************* Unix Pthreads ****************************/
26840#if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
26841
26842#define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
26843/* #include <pthread.h> */
26844
26845/* A running thread */
26846struct SQLiteThread {
26847  pthread_t tid;                 /* Thread ID */
26848  int done;                      /* Set to true when thread finishes */
26849  void *pOut;                    /* Result returned by the thread */
26850  void *(*xTask)(void*);         /* The thread routine */
26851  void *pIn;                     /* Argument to the thread */
26852};
26853
26854/* Create a new thread */
26855SQLITE_PRIVATE int sqlite3ThreadCreate(
26856  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
26857  void *(*xTask)(void*),    /* Routine to run in a separate thread */
26858  void *pIn                 /* Argument passed into xTask() */
26859){
26860  SQLiteThread *p;
26861  int rc;
26862
26863  assert( ppThread!=0 );
26864  assert( xTask!=0 );
26865  /* This routine is never used in single-threaded mode */
26866  assert( sqlite3GlobalConfig.bCoreMutex!=0 );
26867
26868  *ppThread = 0;
26869  p = sqlite3Malloc(sizeof(*p));
26870  if( p==0 ) return SQLITE_NOMEM_BKPT;
26871  memset(p, 0, sizeof(*p));
26872  p->xTask = xTask;
26873  p->pIn = pIn;
26874  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
26875  ** function that returns SQLITE_ERROR when passed the argument 200, that
26876  ** forces worker threads to run sequentially and deterministically
26877  ** for testing purposes. */
26878  if( sqlite3FaultSim(200) ){
26879    rc = 1;
26880  }else{
26881    rc = pthread_create(&p->tid, 0, xTask, pIn);
26882  }
26883  if( rc ){
26884    p->done = 1;
26885    p->pOut = xTask(pIn);
26886  }
26887  *ppThread = p;
26888  return SQLITE_OK;
26889}
26890
26891/* Get the results of the thread */
26892SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26893  int rc;
26894
26895  assert( ppOut!=0 );
26896  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26897  if( p->done ){
26898    *ppOut = p->pOut;
26899    rc = SQLITE_OK;
26900  }else{
26901    rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
26902  }
26903  sqlite3_free(p);
26904  return rc;
26905}
26906
26907#endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
26908/******************************** End Unix Pthreads *************************/
26909
26910
26911/********************************* Win32 Threads ****************************/
26912#if SQLITE_OS_WIN_THREADS
26913
26914#define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
26915#include <process.h>
26916
26917/* A running thread */
26918struct SQLiteThread {
26919  void *tid;               /* The thread handle */
26920  unsigned id;             /* The thread identifier */
26921  void *(*xTask)(void*);   /* The routine to run as a thread */
26922  void *pIn;               /* Argument to xTask */
26923  void *pResult;           /* Result of xTask */
26924};
26925
26926/* Thread procedure Win32 compatibility shim */
26927static unsigned __stdcall sqlite3ThreadProc(
26928  void *pArg  /* IN: Pointer to the SQLiteThread structure */
26929){
26930  SQLiteThread *p = (SQLiteThread *)pArg;
26931
26932  assert( p!=0 );
26933#if 0
26934  /*
26935  ** This assert appears to trigger spuriously on certain
26936  ** versions of Windows, possibly due to _beginthreadex()
26937  ** and/or CreateThread() not fully setting their thread
26938  ** ID parameter before starting the thread.
26939  */
26940  assert( p->id==GetCurrentThreadId() );
26941#endif
26942  assert( p->xTask!=0 );
26943  p->pResult = p->xTask(p->pIn);
26944
26945  _endthreadex(0);
26946  return 0; /* NOT REACHED */
26947}
26948
26949/* Create a new thread */
26950SQLITE_PRIVATE int sqlite3ThreadCreate(
26951  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
26952  void *(*xTask)(void*),    /* Routine to run in a separate thread */
26953  void *pIn                 /* Argument passed into xTask() */
26954){
26955  SQLiteThread *p;
26956
26957  assert( ppThread!=0 );
26958  assert( xTask!=0 );
26959  *ppThread = 0;
26960  p = sqlite3Malloc(sizeof(*p));
26961  if( p==0 ) return SQLITE_NOMEM_BKPT;
26962  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
26963  ** function that returns SQLITE_ERROR when passed the argument 200, that
26964  ** forces worker threads to run sequentially and deterministically
26965  ** (via the sqlite3FaultSim() term of the conditional) for testing
26966  ** purposes. */
26967  if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
26968    memset(p, 0, sizeof(*p));
26969  }else{
26970    p->xTask = xTask;
26971    p->pIn = pIn;
26972    p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
26973    if( p->tid==0 ){
26974      memset(p, 0, sizeof(*p));
26975    }
26976  }
26977  if( p->xTask==0 ){
26978    p->id = GetCurrentThreadId();
26979    p->pResult = xTask(pIn);
26980  }
26981  *ppThread = p;
26982  return SQLITE_OK;
26983}
26984
26985SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
26986
26987/* Get the results of the thread */
26988SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26989  DWORD rc;
26990  BOOL bRc;
26991
26992  assert( ppOut!=0 );
26993  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26994  if( p->xTask==0 ){
26995    /* assert( p->id==GetCurrentThreadId() ); */
26996    rc = WAIT_OBJECT_0;
26997    assert( p->tid==0 );
26998  }else{
26999    assert( p->id!=0 && p->id!=GetCurrentThreadId() );
27000    rc = sqlite3Win32Wait((HANDLE)p->tid);
27001    assert( rc!=WAIT_IO_COMPLETION );
27002    bRc = CloseHandle((HANDLE)p->tid);
27003    assert( bRc );
27004  }
27005  if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
27006  sqlite3_free(p);
27007  return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
27008}
27009
27010#endif /* SQLITE_OS_WIN_THREADS */
27011/******************************** End Win32 Threads *************************/
27012
27013
27014/********************************* Single-Threaded **************************/
27015#ifndef SQLITE_THREADS_IMPLEMENTED
27016/*
27017** This implementation does not actually create a new thread.  It does the
27018** work of the thread in the main thread, when either the thread is created
27019** or when it is joined
27020*/
27021
27022/* A running thread */
27023struct SQLiteThread {
27024  void *(*xTask)(void*);   /* The routine to run as a thread */
27025  void *pIn;               /* Argument to xTask */
27026  void *pResult;           /* Result of xTask */
27027};
27028
27029/* Create a new thread */
27030SQLITE_PRIVATE int sqlite3ThreadCreate(
27031  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
27032  void *(*xTask)(void*),    /* Routine to run in a separate thread */
27033  void *pIn                 /* Argument passed into xTask() */
27034){
27035  SQLiteThread *p;
27036
27037  assert( ppThread!=0 );
27038  assert( xTask!=0 );
27039  *ppThread = 0;
27040  p = sqlite3Malloc(sizeof(*p));
27041  if( p==0 ) return SQLITE_NOMEM_BKPT;
27042  if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
27043    p->xTask = xTask;
27044    p->pIn = pIn;
27045  }else{
27046    p->xTask = 0;
27047    p->pResult = xTask(pIn);
27048  }
27049  *ppThread = p;
27050  return SQLITE_OK;
27051}
27052
27053/* Get the results of the thread */
27054SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
27055
27056  assert( ppOut!=0 );
27057  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
27058  if( p->xTask ){
27059    *ppOut = p->xTask(p->pIn);
27060  }else{
27061    *ppOut = p->pResult;
27062  }
27063  sqlite3_free(p);
27064
27065#if defined(SQLITE_TEST)
27066  {
27067    void *pTstAlloc = sqlite3Malloc(10);
27068    if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
27069    sqlite3_free(pTstAlloc);
27070  }
27071#endif
27072
27073  return SQLITE_OK;
27074}
27075
27076#endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
27077/****************************** End Single-Threaded *************************/
27078#endif /* SQLITE_MAX_WORKER_THREADS>0 */
27079
27080/************** End of threads.c *********************************************/
27081/************** Begin file utf.c *********************************************/
27082/*
27083** 2004 April 13
27084**
27085** The author disclaims copyright to this source code.  In place of
27086** a legal notice, here is a blessing:
27087**
27088**    May you do good and not evil.
27089**    May you find forgiveness for yourself and forgive others.
27090**    May you share freely, never taking more than you give.
27091**
27092*************************************************************************
27093** This file contains routines used to translate between UTF-8,
27094** UTF-16, UTF-16BE, and UTF-16LE.
27095**
27096** Notes on UTF-8:
27097**
27098**   Byte-0    Byte-1    Byte-2    Byte-3    Value
27099**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
27100**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
27101**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
27102**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
27103**
27104**
27105** Notes on UTF-16:  (with wwww+1==uuuuu)
27106**
27107**      Word-0               Word-1          Value
27108**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
27109**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
27110**
27111**
27112** BOM or Byte Order Mark:
27113**     0xff 0xfe   little-endian utf-16 follows
27114**     0xfe 0xff   big-endian utf-16 follows
27115**
27116*/
27117/* #include "sqliteInt.h" */
27118/* #include <assert.h> */
27119/* #include "vdbeInt.h" */
27120
27121#if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
27122/*
27123** The following constant value is used by the SQLITE_BIGENDIAN and
27124** SQLITE_LITTLEENDIAN macros.
27125*/
27126SQLITE_PRIVATE const int sqlite3one = 1;
27127#endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
27128
27129/*
27130** This lookup table is used to help decode the first byte of
27131** a multi-byte UTF8 character.
27132*/
27133static const unsigned char sqlite3Utf8Trans1[] = {
27134  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
27135  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
27136  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
27137  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
27138  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
27139  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
27140  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
27141  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
27142};
27143
27144
27145#define WRITE_UTF8(zOut, c) {                          \
27146  if( c<0x00080 ){                                     \
27147    *zOut++ = (u8)(c&0xFF);                            \
27148  }                                                    \
27149  else if( c<0x00800 ){                                \
27150    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
27151    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
27152  }                                                    \
27153  else if( c<0x10000 ){                                \
27154    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
27155    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
27156    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
27157  }else{                                               \
27158    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
27159    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
27160    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
27161    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
27162  }                                                    \
27163}
27164
27165#define WRITE_UTF16LE(zOut, c) {                                    \
27166  if( c<=0xFFFF ){                                                  \
27167    *zOut++ = (u8)(c&0x00FF);                                       \
27168    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
27169  }else{                                                            \
27170    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
27171    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
27172    *zOut++ = (u8)(c&0x00FF);                                       \
27173    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
27174  }                                                                 \
27175}
27176
27177#define WRITE_UTF16BE(zOut, c) {                                    \
27178  if( c<=0xFFFF ){                                                  \
27179    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
27180    *zOut++ = (u8)(c&0x00FF);                                       \
27181  }else{                                                            \
27182    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
27183    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
27184    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
27185    *zOut++ = (u8)(c&0x00FF);                                       \
27186  }                                                                 \
27187}
27188
27189#define READ_UTF16LE(zIn, TERM, c){                                   \
27190  c = (*zIn++);                                                       \
27191  c += ((*zIn++)<<8);                                                 \
27192  if( c>=0xD800 && c<0xE000 && TERM ){                                \
27193    int c2 = (*zIn++);                                                \
27194    c2 += ((*zIn++)<<8);                                              \
27195    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
27196  }                                                                   \
27197}
27198
27199#define READ_UTF16BE(zIn, TERM, c){                                   \
27200  c = ((*zIn++)<<8);                                                  \
27201  c += (*zIn++);                                                      \
27202  if( c>=0xD800 && c<0xE000 && TERM ){                                \
27203    int c2 = ((*zIn++)<<8);                                           \
27204    c2 += (*zIn++);                                                   \
27205    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
27206  }                                                                   \
27207}
27208
27209/*
27210** Translate a single UTF-8 character.  Return the unicode value.
27211**
27212** During translation, assume that the byte that zTerm points
27213** is a 0x00.
27214**
27215** Write a pointer to the next unread byte back into *pzNext.
27216**
27217** Notes On Invalid UTF-8:
27218**
27219**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
27220**     be encoded as a multi-byte character.  Any multi-byte character that
27221**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
27222**
27223**  *  This routine never allows a UTF16 surrogate value to be encoded.
27224**     If a multi-byte character attempts to encode a value between
27225**     0xd800 and 0xe000 then it is rendered as 0xfffd.
27226**
27227**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
27228**     byte of a character are interpreted as single-byte characters
27229**     and rendered as themselves even though they are technically
27230**     invalid characters.
27231**
27232**  *  This routine accepts over-length UTF8 encodings
27233**     for unicode values 0x80 and greater.  It does not change over-length
27234**     encodings to 0xfffd as some systems recommend.
27235*/
27236#define READ_UTF8(zIn, zTerm, c)                           \
27237  c = *(zIn++);                                            \
27238  if( c>=0xc0 ){                                           \
27239    c = sqlite3Utf8Trans1[c-0xc0];                         \
27240    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
27241      c = (c<<6) + (0x3f & *(zIn++));                      \
27242    }                                                      \
27243    if( c<0x80                                             \
27244        || (c&0xFFFFF800)==0xD800                          \
27245        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
27246  }
27247SQLITE_PRIVATE u32 sqlite3Utf8Read(
27248  const unsigned char **pz    /* Pointer to string from which to read char */
27249){
27250  unsigned int c;
27251
27252  /* Same as READ_UTF8() above but without the zTerm parameter.
27253  ** For this routine, we assume the UTF8 string is always zero-terminated.
27254  */
27255  c = *((*pz)++);
27256  if( c>=0xc0 ){
27257    c = sqlite3Utf8Trans1[c-0xc0];
27258    while( (*(*pz) & 0xc0)==0x80 ){
27259      c = (c<<6) + (0x3f & *((*pz)++));
27260    }
27261    if( c<0x80
27262        || (c&0xFFFFF800)==0xD800
27263        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
27264  }
27265  return c;
27266}
27267
27268
27269
27270
27271/*
27272** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
27273** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
27274*/
27275/* #define TRANSLATE_TRACE 1 */
27276
27277#ifndef SQLITE_OMIT_UTF16
27278/*
27279** This routine transforms the internal text encoding used by pMem to
27280** desiredEnc. It is an error if the string is already of the desired
27281** encoding, or if *pMem does not contain a string value.
27282*/
27283SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
27284  int len;                    /* Maximum length of output string in bytes */
27285  unsigned char *zOut;                  /* Output buffer */
27286  unsigned char *zIn;                   /* Input iterator */
27287  unsigned char *zTerm;                 /* End of input */
27288  unsigned char *z;                     /* Output iterator */
27289  unsigned int c;
27290
27291  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
27292  assert( pMem->flags&MEM_Str );
27293  assert( pMem->enc!=desiredEnc );
27294  assert( pMem->enc!=0 );
27295  assert( pMem->n>=0 );
27296
27297#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
27298  {
27299    char zBuf[100];
27300    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
27301    fprintf(stderr, "INPUT:  %s\n", zBuf);
27302  }
27303#endif
27304
27305  /* If the translation is between UTF-16 little and big endian, then
27306  ** all that is required is to swap the byte order. This case is handled
27307  ** differently from the others.
27308  */
27309  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
27310    u8 temp;
27311    int rc;
27312    rc = sqlite3VdbeMemMakeWriteable(pMem);
27313    if( rc!=SQLITE_OK ){
27314      assert( rc==SQLITE_NOMEM );
27315      return SQLITE_NOMEM_BKPT;
27316    }
27317    zIn = (u8*)pMem->z;
27318    zTerm = &zIn[pMem->n&~1];
27319    while( zIn<zTerm ){
27320      temp = *zIn;
27321      *zIn = *(zIn+1);
27322      zIn++;
27323      *zIn++ = temp;
27324    }
27325    pMem->enc = desiredEnc;
27326    goto translate_out;
27327  }
27328
27329  /* Set len to the maximum number of bytes required in the output buffer. */
27330  if( desiredEnc==SQLITE_UTF8 ){
27331    /* When converting from UTF-16, the maximum growth results from
27332    ** translating a 2-byte character to a 4-byte UTF-8 character.
27333    ** A single byte is required for the output string
27334    ** nul-terminator.
27335    */
27336    pMem->n &= ~1;
27337    len = pMem->n * 2 + 1;
27338  }else{
27339    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
27340    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
27341    ** character. Two bytes are required in the output buffer for the
27342    ** nul-terminator.
27343    */
27344    len = pMem->n * 2 + 2;
27345  }
27346
27347  /* Set zIn to point at the start of the input buffer and zTerm to point 1
27348  ** byte past the end.
27349  **
27350  ** Variable zOut is set to point at the output buffer, space obtained
27351  ** from sqlite3_malloc().
27352  */
27353  zIn = (u8*)pMem->z;
27354  zTerm = &zIn[pMem->n];
27355  zOut = sqlite3DbMallocRaw(pMem->db, len);
27356  if( !zOut ){
27357    return SQLITE_NOMEM_BKPT;
27358  }
27359  z = zOut;
27360
27361  if( pMem->enc==SQLITE_UTF8 ){
27362    if( desiredEnc==SQLITE_UTF16LE ){
27363      /* UTF-8 -> UTF-16 Little-endian */
27364      while( zIn<zTerm ){
27365        READ_UTF8(zIn, zTerm, c);
27366        WRITE_UTF16LE(z, c);
27367      }
27368    }else{
27369      assert( desiredEnc==SQLITE_UTF16BE );
27370      /* UTF-8 -> UTF-16 Big-endian */
27371      while( zIn<zTerm ){
27372        READ_UTF8(zIn, zTerm, c);
27373        WRITE_UTF16BE(z, c);
27374      }
27375    }
27376    pMem->n = (int)(z - zOut);
27377    *z++ = 0;
27378  }else{
27379    assert( desiredEnc==SQLITE_UTF8 );
27380    if( pMem->enc==SQLITE_UTF16LE ){
27381      /* UTF-16 Little-endian -> UTF-8 */
27382      while( zIn<zTerm ){
27383        READ_UTF16LE(zIn, zIn<zTerm, c);
27384        WRITE_UTF8(z, c);
27385      }
27386    }else{
27387      /* UTF-16 Big-endian -> UTF-8 */
27388      while( zIn<zTerm ){
27389        READ_UTF16BE(zIn, zIn<zTerm, c);
27390        WRITE_UTF8(z, c);
27391      }
27392    }
27393    pMem->n = (int)(z - zOut);
27394  }
27395  *z = 0;
27396  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
27397
27398  c = pMem->flags;
27399  sqlite3VdbeMemRelease(pMem);
27400  pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
27401  pMem->enc = desiredEnc;
27402  pMem->z = (char*)zOut;
27403  pMem->zMalloc = pMem->z;
27404  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
27405
27406translate_out:
27407#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
27408  {
27409    char zBuf[100];
27410    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
27411    fprintf(stderr, "OUTPUT: %s\n", zBuf);
27412  }
27413#endif
27414  return SQLITE_OK;
27415}
27416
27417/*
27418** This routine checks for a byte-order mark at the beginning of the
27419** UTF-16 string stored in *pMem. If one is present, it is removed and
27420** the encoding of the Mem adjusted. This routine does not do any
27421** byte-swapping, it just sets Mem.enc appropriately.
27422**
27423** The allocation (static, dynamic etc.) and encoding of the Mem may be
27424** changed by this function.
27425*/
27426SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
27427  int rc = SQLITE_OK;
27428  u8 bom = 0;
27429
27430  assert( pMem->n>=0 );
27431  if( pMem->n>1 ){
27432    u8 b1 = *(u8 *)pMem->z;
27433    u8 b2 = *(((u8 *)pMem->z) + 1);
27434    if( b1==0xFE && b2==0xFF ){
27435      bom = SQLITE_UTF16BE;
27436    }
27437    if( b1==0xFF && b2==0xFE ){
27438      bom = SQLITE_UTF16LE;
27439    }
27440  }
27441
27442  if( bom ){
27443    rc = sqlite3VdbeMemMakeWriteable(pMem);
27444    if( rc==SQLITE_OK ){
27445      pMem->n -= 2;
27446      memmove(pMem->z, &pMem->z[2], pMem->n);
27447      pMem->z[pMem->n] = '\0';
27448      pMem->z[pMem->n+1] = '\0';
27449      pMem->flags |= MEM_Term;
27450      pMem->enc = bom;
27451    }
27452  }
27453  return rc;
27454}
27455#endif /* SQLITE_OMIT_UTF16 */
27456
27457/*
27458** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
27459** return the number of unicode characters in pZ up to (but not including)
27460** the first 0x00 byte. If nByte is not less than zero, return the
27461** number of unicode characters in the first nByte of pZ (or up to
27462** the first 0x00, whichever comes first).
27463*/
27464SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
27465  int r = 0;
27466  const u8 *z = (const u8*)zIn;
27467  const u8 *zTerm;
27468  if( nByte>=0 ){
27469    zTerm = &z[nByte];
27470  }else{
27471    zTerm = (const u8*)(-1);
27472  }
27473  assert( z<=zTerm );
27474  while( *z!=0 && z<zTerm ){
27475    SQLITE_SKIP_UTF8(z);
27476    r++;
27477  }
27478  return r;
27479}
27480
27481/* This test function is not currently used by the automated test-suite.
27482** Hence it is only available in debug builds.
27483*/
27484#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
27485/*
27486** Translate UTF-8 to UTF-8.
27487**
27488** This has the effect of making sure that the string is well-formed
27489** UTF-8.  Miscoded characters are removed.
27490**
27491** The translation is done in-place and aborted if the output
27492** overruns the input.
27493*/
27494SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
27495  unsigned char *zOut = zIn;
27496  unsigned char *zStart = zIn;
27497  u32 c;
27498
27499  while( zIn[0] && zOut<=zIn ){
27500    c = sqlite3Utf8Read((const u8**)&zIn);
27501    if( c!=0xfffd ){
27502      WRITE_UTF8(zOut, c);
27503    }
27504  }
27505  *zOut = 0;
27506  return (int)(zOut - zStart);
27507}
27508#endif
27509
27510#ifndef SQLITE_OMIT_UTF16
27511/*
27512** Convert a UTF-16 string in the native encoding into a UTF-8 string.
27513** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
27514** be freed by the calling function.
27515**
27516** NULL is returned if there is an allocation error.
27517*/
27518SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
27519  Mem m;
27520  memset(&m, 0, sizeof(m));
27521  m.db = db;
27522  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
27523  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
27524  if( db->mallocFailed ){
27525    sqlite3VdbeMemRelease(&m);
27526    m.z = 0;
27527  }
27528  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
27529  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
27530  assert( m.z || db->mallocFailed );
27531  return m.z;
27532}
27533
27534/*
27535** zIn is a UTF-16 encoded unicode string at least nChar characters long.
27536** Return the number of bytes in the first nChar unicode characters
27537** in pZ.  nChar must be non-negative.
27538*/
27539SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
27540  int c;
27541  unsigned char const *z = zIn;
27542  int n = 0;
27543
27544  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
27545    while( n<nChar ){
27546      READ_UTF16BE(z, 1, c);
27547      n++;
27548    }
27549  }else{
27550    while( n<nChar ){
27551      READ_UTF16LE(z, 1, c);
27552      n++;
27553    }
27554  }
27555  return (int)(z-(unsigned char const *)zIn);
27556}
27557
27558#if defined(SQLITE_TEST)
27559/*
27560** This routine is called from the TCL test function "translate_selftest".
27561** It checks that the primitives for serializing and deserializing
27562** characters in each encoding are inverses of each other.
27563*/
27564SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
27565  unsigned int i, t;
27566  unsigned char zBuf[20];
27567  unsigned char *z;
27568  int n;
27569  unsigned int c;
27570
27571  for(i=0; i<0x00110000; i++){
27572    z = zBuf;
27573    WRITE_UTF8(z, i);
27574    n = (int)(z-zBuf);
27575    assert( n>0 && n<=4 );
27576    z[0] = 0;
27577    z = zBuf;
27578    c = sqlite3Utf8Read((const u8**)&z);
27579    t = i;
27580    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
27581    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
27582    assert( c==t );
27583    assert( (z-zBuf)==n );
27584  }
27585  for(i=0; i<0x00110000; i++){
27586    if( i>=0xD800 && i<0xE000 ) continue;
27587    z = zBuf;
27588    WRITE_UTF16LE(z, i);
27589    n = (int)(z-zBuf);
27590    assert( n>0 && n<=4 );
27591    z[0] = 0;
27592    z = zBuf;
27593    READ_UTF16LE(z, 1, c);
27594    assert( c==i );
27595    assert( (z-zBuf)==n );
27596  }
27597  for(i=0; i<0x00110000; i++){
27598    if( i>=0xD800 && i<0xE000 ) continue;
27599    z = zBuf;
27600    WRITE_UTF16BE(z, i);
27601    n = (int)(z-zBuf);
27602    assert( n>0 && n<=4 );
27603    z[0] = 0;
27604    z = zBuf;
27605    READ_UTF16BE(z, 1, c);
27606    assert( c==i );
27607    assert( (z-zBuf)==n );
27608  }
27609}
27610#endif /* SQLITE_TEST */
27611#endif /* SQLITE_OMIT_UTF16 */
27612
27613/************** End of utf.c *************************************************/
27614/************** Begin file util.c ********************************************/
27615/*
27616** 2001 September 15
27617**
27618** The author disclaims copyright to this source code.  In place of
27619** a legal notice, here is a blessing:
27620**
27621**    May you do good and not evil.
27622**    May you find forgiveness for yourself and forgive others.
27623**    May you share freely, never taking more than you give.
27624**
27625*************************************************************************
27626** Utility functions used throughout sqlite.
27627**
27628** This file contains functions for allocating memory, comparing
27629** strings, and stuff like that.
27630**
27631*/
27632/* #include "sqliteInt.h" */
27633/* #include <stdarg.h> */
27634#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
27635# include <math.h>
27636#endif
27637
27638/*
27639** Routine needed to support the testcase() macro.
27640*/
27641#ifdef SQLITE_COVERAGE_TEST
27642SQLITE_PRIVATE void sqlite3Coverage(int x){
27643  static unsigned dummy = 0;
27644  dummy += (unsigned)x;
27645}
27646#endif
27647
27648/*
27649** Give a callback to the test harness that can be used to simulate faults
27650** in places where it is difficult or expensive to do so purely by means
27651** of inputs.
27652**
27653** The intent of the integer argument is to let the fault simulator know
27654** which of multiple sqlite3FaultSim() calls has been hit.
27655**
27656** Return whatever integer value the test callback returns, or return
27657** SQLITE_OK if no test callback is installed.
27658*/
27659#ifndef SQLITE_UNTESTABLE
27660SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
27661  int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
27662  return xCallback ? xCallback(iTest) : SQLITE_OK;
27663}
27664#endif
27665
27666#ifndef SQLITE_OMIT_FLOATING_POINT
27667/*
27668** Return true if the floating point value is Not a Number (NaN).
27669**
27670** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
27671** Otherwise, we have our own implementation that works on most systems.
27672*/
27673SQLITE_PRIVATE int sqlite3IsNaN(double x){
27674  int rc;   /* The value return */
27675#if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
27676  /*
27677  ** Systems that support the isnan() library function should probably
27678  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
27679  ** found that many systems do not have a working isnan() function so
27680  ** this implementation is provided as an alternative.
27681  **
27682  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
27683  ** On the other hand, the use of -ffast-math comes with the following
27684  ** warning:
27685  **
27686  **      This option [-ffast-math] should never be turned on by any
27687  **      -O option since it can result in incorrect output for programs
27688  **      which depend on an exact implementation of IEEE or ISO
27689  **      rules/specifications for math functions.
27690  **
27691  ** Under MSVC, this NaN test may fail if compiled with a floating-
27692  ** point precision mode other than /fp:precise.  From the MSDN
27693  ** documentation:
27694  **
27695  **      The compiler [with /fp:precise] will properly handle comparisons
27696  **      involving NaN. For example, x != x evaluates to true if x is NaN
27697  **      ...
27698  */
27699#ifdef __FAST_MATH__
27700# error SQLite will not work correctly with the -ffast-math option of GCC.
27701#endif
27702  volatile double y = x;
27703  volatile double z = y;
27704  rc = (y!=z);
27705#else  /* if HAVE_ISNAN */
27706  rc = isnan(x);
27707#endif /* HAVE_ISNAN */
27708  testcase( rc );
27709  return rc;
27710}
27711#endif /* SQLITE_OMIT_FLOATING_POINT */
27712
27713/*
27714** Compute a string length that is limited to what can be stored in
27715** lower 30 bits of a 32-bit signed integer.
27716**
27717** The value returned will never be negative.  Nor will it ever be greater
27718** than the actual length of the string.  For very long strings (greater
27719** than 1GiB) the value returned might be less than the true string length.
27720*/
27721SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
27722  if( z==0 ) return 0;
27723  return 0x3fffffff & (int)strlen(z);
27724}
27725
27726/*
27727** Return the declared type of a column.  Or return zDflt if the column
27728** has no declared type.
27729**
27730** The column type is an extra string stored after the zero-terminator on
27731** the column name if and only if the COLFLAG_HASTYPE flag is set.
27732*/
27733SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
27734  if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
27735  return pCol->zName + strlen(pCol->zName) + 1;
27736}
27737
27738/*
27739** Helper function for sqlite3Error() - called rarely.  Broken out into
27740** a separate routine to avoid unnecessary register saves on entry to
27741** sqlite3Error().
27742*/
27743static SQLITE_NOINLINE void  sqlite3ErrorFinish(sqlite3 *db, int err_code){
27744  if( db->pErr ) sqlite3ValueSetNull(db->pErr);
27745  sqlite3SystemError(db, err_code);
27746}
27747
27748/*
27749** Set the current error code to err_code and clear any prior error message.
27750** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
27751** that would be appropriate.
27752*/
27753SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
27754  assert( db!=0 );
27755  db->errCode = err_code;
27756  if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
27757}
27758
27759/*
27760** Load the sqlite3.iSysErrno field if that is an appropriate thing
27761** to do based on the SQLite error code in rc.
27762*/
27763SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
27764  if( rc==SQLITE_IOERR_NOMEM ) return;
27765  rc &= 0xff;
27766  if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
27767    db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
27768  }
27769}
27770
27771/*
27772** Set the most recent error code and error string for the sqlite
27773** handle "db". The error code is set to "err_code".
27774**
27775** If it is not NULL, string zFormat specifies the format of the
27776** error string in the style of the printf functions: The following
27777** format characters are allowed:
27778**
27779**      %s      Insert a string
27780**      %z      A string that should be freed after use
27781**      %d      Insert an integer
27782**      %T      Insert a token
27783**      %S      Insert the first element of a SrcList
27784**
27785** zFormat and any string tokens that follow it are assumed to be
27786** encoded in UTF-8.
27787**
27788** To clear the most recent error for sqlite handle "db", sqlite3Error
27789** should be called with err_code set to SQLITE_OK and zFormat set
27790** to NULL.
27791*/
27792SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
27793  assert( db!=0 );
27794  db->errCode = err_code;
27795  sqlite3SystemError(db, err_code);
27796  if( zFormat==0 ){
27797    sqlite3Error(db, err_code);
27798  }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
27799    char *z;
27800    va_list ap;
27801    va_start(ap, zFormat);
27802    z = sqlite3VMPrintf(db, zFormat, ap);
27803    va_end(ap);
27804    sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
27805  }
27806}
27807
27808/*
27809** Add an error message to pParse->zErrMsg and increment pParse->nErr.
27810** The following formatting characters are allowed:
27811**
27812**      %s      Insert a string
27813**      %z      A string that should be freed after use
27814**      %d      Insert an integer
27815**      %T      Insert a token
27816**      %S      Insert the first element of a SrcList
27817**
27818** This function should be used to report any error that occurs while
27819** compiling an SQL statement (i.e. within sqlite3_prepare()). The
27820** last thing the sqlite3_prepare() function does is copy the error
27821** stored by this function into the database handle using sqlite3Error().
27822** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
27823** during statement execution (sqlite3_step() etc.).
27824*/
27825SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
27826  char *zMsg;
27827  va_list ap;
27828  sqlite3 *db = pParse->db;
27829  va_start(ap, zFormat);
27830  zMsg = sqlite3VMPrintf(db, zFormat, ap);
27831  va_end(ap);
27832  if( db->suppressErr ){
27833    sqlite3DbFree(db, zMsg);
27834  }else{
27835    pParse->nErr++;
27836    sqlite3DbFree(db, pParse->zErrMsg);
27837    pParse->zErrMsg = zMsg;
27838    pParse->rc = SQLITE_ERROR;
27839  }
27840}
27841
27842/*
27843** Convert an SQL-style quoted string into a normal string by removing
27844** the quote characters.  The conversion is done in-place.  If the
27845** input does not begin with a quote character, then this routine
27846** is a no-op.
27847**
27848** The input string must be zero-terminated.  A new zero-terminator
27849** is added to the dequoted string.
27850**
27851** The return value is -1 if no dequoting occurs or the length of the
27852** dequoted string, exclusive of the zero terminator, if dequoting does
27853** occur.
27854**
27855** 2002-Feb-14: This routine is extended to remove MS-Access style
27856** brackets from around identifiers.  For example:  "[a-b-c]" becomes
27857** "a-b-c".
27858*/
27859SQLITE_PRIVATE void sqlite3Dequote(char *z){
27860  char quote;
27861  int i, j;
27862  if( z==0 ) return;
27863  quote = z[0];
27864  if( !sqlite3Isquote(quote) ) return;
27865  if( quote=='[' ) quote = ']';
27866  for(i=1, j=0;; i++){
27867    assert( z[i] );
27868    if( z[i]==quote ){
27869      if( z[i+1]==quote ){
27870        z[j++] = quote;
27871        i++;
27872      }else{
27873        break;
27874      }
27875    }else{
27876      z[j++] = z[i];
27877    }
27878  }
27879  z[j] = 0;
27880}
27881
27882/*
27883** Generate a Token object from a string
27884*/
27885SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
27886  p->z = z;
27887  p->n = sqlite3Strlen30(z);
27888}
27889
27890/* Convenient short-hand */
27891#define UpperToLower sqlite3UpperToLower
27892
27893/*
27894** Some systems have stricmp().  Others have strcasecmp().  Because
27895** there is no consistency, we will define our own.
27896**
27897** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
27898** sqlite3_strnicmp() APIs allow applications and extensions to compare
27899** the contents of two buffers containing UTF-8 strings in a
27900** case-independent fashion, using the same definition of "case
27901** independence" that SQLite uses internally when comparing identifiers.
27902*/
27903SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
27904  if( zLeft==0 ){
27905    return zRight ? -1 : 0;
27906  }else if( zRight==0 ){
27907    return 1;
27908  }
27909  return sqlite3StrICmp(zLeft, zRight);
27910}
27911SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
27912  unsigned char *a, *b;
27913  int c;
27914  a = (unsigned char *)zLeft;
27915  b = (unsigned char *)zRight;
27916  for(;;){
27917    c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
27918    if( c || *a==0 ) break;
27919    a++;
27920    b++;
27921  }
27922  return c;
27923}
27924SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
27925  register unsigned char *a, *b;
27926  if( zLeft==0 ){
27927    return zRight ? -1 : 0;
27928  }else if( zRight==0 ){
27929    return 1;
27930  }
27931  a = (unsigned char *)zLeft;
27932  b = (unsigned char *)zRight;
27933  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
27934  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
27935}
27936
27937/*
27938** The string z[] is an text representation of a real number.
27939** Convert this string to a double and write it into *pResult.
27940**
27941** The string z[] is length bytes in length (bytes, not characters) and
27942** uses the encoding enc.  The string is not necessarily zero-terminated.
27943**
27944** Return TRUE if the result is a valid real number (or integer) and FALSE
27945** if the string is empty or contains extraneous text.  Valid numbers
27946** are in one of these formats:
27947**
27948**    [+-]digits[E[+-]digits]
27949**    [+-]digits.[digits][E[+-]digits]
27950**    [+-].digits[E[+-]digits]
27951**
27952** Leading and trailing whitespace is ignored for the purpose of determining
27953** validity.
27954**
27955** If some prefix of the input string is a valid number, this routine
27956** returns FALSE but it still converts the prefix and writes the result
27957** into *pResult.
27958*/
27959SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
27960#ifndef SQLITE_OMIT_FLOATING_POINT
27961  int incr;
27962  const char *zEnd = z + length;
27963  /* sign * significand * (10 ^ (esign * exponent)) */
27964  int sign = 1;    /* sign of significand */
27965  i64 s = 0;       /* significand */
27966  int d = 0;       /* adjust exponent for shifting decimal point */
27967  int esign = 1;   /* sign of exponent */
27968  int e = 0;       /* exponent */
27969  int eValid = 1;  /* True exponent is either not used or is well-formed */
27970  double result;
27971  int nDigits = 0;
27972  int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
27973
27974  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27975  *pResult = 0.0;   /* Default return value, in case of an error */
27976
27977  if( enc==SQLITE_UTF8 ){
27978    incr = 1;
27979  }else{
27980    int i;
27981    incr = 2;
27982    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27983    for(i=3-enc; i<length && z[i]==0; i+=2){}
27984    nonNum = i<length;
27985    zEnd = &z[i^1];
27986    z += (enc&1);
27987  }
27988
27989  /* skip leading spaces */
27990  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
27991  if( z>=zEnd ) return 0;
27992
27993  /* get sign of significand */
27994  if( *z=='-' ){
27995    sign = -1;
27996    z+=incr;
27997  }else if( *z=='+' ){
27998    z+=incr;
27999  }
28000
28001  /* copy max significant digits to significand */
28002  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
28003    s = s*10 + (*z - '0');
28004    z+=incr, nDigits++;
28005  }
28006
28007  /* skip non-significant significand digits
28008  ** (increase exponent by d to shift decimal left) */
28009  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
28010  if( z>=zEnd ) goto do_atof_calc;
28011
28012  /* if decimal point is present */
28013  if( *z=='.' ){
28014    z+=incr;
28015    /* copy digits from after decimal to significand
28016    ** (decrease exponent by d to shift decimal right) */
28017    while( z<zEnd && sqlite3Isdigit(*z) ){
28018      if( s<((LARGEST_INT64-9)/10) ){
28019        s = s*10 + (*z - '0');
28020        d--;
28021      }
28022      z+=incr, nDigits++;
28023    }
28024  }
28025  if( z>=zEnd ) goto do_atof_calc;
28026
28027  /* if exponent is present */
28028  if( *z=='e' || *z=='E' ){
28029    z+=incr;
28030    eValid = 0;
28031
28032    /* This branch is needed to avoid a (harmless) buffer overread.  The
28033    ** special comment alerts the mutation tester that the correct answer
28034    ** is obtained even if the branch is omitted */
28035    if( z>=zEnd ) goto do_atof_calc;              /*PREVENTS-HARMLESS-OVERREAD*/
28036
28037    /* get sign of exponent */
28038    if( *z=='-' ){
28039      esign = -1;
28040      z+=incr;
28041    }else if( *z=='+' ){
28042      z+=incr;
28043    }
28044    /* copy digits to exponent */
28045    while( z<zEnd && sqlite3Isdigit(*z) ){
28046      e = e<10000 ? (e*10 + (*z - '0')) : 10000;
28047      z+=incr;
28048      eValid = 1;
28049    }
28050  }
28051
28052  /* skip trailing spaces */
28053  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
28054
28055do_atof_calc:
28056  /* adjust exponent by d, and update sign */
28057  e = (e*esign) + d;
28058  if( e<0 ) {
28059    esign = -1;
28060    e *= -1;
28061  } else {
28062    esign = 1;
28063  }
28064
28065  if( s==0 ) {
28066    /* In the IEEE 754 standard, zero is signed. */
28067    result = sign<0 ? -(double)0 : (double)0;
28068  } else {
28069    /* Attempt to reduce exponent.
28070    **
28071    ** Branches that are not required for the correct answer but which only
28072    ** help to obtain the correct answer faster are marked with special
28073    ** comments, as a hint to the mutation tester.
28074    */
28075    while( e>0 ){                                       /*OPTIMIZATION-IF-TRUE*/
28076      if( esign>0 ){
28077        if( s>=(LARGEST_INT64/10) ) break;             /*OPTIMIZATION-IF-FALSE*/
28078        s *= 10;
28079      }else{
28080        if( s%10!=0 ) break;                           /*OPTIMIZATION-IF-FALSE*/
28081        s /= 10;
28082      }
28083      e--;
28084    }
28085
28086    /* adjust the sign of significand */
28087    s = sign<0 ? -s : s;
28088
28089    if( e==0 ){                                         /*OPTIMIZATION-IF-TRUE*/
28090      result = (double)s;
28091    }else{
28092      LONGDOUBLE_TYPE scale = 1.0;
28093      /* attempt to handle extremely small/large numbers better */
28094      if( e>307 ){                                      /*OPTIMIZATION-IF-TRUE*/
28095        if( e<342 ){                                    /*OPTIMIZATION-IF-TRUE*/
28096          while( e%308 ) { scale *= 1.0e+1; e -= 1; }
28097          if( esign<0 ){
28098            result = s / scale;
28099            result /= 1.0e+308;
28100          }else{
28101            result = s * scale;
28102            result *= 1.0e+308;
28103          }
28104        }else{ assert( e>=342 );
28105          if( esign<0 ){
28106            result = 0.0*s;
28107          }else{
28108            result = 1e308*1e308*s;  /* Infinity */
28109          }
28110        }
28111      }else{
28112        /* 1.0e+22 is the largest power of 10 than can be
28113        ** represented exactly. */
28114        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
28115        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
28116        if( esign<0 ){
28117          result = s / scale;
28118        }else{
28119          result = s * scale;
28120        }
28121      }
28122    }
28123  }
28124
28125  /* store the result */
28126  *pResult = result;
28127
28128  /* return true if number and no extra non-whitespace chracters after */
28129  return z==zEnd && nDigits>0 && eValid && nonNum==0;
28130#else
28131  return !sqlite3Atoi64(z, pResult, length, enc);
28132#endif /* SQLITE_OMIT_FLOATING_POINT */
28133}
28134
28135/*
28136** Compare the 19-character string zNum against the text representation
28137** value 2^63:  9223372036854775808.  Return negative, zero, or positive
28138** if zNum is less than, equal to, or greater than the string.
28139** Note that zNum must contain exactly 19 characters.
28140**
28141** Unlike memcmp() this routine is guaranteed to return the difference
28142** in the values of the last digit if the only difference is in the
28143** last digit.  So, for example,
28144**
28145**      compare2pow63("9223372036854775800", 1)
28146**
28147** will return -8.
28148*/
28149static int compare2pow63(const char *zNum, int incr){
28150  int c = 0;
28151  int i;
28152                    /* 012345678901234567 */
28153  const char *pow63 = "922337203685477580";
28154  for(i=0; c==0 && i<18; i++){
28155    c = (zNum[i*incr]-pow63[i])*10;
28156  }
28157  if( c==0 ){
28158    c = zNum[18*incr] - '8';
28159    testcase( c==(-1) );
28160    testcase( c==0 );
28161    testcase( c==(+1) );
28162  }
28163  return c;
28164}
28165
28166/*
28167** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
28168** routine does *not* accept hexadecimal notation.
28169**
28170** If the zNum value is representable as a 64-bit twos-complement
28171** integer, then write that value into *pNum and return 0.
28172**
28173** If zNum is exactly 9223372036854775808, return 2.  This special
28174** case is broken out because while 9223372036854775808 cannot be a
28175** signed 64-bit integer, its negative -9223372036854775808 can be.
28176**
28177** If zNum is too big for a 64-bit integer and is not
28178** 9223372036854775808  or if zNum contains any non-numeric text,
28179** then return 1.
28180**
28181** length is the number of bytes in the string (bytes, not characters).
28182** The string is not necessarily zero-terminated.  The encoding is
28183** given by enc.
28184*/
28185SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
28186  int incr;
28187  u64 u = 0;
28188  int neg = 0; /* assume positive */
28189  int i;
28190  int c = 0;
28191  int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
28192  const char *zStart;
28193  const char *zEnd = zNum + length;
28194  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
28195  if( enc==SQLITE_UTF8 ){
28196    incr = 1;
28197  }else{
28198    incr = 2;
28199    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
28200    for(i=3-enc; i<length && zNum[i]==0; i+=2){}
28201    nonNum = i<length;
28202    zEnd = &zNum[i^1];
28203    zNum += (enc&1);
28204  }
28205  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
28206  if( zNum<zEnd ){
28207    if( *zNum=='-' ){
28208      neg = 1;
28209      zNum+=incr;
28210    }else if( *zNum=='+' ){
28211      zNum+=incr;
28212    }
28213  }
28214  zStart = zNum;
28215  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
28216  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
28217    u = u*10 + c - '0';
28218  }
28219  if( u>LARGEST_INT64 ){
28220    *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
28221  }else if( neg ){
28222    *pNum = -(i64)u;
28223  }else{
28224    *pNum = (i64)u;
28225  }
28226  testcase( i==18 );
28227  testcase( i==19 );
28228  testcase( i==20 );
28229  if( &zNum[i]<zEnd              /* Extra bytes at the end */
28230   || (i==0 && zStart==zNum)     /* No digits */
28231   || i>19*incr                  /* Too many digits */
28232   || nonNum                     /* UTF16 with high-order bytes non-zero */
28233  ){
28234    /* zNum is empty or contains non-numeric text or is longer
28235    ** than 19 digits (thus guaranteeing that it is too large) */
28236    return 1;
28237  }else if( i<19*incr ){
28238    /* Less than 19 digits, so we know that it fits in 64 bits */
28239    assert( u<=LARGEST_INT64 );
28240    return 0;
28241  }else{
28242    /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
28243    c = compare2pow63(zNum, incr);
28244    if( c<0 ){
28245      /* zNum is less than 9223372036854775808 so it fits */
28246      assert( u<=LARGEST_INT64 );
28247      return 0;
28248    }else if( c>0 ){
28249      /* zNum is greater than 9223372036854775808 so it overflows */
28250      return 1;
28251    }else{
28252      /* zNum is exactly 9223372036854775808.  Fits if negative.  The
28253      ** special case 2 overflow if positive */
28254      assert( u-1==LARGEST_INT64 );
28255      return neg ? 0 : 2;
28256    }
28257  }
28258}
28259
28260/*
28261** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
28262** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
28263** whereas sqlite3Atoi64() does not.
28264**
28265** Returns:
28266**
28267**     0    Successful transformation.  Fits in a 64-bit signed integer.
28268**     1    Integer too large for a 64-bit signed integer or is malformed
28269**     2    Special case of 9223372036854775808
28270*/
28271SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
28272#ifndef SQLITE_OMIT_HEX_INTEGER
28273  if( z[0]=='0'
28274   && (z[1]=='x' || z[1]=='X')
28275  ){
28276    u64 u = 0;
28277    int i, k;
28278    for(i=2; z[i]=='0'; i++){}
28279    for(k=i; sqlite3Isxdigit(z[k]); k++){
28280      u = u*16 + sqlite3HexToInt(z[k]);
28281    }
28282    memcpy(pOut, &u, 8);
28283    return (z[k]==0 && k-i<=16) ? 0 : 1;
28284  }else
28285#endif /* SQLITE_OMIT_HEX_INTEGER */
28286  {
28287    return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
28288  }
28289}
28290
28291/*
28292** If zNum represents an integer that will fit in 32-bits, then set
28293** *pValue to that integer and return true.  Otherwise return false.
28294**
28295** This routine accepts both decimal and hexadecimal notation for integers.
28296**
28297** Any non-numeric characters that following zNum are ignored.
28298** This is different from sqlite3Atoi64() which requires the
28299** input number to be zero-terminated.
28300*/
28301SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
28302  sqlite_int64 v = 0;
28303  int i, c;
28304  int neg = 0;
28305  if( zNum[0]=='-' ){
28306    neg = 1;
28307    zNum++;
28308  }else if( zNum[0]=='+' ){
28309    zNum++;
28310  }
28311#ifndef SQLITE_OMIT_HEX_INTEGER
28312  else if( zNum[0]=='0'
28313        && (zNum[1]=='x' || zNum[1]=='X')
28314        && sqlite3Isxdigit(zNum[2])
28315  ){
28316    u32 u = 0;
28317    zNum += 2;
28318    while( zNum[0]=='0' ) zNum++;
28319    for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
28320      u = u*16 + sqlite3HexToInt(zNum[i]);
28321    }
28322    if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
28323      memcpy(pValue, &u, 4);
28324      return 1;
28325    }else{
28326      return 0;
28327    }
28328  }
28329#endif
28330  while( zNum[0]=='0' ) zNum++;
28331  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
28332    v = v*10 + c;
28333  }
28334
28335  /* The longest decimal representation of a 32 bit integer is 10 digits:
28336  **
28337  **             1234567890
28338  **     2^31 -> 2147483648
28339  */
28340  testcase( i==10 );
28341  if( i>10 ){
28342    return 0;
28343  }
28344  testcase( v-neg==2147483647 );
28345  if( v-neg>2147483647 ){
28346    return 0;
28347  }
28348  if( neg ){
28349    v = -v;
28350  }
28351  *pValue = (int)v;
28352  return 1;
28353}
28354
28355/*
28356** Return a 32-bit integer value extracted from a string.  If the
28357** string is not an integer, just return 0.
28358*/
28359SQLITE_PRIVATE int sqlite3Atoi(const char *z){
28360  int x = 0;
28361  if( z ) sqlite3GetInt32(z, &x);
28362  return x;
28363}
28364
28365/*
28366** The variable-length integer encoding is as follows:
28367**
28368** KEY:
28369**         A = 0xxxxxxx    7 bits of data and one flag bit
28370**         B = 1xxxxxxx    7 bits of data and one flag bit
28371**         C = xxxxxxxx    8 bits of data
28372**
28373**  7 bits - A
28374** 14 bits - BA
28375** 21 bits - BBA
28376** 28 bits - BBBA
28377** 35 bits - BBBBA
28378** 42 bits - BBBBBA
28379** 49 bits - BBBBBBA
28380** 56 bits - BBBBBBBA
28381** 64 bits - BBBBBBBBC
28382*/
28383
28384/*
28385** Write a 64-bit variable-length integer to memory starting at p[0].
28386** The length of data write will be between 1 and 9 bytes.  The number
28387** of bytes written is returned.
28388**
28389** A variable-length integer consists of the lower 7 bits of each byte
28390** for all bytes that have the 8th bit set and one byte with the 8th
28391** bit clear.  Except, if we get to the 9th byte, it stores the full
28392** 8 bits and is the last byte.
28393*/
28394static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
28395  int i, j, n;
28396  u8 buf[10];
28397  if( v & (((u64)0xff000000)<<32) ){
28398    p[8] = (u8)v;
28399    v >>= 8;
28400    for(i=7; i>=0; i--){
28401      p[i] = (u8)((v & 0x7f) | 0x80);
28402      v >>= 7;
28403    }
28404    return 9;
28405  }
28406  n = 0;
28407  do{
28408    buf[n++] = (u8)((v & 0x7f) | 0x80);
28409    v >>= 7;
28410  }while( v!=0 );
28411  buf[0] &= 0x7f;
28412  assert( n<=9 );
28413  for(i=0, j=n-1; j>=0; j--, i++){
28414    p[i] = buf[j];
28415  }
28416  return n;
28417}
28418SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
28419  if( v<=0x7f ){
28420    p[0] = v&0x7f;
28421    return 1;
28422  }
28423  if( v<=0x3fff ){
28424    p[0] = ((v>>7)&0x7f)|0x80;
28425    p[1] = v&0x7f;
28426    return 2;
28427  }
28428  return putVarint64(p,v);
28429}
28430
28431/*
28432** Bitmasks used by sqlite3GetVarint().  These precomputed constants
28433** are defined here rather than simply putting the constant expressions
28434** inline in order to work around bugs in the RVT compiler.
28435**
28436** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
28437**
28438** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
28439*/
28440#define SLOT_2_0     0x001fc07f
28441#define SLOT_4_2_0   0xf01fc07f
28442
28443
28444/*
28445** Read a 64-bit variable-length integer from memory starting at p[0].
28446** Return the number of bytes read.  The value is stored in *v.
28447*/
28448SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
28449  u32 a,b,s;
28450
28451  a = *p;
28452  /* a: p0 (unmasked) */
28453  if (!(a&0x80))
28454  {
28455    *v = a;
28456    return 1;
28457  }
28458
28459  p++;
28460  b = *p;
28461  /* b: p1 (unmasked) */
28462  if (!(b&0x80))
28463  {
28464    a &= 0x7f;
28465    a = a<<7;
28466    a |= b;
28467    *v = a;
28468    return 2;
28469  }
28470
28471  /* Verify that constants are precomputed correctly */
28472  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
28473  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
28474
28475  p++;
28476  a = a<<14;
28477  a |= *p;
28478  /* a: p0<<14 | p2 (unmasked) */
28479  if (!(a&0x80))
28480  {
28481    a &= SLOT_2_0;
28482    b &= 0x7f;
28483    b = b<<7;
28484    a |= b;
28485    *v = a;
28486    return 3;
28487  }
28488
28489  /* CSE1 from below */
28490  a &= SLOT_2_0;
28491  p++;
28492  b = b<<14;
28493  b |= *p;
28494  /* b: p1<<14 | p3 (unmasked) */
28495  if (!(b&0x80))
28496  {
28497    b &= SLOT_2_0;
28498    /* moved CSE1 up */
28499    /* a &= (0x7f<<14)|(0x7f); */
28500    a = a<<7;
28501    a |= b;
28502    *v = a;
28503    return 4;
28504  }
28505
28506  /* a: p0<<14 | p2 (masked) */
28507  /* b: p1<<14 | p3 (unmasked) */
28508  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28509  /* moved CSE1 up */
28510  /* a &= (0x7f<<14)|(0x7f); */
28511  b &= SLOT_2_0;
28512  s = a;
28513  /* s: p0<<14 | p2 (masked) */
28514
28515  p++;
28516  a = a<<14;
28517  a |= *p;
28518  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
28519  if (!(a&0x80))
28520  {
28521    /* we can skip these cause they were (effectively) done above
28522    ** while calculating s */
28523    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
28524    /* b &= (0x7f<<14)|(0x7f); */
28525    b = b<<7;
28526    a |= b;
28527    s = s>>18;
28528    *v = ((u64)s)<<32 | a;
28529    return 5;
28530  }
28531
28532  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28533  s = s<<7;
28534  s |= b;
28535  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28536
28537  p++;
28538  b = b<<14;
28539  b |= *p;
28540  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
28541  if (!(b&0x80))
28542  {
28543    /* we can skip this cause it was (effectively) done above in calc'ing s */
28544    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
28545    a &= SLOT_2_0;
28546    a = a<<7;
28547    a |= b;
28548    s = s>>18;
28549    *v = ((u64)s)<<32 | a;
28550    return 6;
28551  }
28552
28553  p++;
28554  a = a<<14;
28555  a |= *p;
28556  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
28557  if (!(a&0x80))
28558  {
28559    a &= SLOT_4_2_0;
28560    b &= SLOT_2_0;
28561    b = b<<7;
28562    a |= b;
28563    s = s>>11;
28564    *v = ((u64)s)<<32 | a;
28565    return 7;
28566  }
28567
28568  /* CSE2 from below */
28569  a &= SLOT_2_0;
28570  p++;
28571  b = b<<14;
28572  b |= *p;
28573  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
28574  if (!(b&0x80))
28575  {
28576    b &= SLOT_4_2_0;
28577    /* moved CSE2 up */
28578    /* a &= (0x7f<<14)|(0x7f); */
28579    a = a<<7;
28580    a |= b;
28581    s = s>>4;
28582    *v = ((u64)s)<<32 | a;
28583    return 8;
28584  }
28585
28586  p++;
28587  a = a<<15;
28588  a |= *p;
28589  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
28590
28591  /* moved CSE2 up */
28592  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
28593  b &= SLOT_2_0;
28594  b = b<<8;
28595  a |= b;
28596
28597  s = s<<4;
28598  b = p[-4];
28599  b &= 0x7f;
28600  b = b>>3;
28601  s |= b;
28602
28603  *v = ((u64)s)<<32 | a;
28604
28605  return 9;
28606}
28607
28608/*
28609** Read a 32-bit variable-length integer from memory starting at p[0].
28610** Return the number of bytes read.  The value is stored in *v.
28611**
28612** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
28613** integer, then set *v to 0xffffffff.
28614**
28615** A MACRO version, getVarint32, is provided which inlines the
28616** single-byte case.  All code should use the MACRO version as
28617** this function assumes the single-byte case has already been handled.
28618*/
28619SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
28620  u32 a,b;
28621
28622  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
28623  ** by the getVarin32() macro */
28624  a = *p;
28625  /* a: p0 (unmasked) */
28626#ifndef getVarint32
28627  if (!(a&0x80))
28628  {
28629    /* Values between 0 and 127 */
28630    *v = a;
28631    return 1;
28632  }
28633#endif
28634
28635  /* The 2-byte case */
28636  p++;
28637  b = *p;
28638  /* b: p1 (unmasked) */
28639  if (!(b&0x80))
28640  {
28641    /* Values between 128 and 16383 */
28642    a &= 0x7f;
28643    a = a<<7;
28644    *v = a | b;
28645    return 2;
28646  }
28647
28648  /* The 3-byte case */
28649  p++;
28650  a = a<<14;
28651  a |= *p;
28652  /* a: p0<<14 | p2 (unmasked) */
28653  if (!(a&0x80))
28654  {
28655    /* Values between 16384 and 2097151 */
28656    a &= (0x7f<<14)|(0x7f);
28657    b &= 0x7f;
28658    b = b<<7;
28659    *v = a | b;
28660    return 3;
28661  }
28662
28663  /* A 32-bit varint is used to store size information in btrees.
28664  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
28665  ** A 3-byte varint is sufficient, for example, to record the size
28666  ** of a 1048569-byte BLOB or string.
28667  **
28668  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
28669  ** rare larger cases can be handled by the slower 64-bit varint
28670  ** routine.
28671  */
28672#if 1
28673  {
28674    u64 v64;
28675    u8 n;
28676
28677    p -= 2;
28678    n = sqlite3GetVarint(p, &v64);
28679    assert( n>3 && n<=9 );
28680    if( (v64 & SQLITE_MAX_U32)!=v64 ){
28681      *v = 0xffffffff;
28682    }else{
28683      *v = (u32)v64;
28684    }
28685    return n;
28686  }
28687
28688#else
28689  /* For following code (kept for historical record only) shows an
28690  ** unrolling for the 3- and 4-byte varint cases.  This code is
28691  ** slightly faster, but it is also larger and much harder to test.
28692  */
28693  p++;
28694  b = b<<14;
28695  b |= *p;
28696  /* b: p1<<14 | p3 (unmasked) */
28697  if (!(b&0x80))
28698  {
28699    /* Values between 2097152 and 268435455 */
28700    b &= (0x7f<<14)|(0x7f);
28701    a &= (0x7f<<14)|(0x7f);
28702    a = a<<7;
28703    *v = a | b;
28704    return 4;
28705  }
28706
28707  p++;
28708  a = a<<14;
28709  a |= *p;
28710  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
28711  if (!(a&0x80))
28712  {
28713    /* Values  between 268435456 and 34359738367 */
28714    a &= SLOT_4_2_0;
28715    b &= SLOT_4_2_0;
28716    b = b<<7;
28717    *v = a | b;
28718    return 5;
28719  }
28720
28721  /* We can only reach this point when reading a corrupt database
28722  ** file.  In that case we are not in any hurry.  Use the (relatively
28723  ** slow) general-purpose sqlite3GetVarint() routine to extract the
28724  ** value. */
28725  {
28726    u64 v64;
28727    u8 n;
28728
28729    p -= 4;
28730    n = sqlite3GetVarint(p, &v64);
28731    assert( n>5 && n<=9 );
28732    *v = (u32)v64;
28733    return n;
28734  }
28735#endif
28736}
28737
28738/*
28739** Return the number of bytes that will be needed to store the given
28740** 64-bit integer.
28741*/
28742SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
28743  int i;
28744  for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
28745  return i;
28746}
28747
28748
28749/*
28750** Read or write a four-byte big-endian integer value.
28751*/
28752SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
28753#if SQLITE_BYTEORDER==4321
28754  u32 x;
28755  memcpy(&x,p,4);
28756  return x;
28757#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
28758  u32 x;
28759  memcpy(&x,p,4);
28760  return __builtin_bswap32(x);
28761#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
28762  u32 x;
28763  memcpy(&x,p,4);
28764  return _byteswap_ulong(x);
28765#else
28766  testcase( p[0]&0x80 );
28767  return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
28768#endif
28769}
28770SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
28771#if SQLITE_BYTEORDER==4321
28772  memcpy(p,&v,4);
28773#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
28774  u32 x = __builtin_bswap32(v);
28775  memcpy(p,&x,4);
28776#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
28777  u32 x = _byteswap_ulong(v);
28778  memcpy(p,&x,4);
28779#else
28780  p[0] = (u8)(v>>24);
28781  p[1] = (u8)(v>>16);
28782  p[2] = (u8)(v>>8);
28783  p[3] = (u8)v;
28784#endif
28785}
28786
28787
28788
28789/*
28790** Translate a single byte of Hex into an integer.
28791** This routine only works if h really is a valid hexadecimal
28792** character:  0..9a..fA..F
28793*/
28794SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
28795  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
28796#ifdef SQLITE_ASCII
28797  h += 9*(1&(h>>6));
28798#endif
28799#ifdef SQLITE_EBCDIC
28800  h += 9*(1&~(h>>4));
28801#endif
28802  return (u8)(h & 0xf);
28803}
28804
28805#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
28806/*
28807** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
28808** value.  Return a pointer to its binary value.  Space to hold the
28809** binary value has been obtained from malloc and must be freed by
28810** the calling routine.
28811*/
28812SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
28813  char *zBlob;
28814  int i;
28815
28816  zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
28817  n--;
28818  if( zBlob ){
28819    for(i=0; i<n; i+=2){
28820      zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
28821    }
28822    zBlob[i/2] = 0;
28823  }
28824  return zBlob;
28825}
28826#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
28827
28828/*
28829** Log an error that is an API call on a connection pointer that should
28830** not have been used.  The "type" of connection pointer is given as the
28831** argument.  The zType is a word like "NULL" or "closed" or "invalid".
28832*/
28833static void logBadConnection(const char *zType){
28834  sqlite3_log(SQLITE_MISUSE,
28835     "API call with %s database connection pointer",
28836     zType
28837  );
28838}
28839
28840/*
28841** Check to make sure we have a valid db pointer.  This test is not
28842** foolproof but it does provide some measure of protection against
28843** misuse of the interface such as passing in db pointers that are
28844** NULL or which have been previously closed.  If this routine returns
28845** 1 it means that the db pointer is valid and 0 if it should not be
28846** dereferenced for any reason.  The calling function should invoke
28847** SQLITE_MISUSE immediately.
28848**
28849** sqlite3SafetyCheckOk() requires that the db pointer be valid for
28850** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
28851** open properly and is not fit for general use but which can be
28852** used as an argument to sqlite3_errmsg() or sqlite3_close().
28853*/
28854SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
28855  u32 magic;
28856  if( db==0 ){
28857    logBadConnection("NULL");
28858    return 0;
28859  }
28860  magic = db->magic;
28861  if( magic!=SQLITE_MAGIC_OPEN ){
28862    if( sqlite3SafetyCheckSickOrOk(db) ){
28863      testcase( sqlite3GlobalConfig.xLog!=0 );
28864      logBadConnection("unopened");
28865    }
28866    return 0;
28867  }else{
28868    return 1;
28869  }
28870}
28871SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
28872  u32 magic;
28873  magic = db->magic;
28874  if( magic!=SQLITE_MAGIC_SICK &&
28875      magic!=SQLITE_MAGIC_OPEN &&
28876      magic!=SQLITE_MAGIC_BUSY ){
28877    testcase( sqlite3GlobalConfig.xLog!=0 );
28878    logBadConnection("invalid");
28879    return 0;
28880  }else{
28881    return 1;
28882  }
28883}
28884
28885/*
28886** Attempt to add, substract, or multiply the 64-bit signed value iB against
28887** the other 64-bit signed integer at *pA and store the result in *pA.
28888** Return 0 on success.  Or if the operation would have resulted in an
28889** overflow, leave *pA unchanged and return 1.
28890*/
28891SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
28892#if GCC_VERSION>=5004000
28893  return __builtin_add_overflow(*pA, iB, pA);
28894#else
28895  i64 iA = *pA;
28896  testcase( iA==0 ); testcase( iA==1 );
28897  testcase( iB==-1 ); testcase( iB==0 );
28898  if( iB>=0 ){
28899    testcase( iA>0 && LARGEST_INT64 - iA == iB );
28900    testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
28901    if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
28902  }else{
28903    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
28904    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
28905    if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
28906  }
28907  *pA += iB;
28908  return 0;
28909#endif
28910}
28911SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
28912#if GCC_VERSION>=5004000
28913  return __builtin_sub_overflow(*pA, iB, pA);
28914#else
28915  testcase( iB==SMALLEST_INT64+1 );
28916  if( iB==SMALLEST_INT64 ){
28917    testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
28918    if( (*pA)>=0 ) return 1;
28919    *pA -= iB;
28920    return 0;
28921  }else{
28922    return sqlite3AddInt64(pA, -iB);
28923  }
28924#endif
28925}
28926SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
28927#if GCC_VERSION>=5004000
28928  return __builtin_mul_overflow(*pA, iB, pA);
28929#else
28930  i64 iA = *pA;
28931  if( iB>0 ){
28932    if( iA>LARGEST_INT64/iB ) return 1;
28933    if( iA<SMALLEST_INT64/iB ) return 1;
28934  }else if( iB<0 ){
28935    if( iA>0 ){
28936      if( iB<SMALLEST_INT64/iA ) return 1;
28937    }else if( iA<0 ){
28938      if( iB==SMALLEST_INT64 ) return 1;
28939      if( iA==SMALLEST_INT64 ) return 1;
28940      if( -iA>LARGEST_INT64/-iB ) return 1;
28941    }
28942  }
28943  *pA = iA*iB;
28944  return 0;
28945#endif
28946}
28947
28948/*
28949** Compute the absolute value of a 32-bit signed integer, of possible.  Or
28950** if the integer has a value of -2147483648, return +2147483647
28951*/
28952SQLITE_PRIVATE int sqlite3AbsInt32(int x){
28953  if( x>=0 ) return x;
28954  if( x==(int)0x80000000 ) return 0x7fffffff;
28955  return -x;
28956}
28957
28958#ifdef SQLITE_ENABLE_8_3_NAMES
28959/*
28960** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
28961** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
28962** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
28963** three characters, then shorten the suffix on z[] to be the last three
28964** characters of the original suffix.
28965**
28966** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
28967** do the suffix shortening regardless of URI parameter.
28968**
28969** Examples:
28970**
28971**     test.db-journal    =>   test.nal
28972**     test.db-wal        =>   test.wal
28973**     test.db-shm        =>   test.shm
28974**     test.db-mj7f3319fa =>   test.9fa
28975*/
28976SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
28977#if SQLITE_ENABLE_8_3_NAMES<2
28978  if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
28979#endif
28980  {
28981    int i, sz;
28982    sz = sqlite3Strlen30(z);
28983    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
28984    if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
28985  }
28986}
28987#endif
28988
28989/*
28990** Find (an approximate) sum of two LogEst values.  This computation is
28991** not a simple "+" operator because LogEst is stored as a logarithmic
28992** value.
28993**
28994*/
28995SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
28996  static const unsigned char x[] = {
28997     10, 10,                         /* 0,1 */
28998      9, 9,                          /* 2,3 */
28999      8, 8,                          /* 4,5 */
29000      7, 7, 7,                       /* 6,7,8 */
29001      6, 6, 6,                       /* 9,10,11 */
29002      5, 5, 5,                       /* 12-14 */
29003      4, 4, 4, 4,                    /* 15-18 */
29004      3, 3, 3, 3, 3, 3,              /* 19-24 */
29005      2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
29006  };
29007  if( a>=b ){
29008    if( a>b+49 ) return a;
29009    if( a>b+31 ) return a+1;
29010    return a+x[a-b];
29011  }else{
29012    if( b>a+49 ) return b;
29013    if( b>a+31 ) return b+1;
29014    return b+x[b-a];
29015  }
29016}
29017
29018/*
29019** Convert an integer into a LogEst.  In other words, compute an
29020** approximation for 10*log2(x).
29021*/
29022SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
29023  static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
29024  LogEst y = 40;
29025  if( x<8 ){
29026    if( x<2 ) return 0;
29027    while( x<8 ){  y -= 10; x <<= 1; }
29028  }else{
29029    while( x>255 ){ y += 40; x >>= 4; }  /*OPTIMIZATION-IF-TRUE*/
29030    while( x>15 ){  y += 10; x >>= 1; }
29031  }
29032  return a[x&7] + y - 10;
29033}
29034
29035#ifndef SQLITE_OMIT_VIRTUALTABLE
29036/*
29037** Convert a double into a LogEst
29038** In other words, compute an approximation for 10*log2(x).
29039*/
29040SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
29041  u64 a;
29042  LogEst e;
29043  assert( sizeof(x)==8 && sizeof(a)==8 );
29044  if( x<=1 ) return 0;
29045  if( x<=2000000000 ) return sqlite3LogEst((u64)x);
29046  memcpy(&a, &x, 8);
29047  e = (a>>52) - 1022;
29048  return e*10;
29049}
29050#endif /* SQLITE_OMIT_VIRTUALTABLE */
29051
29052#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
29053    defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
29054    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
29055/*
29056** Convert a LogEst into an integer.
29057**
29058** Note that this routine is only used when one or more of various
29059** non-standard compile-time options is enabled.
29060*/
29061SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
29062  u64 n;
29063  n = x%10;
29064  x /= 10;
29065  if( n>=5 ) n -= 2;
29066  else if( n>=1 ) n -= 1;
29067#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
29068    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
29069  if( x>60 ) return (u64)LARGEST_INT64;
29070#else
29071  /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
29072  ** possible to this routine is 310, resulting in a maximum x of 31 */
29073  assert( x<=60 );
29074#endif
29075  return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
29076}
29077#endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
29078
29079/*
29080** Add a new name/number pair to a VList.  This might require that the
29081** VList object be reallocated, so return the new VList.  If an OOM
29082** error occurs, the original VList returned and the
29083** db->mallocFailed flag is set.
29084**
29085** A VList is really just an array of integers.  To destroy a VList,
29086** simply pass it to sqlite3DbFree().
29087**
29088** The first integer is the number of integers allocated for the whole
29089** VList.  The second integer is the number of integers actually used.
29090** Each name/number pair is encoded by subsequent groups of 3 or more
29091** integers.
29092**
29093** Each name/number pair starts with two integers which are the numeric
29094** value for the pair and the size of the name/number pair, respectively.
29095** The text name overlays one or more following integers.  The text name
29096** is always zero-terminated.
29097**
29098** Conceptually:
29099**
29100**    struct VList {
29101**      int nAlloc;   // Number of allocated slots
29102**      int nUsed;    // Number of used slots
29103**      struct VListEntry {
29104**        int iValue;    // Value for this entry
29105**        int nSlot;     // Slots used by this entry
29106**        // ... variable name goes here
29107**      } a[0];
29108**    }
29109**
29110** During code generation, pointers to the variable names within the
29111** VList are taken.  When that happens, nAlloc is set to zero as an
29112** indication that the VList may never again be enlarged, since the
29113** accompanying realloc() would invalidate the pointers.
29114*/
29115SQLITE_PRIVATE VList *sqlite3VListAdd(
29116  sqlite3 *db,           /* The database connection used for malloc() */
29117  VList *pIn,            /* The input VList.  Might be NULL */
29118  const char *zName,     /* Name of symbol to add */
29119  int nName,             /* Bytes of text in zName */
29120  int iVal               /* Value to associate with zName */
29121){
29122  int nInt;              /* number of sizeof(int) objects needed for zName */
29123  char *z;               /* Pointer to where zName will be stored */
29124  int i;                 /* Index in pIn[] where zName is stored */
29125
29126  nInt = nName/4 + 3;
29127  assert( pIn==0 || pIn[0]>=3 );  /* Verify ok to add new elements */
29128  if( pIn==0 || pIn[1]+nInt > pIn[0] ){
29129    /* Enlarge the allocation */
29130    int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt;
29131    VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
29132    if( pOut==0 ) return pIn;
29133    if( pIn==0 ) pOut[1] = 2;
29134    pIn = pOut;
29135    pIn[0] = nAlloc;
29136  }
29137  i = pIn[1];
29138  pIn[i] = iVal;
29139  pIn[i+1] = nInt;
29140  z = (char*)&pIn[i+2];
29141  pIn[1] = i+nInt;
29142  assert( pIn[1]<=pIn[0] );
29143  memcpy(z, zName, nName);
29144  z[nName] = 0;
29145  return pIn;
29146}
29147
29148/*
29149** Return a pointer to the name of a variable in the given VList that
29150** has the value iVal.  Or return a NULL if there is no such variable in
29151** the list
29152*/
29153SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
29154  int i, mx;
29155  if( pIn==0 ) return 0;
29156  mx = pIn[1];
29157  i = 2;
29158  do{
29159    if( pIn[i]==iVal ) return (char*)&pIn[i+2];
29160    i += pIn[i+1];
29161  }while( i<mx );
29162  return 0;
29163}
29164
29165/*
29166** Return the number of the variable named zName, if it is in VList.
29167** or return 0 if there is no such variable.
29168*/
29169SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
29170  int i, mx;
29171  if( pIn==0 ) return 0;
29172  mx = pIn[1];
29173  i = 2;
29174  do{
29175    const char *z = (const char*)&pIn[i+2];
29176    if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
29177    i += pIn[i+1];
29178  }while( i<mx );
29179  return 0;
29180}
29181
29182/************** End of util.c ************************************************/
29183/************** Begin file hash.c ********************************************/
29184/*
29185** 2001 September 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** This is the implementation of generic hash-tables
29196** used in SQLite.
29197*/
29198/* #include "sqliteInt.h" */
29199/* #include <assert.h> */
29200
29201/* Turn bulk memory into a hash table object by initializing the
29202** fields of the Hash structure.
29203**
29204** "pNew" is a pointer to the hash table that is to be initialized.
29205*/
29206SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
29207  assert( pNew!=0 );
29208  pNew->first = 0;
29209  pNew->count = 0;
29210  pNew->htsize = 0;
29211  pNew->ht = 0;
29212}
29213
29214/* Remove all entries from a hash table.  Reclaim all memory.
29215** Call this routine to delete a hash table or to reset a hash table
29216** to the empty state.
29217*/
29218SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
29219  HashElem *elem;         /* For looping over all elements of the table */
29220
29221  assert( pH!=0 );
29222  elem = pH->first;
29223  pH->first = 0;
29224  sqlite3_free(pH->ht);
29225  pH->ht = 0;
29226  pH->htsize = 0;
29227  while( elem ){
29228    HashElem *next_elem = elem->next;
29229    sqlite3_free(elem);
29230    elem = next_elem;
29231  }
29232  pH->count = 0;
29233}
29234
29235/*
29236** The hashing function.
29237*/
29238static unsigned int strHash(const char *z){
29239  unsigned int h = 0;
29240  unsigned char c;
29241  while( (c = (unsigned char)*z++)!=0 ){     /*OPTIMIZATION-IF-TRUE*/
29242    /* Knuth multiplicative hashing.  (Sorting & Searching, p. 510).
29243    ** 0x9e3779b1 is 2654435761 which is the closest prime number to
29244    ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
29245    h += sqlite3UpperToLower[c];
29246    h *= 0x9e3779b1;
29247  }
29248  return h;
29249}
29250
29251
29252/* Link pNew element into the hash table pH.  If pEntry!=0 then also
29253** insert pNew into the pEntry hash bucket.
29254*/
29255static void insertElement(
29256  Hash *pH,              /* The complete hash table */
29257  struct _ht *pEntry,    /* The entry into which pNew is inserted */
29258  HashElem *pNew         /* The element to be inserted */
29259){
29260  HashElem *pHead;       /* First element already in pEntry */
29261  if( pEntry ){
29262    pHead = pEntry->count ? pEntry->chain : 0;
29263    pEntry->count++;
29264    pEntry->chain = pNew;
29265  }else{
29266    pHead = 0;
29267  }
29268  if( pHead ){
29269    pNew->next = pHead;
29270    pNew->prev = pHead->prev;
29271    if( pHead->prev ){ pHead->prev->next = pNew; }
29272    else             { pH->first = pNew; }
29273    pHead->prev = pNew;
29274  }else{
29275    pNew->next = pH->first;
29276    if( pH->first ){ pH->first->prev = pNew; }
29277    pNew->prev = 0;
29278    pH->first = pNew;
29279  }
29280}
29281
29282
29283/* Resize the hash table so that it cantains "new_size" buckets.
29284**
29285** The hash table might fail to resize if sqlite3_malloc() fails or
29286** if the new size is the same as the prior size.
29287** Return TRUE if the resize occurs and false if not.
29288*/
29289static int rehash(Hash *pH, unsigned int new_size){
29290  struct _ht *new_ht;            /* The new hash table */
29291  HashElem *elem, *next_elem;    /* For looping over existing elements */
29292
29293#if SQLITE_MALLOC_SOFT_LIMIT>0
29294  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
29295    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
29296  }
29297  if( new_size==pH->htsize ) return 0;
29298#endif
29299
29300  /* The inability to allocates space for a larger hash table is
29301  ** a performance hit but it is not a fatal error.  So mark the
29302  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
29303  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
29304  ** only zeroes the requested number of bytes whereas this module will
29305  ** use the actual amount of space allocated for the hash table (which
29306  ** may be larger than the requested amount).
29307  */
29308  sqlite3BeginBenignMalloc();
29309  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
29310  sqlite3EndBenignMalloc();
29311
29312  if( new_ht==0 ) return 0;
29313  sqlite3_free(pH->ht);
29314  pH->ht = new_ht;
29315  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
29316  memset(new_ht, 0, new_size*sizeof(struct _ht));
29317  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
29318    unsigned int h = strHash(elem->pKey) % new_size;
29319    next_elem = elem->next;
29320    insertElement(pH, &new_ht[h], elem);
29321  }
29322  return 1;
29323}
29324
29325/* This function (for internal use only) locates an element in an
29326** hash table that matches the given key.  The hash for this key is
29327** also computed and returned in the *pH parameter.
29328*/
29329static HashElem *findElementWithHash(
29330  const Hash *pH,     /* The pH to be searched */
29331  const char *pKey,   /* The key we are searching for */
29332  unsigned int *pHash /* Write the hash value here */
29333){
29334  HashElem *elem;                /* Used to loop thru the element list */
29335  int count;                     /* Number of elements left to test */
29336  unsigned int h;                /* The computed hash */
29337
29338  if( pH->ht ){   /*OPTIMIZATION-IF-TRUE*/
29339    struct _ht *pEntry;
29340    h = strHash(pKey) % pH->htsize;
29341    pEntry = &pH->ht[h];
29342    elem = pEntry->chain;
29343    count = pEntry->count;
29344  }else{
29345    h = 0;
29346    elem = pH->first;
29347    count = pH->count;
29348  }
29349  *pHash = h;
29350  while( count-- ){
29351    assert( elem!=0 );
29352    if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
29353      return elem;
29354    }
29355    elem = elem->next;
29356  }
29357  return 0;
29358}
29359
29360/* Remove a single entry from the hash table given a pointer to that
29361** element and a hash on the element's key.
29362*/
29363static void removeElementGivenHash(
29364  Hash *pH,         /* The pH containing "elem" */
29365  HashElem* elem,   /* The element to be removed from the pH */
29366  unsigned int h    /* Hash value for the element */
29367){
29368  struct _ht *pEntry;
29369  if( elem->prev ){
29370    elem->prev->next = elem->next;
29371  }else{
29372    pH->first = elem->next;
29373  }
29374  if( elem->next ){
29375    elem->next->prev = elem->prev;
29376  }
29377  if( pH->ht ){
29378    pEntry = &pH->ht[h];
29379    if( pEntry->chain==elem ){
29380      pEntry->chain = elem->next;
29381    }
29382    pEntry->count--;
29383    assert( pEntry->count>=0 );
29384  }
29385  sqlite3_free( elem );
29386  pH->count--;
29387  if( pH->count==0 ){
29388    assert( pH->first==0 );
29389    assert( pH->count==0 );
29390    sqlite3HashClear(pH);
29391  }
29392}
29393
29394/* Attempt to locate an element of the hash table pH with a key
29395** that matches pKey.  Return the data for this element if it is
29396** found, or NULL if there is no match.
29397*/
29398SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
29399  HashElem *elem;    /* The element that matches key */
29400  unsigned int h;    /* A hash on key */
29401
29402  assert( pH!=0 );
29403  assert( pKey!=0 );
29404  elem = findElementWithHash(pH, pKey, &h);
29405  return elem ? elem->data : 0;
29406}
29407
29408/* Insert an element into the hash table pH.  The key is pKey
29409** and the data is "data".
29410**
29411** If no element exists with a matching key, then a new
29412** element is created and NULL is returned.
29413**
29414** If another element already exists with the same key, then the
29415** new data replaces the old data and the old data is returned.
29416** The key is not copied in this instance.  If a malloc fails, then
29417** the new data is returned and the hash table is unchanged.
29418**
29419** If the "data" parameter to this function is NULL, then the
29420** element corresponding to "key" is removed from the hash table.
29421*/
29422SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
29423  unsigned int h;       /* the hash of the key modulo hash table size */
29424  HashElem *elem;       /* Used to loop thru the element list */
29425  HashElem *new_elem;   /* New element added to the pH */
29426
29427  assert( pH!=0 );
29428  assert( pKey!=0 );
29429  elem = findElementWithHash(pH,pKey,&h);
29430  if( elem ){
29431    void *old_data = elem->data;
29432    if( data==0 ){
29433      removeElementGivenHash(pH,elem,h);
29434    }else{
29435      elem->data = data;
29436      elem->pKey = pKey;
29437    }
29438    return old_data;
29439  }
29440  if( data==0 ) return 0;
29441  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
29442  if( new_elem==0 ) return data;
29443  new_elem->pKey = pKey;
29444  new_elem->data = data;
29445  pH->count++;
29446  if( pH->count>=10 && pH->count > 2*pH->htsize ){
29447    if( rehash(pH, pH->count*2) ){
29448      assert( pH->htsize>0 );
29449      h = strHash(pKey) % pH->htsize;
29450    }
29451  }
29452  insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
29453  return 0;
29454}
29455
29456/************** End of hash.c ************************************************/
29457/************** Begin file opcodes.c *****************************************/
29458/* Automatically generated.  Do not edit */
29459/* See the tool/mkopcodec.tcl script for details. */
29460#if !defined(SQLITE_OMIT_EXPLAIN) \
29461 || defined(VDBE_PROFILE) \
29462 || defined(SQLITE_DEBUG)
29463#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
29464# define OpHelp(X) "\0" X
29465#else
29466# define OpHelp(X)
29467#endif
29468SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
29469 static const char *const azName[] = {
29470    /*   0 */ "Savepoint"        OpHelp(""),
29471    /*   1 */ "AutoCommit"       OpHelp(""),
29472    /*   2 */ "Transaction"      OpHelp(""),
29473    /*   3 */ "SorterNext"       OpHelp(""),
29474    /*   4 */ "PrevIfOpen"       OpHelp(""),
29475    /*   5 */ "NextIfOpen"       OpHelp(""),
29476    /*   6 */ "Prev"             OpHelp(""),
29477    /*   7 */ "Next"             OpHelp(""),
29478    /*   8 */ "Checkpoint"       OpHelp(""),
29479    /*   9 */ "JournalMode"      OpHelp(""),
29480    /*  10 */ "Vacuum"           OpHelp(""),
29481    /*  11 */ "VFilter"          OpHelp("iplan=r[P3] zplan='P4'"),
29482    /*  12 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
29483    /*  13 */ "Goto"             OpHelp(""),
29484    /*  14 */ "Gosub"            OpHelp(""),
29485    /*  15 */ "InitCoroutine"    OpHelp(""),
29486    /*  16 */ "Yield"            OpHelp(""),
29487    /*  17 */ "MustBeInt"        OpHelp(""),
29488    /*  18 */ "Jump"             OpHelp(""),
29489    /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
29490    /*  20 */ "Once"             OpHelp(""),
29491    /*  21 */ "If"               OpHelp(""),
29492    /*  22 */ "IfNot"            OpHelp(""),
29493    /*  23 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
29494    /*  24 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
29495    /*  25 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
29496    /*  26 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
29497    /*  27 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
29498    /*  28 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
29499    /*  29 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
29500    /*  30 */ "NotFound"         OpHelp("key=r[P3@P4]"),
29501    /*  31 */ "Found"            OpHelp("key=r[P3@P4]"),
29502    /*  32 */ "SeekRowid"        OpHelp("intkey=r[P3]"),
29503    /*  33 */ "NotExists"        OpHelp("intkey=r[P3]"),
29504    /*  34 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
29505    /*  35 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
29506    /*  36 */ "Ne"               OpHelp("IF r[P3]!=r[P1]"),
29507    /*  37 */ "Eq"               OpHelp("IF r[P3]==r[P1]"),
29508    /*  38 */ "Gt"               OpHelp("IF r[P3]>r[P1]"),
29509    /*  39 */ "Le"               OpHelp("IF r[P3]<=r[P1]"),
29510    /*  40 */ "Lt"               OpHelp("IF r[P3]<r[P1]"),
29511    /*  41 */ "Ge"               OpHelp("IF r[P3]>=r[P1]"),
29512    /*  42 */ "ElseNotEq"        OpHelp(""),
29513    /*  43 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
29514    /*  44 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
29515    /*  45 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
29516    /*  46 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
29517    /*  47 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
29518    /*  48 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
29519    /*  49 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
29520    /*  50 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
29521    /*  51 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
29522    /*  52 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
29523    /*  53 */ "Last"             OpHelp(""),
29524    /*  54 */ "BitNot"           OpHelp("r[P1]= ~r[P1]"),
29525    /*  55 */ "IfSmaller"        OpHelp(""),
29526    /*  56 */ "SorterSort"       OpHelp(""),
29527    /*  57 */ "Sort"             OpHelp(""),
29528    /*  58 */ "Rewind"           OpHelp(""),
29529    /*  59 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
29530    /*  60 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
29531    /*  61 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
29532    /*  62 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
29533    /*  63 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
29534    /*  64 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
29535    /*  65 */ "Program"          OpHelp(""),
29536    /*  66 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
29537    /*  67 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
29538    /*  68 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
29539    /*  69 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
29540    /*  70 */ "IncrVacuum"       OpHelp(""),
29541    /*  71 */ "VNext"            OpHelp(""),
29542    /*  72 */ "Init"             OpHelp("Start at P2"),
29543    /*  73 */ "Return"           OpHelp(""),
29544    /*  74 */ "EndCoroutine"     OpHelp(""),
29545    /*  75 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
29546    /*  76 */ "Halt"             OpHelp(""),
29547    /*  77 */ "Integer"          OpHelp("r[P2]=P1"),
29548    /*  78 */ "Int64"            OpHelp("r[P2]=P4"),
29549    /*  79 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
29550    /*  80 */ "Null"             OpHelp("r[P2..P3]=NULL"),
29551    /*  81 */ "SoftNull"         OpHelp("r[P1]=NULL"),
29552    /*  82 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
29553    /*  83 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
29554    /*  84 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
29555    /*  85 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
29556    /*  86 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
29557    /*  87 */ "IntCopy"          OpHelp("r[P2]=r[P1]"),
29558    /*  88 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
29559    /*  89 */ "CollSeq"          OpHelp(""),
29560    /*  90 */ "Function0"        OpHelp("r[P3]=func(r[P2@P5])"),
29561    /*  91 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
29562    /*  92 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
29563    /*  93 */ "RealAffinity"     OpHelp(""),
29564    /*  94 */ "Cast"             OpHelp("affinity(r[P1])"),
29565    /*  95 */ "Permutation"      OpHelp(""),
29566    /*  96 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
29567    /*  97 */ "String8"          OpHelp("r[P2]='P4'"),
29568    /*  98 */ "Column"           OpHelp("r[P3]=PX"),
29569    /*  99 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
29570    /* 100 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
29571    /* 101 */ "Count"            OpHelp("r[P2]=count()"),
29572    /* 102 */ "ReadCookie"       OpHelp(""),
29573    /* 103 */ "SetCookie"        OpHelp(""),
29574    /* 104 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
29575    /* 105 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
29576    /* 106 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
29577    /* 107 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
29578    /* 108 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
29579    /* 109 */ "SorterOpen"       OpHelp(""),
29580    /* 110 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
29581    /* 111 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
29582    /* 112 */ "Close"            OpHelp(""),
29583    /* 113 */ "ColumnsUsed"      OpHelp(""),
29584    /* 114 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
29585    /* 115 */ "NewRowid"         OpHelp("r[P2]=rowid"),
29586    /* 116 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
29587    /* 117 */ "InsertInt"        OpHelp("intkey=P3 data=r[P2]"),
29588    /* 118 */ "Delete"           OpHelp(""),
29589    /* 119 */ "ResetCount"       OpHelp(""),
29590    /* 120 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
29591    /* 121 */ "SorterData"       OpHelp("r[P2]=data"),
29592    /* 122 */ "RowData"          OpHelp("r[P2]=data"),
29593    /* 123 */ "Rowid"            OpHelp("r[P2]=rowid"),
29594    /* 124 */ "NullRow"          OpHelp(""),
29595    /* 125 */ "SorterInsert"     OpHelp("key=r[P2]"),
29596    /* 126 */ "IdxInsert"        OpHelp("key=r[P2]"),
29597    /* 127 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
29598    /* 128 */ "Seek"             OpHelp("Move P3 to P1.rowid"),
29599    /* 129 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
29600    /* 130 */ "Destroy"          OpHelp(""),
29601    /* 131 */ "Clear"            OpHelp(""),
29602    /* 132 */ "Real"             OpHelp("r[P2]=P4"),
29603    /* 133 */ "ResetSorter"      OpHelp(""),
29604    /* 134 */ "CreateIndex"      OpHelp("r[P2]=root iDb=P1"),
29605    /* 135 */ "CreateTable"      OpHelp("r[P2]=root iDb=P1"),
29606    /* 136 */ "SqlExec"          OpHelp(""),
29607    /* 137 */ "ParseSchema"      OpHelp(""),
29608    /* 138 */ "LoadAnalysis"     OpHelp(""),
29609    /* 139 */ "DropTable"        OpHelp(""),
29610    /* 140 */ "DropIndex"        OpHelp(""),
29611    /* 141 */ "DropTrigger"      OpHelp(""),
29612    /* 142 */ "IntegrityCk"      OpHelp(""),
29613    /* 143 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
29614    /* 144 */ "Param"            OpHelp(""),
29615    /* 145 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
29616    /* 146 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
29617    /* 147 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
29618    /* 148 */ "AggStep0"         OpHelp("accum=r[P3] step(r[P2@P5])"),
29619    /* 149 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
29620    /* 150 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
29621    /* 151 */ "Expire"           OpHelp(""),
29622    /* 152 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
29623    /* 153 */ "VBegin"           OpHelp(""),
29624    /* 154 */ "VCreate"          OpHelp(""),
29625    /* 155 */ "VDestroy"         OpHelp(""),
29626    /* 156 */ "VOpen"            OpHelp(""),
29627    /* 157 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
29628    /* 158 */ "VRename"          OpHelp(""),
29629    /* 159 */ "Pagecount"        OpHelp(""),
29630    /* 160 */ "MaxPgcnt"         OpHelp(""),
29631    /* 161 */ "CursorHint"       OpHelp(""),
29632    /* 162 */ "Noop"             OpHelp(""),
29633    /* 163 */ "Explain"          OpHelp(""),
29634  };
29635  return azName[i];
29636}
29637#endif
29638
29639/************** End of opcodes.c *********************************************/
29640/************** Begin file os_unix.c *****************************************/
29641/*
29642** 2004 May 22
29643**
29644** The author disclaims copyright to this source code.  In place of
29645** a legal notice, here is a blessing:
29646**
29647**    May you do good and not evil.
29648**    May you find forgiveness for yourself and forgive others.
29649**    May you share freely, never taking more than you give.
29650**
29651******************************************************************************
29652**
29653** This file contains the VFS implementation for unix-like operating systems
29654** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
29655**
29656** There are actually several different VFS implementations in this file.
29657** The differences are in the way that file locking is done.  The default
29658** implementation uses Posix Advisory Locks.  Alternative implementations
29659** use flock(), dot-files, various proprietary locking schemas, or simply
29660** skip locking all together.
29661**
29662** This source file is organized into divisions where the logic for various
29663** subfunctions is contained within the appropriate division.  PLEASE
29664** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
29665** in the correct division and should be clearly labeled.
29666**
29667** The layout of divisions is as follows:
29668**
29669**   *  General-purpose declarations and utility functions.
29670**   *  Unique file ID logic used by VxWorks.
29671**   *  Various locking primitive implementations (all except proxy locking):
29672**      + for Posix Advisory Locks
29673**      + for no-op locks
29674**      + for dot-file locks
29675**      + for flock() locking
29676**      + for named semaphore locks (VxWorks only)
29677**      + for AFP filesystem locks (MacOSX only)
29678**   *  sqlite3_file methods not associated with locking.
29679**   *  Definitions of sqlite3_io_methods objects for all locking
29680**      methods plus "finder" functions for each locking method.
29681**   *  sqlite3_vfs method implementations.
29682**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
29683**   *  Definitions of sqlite3_vfs objects for all locking methods
29684**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
29685*/
29686/* #include "sqliteInt.h" */
29687#if SQLITE_OS_UNIX              /* This file is used on unix only */
29688
29689/*
29690** There are various methods for file locking used for concurrency
29691** control:
29692**
29693**   1. POSIX locking (the default),
29694**   2. No locking,
29695**   3. Dot-file locking,
29696**   4. flock() locking,
29697**   5. AFP locking (OSX only),
29698**   6. Named POSIX semaphores (VXWorks only),
29699**   7. proxy locking. (OSX only)
29700**
29701** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
29702** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
29703** selection of the appropriate locking style based on the filesystem
29704** where the database is located.
29705*/
29706#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
29707#  if defined(__APPLE__)
29708#    define SQLITE_ENABLE_LOCKING_STYLE 1
29709#  else
29710#    define SQLITE_ENABLE_LOCKING_STYLE 0
29711#  endif
29712#endif
29713
29714/* Use pread() and pwrite() if they are available */
29715#if defined(__APPLE__)
29716# define HAVE_PREAD 1
29717# define HAVE_PWRITE 1
29718#endif
29719#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
29720# undef USE_PREAD
29721# define USE_PREAD64 1
29722#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
29723# undef USE_PREAD64
29724# define USE_PREAD 1
29725#endif
29726
29727/*
29728** standard include files.
29729*/
29730#include <sys/types.h>
29731#include <sys/stat.h>
29732#include <fcntl.h>
29733#include <unistd.h>
29734/* #include <time.h> */
29735#include <sys/time.h>
29736#include <errno.h>
29737#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29738# include <sys/mman.h>
29739#endif
29740
29741#if SQLITE_ENABLE_LOCKING_STYLE
29742# include <sys/ioctl.h>
29743# include <sys/file.h>
29744# include <sys/param.h>
29745#endif /* SQLITE_ENABLE_LOCKING_STYLE */
29746
29747#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
29748                           (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
29749#  if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
29750       && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
29751#    define HAVE_GETHOSTUUID 1
29752#  else
29753#    warning "gethostuuid() is disabled."
29754#  endif
29755#endif
29756
29757
29758#if OS_VXWORKS
29759/* # include <sys/ioctl.h> */
29760# include <semaphore.h>
29761# include <limits.h>
29762#endif /* OS_VXWORKS */
29763
29764#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29765# include <sys/mount.h>
29766#endif
29767
29768#ifdef HAVE_UTIME
29769# include <utime.h>
29770#endif
29771
29772/*
29773** Allowed values of unixFile.fsFlags
29774*/
29775#define SQLITE_FSFLAGS_IS_MSDOS     0x1
29776
29777/*
29778** If we are to be thread-safe, include the pthreads header and define
29779** the SQLITE_UNIX_THREADS macro.
29780*/
29781#if SQLITE_THREADSAFE
29782/* # include <pthread.h> */
29783# define SQLITE_UNIX_THREADS 1
29784#endif
29785
29786/*
29787** Default permissions when creating a new file
29788*/
29789#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
29790# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
29791#endif
29792
29793/*
29794** Default permissions when creating auto proxy dir
29795*/
29796#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29797# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
29798#endif
29799
29800/*
29801** Maximum supported path-length.
29802*/
29803#define MAX_PATHNAME 512
29804
29805/*
29806** Maximum supported symbolic links
29807*/
29808#define SQLITE_MAX_SYMLINKS 100
29809
29810/* Always cast the getpid() return type for compatibility with
29811** kernel modules in VxWorks. */
29812#define osGetpid(X) (pid_t)getpid()
29813
29814/*
29815** Only set the lastErrno if the error code is a real error and not
29816** a normal expected return code of SQLITE_BUSY or SQLITE_OK
29817*/
29818#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
29819
29820/* Forward references */
29821typedef struct unixShm unixShm;               /* Connection shared memory */
29822typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
29823typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
29824typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
29825
29826/*
29827** Sometimes, after a file handle is closed by SQLite, the file descriptor
29828** cannot be closed immediately. In these cases, instances of the following
29829** structure are used to store the file descriptor while waiting for an
29830** opportunity to either close or reuse it.
29831*/
29832struct UnixUnusedFd {
29833  int fd;                   /* File descriptor to close */
29834  int flags;                /* Flags this file descriptor was opened with */
29835  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
29836};
29837
29838/*
29839** The unixFile structure is subclass of sqlite3_file specific to the unix
29840** VFS implementations.
29841*/
29842typedef struct unixFile unixFile;
29843struct unixFile {
29844  sqlite3_io_methods const *pMethod;  /* Always the first entry */
29845  sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
29846  unixInodeInfo *pInode;              /* Info about locks on this inode */
29847  int h;                              /* The file descriptor */
29848  unsigned char eFileLock;            /* The type of lock held on this fd */
29849  unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
29850  int lastErrno;                      /* The unix errno from last I/O error */
29851  void *lockingContext;               /* Locking style specific state */
29852  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
29853  const char *zPath;                  /* Name of the file */
29854  unixShm *pShm;                      /* Shared memory segment information */
29855  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
29856#if SQLITE_MAX_MMAP_SIZE>0
29857  int nFetchOut;                      /* Number of outstanding xFetch refs */
29858  sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
29859  sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
29860  sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
29861  void *pMapRegion;                   /* Memory mapped region */
29862#endif
29863#ifdef __QNXNTO__
29864  int sectorSize;                     /* Device sector size */
29865  int deviceCharacteristics;          /* Precomputed device characteristics */
29866#endif
29867#if SQLITE_ENABLE_LOCKING_STYLE
29868  int openFlags;                      /* The flags specified at open() */
29869#endif
29870#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
29871  unsigned fsFlags;                   /* cached details from statfs() */
29872#endif
29873#if OS_VXWORKS
29874  struct vxworksFileId *pId;          /* Unique file ID */
29875#endif
29876#ifdef SQLITE_DEBUG
29877  /* The next group of variables are used to track whether or not the
29878  ** transaction counter in bytes 24-27 of database files are updated
29879  ** whenever any part of the database changes.  An assertion fault will
29880  ** occur if a file is updated without also updating the transaction
29881  ** counter.  This test is made to avoid new problems similar to the
29882  ** one described by ticket #3584.
29883  */
29884  unsigned char transCntrChng;   /* True if the transaction counter changed */
29885  unsigned char dbUpdate;        /* True if any part of database file changed */
29886  unsigned char inNormalWrite;   /* True if in a normal write operation */
29887
29888#endif
29889
29890#ifdef SQLITE_TEST
29891  /* In test mode, increase the size of this structure a bit so that
29892  ** it is larger than the struct CrashFile defined in test6.c.
29893  */
29894  char aPadding[32];
29895#endif
29896};
29897
29898/* This variable holds the process id (pid) from when the xRandomness()
29899** method was called.  If xOpen() is called from a different process id,
29900** indicating that a fork() has occurred, the PRNG will be reset.
29901*/
29902static pid_t randomnessPid = 0;
29903
29904/*
29905** Allowed values for the unixFile.ctrlFlags bitmask:
29906*/
29907#define UNIXFILE_EXCL        0x01     /* Connections from one process only */
29908#define UNIXFILE_RDONLY      0x02     /* Connection is read only */
29909#define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
29910#ifndef SQLITE_DISABLE_DIRSYNC
29911# define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
29912#else
29913# define UNIXFILE_DIRSYNC    0x00
29914#endif
29915#define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
29916#define UNIXFILE_DELETE      0x20     /* Delete on close */
29917#define UNIXFILE_URI         0x40     /* Filename might have query parameters */
29918#define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
29919
29920/*
29921** Include code that is common to all os_*.c files
29922*/
29923/************** Include os_common.h in the middle of os_unix.c ***************/
29924/************** Begin file os_common.h ***************************************/
29925/*
29926** 2004 May 22
29927**
29928** The author disclaims copyright to this source code.  In place of
29929** a legal notice, here is a blessing:
29930**
29931**    May you do good and not evil.
29932**    May you find forgiveness for yourself and forgive others.
29933**    May you share freely, never taking more than you give.
29934**
29935******************************************************************************
29936**
29937** This file contains macros and a little bit of code that is common to
29938** all of the platform-specific files (os_*.c) and is #included into those
29939** files.
29940**
29941** This file should be #included by the os_*.c files only.  It is not a
29942** general purpose header file.
29943*/
29944#ifndef _OS_COMMON_H_
29945#define _OS_COMMON_H_
29946
29947/*
29948** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29949** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29950** switch.  The following code should catch this problem at compile-time.
29951*/
29952#ifdef MEMORY_DEBUG
29953# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
29954#endif
29955
29956/*
29957** Macros for performance tracing.  Normally turned off.  Only works
29958** on i486 hardware.
29959*/
29960#ifdef SQLITE_PERFORMANCE_TRACE
29961
29962/*
29963** hwtime.h contains inline assembler code for implementing
29964** high-performance timing routines.
29965*/
29966/************** Include hwtime.h in the middle of os_common.h ****************/
29967/************** Begin file hwtime.h ******************************************/
29968/*
29969** 2008 May 27
29970**
29971** The author disclaims copyright to this source code.  In place of
29972** a legal notice, here is a blessing:
29973**
29974**    May you do good and not evil.
29975**    May you find forgiveness for yourself and forgive others.
29976**    May you share freely, never taking more than you give.
29977**
29978******************************************************************************
29979**
29980** This file contains inline asm code for retrieving "high-performance"
29981** counters for x86 class CPUs.
29982*/
29983#ifndef SQLITE_HWTIME_H
29984#define SQLITE_HWTIME_H
29985
29986/*
29987** The following routine only works on pentium-class (or newer) processors.
29988** It uses the RDTSC opcode to read the cycle count value out of the
29989** processor and returns that value.  This can be used for high-res
29990** profiling.
29991*/
29992#if (defined(__GNUC__) || defined(_MSC_VER)) && \
29993      (defined(i386) || defined(__i386__) || defined(_M_IX86))
29994
29995  #if defined(__GNUC__)
29996
29997  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29998     unsigned int lo, hi;
29999     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
30000     return (sqlite_uint64)hi << 32 | lo;
30001  }
30002
30003  #elif defined(_MSC_VER)
30004
30005  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
30006     __asm {
30007        rdtsc
30008        ret       ; return value at EDX:EAX
30009     }
30010  }
30011
30012  #endif
30013
30014#elif (defined(__GNUC__) && defined(__x86_64__))
30015
30016  __inline__ sqlite_uint64 sqlite3Hwtime(void){
30017      unsigned long val;
30018      __asm__ __volatile__ ("rdtsc" : "=A" (val));
30019      return val;
30020  }
30021
30022#elif (defined(__GNUC__) && defined(__ppc__))
30023
30024  __inline__ sqlite_uint64 sqlite3Hwtime(void){
30025      unsigned long long retval;
30026      unsigned long junk;
30027      __asm__ __volatile__ ("\n\
30028          1:      mftbu   %1\n\
30029                  mftb    %L0\n\
30030                  mftbu   %0\n\
30031                  cmpw    %0,%1\n\
30032                  bne     1b"
30033                  : "=r" (retval), "=r" (junk));
30034      return retval;
30035  }
30036
30037#else
30038
30039  #error Need implementation of sqlite3Hwtime() for your platform.
30040
30041  /*
30042  ** To compile without implementing sqlite3Hwtime() for your platform,
30043  ** you can remove the above #error and use the following
30044  ** stub function.  You will lose timing support for many
30045  ** of the debugging and testing utilities, but it should at
30046  ** least compile and run.
30047  */
30048SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
30049
30050#endif
30051
30052#endif /* !defined(SQLITE_HWTIME_H) */
30053
30054/************** End of hwtime.h **********************************************/
30055/************** Continuing where we left off in os_common.h ******************/
30056
30057static sqlite_uint64 g_start;
30058static sqlite_uint64 g_elapsed;
30059#define TIMER_START       g_start=sqlite3Hwtime()
30060#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
30061#define TIMER_ELAPSED     g_elapsed
30062#else
30063#define TIMER_START
30064#define TIMER_END
30065#define TIMER_ELAPSED     ((sqlite_uint64)0)
30066#endif
30067
30068/*
30069** If we compile with the SQLITE_TEST macro set, then the following block
30070** of code will give us the ability to simulate a disk I/O error.  This
30071** is used for testing the I/O recovery logic.
30072*/
30073#if defined(SQLITE_TEST)
30074SQLITE_API extern int sqlite3_io_error_hit;
30075SQLITE_API extern int sqlite3_io_error_hardhit;
30076SQLITE_API extern int sqlite3_io_error_pending;
30077SQLITE_API extern int sqlite3_io_error_persist;
30078SQLITE_API extern int sqlite3_io_error_benign;
30079SQLITE_API extern int sqlite3_diskfull_pending;
30080SQLITE_API extern int sqlite3_diskfull;
30081#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
30082#define SimulateIOError(CODE)  \
30083  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
30084       || sqlite3_io_error_pending-- == 1 )  \
30085              { local_ioerr(); CODE; }
30086static void local_ioerr(){
30087  IOTRACE(("IOERR\n"));
30088  sqlite3_io_error_hit++;
30089  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
30090}
30091#define SimulateDiskfullError(CODE) \
30092   if( sqlite3_diskfull_pending ){ \
30093     if( sqlite3_diskfull_pending == 1 ){ \
30094       local_ioerr(); \
30095       sqlite3_diskfull = 1; \
30096       sqlite3_io_error_hit = 1; \
30097       CODE; \
30098     }else{ \
30099       sqlite3_diskfull_pending--; \
30100     } \
30101   }
30102#else
30103#define SimulateIOErrorBenign(X)
30104#define SimulateIOError(A)
30105#define SimulateDiskfullError(A)
30106#endif /* defined(SQLITE_TEST) */
30107
30108/*
30109** When testing, keep a count of the number of open files.
30110*/
30111#if defined(SQLITE_TEST)
30112SQLITE_API extern int sqlite3_open_file_count;
30113#define OpenCounter(X)  sqlite3_open_file_count+=(X)
30114#else
30115#define OpenCounter(X)
30116#endif /* defined(SQLITE_TEST) */
30117
30118#endif /* !defined(_OS_COMMON_H_) */
30119
30120/************** End of os_common.h *******************************************/
30121/************** Continuing where we left off in os_unix.c ********************/
30122
30123/*
30124** Define various macros that are missing from some systems.
30125*/
30126#ifndef O_LARGEFILE
30127# define O_LARGEFILE 0
30128#endif
30129#ifdef SQLITE_DISABLE_LFS
30130# undef O_LARGEFILE
30131# define O_LARGEFILE 0
30132#endif
30133#ifndef O_NOFOLLOW
30134# define O_NOFOLLOW 0
30135#endif
30136#ifndef O_BINARY
30137# define O_BINARY 0
30138#endif
30139
30140/*
30141** The threadid macro resolves to the thread-id or to 0.  Used for
30142** testing and debugging only.
30143*/
30144#if SQLITE_THREADSAFE
30145#define threadid pthread_self()
30146#else
30147#define threadid 0
30148#endif
30149
30150/*
30151** HAVE_MREMAP defaults to true on Linux and false everywhere else.
30152*/
30153#if !defined(HAVE_MREMAP)
30154# if defined(__linux__) && defined(_GNU_SOURCE)
30155#  define HAVE_MREMAP 1
30156# else
30157#  define HAVE_MREMAP 0
30158# endif
30159#endif
30160
30161/*
30162** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
30163** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
30164*/
30165#ifdef __ANDROID__
30166# define lseek lseek64
30167#endif
30168
30169/*
30170** Different Unix systems declare open() in different ways.  Same use
30171** open(const char*,int,mode_t).  Others use open(const char*,int,...).
30172** The difference is important when using a pointer to the function.
30173**
30174** The safest way to deal with the problem is to always use this wrapper
30175** which always has the same well-defined interface.
30176*/
30177static int posixOpen(const char *zFile, int flags, int mode){
30178  return open(zFile, flags, mode);
30179}
30180
30181/* Forward reference */
30182static int openDirectory(const char*, int*);
30183static int unixGetpagesize(void);
30184
30185/*
30186** Many system calls are accessed through pointer-to-functions so that
30187** they may be overridden at runtime to facilitate fault injection during
30188** testing and sandboxing.  The following array holds the names and pointers
30189** to all overrideable system calls.
30190*/
30191static struct unix_syscall {
30192  const char *zName;            /* Name of the system call */
30193  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
30194  sqlite3_syscall_ptr pDefault; /* Default value */
30195} aSyscall[] = {
30196  { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
30197#define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
30198
30199  { "close",        (sqlite3_syscall_ptr)close,      0  },
30200#define osClose     ((int(*)(int))aSyscall[1].pCurrent)
30201
30202  { "access",       (sqlite3_syscall_ptr)access,     0  },
30203#define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
30204
30205  { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
30206#define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
30207
30208  { "stat",         (sqlite3_syscall_ptr)stat,       0  },
30209#define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
30210
30211/*
30212** The DJGPP compiler environment looks mostly like Unix, but it
30213** lacks the fcntl() system call.  So redefine fcntl() to be something
30214** that always succeeds.  This means that locking does not occur under
30215** DJGPP.  But it is DOS - what did you expect?
30216*/
30217#ifdef __DJGPP__
30218  { "fstat",        0,                 0  },
30219#define osFstat(a,b,c)    0
30220#else
30221  { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
30222#define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
30223#endif
30224
30225  { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
30226#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
30227
30228  { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
30229#define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
30230
30231  { "read",         (sqlite3_syscall_ptr)read,       0  },
30232#define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
30233
30234#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
30235  { "pread",        (sqlite3_syscall_ptr)pread,      0  },
30236#else
30237  { "pread",        (sqlite3_syscall_ptr)0,          0  },
30238#endif
30239#define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
30240
30241#if defined(USE_PREAD64)
30242  { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
30243#else
30244  { "pread64",      (sqlite3_syscall_ptr)0,          0  },
30245#endif
30246#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
30247
30248  { "write",        (sqlite3_syscall_ptr)write,      0  },
30249#define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
30250
30251#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
30252  { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
30253#else
30254  { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
30255#endif
30256#define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
30257                    aSyscall[12].pCurrent)
30258
30259#if defined(USE_PREAD64)
30260  { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
30261#else
30262  { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
30263#endif
30264#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off64_t))\
30265                    aSyscall[13].pCurrent)
30266
30267  { "fchmod",       (sqlite3_syscall_ptr)fchmod,          0  },
30268#define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
30269
30270#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
30271  { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
30272#else
30273  { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
30274#endif
30275#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
30276
30277  { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
30278#define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
30279
30280  { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
30281#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
30282
30283  { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
30284#define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
30285
30286  { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
30287#define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
30288
30289#if defined(HAVE_FCHOWN)
30290  { "fchown",       (sqlite3_syscall_ptr)fchown,          0 },
30291#else
30292  { "fchown",       (sqlite3_syscall_ptr)0,               0 },
30293#endif
30294#define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
30295
30296  { "geteuid",      (sqlite3_syscall_ptr)geteuid,         0 },
30297#define osGeteuid   ((uid_t(*)(void))aSyscall[21].pCurrent)
30298
30299#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
30300  { "mmap",         (sqlite3_syscall_ptr)mmap,            0 },
30301#else
30302  { "mmap",         (sqlite3_syscall_ptr)0,               0 },
30303#endif
30304#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
30305
30306#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
30307  { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
30308#else
30309  { "munmap",       (sqlite3_syscall_ptr)0,               0 },
30310#endif
30311#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
30312
30313#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
30314  { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
30315#else
30316  { "mremap",       (sqlite3_syscall_ptr)0,               0 },
30317#endif
30318#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
30319
30320#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
30321  { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
30322#else
30323  { "getpagesize",  (sqlite3_syscall_ptr)0,               0 },
30324#endif
30325#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
30326
30327#if defined(HAVE_READLINK)
30328  { "readlink",     (sqlite3_syscall_ptr)readlink,        0 },
30329#else
30330  { "readlink",     (sqlite3_syscall_ptr)0,               0 },
30331#endif
30332#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
30333
30334#if defined(HAVE_LSTAT)
30335  { "lstat",         (sqlite3_syscall_ptr)lstat,          0 },
30336#else
30337  { "lstat",         (sqlite3_syscall_ptr)0,              0 },
30338#endif
30339#define osLstat      ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
30340
30341}; /* End of the overrideable system calls */
30342
30343
30344/*
30345** On some systems, calls to fchown() will trigger a message in a security
30346** log if they come from non-root processes.  So avoid calling fchown() if
30347** we are not running as root.
30348*/
30349static int robustFchown(int fd, uid_t uid, gid_t gid){
30350#if defined(HAVE_FCHOWN)
30351  return osGeteuid() ? 0 : osFchown(fd,uid,gid);
30352#else
30353  return 0;
30354#endif
30355}
30356
30357/*
30358** This is the xSetSystemCall() method of sqlite3_vfs for all of the
30359** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
30360** system call pointer, or SQLITE_NOTFOUND if there is no configurable
30361** system call named zName.
30362*/
30363static int unixSetSystemCall(
30364  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
30365  const char *zName,            /* Name of system call to override */
30366  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
30367){
30368  unsigned int i;
30369  int rc = SQLITE_NOTFOUND;
30370
30371  UNUSED_PARAMETER(pNotUsed);
30372  if( zName==0 ){
30373    /* If no zName is given, restore all system calls to their default
30374    ** settings and return NULL
30375    */
30376    rc = SQLITE_OK;
30377    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
30378      if( aSyscall[i].pDefault ){
30379        aSyscall[i].pCurrent = aSyscall[i].pDefault;
30380      }
30381    }
30382  }else{
30383    /* If zName is specified, operate on only the one system call
30384    ** specified.
30385    */
30386    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
30387      if( strcmp(zName, aSyscall[i].zName)==0 ){
30388        if( aSyscall[i].pDefault==0 ){
30389          aSyscall[i].pDefault = aSyscall[i].pCurrent;
30390        }
30391        rc = SQLITE_OK;
30392        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
30393        aSyscall[i].pCurrent = pNewFunc;
30394        break;
30395      }
30396    }
30397  }
30398  return rc;
30399}
30400
30401/*
30402** Return the value of a system call.  Return NULL if zName is not a
30403** recognized system call name.  NULL is also returned if the system call
30404** is currently undefined.
30405*/
30406static sqlite3_syscall_ptr unixGetSystemCall(
30407  sqlite3_vfs *pNotUsed,
30408  const char *zName
30409){
30410  unsigned int i;
30411
30412  UNUSED_PARAMETER(pNotUsed);
30413  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
30414    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
30415  }
30416  return 0;
30417}
30418
30419/*
30420** Return the name of the first system call after zName.  If zName==NULL
30421** then return the name of the first system call.  Return NULL if zName
30422** is the last system call or if zName is not the name of a valid
30423** system call.
30424*/
30425static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
30426  int i = -1;
30427
30428  UNUSED_PARAMETER(p);
30429  if( zName ){
30430    for(i=0; i<ArraySize(aSyscall)-1; i++){
30431      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
30432    }
30433  }
30434  for(i++; i<ArraySize(aSyscall); i++){
30435    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
30436  }
30437  return 0;
30438}
30439
30440/*
30441** Do not accept any file descriptor less than this value, in order to avoid
30442** opening database file using file descriptors that are commonly used for
30443** standard input, output, and error.
30444*/
30445#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
30446# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
30447#endif
30448
30449/*
30450** Invoke open().  Do so multiple times, until it either succeeds or
30451** fails for some reason other than EINTR.
30452**
30453** If the file creation mode "m" is 0 then set it to the default for
30454** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
30455** 0644) as modified by the system umask.  If m is not 0, then
30456** make the file creation mode be exactly m ignoring the umask.
30457**
30458** The m parameter will be non-zero only when creating -wal, -journal,
30459** and -shm files.  We want those files to have *exactly* the same
30460** permissions as their original database, unadulterated by the umask.
30461** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
30462** transaction crashes and leaves behind hot journals, then any
30463** process that is able to write to the database will also be able to
30464** recover the hot journals.
30465*/
30466static int robust_open(const char *z, int f, mode_t m){
30467  int fd;
30468  mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
30469  while(1){
30470#if defined(O_CLOEXEC)
30471    fd = osOpen(z,f|O_CLOEXEC,m2);
30472#else
30473    fd = osOpen(z,f,m2);
30474#endif
30475    if( fd<0 ){
30476      if( errno==EINTR ) continue;
30477      break;
30478    }
30479    if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
30480    osClose(fd);
30481    sqlite3_log(SQLITE_WARNING,
30482                "attempt to open \"%s\" as file descriptor %d", z, fd);
30483    fd = -1;
30484    if( osOpen("/dev/null", f, m)<0 ) break;
30485  }
30486  if( fd>=0 ){
30487    if( m!=0 ){
30488      struct stat statbuf;
30489      if( osFstat(fd, &statbuf)==0
30490       && statbuf.st_size==0
30491       && (statbuf.st_mode&0777)!=m
30492      ){
30493        osFchmod(fd, m);
30494      }
30495    }
30496#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
30497    osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
30498#endif
30499  }
30500  return fd;
30501}
30502
30503/*
30504** Helper functions to obtain and relinquish the global mutex. The
30505** global mutex is used to protect the unixInodeInfo and
30506** vxworksFileId objects used by this file, all of which may be
30507** shared by multiple threads.
30508**
30509** Function unixMutexHeld() is used to assert() that the global mutex
30510** is held when required. This function is only used as part of assert()
30511** statements. e.g.
30512**
30513**   unixEnterMutex()
30514**     assert( unixMutexHeld() );
30515**   unixEnterLeave()
30516*/
30517static void unixEnterMutex(void){
30518  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30519}
30520static void unixLeaveMutex(void){
30521  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30522}
30523#ifdef SQLITE_DEBUG
30524static int unixMutexHeld(void) {
30525  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30526}
30527#endif
30528
30529
30530#ifdef SQLITE_HAVE_OS_TRACE
30531/*
30532** Helper function for printing out trace information from debugging
30533** binaries. This returns the string representation of the supplied
30534** integer lock-type.
30535*/
30536static const char *azFileLock(int eFileLock){
30537  switch( eFileLock ){
30538    case NO_LOCK: return "NONE";
30539    case SHARED_LOCK: return "SHARED";
30540    case RESERVED_LOCK: return "RESERVED";
30541    case PENDING_LOCK: return "PENDING";
30542    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
30543  }
30544  return "ERROR";
30545}
30546#endif
30547
30548#ifdef SQLITE_LOCK_TRACE
30549/*
30550** Print out information about all locking operations.
30551**
30552** This routine is used for troubleshooting locks on multithreaded
30553** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
30554** command-line option on the compiler.  This code is normally
30555** turned off.
30556*/
30557static int lockTrace(int fd, int op, struct flock *p){
30558  char *zOpName, *zType;
30559  int s;
30560  int savedErrno;
30561  if( op==F_GETLK ){
30562    zOpName = "GETLK";
30563  }else if( op==F_SETLK ){
30564    zOpName = "SETLK";
30565  }else{
30566    s = osFcntl(fd, op, p);
30567    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
30568    return s;
30569  }
30570  if( p->l_type==F_RDLCK ){
30571    zType = "RDLCK";
30572  }else if( p->l_type==F_WRLCK ){
30573    zType = "WRLCK";
30574  }else if( p->l_type==F_UNLCK ){
30575    zType = "UNLCK";
30576  }else{
30577    assert( 0 );
30578  }
30579  assert( p->l_whence==SEEK_SET );
30580  s = osFcntl(fd, op, p);
30581  savedErrno = errno;
30582  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
30583     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
30584     (int)p->l_pid, s);
30585  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
30586    struct flock l2;
30587    l2 = *p;
30588    osFcntl(fd, F_GETLK, &l2);
30589    if( l2.l_type==F_RDLCK ){
30590      zType = "RDLCK";
30591    }else if( l2.l_type==F_WRLCK ){
30592      zType = "WRLCK";
30593    }else if( l2.l_type==F_UNLCK ){
30594      zType = "UNLCK";
30595    }else{
30596      assert( 0 );
30597    }
30598    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
30599       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
30600  }
30601  errno = savedErrno;
30602  return s;
30603}
30604#undef osFcntl
30605#define osFcntl lockTrace
30606#endif /* SQLITE_LOCK_TRACE */
30607
30608/*
30609** Retry ftruncate() calls that fail due to EINTR
30610**
30611** All calls to ftruncate() within this file should be made through
30612** this wrapper.  On the Android platform, bypassing the logic below
30613** could lead to a corrupt database.
30614*/
30615static int robust_ftruncate(int h, sqlite3_int64 sz){
30616  int rc;
30617#ifdef __ANDROID__
30618  /* On Android, ftruncate() always uses 32-bit offsets, even if
30619  ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
30620  ** truncate a file to any size larger than 2GiB. Silently ignore any
30621  ** such attempts.  */
30622  if( sz>(sqlite3_int64)0x7FFFFFFF ){
30623    rc = SQLITE_OK;
30624  }else
30625#endif
30626  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
30627  return rc;
30628}
30629
30630/*
30631** This routine translates a standard POSIX errno code into something
30632** useful to the clients of the sqlite3 functions.  Specifically, it is
30633** intended to translate a variety of "try again" errors into SQLITE_BUSY
30634** and a variety of "please close the file descriptor NOW" errors into
30635** SQLITE_IOERR
30636**
30637** Errors during initialization of locks, or file system support for locks,
30638** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
30639*/
30640static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
30641  assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
30642          (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
30643          (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
30644          (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
30645  switch (posixError) {
30646  case EACCES:
30647  case EAGAIN:
30648  case ETIMEDOUT:
30649  case EBUSY:
30650  case EINTR:
30651  case ENOLCK:
30652    /* random NFS retry error, unless during file system support
30653     * introspection, in which it actually means what it says */
30654    return SQLITE_BUSY;
30655
30656  case EPERM:
30657    return SQLITE_PERM;
30658
30659  default:
30660    return sqliteIOErr;
30661  }
30662}
30663
30664
30665/******************************************************************************
30666****************** Begin Unique File ID Utility Used By VxWorks ***************
30667**
30668** On most versions of unix, we can get a unique ID for a file by concatenating
30669** the device number and the inode number.  But this does not work on VxWorks.
30670** On VxWorks, a unique file id must be based on the canonical filename.
30671**
30672** A pointer to an instance of the following structure can be used as a
30673** unique file ID in VxWorks.  Each instance of this structure contains
30674** a copy of the canonical filename.  There is also a reference count.
30675** The structure is reclaimed when the number of pointers to it drops to
30676** zero.
30677**
30678** There are never very many files open at one time and lookups are not
30679** a performance-critical path, so it is sufficient to put these
30680** structures on a linked list.
30681*/
30682struct vxworksFileId {
30683  struct vxworksFileId *pNext;  /* Next in a list of them all */
30684  int nRef;                     /* Number of references to this one */
30685  int nName;                    /* Length of the zCanonicalName[] string */
30686  char *zCanonicalName;         /* Canonical filename */
30687};
30688
30689#if OS_VXWORKS
30690/*
30691** All unique filenames are held on a linked list headed by this
30692** variable:
30693*/
30694static struct vxworksFileId *vxworksFileList = 0;
30695
30696/*
30697** Simplify a filename into its canonical form
30698** by making the following changes:
30699**
30700**  * removing any trailing and duplicate /
30701**  * convert /./ into just /
30702**  * convert /A/../ where A is any simple name into just /
30703**
30704** Changes are made in-place.  Return the new name length.
30705**
30706** The original filename is in z[0..n-1].  Return the number of
30707** characters in the simplified name.
30708*/
30709static int vxworksSimplifyName(char *z, int n){
30710  int i, j;
30711  while( n>1 && z[n-1]=='/' ){ n--; }
30712  for(i=j=0; i<n; i++){
30713    if( z[i]=='/' ){
30714      if( z[i+1]=='/' ) continue;
30715      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
30716        i += 1;
30717        continue;
30718      }
30719      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
30720        while( j>0 && z[j-1]!='/' ){ j--; }
30721        if( j>0 ){ j--; }
30722        i += 2;
30723        continue;
30724      }
30725    }
30726    z[j++] = z[i];
30727  }
30728  z[j] = 0;
30729  return j;
30730}
30731
30732/*
30733** Find a unique file ID for the given absolute pathname.  Return
30734** a pointer to the vxworksFileId object.  This pointer is the unique
30735** file ID.
30736**
30737** The nRef field of the vxworksFileId object is incremented before
30738** the object is returned.  A new vxworksFileId object is created
30739** and added to the global list if necessary.
30740**
30741** If a memory allocation error occurs, return NULL.
30742*/
30743static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
30744  struct vxworksFileId *pNew;         /* search key and new file ID */
30745  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
30746  int n;                              /* Length of zAbsoluteName string */
30747
30748  assert( zAbsoluteName[0]=='/' );
30749  n = (int)strlen(zAbsoluteName);
30750  pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
30751  if( pNew==0 ) return 0;
30752  pNew->zCanonicalName = (char*)&pNew[1];
30753  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
30754  n = vxworksSimplifyName(pNew->zCanonicalName, n);
30755
30756  /* Search for an existing entry that matching the canonical name.
30757  ** If found, increment the reference count and return a pointer to
30758  ** the existing file ID.
30759  */
30760  unixEnterMutex();
30761  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
30762    if( pCandidate->nName==n
30763     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
30764    ){
30765       sqlite3_free(pNew);
30766       pCandidate->nRef++;
30767       unixLeaveMutex();
30768       return pCandidate;
30769    }
30770  }
30771
30772  /* No match was found.  We will make a new file ID */
30773  pNew->nRef = 1;
30774  pNew->nName = n;
30775  pNew->pNext = vxworksFileList;
30776  vxworksFileList = pNew;
30777  unixLeaveMutex();
30778  return pNew;
30779}
30780
30781/*
30782** Decrement the reference count on a vxworksFileId object.  Free
30783** the object when the reference count reaches zero.
30784*/
30785static void vxworksReleaseFileId(struct vxworksFileId *pId){
30786  unixEnterMutex();
30787  assert( pId->nRef>0 );
30788  pId->nRef--;
30789  if( pId->nRef==0 ){
30790    struct vxworksFileId **pp;
30791    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
30792    assert( *pp==pId );
30793    *pp = pId->pNext;
30794    sqlite3_free(pId);
30795  }
30796  unixLeaveMutex();
30797}
30798#endif /* OS_VXWORKS */
30799/*************** End of Unique File ID Utility Used By VxWorks ****************
30800******************************************************************************/
30801
30802
30803/******************************************************************************
30804*************************** Posix Advisory Locking ****************************
30805**
30806** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
30807** section 6.5.2.2 lines 483 through 490 specify that when a process
30808** sets or clears a lock, that operation overrides any prior locks set
30809** by the same process.  It does not explicitly say so, but this implies
30810** that it overrides locks set by the same process using a different
30811** file descriptor.  Consider this test case:
30812**
30813**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
30814**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
30815**
30816** Suppose ./file1 and ./file2 are really the same file (because
30817** one is a hard or symbolic link to the other) then if you set
30818** an exclusive lock on fd1, then try to get an exclusive lock
30819** on fd2, it works.  I would have expected the second lock to
30820** fail since there was already a lock on the file due to fd1.
30821** But not so.  Since both locks came from the same process, the
30822** second overrides the first, even though they were on different
30823** file descriptors opened on different file names.
30824**
30825** This means that we cannot use POSIX locks to synchronize file access
30826** among competing threads of the same process.  POSIX locks will work fine
30827** to synchronize access for threads in separate processes, but not
30828** threads within the same process.
30829**
30830** To work around the problem, SQLite has to manage file locks internally
30831** on its own.  Whenever a new database is opened, we have to find the
30832** specific inode of the database file (the inode is determined by the
30833** st_dev and st_ino fields of the stat structure that fstat() fills in)
30834** and check for locks already existing on that inode.  When locks are
30835** created or removed, we have to look at our own internal record of the
30836** locks to see if another thread has previously set a lock on that same
30837** inode.
30838**
30839** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
30840** For VxWorks, we have to use the alternative unique ID system based on
30841** canonical filename and implemented in the previous division.)
30842**
30843** The sqlite3_file structure for POSIX is no longer just an integer file
30844** descriptor.  It is now a structure that holds the integer file
30845** descriptor and a pointer to a structure that describes the internal
30846** locks on the corresponding inode.  There is one locking structure
30847** per inode, so if the same inode is opened twice, both unixFile structures
30848** point to the same locking structure.  The locking structure keeps
30849** a reference count (so we will know when to delete it) and a "cnt"
30850** field that tells us its internal lock status.  cnt==0 means the
30851** file is unlocked.  cnt==-1 means the file has an exclusive lock.
30852** cnt>0 means there are cnt shared locks on the file.
30853**
30854** Any attempt to lock or unlock a file first checks the locking
30855** structure.  The fcntl() system call is only invoked to set a
30856** POSIX lock if the internal lock structure transitions between
30857** a locked and an unlocked state.
30858**
30859** But wait:  there are yet more problems with POSIX advisory locks.
30860**
30861** If you close a file descriptor that points to a file that has locks,
30862** all locks on that file that are owned by the current process are
30863** released.  To work around this problem, each unixInodeInfo object
30864** maintains a count of the number of pending locks on tha inode.
30865** When an attempt is made to close an unixFile, if there are
30866** other unixFile open on the same inode that are holding locks, the call
30867** to close() the file descriptor is deferred until all of the locks clear.
30868** The unixInodeInfo structure keeps a list of file descriptors that need to
30869** be closed and that list is walked (and cleared) when the last lock
30870** clears.
30871**
30872** Yet another problem:  LinuxThreads do not play well with posix locks.
30873**
30874** Many older versions of linux use the LinuxThreads library which is
30875** not posix compliant.  Under LinuxThreads, a lock created by thread
30876** A cannot be modified or overridden by a different thread B.
30877** Only thread A can modify the lock.  Locking behavior is correct
30878** if the appliation uses the newer Native Posix Thread Library (NPTL)
30879** on linux - with NPTL a lock created by thread A can override locks
30880** in thread B.  But there is no way to know at compile-time which
30881** threading library is being used.  So there is no way to know at
30882** compile-time whether or not thread A can override locks on thread B.
30883** One has to do a run-time check to discover the behavior of the
30884** current process.
30885**
30886** SQLite used to support LinuxThreads.  But support for LinuxThreads
30887** was dropped beginning with version 3.7.0.  SQLite will still work with
30888** LinuxThreads provided that (1) there is no more than one connection
30889** per database file in the same process and (2) database connections
30890** do not move across threads.
30891*/
30892
30893/*
30894** An instance of the following structure serves as the key used
30895** to locate a particular unixInodeInfo object.
30896*/
30897struct unixFileId {
30898  dev_t dev;                  /* Device number */
30899#if OS_VXWORKS
30900  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
30901#else
30902  /* We are told that some versions of Android contain a bug that
30903  ** sizes ino_t at only 32-bits instead of 64-bits. (See
30904  ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
30905  ** To work around this, always allocate 64-bits for the inode number.
30906  ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
30907  ** but that should not be a big deal. */
30908  /* WAS:  ino_t ino;   */
30909  u64 ino;                   /* Inode number */
30910#endif
30911};
30912
30913/*
30914** An instance of the following structure is allocated for each open
30915** inode.  Or, on LinuxThreads, there is one of these structures for
30916** each inode opened by each thread.
30917**
30918** A single inode can have multiple file descriptors, so each unixFile
30919** structure contains a pointer to an instance of this object and this
30920** object keeps a count of the number of unixFile pointing to it.
30921*/
30922struct unixInodeInfo {
30923  struct unixFileId fileId;       /* The lookup key */
30924  int nShared;                    /* Number of SHARED locks held */
30925  unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
30926  unsigned char bProcessLock;     /* An exclusive process lock is held */
30927  int nRef;                       /* Number of pointers to this structure */
30928  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
30929  int nLock;                      /* Number of outstanding file locks */
30930  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
30931  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
30932  unixInodeInfo *pPrev;           /*    .... doubly linked */
30933#if SQLITE_ENABLE_LOCKING_STYLE
30934  unsigned long long sharedByte;  /* for AFP simulated shared lock */
30935#endif
30936#if OS_VXWORKS
30937  sem_t *pSem;                    /* Named POSIX semaphore */
30938  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
30939#endif
30940};
30941
30942/*
30943** A lists of all unixInodeInfo objects.
30944*/
30945static unixInodeInfo *inodeList = 0;
30946
30947/*
30948**
30949** This function - unixLogErrorAtLine(), is only ever called via the macro
30950** unixLogError().
30951**
30952** It is invoked after an error occurs in an OS function and errno has been
30953** set. It logs a message using sqlite3_log() containing the current value of
30954** errno and, if possible, the human-readable equivalent from strerror() or
30955** strerror_r().
30956**
30957** The first argument passed to the macro should be the error code that
30958** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
30959** The two subsequent arguments should be the name of the OS function that
30960** failed (e.g. "unlink", "open") and the associated file-system path,
30961** if any.
30962*/
30963#define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
30964static int unixLogErrorAtLine(
30965  int errcode,                    /* SQLite error code */
30966  const char *zFunc,              /* Name of OS function that failed */
30967  const char *zPath,              /* File path associated with error */
30968  int iLine                       /* Source line number where error occurred */
30969){
30970  char *zErr;                     /* Message from strerror() or equivalent */
30971  int iErrno = errno;             /* Saved syscall error number */
30972
30973  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
30974  ** the strerror() function to obtain the human-readable error message
30975  ** equivalent to errno. Otherwise, use strerror_r().
30976  */
30977#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
30978  char aErr[80];
30979  memset(aErr, 0, sizeof(aErr));
30980  zErr = aErr;
30981
30982  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
30983  ** assume that the system provides the GNU version of strerror_r() that
30984  ** returns a pointer to a buffer containing the error message. That pointer
30985  ** may point to aErr[], or it may point to some static storage somewhere.
30986  ** Otherwise, assume that the system provides the POSIX version of
30987  ** strerror_r(), which always writes an error message into aErr[].
30988  **
30989  ** If the code incorrectly assumes that it is the POSIX version that is
30990  ** available, the error message will often be an empty string. Not a
30991  ** huge problem. Incorrectly concluding that the GNU version is available
30992  ** could lead to a segfault though.
30993  */
30994#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
30995  zErr =
30996# endif
30997  strerror_r(iErrno, aErr, sizeof(aErr)-1);
30998
30999#elif SQLITE_THREADSAFE
31000  /* This is a threadsafe build, but strerror_r() is not available. */
31001  zErr = "";
31002#else
31003  /* Non-threadsafe build, use strerror(). */
31004  zErr = strerror(iErrno);
31005#endif
31006
31007  if( zPath==0 ) zPath = "";
31008  sqlite3_log(errcode,
31009      "os_unix.c:%d: (%d) %s(%s) - %s",
31010      iLine, iErrno, zFunc, zPath, zErr
31011  );
31012
31013  return errcode;
31014}
31015
31016/*
31017** Close a file descriptor.
31018**
31019** We assume that close() almost always works, since it is only in a
31020** very sick application or on a very sick platform that it might fail.
31021** If it does fail, simply leak the file descriptor, but do log the
31022** error.
31023**
31024** Note that it is not safe to retry close() after EINTR since the
31025** file descriptor might have already been reused by another thread.
31026** So we don't even try to recover from an EINTR.  Just log the error
31027** and move on.
31028*/
31029static void robust_close(unixFile *pFile, int h, int lineno){
31030  if( osClose(h) ){
31031    unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
31032                       pFile ? pFile->zPath : 0, lineno);
31033  }
31034}
31035
31036/*
31037** Set the pFile->lastErrno.  Do this in a subroutine as that provides
31038** a convenient place to set a breakpoint.
31039*/
31040static void storeLastErrno(unixFile *pFile, int error){
31041  pFile->lastErrno = error;
31042}
31043
31044/*
31045** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
31046*/
31047static void closePendingFds(unixFile *pFile){
31048  unixInodeInfo *pInode = pFile->pInode;
31049  UnixUnusedFd *p;
31050  UnixUnusedFd *pNext;
31051  for(p=pInode->pUnused; p; p=pNext){
31052    pNext = p->pNext;
31053    robust_close(pFile, p->fd, __LINE__);
31054    sqlite3_free(p);
31055  }
31056  pInode->pUnused = 0;
31057}
31058
31059/*
31060** Release a unixInodeInfo structure previously allocated by findInodeInfo().
31061**
31062** The mutex entered using the unixEnterMutex() function must be held
31063** when this function is called.
31064*/
31065static void releaseInodeInfo(unixFile *pFile){
31066  unixInodeInfo *pInode = pFile->pInode;
31067  assert( unixMutexHeld() );
31068  if( ALWAYS(pInode) ){
31069    pInode->nRef--;
31070    if( pInode->nRef==0 ){
31071      assert( pInode->pShmNode==0 );
31072      closePendingFds(pFile);
31073      if( pInode->pPrev ){
31074        assert( pInode->pPrev->pNext==pInode );
31075        pInode->pPrev->pNext = pInode->pNext;
31076      }else{
31077        assert( inodeList==pInode );
31078        inodeList = pInode->pNext;
31079      }
31080      if( pInode->pNext ){
31081        assert( pInode->pNext->pPrev==pInode );
31082        pInode->pNext->pPrev = pInode->pPrev;
31083      }
31084      sqlite3_free(pInode);
31085    }
31086  }
31087}
31088
31089/*
31090** Given a file descriptor, locate the unixInodeInfo object that
31091** describes that file descriptor.  Create a new one if necessary.  The
31092** return value might be uninitialized if an error occurs.
31093**
31094** The mutex entered using the unixEnterMutex() function must be held
31095** when this function is called.
31096**
31097** Return an appropriate error code.
31098*/
31099static int findInodeInfo(
31100  unixFile *pFile,               /* Unix file with file desc used in the key */
31101  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
31102){
31103  int rc;                        /* System call return code */
31104  int fd;                        /* The file descriptor for pFile */
31105  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
31106  struct stat statbuf;           /* Low-level file information */
31107  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
31108
31109  assert( unixMutexHeld() );
31110
31111  /* Get low-level information about the file that we can used to
31112  ** create a unique name for the file.
31113  */
31114  fd = pFile->h;
31115  rc = osFstat(fd, &statbuf);
31116  if( rc!=0 ){
31117    storeLastErrno(pFile, errno);
31118#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
31119    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
31120#endif
31121    return SQLITE_IOERR;
31122  }
31123
31124#ifdef __APPLE__
31125  /* On OS X on an msdos filesystem, the inode number is reported
31126  ** incorrectly for zero-size files.  See ticket #3260.  To work
31127  ** around this problem (we consider it a bug in OS X, not SQLite)
31128  ** we always increase the file size to 1 by writing a single byte
31129  ** prior to accessing the inode number.  The one byte written is
31130  ** an ASCII 'S' character which also happens to be the first byte
31131  ** in the header of every SQLite database.  In this way, if there
31132  ** is a race condition such that another thread has already populated
31133  ** the first page of the database, no damage is done.
31134  */
31135  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
31136    do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
31137    if( rc!=1 ){
31138      storeLastErrno(pFile, errno);
31139      return SQLITE_IOERR;
31140    }
31141    rc = osFstat(fd, &statbuf);
31142    if( rc!=0 ){
31143      storeLastErrno(pFile, errno);
31144      return SQLITE_IOERR;
31145    }
31146  }
31147#endif
31148
31149  memset(&fileId, 0, sizeof(fileId));
31150  fileId.dev = statbuf.st_dev;
31151#if OS_VXWORKS
31152  fileId.pId = pFile->pId;
31153#else
31154  fileId.ino = (u64)statbuf.st_ino;
31155#endif
31156  pInode = inodeList;
31157  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
31158    pInode = pInode->pNext;
31159  }
31160  if( pInode==0 ){
31161    pInode = sqlite3_malloc64( sizeof(*pInode) );
31162    if( pInode==0 ){
31163      return SQLITE_NOMEM_BKPT;
31164    }
31165    memset(pInode, 0, sizeof(*pInode));
31166    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
31167    pInode->nRef = 1;
31168    pInode->pNext = inodeList;
31169    pInode->pPrev = 0;
31170    if( inodeList ) inodeList->pPrev = pInode;
31171    inodeList = pInode;
31172  }else{
31173    pInode->nRef++;
31174  }
31175  *ppInode = pInode;
31176  return SQLITE_OK;
31177}
31178
31179/*
31180** Return TRUE if pFile has been renamed or unlinked since it was first opened.
31181*/
31182static int fileHasMoved(unixFile *pFile){
31183#if OS_VXWORKS
31184  return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
31185#else
31186  struct stat buf;
31187  return pFile->pInode!=0 &&
31188      (osStat(pFile->zPath, &buf)!=0
31189         || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
31190#endif
31191}
31192
31193
31194/*
31195** Check a unixFile that is a database.  Verify the following:
31196**
31197** (1) There is exactly one hard link on the file
31198** (2) The file is not a symbolic link
31199** (3) The file has not been renamed or unlinked
31200**
31201** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
31202*/
31203static void verifyDbFile(unixFile *pFile){
31204  struct stat buf;
31205  int rc;
31206
31207  /* These verifications occurs for the main database only */
31208  if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
31209
31210  rc = osFstat(pFile->h, &buf);
31211  if( rc!=0 ){
31212    sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
31213    return;
31214  }
31215  if( buf.st_nlink==0 ){
31216    sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
31217    return;
31218  }
31219  if( buf.st_nlink>1 ){
31220    sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
31221    return;
31222  }
31223  if( fileHasMoved(pFile) ){
31224    sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
31225    return;
31226  }
31227}
31228
31229
31230/*
31231** This routine checks if there is a RESERVED lock held on the specified
31232** file by this or any other process. If such a lock is held, set *pResOut
31233** to a non-zero value otherwise *pResOut is set to zero.  The return value
31234** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31235*/
31236static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
31237  int rc = SQLITE_OK;
31238  int reserved = 0;
31239  unixFile *pFile = (unixFile*)id;
31240
31241  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31242
31243  assert( pFile );
31244  assert( pFile->eFileLock<=SHARED_LOCK );
31245  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
31246
31247  /* Check if a thread in this process holds such a lock */
31248  if( pFile->pInode->eFileLock>SHARED_LOCK ){
31249    reserved = 1;
31250  }
31251
31252  /* Otherwise see if some other process holds it.
31253  */
31254#ifndef __DJGPP__
31255  if( !reserved && !pFile->pInode->bProcessLock ){
31256    struct flock lock;
31257    lock.l_whence = SEEK_SET;
31258    lock.l_start = RESERVED_BYTE;
31259    lock.l_len = 1;
31260    lock.l_type = F_WRLCK;
31261    if( osFcntl(pFile->h, F_GETLK, &lock) ){
31262      rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
31263      storeLastErrno(pFile, errno);
31264    } else if( lock.l_type!=F_UNLCK ){
31265      reserved = 1;
31266    }
31267  }
31268#endif
31269
31270  unixLeaveMutex();
31271  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
31272
31273  *pResOut = reserved;
31274  return rc;
31275}
31276
31277/*
31278** Attempt to set a system-lock on the file pFile.  The lock is
31279** described by pLock.
31280**
31281** If the pFile was opened read/write from unix-excl, then the only lock
31282** ever obtained is an exclusive lock, and it is obtained exactly once
31283** the first time any lock is attempted.  All subsequent system locking
31284** operations become no-ops.  Locking operations still happen internally,
31285** in order to coordinate access between separate database connections
31286** within this process, but all of that is handled in memory and the
31287** operating system does not participate.
31288**
31289** This function is a pass-through to fcntl(F_SETLK) if pFile is using
31290** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
31291** and is read-only.
31292**
31293** Zero is returned if the call completes successfully, or -1 if a call
31294** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
31295*/
31296static int unixFileLock(unixFile *pFile, struct flock *pLock){
31297  int rc;
31298  unixInodeInfo *pInode = pFile->pInode;
31299  assert( unixMutexHeld() );
31300  assert( pInode!=0 );
31301  if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
31302    if( pInode->bProcessLock==0 ){
31303      struct flock lock;
31304      assert( pInode->nLock==0 );
31305      lock.l_whence = SEEK_SET;
31306      lock.l_start = SHARED_FIRST;
31307      lock.l_len = SHARED_SIZE;
31308      lock.l_type = F_WRLCK;
31309      rc = osFcntl(pFile->h, F_SETLK, &lock);
31310      if( rc<0 ) return rc;
31311      pInode->bProcessLock = 1;
31312      pInode->nLock++;
31313    }else{
31314      rc = 0;
31315    }
31316  }else{
31317    rc = osFcntl(pFile->h, F_SETLK, pLock);
31318  }
31319  return rc;
31320}
31321
31322/*
31323** Lock the file with the lock specified by parameter eFileLock - one
31324** of the following:
31325**
31326**     (1) SHARED_LOCK
31327**     (2) RESERVED_LOCK
31328**     (3) PENDING_LOCK
31329**     (4) EXCLUSIVE_LOCK
31330**
31331** Sometimes when requesting one lock state, additional lock states
31332** are inserted in between.  The locking might fail on one of the later
31333** transitions leaving the lock state different from what it started but
31334** still short of its goal.  The following chart shows the allowed
31335** transitions and the inserted intermediate states:
31336**
31337**    UNLOCKED -> SHARED
31338**    SHARED -> RESERVED
31339**    SHARED -> (PENDING) -> EXCLUSIVE
31340**    RESERVED -> (PENDING) -> EXCLUSIVE
31341**    PENDING -> EXCLUSIVE
31342**
31343** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31344** routine to lower a locking level.
31345*/
31346static int unixLock(sqlite3_file *id, int eFileLock){
31347  /* The following describes the implementation of the various locks and
31348  ** lock transitions in terms of the POSIX advisory shared and exclusive
31349  ** lock primitives (called read-locks and write-locks below, to avoid
31350  ** confusion with SQLite lock names). The algorithms are complicated
31351  ** slightly in order to be compatible with Windows95 systems simultaneously
31352  ** accessing the same database file, in case that is ever required.
31353  **
31354  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
31355  ** byte', each single bytes at well known offsets, and the 'shared byte
31356  ** range', a range of 510 bytes at a well known offset.
31357  **
31358  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
31359  ** byte'.  If this is successful, 'shared byte range' is read-locked
31360  ** and the lock on the 'pending byte' released.  (Legacy note:  When
31361  ** SQLite was first developed, Windows95 systems were still very common,
31362  ** and Widnows95 lacks a shared-lock capability.  So on Windows95, a
31363  ** single randomly selected by from the 'shared byte range' is locked.
31364  ** Windows95 is now pretty much extinct, but this work-around for the
31365  ** lack of shared-locks on Windows95 lives on, for backwards
31366  ** compatibility.)
31367  **
31368  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
31369  ** A RESERVED lock is implemented by grabbing a write-lock on the
31370  ** 'reserved byte'.
31371  **
31372  ** A process may only obtain a PENDING lock after it has obtained a
31373  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
31374  ** on the 'pending byte'. This ensures that no new SHARED locks can be
31375  ** obtained, but existing SHARED locks are allowed to persist. A process
31376  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
31377  ** This property is used by the algorithm for rolling back a journal file
31378  ** after a crash.
31379  **
31380  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
31381  ** implemented by obtaining a write-lock on the entire 'shared byte
31382  ** range'. Since all other locks require a read-lock on one of the bytes
31383  ** within this range, this ensures that no other locks are held on the
31384  ** database.
31385  */
31386  int rc = SQLITE_OK;
31387  unixFile *pFile = (unixFile*)id;
31388  unixInodeInfo *pInode;
31389  struct flock lock;
31390  int tErrno = 0;
31391
31392  assert( pFile );
31393  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
31394      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
31395      azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
31396      osGetpid(0)));
31397
31398  /* If there is already a lock of this type or more restrictive on the
31399  ** unixFile, do nothing. Don't use the end_lock: exit path, as
31400  ** unixEnterMutex() hasn't been called yet.
31401  */
31402  if( pFile->eFileLock>=eFileLock ){
31403    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
31404            azFileLock(eFileLock)));
31405    return SQLITE_OK;
31406  }
31407
31408  /* Make sure the locking sequence is correct.
31409  **  (1) We never move from unlocked to anything higher than shared lock.
31410  **  (2) SQLite never explicitly requests a pendig lock.
31411  **  (3) A shared lock is always held when a reserve lock is requested.
31412  */
31413  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
31414  assert( eFileLock!=PENDING_LOCK );
31415  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
31416
31417  /* This mutex is needed because pFile->pInode is shared across threads
31418  */
31419  unixEnterMutex();
31420  pInode = pFile->pInode;
31421
31422  /* If some thread using this PID has a lock via a different unixFile*
31423  ** handle that precludes the requested lock, return BUSY.
31424  */
31425  if( (pFile->eFileLock!=pInode->eFileLock &&
31426          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
31427  ){
31428    rc = SQLITE_BUSY;
31429    goto end_lock;
31430  }
31431
31432  /* If a SHARED lock is requested, and some thread using this PID already
31433  ** has a SHARED or RESERVED lock, then increment reference counts and
31434  ** return SQLITE_OK.
31435  */
31436  if( eFileLock==SHARED_LOCK &&
31437      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
31438    assert( eFileLock==SHARED_LOCK );
31439    assert( pFile->eFileLock==0 );
31440    assert( pInode->nShared>0 );
31441    pFile->eFileLock = SHARED_LOCK;
31442    pInode->nShared++;
31443    pInode->nLock++;
31444    goto end_lock;
31445  }
31446
31447
31448  /* A PENDING lock is needed before acquiring a SHARED lock and before
31449  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
31450  ** be released.
31451  */
31452  lock.l_len = 1L;
31453  lock.l_whence = SEEK_SET;
31454  if( eFileLock==SHARED_LOCK
31455      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
31456  ){
31457    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
31458    lock.l_start = PENDING_BYTE;
31459    if( unixFileLock(pFile, &lock) ){
31460      tErrno = errno;
31461      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31462      if( rc!=SQLITE_BUSY ){
31463        storeLastErrno(pFile, tErrno);
31464      }
31465      goto end_lock;
31466    }
31467  }
31468
31469
31470  /* If control gets to this point, then actually go ahead and make
31471  ** operating system calls for the specified lock.
31472  */
31473  if( eFileLock==SHARED_LOCK ){
31474    assert( pInode->nShared==0 );
31475    assert( pInode->eFileLock==0 );
31476    assert( rc==SQLITE_OK );
31477
31478    /* Now get the read-lock */
31479    lock.l_start = SHARED_FIRST;
31480    lock.l_len = SHARED_SIZE;
31481    if( unixFileLock(pFile, &lock) ){
31482      tErrno = errno;
31483      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31484    }
31485
31486    /* Drop the temporary PENDING lock */
31487    lock.l_start = PENDING_BYTE;
31488    lock.l_len = 1L;
31489    lock.l_type = F_UNLCK;
31490    if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
31491      /* This could happen with a network mount */
31492      tErrno = errno;
31493      rc = SQLITE_IOERR_UNLOCK;
31494    }
31495
31496    if( rc ){
31497      if( rc!=SQLITE_BUSY ){
31498        storeLastErrno(pFile, tErrno);
31499      }
31500      goto end_lock;
31501    }else{
31502      pFile->eFileLock = SHARED_LOCK;
31503      pInode->nLock++;
31504      pInode->nShared = 1;
31505    }
31506  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
31507    /* We are trying for an exclusive lock but another thread in this
31508    ** same process is still holding a shared lock. */
31509    rc = SQLITE_BUSY;
31510  }else{
31511    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
31512    ** assumed that there is a SHARED or greater lock on the file
31513    ** already.
31514    */
31515    assert( 0!=pFile->eFileLock );
31516    lock.l_type = F_WRLCK;
31517
31518    assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
31519    if( eFileLock==RESERVED_LOCK ){
31520      lock.l_start = RESERVED_BYTE;
31521      lock.l_len = 1L;
31522    }else{
31523      lock.l_start = SHARED_FIRST;
31524      lock.l_len = SHARED_SIZE;
31525    }
31526
31527    if( unixFileLock(pFile, &lock) ){
31528      tErrno = errno;
31529      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31530      if( rc!=SQLITE_BUSY ){
31531        storeLastErrno(pFile, tErrno);
31532      }
31533    }
31534  }
31535
31536
31537#ifdef SQLITE_DEBUG
31538  /* Set up the transaction-counter change checking flags when
31539  ** transitioning from a SHARED to a RESERVED lock.  The change
31540  ** from SHARED to RESERVED marks the beginning of a normal
31541  ** write operation (not a hot journal rollback).
31542  */
31543  if( rc==SQLITE_OK
31544   && pFile->eFileLock<=SHARED_LOCK
31545   && eFileLock==RESERVED_LOCK
31546  ){
31547    pFile->transCntrChng = 0;
31548    pFile->dbUpdate = 0;
31549    pFile->inNormalWrite = 1;
31550  }
31551#endif
31552
31553
31554  if( rc==SQLITE_OK ){
31555    pFile->eFileLock = eFileLock;
31556    pInode->eFileLock = eFileLock;
31557  }else if( eFileLock==EXCLUSIVE_LOCK ){
31558    pFile->eFileLock = PENDING_LOCK;
31559    pInode->eFileLock = PENDING_LOCK;
31560  }
31561
31562end_lock:
31563  unixLeaveMutex();
31564  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
31565      rc==SQLITE_OK ? "ok" : "failed"));
31566  return rc;
31567}
31568
31569/*
31570** Add the file descriptor used by file handle pFile to the corresponding
31571** pUnused list.
31572*/
31573static void setPendingFd(unixFile *pFile){
31574  unixInodeInfo *pInode = pFile->pInode;
31575  UnixUnusedFd *p = pFile->pUnused;
31576  p->pNext = pInode->pUnused;
31577  pInode->pUnused = p;
31578  pFile->h = -1;
31579  pFile->pUnused = 0;
31580}
31581
31582/*
31583** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31584** must be either NO_LOCK or SHARED_LOCK.
31585**
31586** If the locking level of the file descriptor is already at or below
31587** the requested locking level, this routine is a no-op.
31588**
31589** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
31590** the byte range is divided into 2 parts and the first part is unlocked then
31591** set to a read lock, then the other part is simply unlocked.  This works
31592** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
31593** remove the write lock on a region when a read lock is set.
31594*/
31595static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
31596  unixFile *pFile = (unixFile*)id;
31597  unixInodeInfo *pInode;
31598  struct flock lock;
31599  int rc = SQLITE_OK;
31600
31601  assert( pFile );
31602  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
31603      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
31604      osGetpid(0)));
31605
31606  assert( eFileLock<=SHARED_LOCK );
31607  if( pFile->eFileLock<=eFileLock ){
31608    return SQLITE_OK;
31609  }
31610  unixEnterMutex();
31611  pInode = pFile->pInode;
31612  assert( pInode->nShared!=0 );
31613  if( pFile->eFileLock>SHARED_LOCK ){
31614    assert( pInode->eFileLock==pFile->eFileLock );
31615
31616#ifdef SQLITE_DEBUG
31617    /* When reducing a lock such that other processes can start
31618    ** reading the database file again, make sure that the
31619    ** transaction counter was updated if any part of the database
31620    ** file changed.  If the transaction counter is not updated,
31621    ** other connections to the same file might not realize that
31622    ** the file has changed and hence might not know to flush their
31623    ** cache.  The use of a stale cache can lead to database corruption.
31624    */
31625    pFile->inNormalWrite = 0;
31626#endif
31627
31628    /* downgrading to a shared lock on NFS involves clearing the write lock
31629    ** before establishing the readlock - to avoid a race condition we downgrade
31630    ** the lock in 2 blocks, so that part of the range will be covered by a
31631    ** write lock until the rest is covered by a read lock:
31632    **  1:   [WWWWW]
31633    **  2:   [....W]
31634    **  3:   [RRRRW]
31635    **  4:   [RRRR.]
31636    */
31637    if( eFileLock==SHARED_LOCK ){
31638#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
31639      (void)handleNFSUnlock;
31640      assert( handleNFSUnlock==0 );
31641#endif
31642#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31643      if( handleNFSUnlock ){
31644        int tErrno;               /* Error code from system call errors */
31645        off_t divSize = SHARED_SIZE - 1;
31646
31647        lock.l_type = F_UNLCK;
31648        lock.l_whence = SEEK_SET;
31649        lock.l_start = SHARED_FIRST;
31650        lock.l_len = divSize;
31651        if( unixFileLock(pFile, &lock)==(-1) ){
31652          tErrno = errno;
31653          rc = SQLITE_IOERR_UNLOCK;
31654          storeLastErrno(pFile, tErrno);
31655          goto end_unlock;
31656        }
31657        lock.l_type = F_RDLCK;
31658        lock.l_whence = SEEK_SET;
31659        lock.l_start = SHARED_FIRST;
31660        lock.l_len = divSize;
31661        if( unixFileLock(pFile, &lock)==(-1) ){
31662          tErrno = errno;
31663          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
31664          if( IS_LOCK_ERROR(rc) ){
31665            storeLastErrno(pFile, tErrno);
31666          }
31667          goto end_unlock;
31668        }
31669        lock.l_type = F_UNLCK;
31670        lock.l_whence = SEEK_SET;
31671        lock.l_start = SHARED_FIRST+divSize;
31672        lock.l_len = SHARED_SIZE-divSize;
31673        if( unixFileLock(pFile, &lock)==(-1) ){
31674          tErrno = errno;
31675          rc = SQLITE_IOERR_UNLOCK;
31676          storeLastErrno(pFile, tErrno);
31677          goto end_unlock;
31678        }
31679      }else
31680#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31681      {
31682        lock.l_type = F_RDLCK;
31683        lock.l_whence = SEEK_SET;
31684        lock.l_start = SHARED_FIRST;
31685        lock.l_len = SHARED_SIZE;
31686        if( unixFileLock(pFile, &lock) ){
31687          /* In theory, the call to unixFileLock() cannot fail because another
31688          ** process is holding an incompatible lock. If it does, this
31689          ** indicates that the other process is not following the locking
31690          ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
31691          ** SQLITE_BUSY would confuse the upper layer (in practice it causes
31692          ** an assert to fail). */
31693          rc = SQLITE_IOERR_RDLOCK;
31694          storeLastErrno(pFile, errno);
31695          goto end_unlock;
31696        }
31697      }
31698    }
31699    lock.l_type = F_UNLCK;
31700    lock.l_whence = SEEK_SET;
31701    lock.l_start = PENDING_BYTE;
31702    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
31703    if( unixFileLock(pFile, &lock)==0 ){
31704      pInode->eFileLock = SHARED_LOCK;
31705    }else{
31706      rc = SQLITE_IOERR_UNLOCK;
31707      storeLastErrno(pFile, errno);
31708      goto end_unlock;
31709    }
31710  }
31711  if( eFileLock==NO_LOCK ){
31712    /* Decrement the shared lock counter.  Release the lock using an
31713    ** OS call only when all threads in this same process have released
31714    ** the lock.
31715    */
31716    pInode->nShared--;
31717    if( pInode->nShared==0 ){
31718      lock.l_type = F_UNLCK;
31719      lock.l_whence = SEEK_SET;
31720      lock.l_start = lock.l_len = 0L;
31721      if( unixFileLock(pFile, &lock)==0 ){
31722        pInode->eFileLock = NO_LOCK;
31723      }else{
31724        rc = SQLITE_IOERR_UNLOCK;
31725        storeLastErrno(pFile, errno);
31726        pInode->eFileLock = NO_LOCK;
31727        pFile->eFileLock = NO_LOCK;
31728      }
31729    }
31730
31731    /* Decrement the count of locks against this same file.  When the
31732    ** count reaches zero, close any other file descriptors whose close
31733    ** was deferred because of outstanding locks.
31734    */
31735    pInode->nLock--;
31736    assert( pInode->nLock>=0 );
31737    if( pInode->nLock==0 ){
31738      closePendingFds(pFile);
31739    }
31740  }
31741
31742end_unlock:
31743  unixLeaveMutex();
31744  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
31745  return rc;
31746}
31747
31748/*
31749** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31750** must be either NO_LOCK or SHARED_LOCK.
31751**
31752** If the locking level of the file descriptor is already at or below
31753** the requested locking level, this routine is a no-op.
31754*/
31755static int unixUnlock(sqlite3_file *id, int eFileLock){
31756#if SQLITE_MAX_MMAP_SIZE>0
31757  assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
31758#endif
31759  return posixUnlock(id, eFileLock, 0);
31760}
31761
31762#if SQLITE_MAX_MMAP_SIZE>0
31763static int unixMapfile(unixFile *pFd, i64 nByte);
31764static void unixUnmapfile(unixFile *pFd);
31765#endif
31766
31767/*
31768** This function performs the parts of the "close file" operation
31769** common to all locking schemes. It closes the directory and file
31770** handles, if they are valid, and sets all fields of the unixFile
31771** structure to 0.
31772**
31773** It is *not* necessary to hold the mutex when this routine is called,
31774** even on VxWorks.  A mutex will be acquired on VxWorks by the
31775** vxworksReleaseFileId() routine.
31776*/
31777static int closeUnixFile(sqlite3_file *id){
31778  unixFile *pFile = (unixFile*)id;
31779#if SQLITE_MAX_MMAP_SIZE>0
31780  unixUnmapfile(pFile);
31781#endif
31782  if( pFile->h>=0 ){
31783    robust_close(pFile, pFile->h, __LINE__);
31784    pFile->h = -1;
31785  }
31786#if OS_VXWORKS
31787  if( pFile->pId ){
31788    if( pFile->ctrlFlags & UNIXFILE_DELETE ){
31789      osUnlink(pFile->pId->zCanonicalName);
31790    }
31791    vxworksReleaseFileId(pFile->pId);
31792    pFile->pId = 0;
31793  }
31794#endif
31795#ifdef SQLITE_UNLINK_AFTER_CLOSE
31796  if( pFile->ctrlFlags & UNIXFILE_DELETE ){
31797    osUnlink(pFile->zPath);
31798    sqlite3_free(*(char**)&pFile->zPath);
31799    pFile->zPath = 0;
31800  }
31801#endif
31802  OSTRACE(("CLOSE   %-3d\n", pFile->h));
31803  OpenCounter(-1);
31804  sqlite3_free(pFile->pUnused);
31805  memset(pFile, 0, sizeof(unixFile));
31806  return SQLITE_OK;
31807}
31808
31809/*
31810** Close a file.
31811*/
31812static int unixClose(sqlite3_file *id){
31813  int rc = SQLITE_OK;
31814  unixFile *pFile = (unixFile *)id;
31815  verifyDbFile(pFile);
31816  unixUnlock(id, NO_LOCK);
31817  unixEnterMutex();
31818
31819  /* unixFile.pInode is always valid here. Otherwise, a different close
31820  ** routine (e.g. nolockClose()) would be called instead.
31821  */
31822  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
31823  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
31824    /* If there are outstanding locks, do not actually close the file just
31825    ** yet because that would clear those locks.  Instead, add the file
31826    ** descriptor to pInode->pUnused list.  It will be automatically closed
31827    ** when the last lock is cleared.
31828    */
31829    setPendingFd(pFile);
31830  }
31831  releaseInodeInfo(pFile);
31832  rc = closeUnixFile(id);
31833  unixLeaveMutex();
31834  return rc;
31835}
31836
31837/************** End of the posix advisory lock implementation *****************
31838******************************************************************************/
31839
31840/******************************************************************************
31841****************************** No-op Locking **********************************
31842**
31843** Of the various locking implementations available, this is by far the
31844** simplest:  locking is ignored.  No attempt is made to lock the database
31845** file for reading or writing.
31846**
31847** This locking mode is appropriate for use on read-only databases
31848** (ex: databases that are burned into CD-ROM, for example.)  It can
31849** also be used if the application employs some external mechanism to
31850** prevent simultaneous access of the same database by two or more
31851** database connections.  But there is a serious risk of database
31852** corruption if this locking mode is used in situations where multiple
31853** database connections are accessing the same database file at the same
31854** time and one or more of those connections are writing.
31855*/
31856
31857static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
31858  UNUSED_PARAMETER(NotUsed);
31859  *pResOut = 0;
31860  return SQLITE_OK;
31861}
31862static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
31863  UNUSED_PARAMETER2(NotUsed, NotUsed2);
31864  return SQLITE_OK;
31865}
31866static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
31867  UNUSED_PARAMETER2(NotUsed, NotUsed2);
31868  return SQLITE_OK;
31869}
31870
31871/*
31872** Close the file.
31873*/
31874static int nolockClose(sqlite3_file *id) {
31875  return closeUnixFile(id);
31876}
31877
31878/******************* End of the no-op lock implementation *********************
31879******************************************************************************/
31880
31881/******************************************************************************
31882************************* Begin dot-file Locking ******************************
31883**
31884** The dotfile locking implementation uses the existence of separate lock
31885** files (really a directory) to control access to the database.  This works
31886** on just about every filesystem imaginable.  But there are serious downsides:
31887**
31888**    (1)  There is zero concurrency.  A single reader blocks all other
31889**         connections from reading or writing the database.
31890**
31891**    (2)  An application crash or power loss can leave stale lock files
31892**         sitting around that need to be cleared manually.
31893**
31894** Nevertheless, a dotlock is an appropriate locking mode for use if no
31895** other locking strategy is available.
31896**
31897** Dotfile locking works by creating a subdirectory in the same directory as
31898** the database and with the same name but with a ".lock" extension added.
31899** The existence of a lock directory implies an EXCLUSIVE lock.  All other
31900** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
31901*/
31902
31903/*
31904** The file suffix added to the data base filename in order to create the
31905** lock directory.
31906*/
31907#define DOTLOCK_SUFFIX ".lock"
31908
31909/*
31910** This routine checks if there is a RESERVED lock held on the specified
31911** file by this or any other process. If such a lock is held, set *pResOut
31912** to a non-zero value otherwise *pResOut is set to zero.  The return value
31913** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31914**
31915** In dotfile locking, either a lock exists or it does not.  So in this
31916** variation of CheckReservedLock(), *pResOut is set to true if any lock
31917** is held on the file and false if the file is unlocked.
31918*/
31919static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
31920  int rc = SQLITE_OK;
31921  int reserved = 0;
31922  unixFile *pFile = (unixFile*)id;
31923
31924  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31925
31926  assert( pFile );
31927  reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
31928  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
31929  *pResOut = reserved;
31930  return rc;
31931}
31932
31933/*
31934** Lock the file with the lock specified by parameter eFileLock - one
31935** of the following:
31936**
31937**     (1) SHARED_LOCK
31938**     (2) RESERVED_LOCK
31939**     (3) PENDING_LOCK
31940**     (4) EXCLUSIVE_LOCK
31941**
31942** Sometimes when requesting one lock state, additional lock states
31943** are inserted in between.  The locking might fail on one of the later
31944** transitions leaving the lock state different from what it started but
31945** still short of its goal.  The following chart shows the allowed
31946** transitions and the inserted intermediate states:
31947**
31948**    UNLOCKED -> SHARED
31949**    SHARED -> RESERVED
31950**    SHARED -> (PENDING) -> EXCLUSIVE
31951**    RESERVED -> (PENDING) -> EXCLUSIVE
31952**    PENDING -> EXCLUSIVE
31953**
31954** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31955** routine to lower a locking level.
31956**
31957** With dotfile locking, we really only support state (4): EXCLUSIVE.
31958** But we track the other locking levels internally.
31959*/
31960static int dotlockLock(sqlite3_file *id, int eFileLock) {
31961  unixFile *pFile = (unixFile*)id;
31962  char *zLockFile = (char *)pFile->lockingContext;
31963  int rc = SQLITE_OK;
31964
31965
31966  /* If we have any lock, then the lock file already exists.  All we have
31967  ** to do is adjust our internal record of the lock level.
31968  */
31969  if( pFile->eFileLock > NO_LOCK ){
31970    pFile->eFileLock = eFileLock;
31971    /* Always update the timestamp on the old file */
31972#ifdef HAVE_UTIME
31973    utime(zLockFile, NULL);
31974#else
31975    utimes(zLockFile, NULL);
31976#endif
31977    return SQLITE_OK;
31978  }
31979
31980  /* grab an exclusive lock */
31981  rc = osMkdir(zLockFile, 0777);
31982  if( rc<0 ){
31983    /* failed to open/create the lock directory */
31984    int tErrno = errno;
31985    if( EEXIST == tErrno ){
31986      rc = SQLITE_BUSY;
31987    } else {
31988      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31989      if( rc!=SQLITE_BUSY ){
31990        storeLastErrno(pFile, tErrno);
31991      }
31992    }
31993    return rc;
31994  }
31995
31996  /* got it, set the type and return ok */
31997  pFile->eFileLock = eFileLock;
31998  return rc;
31999}
32000
32001/*
32002** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32003** must be either NO_LOCK or SHARED_LOCK.
32004**
32005** If the locking level of the file descriptor is already at or below
32006** the requested locking level, this routine is a no-op.
32007**
32008** When the locking level reaches NO_LOCK, delete the lock file.
32009*/
32010static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
32011  unixFile *pFile = (unixFile*)id;
32012  char *zLockFile = (char *)pFile->lockingContext;
32013  int rc;
32014
32015  assert( pFile );
32016  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
32017           pFile->eFileLock, osGetpid(0)));
32018  assert( eFileLock<=SHARED_LOCK );
32019
32020  /* no-op if possible */
32021  if( pFile->eFileLock==eFileLock ){
32022    return SQLITE_OK;
32023  }
32024
32025  /* To downgrade to shared, simply update our internal notion of the
32026  ** lock state.  No need to mess with the file on disk.
32027  */
32028  if( eFileLock==SHARED_LOCK ){
32029    pFile->eFileLock = SHARED_LOCK;
32030    return SQLITE_OK;
32031  }
32032
32033  /* To fully unlock the database, delete the lock file */
32034  assert( eFileLock==NO_LOCK );
32035  rc = osRmdir(zLockFile);
32036  if( rc<0 ){
32037    int tErrno = errno;
32038    if( tErrno==ENOENT ){
32039      rc = SQLITE_OK;
32040    }else{
32041      rc = SQLITE_IOERR_UNLOCK;
32042      storeLastErrno(pFile, tErrno);
32043    }
32044    return rc;
32045  }
32046  pFile->eFileLock = NO_LOCK;
32047  return SQLITE_OK;
32048}
32049
32050/*
32051** Close a file.  Make sure the lock has been released before closing.
32052*/
32053static int dotlockClose(sqlite3_file *id) {
32054  unixFile *pFile = (unixFile*)id;
32055  assert( id!=0 );
32056  dotlockUnlock(id, NO_LOCK);
32057  sqlite3_free(pFile->lockingContext);
32058  return closeUnixFile(id);
32059}
32060/****************** End of the dot-file lock implementation *******************
32061******************************************************************************/
32062
32063/******************************************************************************
32064************************** Begin flock Locking ********************************
32065**
32066** Use the flock() system call to do file locking.
32067**
32068** flock() locking is like dot-file locking in that the various
32069** fine-grain locking levels supported by SQLite are collapsed into
32070** a single exclusive lock.  In other words, SHARED, RESERVED, and
32071** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
32072** still works when you do this, but concurrency is reduced since
32073** only a single process can be reading the database at a time.
32074**
32075** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
32076*/
32077#if SQLITE_ENABLE_LOCKING_STYLE
32078
32079/*
32080** Retry flock() calls that fail with EINTR
32081*/
32082#ifdef EINTR
32083static int robust_flock(int fd, int op){
32084  int rc;
32085  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
32086  return rc;
32087}
32088#else
32089# define robust_flock(a,b) flock(a,b)
32090#endif
32091
32092
32093/*
32094** This routine checks if there is a RESERVED lock held on the specified
32095** file by this or any other process. If such a lock is held, set *pResOut
32096** to a non-zero value otherwise *pResOut is set to zero.  The return value
32097** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32098*/
32099static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
32100  int rc = SQLITE_OK;
32101  int reserved = 0;
32102  unixFile *pFile = (unixFile*)id;
32103
32104  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32105
32106  assert( pFile );
32107
32108  /* Check if a thread in this process holds such a lock */
32109  if( pFile->eFileLock>SHARED_LOCK ){
32110    reserved = 1;
32111  }
32112
32113  /* Otherwise see if some other process holds it. */
32114  if( !reserved ){
32115    /* attempt to get the lock */
32116    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
32117    if( !lrc ){
32118      /* got the lock, unlock it */
32119      lrc = robust_flock(pFile->h, LOCK_UN);
32120      if ( lrc ) {
32121        int tErrno = errno;
32122        /* unlock failed with an error */
32123        lrc = SQLITE_IOERR_UNLOCK;
32124        storeLastErrno(pFile, tErrno);
32125        rc = lrc;
32126      }
32127    } else {
32128      int tErrno = errno;
32129      reserved = 1;
32130      /* someone else might have it reserved */
32131      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
32132      if( IS_LOCK_ERROR(lrc) ){
32133        storeLastErrno(pFile, tErrno);
32134        rc = lrc;
32135      }
32136    }
32137  }
32138  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
32139
32140#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
32141  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
32142    rc = SQLITE_OK;
32143    reserved=1;
32144  }
32145#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
32146  *pResOut = reserved;
32147  return rc;
32148}
32149
32150/*
32151** Lock the file with the lock specified by parameter eFileLock - one
32152** of the following:
32153**
32154**     (1) SHARED_LOCK
32155**     (2) RESERVED_LOCK
32156**     (3) PENDING_LOCK
32157**     (4) EXCLUSIVE_LOCK
32158**
32159** Sometimes when requesting one lock state, additional lock states
32160** are inserted in between.  The locking might fail on one of the later
32161** transitions leaving the lock state different from what it started but
32162** still short of its goal.  The following chart shows the allowed
32163** transitions and the inserted intermediate states:
32164**
32165**    UNLOCKED -> SHARED
32166**    SHARED -> RESERVED
32167**    SHARED -> (PENDING) -> EXCLUSIVE
32168**    RESERVED -> (PENDING) -> EXCLUSIVE
32169**    PENDING -> EXCLUSIVE
32170**
32171** flock() only really support EXCLUSIVE locks.  We track intermediate
32172** lock states in the sqlite3_file structure, but all locks SHARED or
32173** above are really EXCLUSIVE locks and exclude all other processes from
32174** access the file.
32175**
32176** This routine will only increase a lock.  Use the sqlite3OsUnlock()
32177** routine to lower a locking level.
32178*/
32179static int flockLock(sqlite3_file *id, int eFileLock) {
32180  int rc = SQLITE_OK;
32181  unixFile *pFile = (unixFile*)id;
32182
32183  assert( pFile );
32184
32185  /* if we already have a lock, it is exclusive.
32186  ** Just adjust level and punt on outta here. */
32187  if (pFile->eFileLock > NO_LOCK) {
32188    pFile->eFileLock = eFileLock;
32189    return SQLITE_OK;
32190  }
32191
32192  /* grab an exclusive lock */
32193
32194  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
32195    int tErrno = errno;
32196    /* didn't get, must be busy */
32197    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
32198    if( IS_LOCK_ERROR(rc) ){
32199      storeLastErrno(pFile, tErrno);
32200    }
32201  } else {
32202    /* got it, set the type and return ok */
32203    pFile->eFileLock = eFileLock;
32204  }
32205  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
32206           rc==SQLITE_OK ? "ok" : "failed"));
32207#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
32208  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
32209    rc = SQLITE_BUSY;
32210  }
32211#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
32212  return rc;
32213}
32214
32215
32216/*
32217** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32218** must be either NO_LOCK or SHARED_LOCK.
32219**
32220** If the locking level of the file descriptor is already at or below
32221** the requested locking level, this routine is a no-op.
32222*/
32223static int flockUnlock(sqlite3_file *id, int eFileLock) {
32224  unixFile *pFile = (unixFile*)id;
32225
32226  assert( pFile );
32227  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
32228           pFile->eFileLock, osGetpid(0)));
32229  assert( eFileLock<=SHARED_LOCK );
32230
32231  /* no-op if possible */
32232  if( pFile->eFileLock==eFileLock ){
32233    return SQLITE_OK;
32234  }
32235
32236  /* shared can just be set because we always have an exclusive */
32237  if (eFileLock==SHARED_LOCK) {
32238    pFile->eFileLock = eFileLock;
32239    return SQLITE_OK;
32240  }
32241
32242  /* no, really, unlock. */
32243  if( robust_flock(pFile->h, LOCK_UN) ){
32244#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
32245    return SQLITE_OK;
32246#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
32247    return SQLITE_IOERR_UNLOCK;
32248  }else{
32249    pFile->eFileLock = NO_LOCK;
32250    return SQLITE_OK;
32251  }
32252}
32253
32254/*
32255** Close a file.
32256*/
32257static int flockClose(sqlite3_file *id) {
32258  assert( id!=0 );
32259  flockUnlock(id, NO_LOCK);
32260  return closeUnixFile(id);
32261}
32262
32263#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
32264
32265/******************* End of the flock lock implementation *********************
32266******************************************************************************/
32267
32268/******************************************************************************
32269************************ Begin Named Semaphore Locking ************************
32270**
32271** Named semaphore locking is only supported on VxWorks.
32272**
32273** Semaphore locking is like dot-lock and flock in that it really only
32274** supports EXCLUSIVE locking.  Only a single process can read or write
32275** the database file at a time.  This reduces potential concurrency, but
32276** makes the lock implementation much easier.
32277*/
32278#if OS_VXWORKS
32279
32280/*
32281** This routine checks if there is a RESERVED lock held on the specified
32282** file by this or any other process. If such a lock is held, set *pResOut
32283** to a non-zero value otherwise *pResOut is set to zero.  The return value
32284** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32285*/
32286static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
32287  int rc = SQLITE_OK;
32288  int reserved = 0;
32289  unixFile *pFile = (unixFile*)id;
32290
32291  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32292
32293  assert( pFile );
32294
32295  /* Check if a thread in this process holds such a lock */
32296  if( pFile->eFileLock>SHARED_LOCK ){
32297    reserved = 1;
32298  }
32299
32300  /* Otherwise see if some other process holds it. */
32301  if( !reserved ){
32302    sem_t *pSem = pFile->pInode->pSem;
32303
32304    if( sem_trywait(pSem)==-1 ){
32305      int tErrno = errno;
32306      if( EAGAIN != tErrno ){
32307        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
32308        storeLastErrno(pFile, tErrno);
32309      } else {
32310        /* someone else has the lock when we are in NO_LOCK */
32311        reserved = (pFile->eFileLock < SHARED_LOCK);
32312      }
32313    }else{
32314      /* we could have it if we want it */
32315      sem_post(pSem);
32316    }
32317  }
32318  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
32319
32320  *pResOut = reserved;
32321  return rc;
32322}
32323
32324/*
32325** Lock the file with the lock specified by parameter eFileLock - one
32326** of the following:
32327**
32328**     (1) SHARED_LOCK
32329**     (2) RESERVED_LOCK
32330**     (3) PENDING_LOCK
32331**     (4) EXCLUSIVE_LOCK
32332**
32333** Sometimes when requesting one lock state, additional lock states
32334** are inserted in between.  The locking might fail on one of the later
32335** transitions leaving the lock state different from what it started but
32336** still short of its goal.  The following chart shows the allowed
32337** transitions and the inserted intermediate states:
32338**
32339**    UNLOCKED -> SHARED
32340**    SHARED -> RESERVED
32341**    SHARED -> (PENDING) -> EXCLUSIVE
32342**    RESERVED -> (PENDING) -> EXCLUSIVE
32343**    PENDING -> EXCLUSIVE
32344**
32345** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
32346** lock states in the sqlite3_file structure, but all locks SHARED or
32347** above are really EXCLUSIVE locks and exclude all other processes from
32348** access the file.
32349**
32350** This routine will only increase a lock.  Use the sqlite3OsUnlock()
32351** routine to lower a locking level.
32352*/
32353static int semXLock(sqlite3_file *id, int eFileLock) {
32354  unixFile *pFile = (unixFile*)id;
32355  sem_t *pSem = pFile->pInode->pSem;
32356  int rc = SQLITE_OK;
32357
32358  /* if we already have a lock, it is exclusive.
32359  ** Just adjust level and punt on outta here. */
32360  if (pFile->eFileLock > NO_LOCK) {
32361    pFile->eFileLock = eFileLock;
32362    rc = SQLITE_OK;
32363    goto sem_end_lock;
32364  }
32365
32366  /* lock semaphore now but bail out when already locked. */
32367  if( sem_trywait(pSem)==-1 ){
32368    rc = SQLITE_BUSY;
32369    goto sem_end_lock;
32370  }
32371
32372  /* got it, set the type and return ok */
32373  pFile->eFileLock = eFileLock;
32374
32375 sem_end_lock:
32376  return rc;
32377}
32378
32379/*
32380** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32381** must be either NO_LOCK or SHARED_LOCK.
32382**
32383** If the locking level of the file descriptor is already at or below
32384** the requested locking level, this routine is a no-op.
32385*/
32386static int semXUnlock(sqlite3_file *id, int eFileLock) {
32387  unixFile *pFile = (unixFile*)id;
32388  sem_t *pSem = pFile->pInode->pSem;
32389
32390  assert( pFile );
32391  assert( pSem );
32392  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
32393           pFile->eFileLock, osGetpid(0)));
32394  assert( eFileLock<=SHARED_LOCK );
32395
32396  /* no-op if possible */
32397  if( pFile->eFileLock==eFileLock ){
32398    return SQLITE_OK;
32399  }
32400
32401  /* shared can just be set because we always have an exclusive */
32402  if (eFileLock==SHARED_LOCK) {
32403    pFile->eFileLock = eFileLock;
32404    return SQLITE_OK;
32405  }
32406
32407  /* no, really unlock. */
32408  if ( sem_post(pSem)==-1 ) {
32409    int rc, tErrno = errno;
32410    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
32411    if( IS_LOCK_ERROR(rc) ){
32412      storeLastErrno(pFile, tErrno);
32413    }
32414    return rc;
32415  }
32416  pFile->eFileLock = NO_LOCK;
32417  return SQLITE_OK;
32418}
32419
32420/*
32421 ** Close a file.
32422 */
32423static int semXClose(sqlite3_file *id) {
32424  if( id ){
32425    unixFile *pFile = (unixFile*)id;
32426    semXUnlock(id, NO_LOCK);
32427    assert( pFile );
32428    unixEnterMutex();
32429    releaseInodeInfo(pFile);
32430    unixLeaveMutex();
32431    closeUnixFile(id);
32432  }
32433  return SQLITE_OK;
32434}
32435
32436#endif /* OS_VXWORKS */
32437/*
32438** Named semaphore locking is only available on VxWorks.
32439**
32440*************** End of the named semaphore lock implementation ****************
32441******************************************************************************/
32442
32443
32444/******************************************************************************
32445*************************** Begin AFP Locking *********************************
32446**
32447** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
32448** on Apple Macintosh computers - both OS9 and OSX.
32449**
32450** Third-party implementations of AFP are available.  But this code here
32451** only works on OSX.
32452*/
32453
32454#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
32455/*
32456** The afpLockingContext structure contains all afp lock specific state
32457*/
32458typedef struct afpLockingContext afpLockingContext;
32459struct afpLockingContext {
32460  int reserved;
32461  const char *dbPath;             /* Name of the open file */
32462};
32463
32464struct ByteRangeLockPB2
32465{
32466  unsigned long long offset;        /* offset to first byte to lock */
32467  unsigned long long length;        /* nbr of bytes to lock */
32468  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
32469  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
32470  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
32471  int fd;                           /* file desc to assoc this lock with */
32472};
32473
32474#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
32475
32476/*
32477** This is a utility for setting or clearing a bit-range lock on an
32478** AFP filesystem.
32479**
32480** Return SQLITE_OK on success, SQLITE_BUSY on failure.
32481*/
32482static int afpSetLock(
32483  const char *path,              /* Name of the file to be locked or unlocked */
32484  unixFile *pFile,               /* Open file descriptor on path */
32485  unsigned long long offset,     /* First byte to be locked */
32486  unsigned long long length,     /* Number of bytes to lock */
32487  int setLockFlag                /* True to set lock.  False to clear lock */
32488){
32489  struct ByteRangeLockPB2 pb;
32490  int err;
32491
32492  pb.unLockFlag = setLockFlag ? 0 : 1;
32493  pb.startEndFlag = 0;
32494  pb.offset = offset;
32495  pb.length = length;
32496  pb.fd = pFile->h;
32497
32498  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
32499    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
32500    offset, length));
32501  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
32502  if ( err==-1 ) {
32503    int rc;
32504    int tErrno = errno;
32505    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
32506             path, tErrno, strerror(tErrno)));
32507#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
32508    rc = SQLITE_BUSY;
32509#else
32510    rc = sqliteErrorFromPosixError(tErrno,
32511                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
32512#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
32513    if( IS_LOCK_ERROR(rc) ){
32514      storeLastErrno(pFile, tErrno);
32515    }
32516    return rc;
32517  } else {
32518    return SQLITE_OK;
32519  }
32520}
32521
32522/*
32523** This routine checks if there is a RESERVED lock held on the specified
32524** file by this or any other process. If such a lock is held, set *pResOut
32525** to a non-zero value otherwise *pResOut is set to zero.  The return value
32526** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32527*/
32528static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
32529  int rc = SQLITE_OK;
32530  int reserved = 0;
32531  unixFile *pFile = (unixFile*)id;
32532  afpLockingContext *context;
32533
32534  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32535
32536  assert( pFile );
32537  context = (afpLockingContext *) pFile->lockingContext;
32538  if( context->reserved ){
32539    *pResOut = 1;
32540    return SQLITE_OK;
32541  }
32542  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
32543
32544  /* Check if a thread in this process holds such a lock */
32545  if( pFile->pInode->eFileLock>SHARED_LOCK ){
32546    reserved = 1;
32547  }
32548
32549  /* Otherwise see if some other process holds it.
32550   */
32551  if( !reserved ){
32552    /* lock the RESERVED byte */
32553    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
32554    if( SQLITE_OK==lrc ){
32555      /* if we succeeded in taking the reserved lock, unlock it to restore
32556      ** the original state */
32557      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
32558    } else {
32559      /* if we failed to get the lock then someone else must have it */
32560      reserved = 1;
32561    }
32562    if( IS_LOCK_ERROR(lrc) ){
32563      rc=lrc;
32564    }
32565  }
32566
32567  unixLeaveMutex();
32568  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
32569
32570  *pResOut = reserved;
32571  return rc;
32572}
32573
32574/*
32575** Lock the file with the lock specified by parameter eFileLock - one
32576** of the following:
32577**
32578**     (1) SHARED_LOCK
32579**     (2) RESERVED_LOCK
32580**     (3) PENDING_LOCK
32581**     (4) EXCLUSIVE_LOCK
32582**
32583** Sometimes when requesting one lock state, additional lock states
32584** are inserted in between.  The locking might fail on one of the later
32585** transitions leaving the lock state different from what it started but
32586** still short of its goal.  The following chart shows the allowed
32587** transitions and the inserted intermediate states:
32588**
32589**    UNLOCKED -> SHARED
32590**    SHARED -> RESERVED
32591**    SHARED -> (PENDING) -> EXCLUSIVE
32592**    RESERVED -> (PENDING) -> EXCLUSIVE
32593**    PENDING -> EXCLUSIVE
32594**
32595** This routine will only increase a lock.  Use the sqlite3OsUnlock()
32596** routine to lower a locking level.
32597*/
32598static int afpLock(sqlite3_file *id, int eFileLock){
32599  int rc = SQLITE_OK;
32600  unixFile *pFile = (unixFile*)id;
32601  unixInodeInfo *pInode = pFile->pInode;
32602  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
32603
32604  assert( pFile );
32605  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
32606           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
32607           azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
32608
32609  /* If there is already a lock of this type or more restrictive on the
32610  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
32611  ** unixEnterMutex() hasn't been called yet.
32612  */
32613  if( pFile->eFileLock>=eFileLock ){
32614    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
32615           azFileLock(eFileLock)));
32616    return SQLITE_OK;
32617  }
32618
32619  /* Make sure the locking sequence is correct
32620  **  (1) We never move from unlocked to anything higher than shared lock.
32621  **  (2) SQLite never explicitly requests a pendig lock.
32622  **  (3) A shared lock is always held when a reserve lock is requested.
32623  */
32624  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
32625  assert( eFileLock!=PENDING_LOCK );
32626  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
32627
32628  /* This mutex is needed because pFile->pInode is shared across threads
32629  */
32630  unixEnterMutex();
32631  pInode = pFile->pInode;
32632
32633  /* If some thread using this PID has a lock via a different unixFile*
32634  ** handle that precludes the requested lock, return BUSY.
32635  */
32636  if( (pFile->eFileLock!=pInode->eFileLock &&
32637       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
32638     ){
32639    rc = SQLITE_BUSY;
32640    goto afp_end_lock;
32641  }
32642
32643  /* If a SHARED lock is requested, and some thread using this PID already
32644  ** has a SHARED or RESERVED lock, then increment reference counts and
32645  ** return SQLITE_OK.
32646  */
32647  if( eFileLock==SHARED_LOCK &&
32648     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
32649    assert( eFileLock==SHARED_LOCK );
32650    assert( pFile->eFileLock==0 );
32651    assert( pInode->nShared>0 );
32652    pFile->eFileLock = SHARED_LOCK;
32653    pInode->nShared++;
32654    pInode->nLock++;
32655    goto afp_end_lock;
32656  }
32657
32658  /* A PENDING lock is needed before acquiring a SHARED lock and before
32659  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
32660  ** be released.
32661  */
32662  if( eFileLock==SHARED_LOCK
32663      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
32664  ){
32665    int failed;
32666    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
32667    if (failed) {
32668      rc = failed;
32669      goto afp_end_lock;
32670    }
32671  }
32672
32673  /* If control gets to this point, then actually go ahead and make
32674  ** operating system calls for the specified lock.
32675  */
32676  if( eFileLock==SHARED_LOCK ){
32677    int lrc1, lrc2, lrc1Errno = 0;
32678    long lk, mask;
32679
32680    assert( pInode->nShared==0 );
32681    assert( pInode->eFileLock==0 );
32682
32683    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
32684    /* Now get the read-lock SHARED_LOCK */
32685    /* note that the quality of the randomness doesn't matter that much */
32686    lk = random();
32687    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
32688    lrc1 = afpSetLock(context->dbPath, pFile,
32689          SHARED_FIRST+pInode->sharedByte, 1, 1);
32690    if( IS_LOCK_ERROR(lrc1) ){
32691      lrc1Errno = pFile->lastErrno;
32692    }
32693    /* Drop the temporary PENDING lock */
32694    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
32695
32696    if( IS_LOCK_ERROR(lrc1) ) {
32697      storeLastErrno(pFile, lrc1Errno);
32698      rc = lrc1;
32699      goto afp_end_lock;
32700    } else if( IS_LOCK_ERROR(lrc2) ){
32701      rc = lrc2;
32702      goto afp_end_lock;
32703    } else if( lrc1 != SQLITE_OK ) {
32704      rc = lrc1;
32705    } else {
32706      pFile->eFileLock = SHARED_LOCK;
32707      pInode->nLock++;
32708      pInode->nShared = 1;
32709    }
32710  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
32711    /* We are trying for an exclusive lock but another thread in this
32712     ** same process is still holding a shared lock. */
32713    rc = SQLITE_BUSY;
32714  }else{
32715    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
32716    ** assumed that there is a SHARED or greater lock on the file
32717    ** already.
32718    */
32719    int failed = 0;
32720    assert( 0!=pFile->eFileLock );
32721    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
32722        /* Acquire a RESERVED lock */
32723        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
32724      if( !failed ){
32725        context->reserved = 1;
32726      }
32727    }
32728    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
32729      /* Acquire an EXCLUSIVE lock */
32730
32731      /* Remove the shared lock before trying the range.  we'll need to
32732      ** reestablish the shared lock if we can't get the  afpUnlock
32733      */
32734      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
32735                         pInode->sharedByte, 1, 0)) ){
32736        int failed2 = SQLITE_OK;
32737        /* now attemmpt to get the exclusive lock range */
32738        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
32739                               SHARED_SIZE, 1);
32740        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
32741                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
32742          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
32743          ** a critical I/O error
32744          */
32745          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
32746               SQLITE_IOERR_LOCK;
32747          goto afp_end_lock;
32748        }
32749      }else{
32750        rc = failed;
32751      }
32752    }
32753    if( failed ){
32754      rc = failed;
32755    }
32756  }
32757
32758  if( rc==SQLITE_OK ){
32759    pFile->eFileLock = eFileLock;
32760    pInode->eFileLock = eFileLock;
32761  }else if( eFileLock==EXCLUSIVE_LOCK ){
32762    pFile->eFileLock = PENDING_LOCK;
32763    pInode->eFileLock = PENDING_LOCK;
32764  }
32765
32766afp_end_lock:
32767  unixLeaveMutex();
32768  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
32769         rc==SQLITE_OK ? "ok" : "failed"));
32770  return rc;
32771}
32772
32773/*
32774** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32775** must be either NO_LOCK or SHARED_LOCK.
32776**
32777** If the locking level of the file descriptor is already at or below
32778** the requested locking level, this routine is a no-op.
32779*/
32780static int afpUnlock(sqlite3_file *id, int eFileLock) {
32781  int rc = SQLITE_OK;
32782  unixFile *pFile = (unixFile*)id;
32783  unixInodeInfo *pInode;
32784  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
32785  int skipShared = 0;
32786#ifdef SQLITE_TEST
32787  int h = pFile->h;
32788#endif
32789
32790  assert( pFile );
32791  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
32792           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
32793           osGetpid(0)));
32794
32795  assert( eFileLock<=SHARED_LOCK );
32796  if( pFile->eFileLock<=eFileLock ){
32797    return SQLITE_OK;
32798  }
32799  unixEnterMutex();
32800  pInode = pFile->pInode;
32801  assert( pInode->nShared!=0 );
32802  if( pFile->eFileLock>SHARED_LOCK ){
32803    assert( pInode->eFileLock==pFile->eFileLock );
32804    SimulateIOErrorBenign(1);
32805    SimulateIOError( h=(-1) )
32806    SimulateIOErrorBenign(0);
32807
32808#ifdef SQLITE_DEBUG
32809    /* When reducing a lock such that other processes can start
32810    ** reading the database file again, make sure that the
32811    ** transaction counter was updated if any part of the database
32812    ** file changed.  If the transaction counter is not updated,
32813    ** other connections to the same file might not realize that
32814    ** the file has changed and hence might not know to flush their
32815    ** cache.  The use of a stale cache can lead to database corruption.
32816    */
32817    assert( pFile->inNormalWrite==0
32818           || pFile->dbUpdate==0
32819           || pFile->transCntrChng==1 );
32820    pFile->inNormalWrite = 0;
32821#endif
32822
32823    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
32824      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
32825      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
32826        /* only re-establish the shared lock if necessary */
32827        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
32828        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
32829      } else {
32830        skipShared = 1;
32831      }
32832    }
32833    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
32834      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
32835    }
32836    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
32837      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
32838      if( !rc ){
32839        context->reserved = 0;
32840      }
32841    }
32842    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
32843      pInode->eFileLock = SHARED_LOCK;
32844    }
32845  }
32846  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
32847
32848    /* Decrement the shared lock counter.  Release the lock using an
32849    ** OS call only when all threads in this same process have released
32850    ** the lock.
32851    */
32852    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
32853    pInode->nShared--;
32854    if( pInode->nShared==0 ){
32855      SimulateIOErrorBenign(1);
32856      SimulateIOError( h=(-1) )
32857      SimulateIOErrorBenign(0);
32858      if( !skipShared ){
32859        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
32860      }
32861      if( !rc ){
32862        pInode->eFileLock = NO_LOCK;
32863        pFile->eFileLock = NO_LOCK;
32864      }
32865    }
32866    if( rc==SQLITE_OK ){
32867      pInode->nLock--;
32868      assert( pInode->nLock>=0 );
32869      if( pInode->nLock==0 ){
32870        closePendingFds(pFile);
32871      }
32872    }
32873  }
32874
32875  unixLeaveMutex();
32876  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
32877  return rc;
32878}
32879
32880/*
32881** Close a file & cleanup AFP specific locking context
32882*/
32883static int afpClose(sqlite3_file *id) {
32884  int rc = SQLITE_OK;
32885  unixFile *pFile = (unixFile*)id;
32886  assert( id!=0 );
32887  afpUnlock(id, NO_LOCK);
32888  unixEnterMutex();
32889  if( pFile->pInode && pFile->pInode->nLock ){
32890    /* If there are outstanding locks, do not actually close the file just
32891    ** yet because that would clear those locks.  Instead, add the file
32892    ** descriptor to pInode->aPending.  It will be automatically closed when
32893    ** the last lock is cleared.
32894    */
32895    setPendingFd(pFile);
32896  }
32897  releaseInodeInfo(pFile);
32898  sqlite3_free(pFile->lockingContext);
32899  rc = closeUnixFile(id);
32900  unixLeaveMutex();
32901  return rc;
32902}
32903
32904#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32905/*
32906** The code above is the AFP lock implementation.  The code is specific
32907** to MacOSX and does not work on other unix platforms.  No alternative
32908** is available.  If you don't compile for a mac, then the "unix-afp"
32909** VFS is not available.
32910**
32911********************* End of the AFP lock implementation **********************
32912******************************************************************************/
32913
32914/******************************************************************************
32915*************************** Begin NFS Locking ********************************/
32916
32917#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
32918/*
32919 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32920 ** must be either NO_LOCK or SHARED_LOCK.
32921 **
32922 ** If the locking level of the file descriptor is already at or below
32923 ** the requested locking level, this routine is a no-op.
32924 */
32925static int nfsUnlock(sqlite3_file *id, int eFileLock){
32926  return posixUnlock(id, eFileLock, 1);
32927}
32928
32929#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32930/*
32931** The code above is the NFS lock implementation.  The code is specific
32932** to MacOSX and does not work on other unix platforms.  No alternative
32933** is available.
32934**
32935********************* End of the NFS lock implementation **********************
32936******************************************************************************/
32937
32938/******************************************************************************
32939**************** Non-locking sqlite3_file methods *****************************
32940**
32941** The next division contains implementations for all methods of the
32942** sqlite3_file object other than the locking methods.  The locking
32943** methods were defined in divisions above (one locking method per
32944** division).  Those methods that are common to all locking modes
32945** are gather together into this division.
32946*/
32947
32948/*
32949** Seek to the offset passed as the second argument, then read cnt
32950** bytes into pBuf. Return the number of bytes actually read.
32951**
32952** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
32953** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
32954** one system to another.  Since SQLite does not define USE_PREAD
32955** in any form by default, we will not attempt to define _XOPEN_SOURCE.
32956** See tickets #2741 and #2681.
32957**
32958** To avoid stomping the errno value on a failed read the lastErrno value
32959** is set before returning.
32960*/
32961static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
32962  int got;
32963  int prior = 0;
32964#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
32965  i64 newOffset;
32966#endif
32967  TIMER_START;
32968  assert( cnt==(cnt&0x1ffff) );
32969  assert( id->h>2 );
32970  do{
32971#if defined(USE_PREAD)
32972    got = osPread(id->h, pBuf, cnt, offset);
32973    SimulateIOError( got = -1 );
32974#elif defined(USE_PREAD64)
32975    got = osPread64(id->h, pBuf, cnt, offset);
32976    SimulateIOError( got = -1 );
32977#else
32978    newOffset = lseek(id->h, offset, SEEK_SET);
32979    SimulateIOError( newOffset = -1 );
32980    if( newOffset<0 ){
32981      storeLastErrno((unixFile*)id, errno);
32982      return -1;
32983    }
32984    got = osRead(id->h, pBuf, cnt);
32985#endif
32986    if( got==cnt ) break;
32987    if( got<0 ){
32988      if( errno==EINTR ){ got = 1; continue; }
32989      prior = 0;
32990      storeLastErrno((unixFile*)id,  errno);
32991      break;
32992    }else if( got>0 ){
32993      cnt -= got;
32994      offset += got;
32995      prior += got;
32996      pBuf = (void*)(got + (char*)pBuf);
32997    }
32998  }while( got>0 );
32999  TIMER_END;
33000  OSTRACE(("READ    %-3d %5d %7lld %llu\n",
33001            id->h, got+prior, offset-prior, TIMER_ELAPSED));
33002  return got+prior;
33003}
33004
33005/*
33006** Read data from a file into a buffer.  Return SQLITE_OK if all
33007** bytes were read successfully and SQLITE_IOERR if anything goes
33008** wrong.
33009*/
33010static int unixRead(
33011  sqlite3_file *id,
33012  void *pBuf,
33013  int amt,
33014  sqlite3_int64 offset
33015){
33016  unixFile *pFile = (unixFile *)id;
33017  int got;
33018  assert( id );
33019  assert( offset>=0 );
33020  assert( amt>0 );
33021
33022  /* If this is a database file (not a journal, master-journal or temp
33023  ** file), the bytes in the locking range should never be read or written. */
33024#if 0
33025  assert( pFile->pUnused==0
33026       || offset>=PENDING_BYTE+512
33027       || offset+amt<=PENDING_BYTE
33028  );
33029#endif
33030
33031#if SQLITE_MAX_MMAP_SIZE>0
33032  /* Deal with as much of this read request as possible by transfering
33033  ** data from the memory mapping using memcpy().  */
33034  if( offset<pFile->mmapSize ){
33035    if( offset+amt <= pFile->mmapSize ){
33036      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
33037      return SQLITE_OK;
33038    }else{
33039      int nCopy = pFile->mmapSize - offset;
33040      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
33041      pBuf = &((u8 *)pBuf)[nCopy];
33042      amt -= nCopy;
33043      offset += nCopy;
33044    }
33045  }
33046#endif
33047
33048  got = seekAndRead(pFile, offset, pBuf, amt);
33049  if( got==amt ){
33050    return SQLITE_OK;
33051  }else if( got<0 ){
33052    /* lastErrno set by seekAndRead */
33053    return SQLITE_IOERR_READ;
33054  }else{
33055    storeLastErrno(pFile, 0);   /* not a system error */
33056    /* Unread parts of the buffer must be zero-filled */
33057    memset(&((char*)pBuf)[got], 0, amt-got);
33058    return SQLITE_IOERR_SHORT_READ;
33059  }
33060}
33061
33062/*
33063** Attempt to seek the file-descriptor passed as the first argument to
33064** absolute offset iOff, then attempt to write nBuf bytes of data from
33065** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
33066** return the actual number of bytes written (which may be less than
33067** nBuf).
33068*/
33069static int seekAndWriteFd(
33070  int fd,                         /* File descriptor to write to */
33071  i64 iOff,                       /* File offset to begin writing at */
33072  const void *pBuf,               /* Copy data from this buffer to the file */
33073  int nBuf,                       /* Size of buffer pBuf in bytes */
33074  int *piErrno                    /* OUT: Error number if error occurs */
33075){
33076  int rc = 0;                     /* Value returned by system call */
33077
33078  assert( nBuf==(nBuf&0x1ffff) );
33079  assert( fd>2 );
33080  assert( piErrno!=0 );
33081  nBuf &= 0x1ffff;
33082  TIMER_START;
33083
33084#if defined(USE_PREAD)
33085  do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
33086#elif defined(USE_PREAD64)
33087  do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
33088#else
33089  do{
33090    i64 iSeek = lseek(fd, iOff, SEEK_SET);
33091    SimulateIOError( iSeek = -1 );
33092    if( iSeek<0 ){
33093      rc = -1;
33094      break;
33095    }
33096    rc = osWrite(fd, pBuf, nBuf);
33097  }while( rc<0 && errno==EINTR );
33098#endif
33099
33100  TIMER_END;
33101  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
33102
33103  if( rc<0 ) *piErrno = errno;
33104  return rc;
33105}
33106
33107
33108/*
33109** Seek to the offset in id->offset then read cnt bytes into pBuf.
33110** Return the number of bytes actually read.  Update the offset.
33111**
33112** To avoid stomping the errno value on a failed write the lastErrno value
33113** is set before returning.
33114*/
33115static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
33116  return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
33117}
33118
33119
33120/*
33121** Write data from a buffer into a file.  Return SQLITE_OK on success
33122** or some other error code on failure.
33123*/
33124static int unixWrite(
33125  sqlite3_file *id,
33126  const void *pBuf,
33127  int amt,
33128  sqlite3_int64 offset
33129){
33130  unixFile *pFile = (unixFile*)id;
33131  int wrote = 0;
33132  assert( id );
33133  assert( amt>0 );
33134
33135  /* If this is a database file (not a journal, master-journal or temp
33136  ** file), the bytes in the locking range should never be read or written. */
33137#if 0
33138  assert( pFile->pUnused==0
33139       || offset>=PENDING_BYTE+512
33140       || offset+amt<=PENDING_BYTE
33141  );
33142#endif
33143
33144#ifdef SQLITE_DEBUG
33145  /* If we are doing a normal write to a database file (as opposed to
33146  ** doing a hot-journal rollback or a write to some file other than a
33147  ** normal database file) then record the fact that the database
33148  ** has changed.  If the transaction counter is modified, record that
33149  ** fact too.
33150  */
33151  if( pFile->inNormalWrite ){
33152    pFile->dbUpdate = 1;  /* The database has been modified */
33153    if( offset<=24 && offset+amt>=27 ){
33154      int rc;
33155      char oldCntr[4];
33156      SimulateIOErrorBenign(1);
33157      rc = seekAndRead(pFile, 24, oldCntr, 4);
33158      SimulateIOErrorBenign(0);
33159      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
33160        pFile->transCntrChng = 1;  /* The transaction counter has changed */
33161      }
33162    }
33163  }
33164#endif
33165
33166#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
33167  /* Deal with as much of this write request as possible by transfering
33168  ** data from the memory mapping using memcpy().  */
33169  if( offset<pFile->mmapSize ){
33170    if( offset+amt <= pFile->mmapSize ){
33171      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
33172      return SQLITE_OK;
33173    }else{
33174      int nCopy = pFile->mmapSize - offset;
33175      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
33176      pBuf = &((u8 *)pBuf)[nCopy];
33177      amt -= nCopy;
33178      offset += nCopy;
33179    }
33180  }
33181#endif
33182
33183  while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
33184    amt -= wrote;
33185    offset += wrote;
33186    pBuf = &((char*)pBuf)[wrote];
33187  }
33188  SimulateIOError(( wrote=(-1), amt=1 ));
33189  SimulateDiskfullError(( wrote=0, amt=1 ));
33190
33191  if( amt>wrote ){
33192    if( wrote<0 && pFile->lastErrno!=ENOSPC ){
33193      /* lastErrno set by seekAndWrite */
33194      return SQLITE_IOERR_WRITE;
33195    }else{
33196      storeLastErrno(pFile, 0); /* not a system error */
33197      return SQLITE_FULL;
33198    }
33199  }
33200
33201  return SQLITE_OK;
33202}
33203
33204#ifdef SQLITE_TEST
33205/*
33206** Count the number of fullsyncs and normal syncs.  This is used to test
33207** that syncs and fullsyncs are occurring at the right times.
33208*/
33209SQLITE_API int sqlite3_sync_count = 0;
33210SQLITE_API int sqlite3_fullsync_count = 0;
33211#endif
33212
33213/*
33214** We do not trust systems to provide a working fdatasync().  Some do.
33215** Others do no.  To be safe, we will stick with the (slightly slower)
33216** fsync(). If you know that your system does support fdatasync() correctly,
33217** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
33218*/
33219#if !defined(fdatasync) && !HAVE_FDATASYNC
33220# define fdatasync fsync
33221#endif
33222
33223/*
33224** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
33225** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
33226** only available on Mac OS X.  But that could change.
33227*/
33228#ifdef F_FULLFSYNC
33229# define HAVE_FULLFSYNC 1
33230#else
33231# define HAVE_FULLFSYNC 0
33232#endif
33233
33234
33235/*
33236** The fsync() system call does not work as advertised on many
33237** unix systems.  The following procedure is an attempt to make
33238** it work better.
33239**
33240** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
33241** for testing when we want to run through the test suite quickly.
33242** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
33243** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
33244** or power failure will likely corrupt the database file.
33245**
33246** SQLite sets the dataOnly flag if the size of the file is unchanged.
33247** The idea behind dataOnly is that it should only write the file content
33248** to disk, not the inode.  We only set dataOnly if the file size is
33249** unchanged since the file size is part of the inode.  However,
33250** Ted Ts'o tells us that fdatasync() will also write the inode if the
33251** file size has changed.  The only real difference between fdatasync()
33252** and fsync(), Ted tells us, is that fdatasync() will not flush the
33253** inode if the mtime or owner or other inode attributes have changed.
33254** We only care about the file size, not the other file attributes, so
33255** as far as SQLite is concerned, an fdatasync() is always adequate.
33256** So, we always use fdatasync() if it is available, regardless of
33257** the value of the dataOnly flag.
33258*/
33259static int full_fsync(int fd, int fullSync, int dataOnly){
33260  int rc;
33261
33262  /* The following "ifdef/elif/else/" block has the same structure as
33263  ** the one below. It is replicated here solely to avoid cluttering
33264  ** up the real code with the UNUSED_PARAMETER() macros.
33265  */
33266#ifdef SQLITE_NO_SYNC
33267  UNUSED_PARAMETER(fd);
33268  UNUSED_PARAMETER(fullSync);
33269  UNUSED_PARAMETER(dataOnly);
33270#elif HAVE_FULLFSYNC
33271  UNUSED_PARAMETER(dataOnly);
33272#else
33273  UNUSED_PARAMETER(fullSync);
33274  UNUSED_PARAMETER(dataOnly);
33275#endif
33276
33277  /* Record the number of times that we do a normal fsync() and
33278  ** FULLSYNC.  This is used during testing to verify that this procedure
33279  ** gets called with the correct arguments.
33280  */
33281#ifdef SQLITE_TEST
33282  if( fullSync ) sqlite3_fullsync_count++;
33283  sqlite3_sync_count++;
33284#endif
33285
33286  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
33287  ** no-op.  But go ahead and call fstat() to validate the file
33288  ** descriptor as we need a method to provoke a failure during
33289  ** coverate testing.
33290  */
33291#ifdef SQLITE_NO_SYNC
33292  {
33293    struct stat buf;
33294    rc = osFstat(fd, &buf);
33295  }
33296#elif HAVE_FULLFSYNC
33297  if( fullSync ){
33298    rc = osFcntl(fd, F_FULLFSYNC, 0);
33299  }else{
33300    rc = 1;
33301  }
33302  /* If the FULLFSYNC failed, fall back to attempting an fsync().
33303  ** It shouldn't be possible for fullfsync to fail on the local
33304  ** file system (on OSX), so failure indicates that FULLFSYNC
33305  ** isn't supported for this file system. So, attempt an fsync
33306  ** and (for now) ignore the overhead of a superfluous fcntl call.
33307  ** It'd be better to detect fullfsync support once and avoid
33308  ** the fcntl call every time sync is called.
33309  */
33310  if( rc ) rc = fsync(fd);
33311
33312#elif defined(__APPLE__)
33313  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
33314  ** so currently we default to the macro that redefines fdatasync to fsync
33315  */
33316  rc = fsync(fd);
33317#else
33318  rc = fdatasync(fd);
33319#if OS_VXWORKS
33320  if( rc==-1 && errno==ENOTSUP ){
33321    rc = fsync(fd);
33322  }
33323#endif /* OS_VXWORKS */
33324#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
33325
33326  if( OS_VXWORKS && rc!= -1 ){
33327    rc = 0;
33328  }
33329  return rc;
33330}
33331
33332/*
33333** Open a file descriptor to the directory containing file zFilename.
33334** If successful, *pFd is set to the opened file descriptor and
33335** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
33336** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
33337** value.
33338**
33339** The directory file descriptor is used for only one thing - to
33340** fsync() a directory to make sure file creation and deletion events
33341** are flushed to disk.  Such fsyncs are not needed on newer
33342** journaling filesystems, but are required on older filesystems.
33343**
33344** This routine can be overridden using the xSetSysCall interface.
33345** The ability to override this routine was added in support of the
33346** chromium sandbox.  Opening a directory is a security risk (we are
33347** told) so making it overrideable allows the chromium sandbox to
33348** replace this routine with a harmless no-op.  To make this routine
33349** a no-op, replace it with a stub that returns SQLITE_OK but leaves
33350** *pFd set to a negative number.
33351**
33352** If SQLITE_OK is returned, the caller is responsible for closing
33353** the file descriptor *pFd using close().
33354*/
33355static int openDirectory(const char *zFilename, int *pFd){
33356  int ii;
33357  int fd = -1;
33358  char zDirname[MAX_PATHNAME+1];
33359
33360  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
33361  for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
33362  if( ii>0 ){
33363    zDirname[ii] = '\0';
33364  }else{
33365    if( zDirname[0]!='/' ) zDirname[0] = '.';
33366    zDirname[1] = 0;
33367  }
33368  fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
33369  if( fd>=0 ){
33370    OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
33371  }
33372  *pFd = fd;
33373  if( fd>=0 ) return SQLITE_OK;
33374  return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
33375}
33376
33377/*
33378** Make sure all writes to a particular file are committed to disk.
33379**
33380** If dataOnly==0 then both the file itself and its metadata (file
33381** size, access time, etc) are synced.  If dataOnly!=0 then only the
33382** file data is synced.
33383**
33384** Under Unix, also make sure that the directory entry for the file
33385** has been created by fsync-ing the directory that contains the file.
33386** If we do not do this and we encounter a power failure, the directory
33387** entry for the journal might not exist after we reboot.  The next
33388** SQLite to access the file will not know that the journal exists (because
33389** the directory entry for the journal was never created) and the transaction
33390** will not roll back - possibly leading to database corruption.
33391*/
33392static int unixSync(sqlite3_file *id, int flags){
33393  int rc;
33394  unixFile *pFile = (unixFile*)id;
33395
33396  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
33397  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
33398
33399  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
33400  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
33401      || (flags&0x0F)==SQLITE_SYNC_FULL
33402  );
33403
33404  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
33405  ** line is to test that doing so does not cause any problems.
33406  */
33407  SimulateDiskfullError( return SQLITE_FULL );
33408
33409  assert( pFile );
33410  OSTRACE(("SYNC    %-3d\n", pFile->h));
33411  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
33412  SimulateIOError( rc=1 );
33413  if( rc ){
33414    storeLastErrno(pFile, errno);
33415    return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
33416  }
33417
33418  /* Also fsync the directory containing the file if the DIRSYNC flag
33419  ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
33420  ** are unable to fsync a directory, so ignore errors on the fsync.
33421  */
33422  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
33423    int dirfd;
33424    OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
33425            HAVE_FULLFSYNC, isFullsync));
33426    rc = osOpenDirectory(pFile->zPath, &dirfd);
33427    if( rc==SQLITE_OK ){
33428      full_fsync(dirfd, 0, 0);
33429      robust_close(pFile, dirfd, __LINE__);
33430    }else{
33431      assert( rc==SQLITE_CANTOPEN );
33432      rc = SQLITE_OK;
33433    }
33434    pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
33435  }
33436  return rc;
33437}
33438
33439/*
33440** Truncate an open file to a specified size
33441*/
33442static int unixTruncate(sqlite3_file *id, i64 nByte){
33443  unixFile *pFile = (unixFile *)id;
33444  int rc;
33445  assert( pFile );
33446  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
33447
33448  /* If the user has configured a chunk-size for this file, truncate the
33449  ** file so that it consists of an integer number of chunks (i.e. the
33450  ** actual file size after the operation may be larger than the requested
33451  ** size).
33452  */
33453  if( pFile->szChunk>0 ){
33454    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
33455  }
33456
33457  rc = robust_ftruncate(pFile->h, nByte);
33458  if( rc ){
33459    storeLastErrno(pFile, errno);
33460    return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
33461  }else{
33462#ifdef SQLITE_DEBUG
33463    /* If we are doing a normal write to a database file (as opposed to
33464    ** doing a hot-journal rollback or a write to some file other than a
33465    ** normal database file) and we truncate the file to zero length,
33466    ** that effectively updates the change counter.  This might happen
33467    ** when restoring a database using the backup API from a zero-length
33468    ** source.
33469    */
33470    if( pFile->inNormalWrite && nByte==0 ){
33471      pFile->transCntrChng = 1;
33472    }
33473#endif
33474
33475#if SQLITE_MAX_MMAP_SIZE>0
33476    /* If the file was just truncated to a size smaller than the currently
33477    ** mapped region, reduce the effective mapping size as well. SQLite will
33478    ** use read() and write() to access data beyond this point from now on.
33479    */
33480    if( nByte<pFile->mmapSize ){
33481      pFile->mmapSize = nByte;
33482    }
33483#endif
33484
33485    return SQLITE_OK;
33486  }
33487}
33488
33489/*
33490** Determine the current size of a file in bytes
33491*/
33492static int unixFileSize(sqlite3_file *id, i64 *pSize){
33493  int rc;
33494  struct stat buf;
33495  assert( id );
33496  rc = osFstat(((unixFile*)id)->h, &buf);
33497  SimulateIOError( rc=1 );
33498  if( rc!=0 ){
33499    storeLastErrno((unixFile*)id, errno);
33500    return unixLogError(SQLITE_IOERR_FSTAT, "fstat", ((unixFile*)id)->zPath);
33501  }
33502  *pSize = buf.st_size;
33503
33504  /* When opening a zero-size database, the findInodeInfo() procedure
33505  ** writes a single byte into that file in order to work around a bug
33506  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
33507  ** layers, we need to report this file size as zero even though it is
33508  ** really 1.   Ticket #3260.
33509  */
33510  if( *pSize==1 ) *pSize = 0;
33511
33512
33513  return SQLITE_OK;
33514}
33515
33516#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
33517/*
33518** Handler for proxy-locking file-control verbs.  Defined below in the
33519** proxying locking division.
33520*/
33521static int proxyFileControl(sqlite3_file*,int,void*);
33522#endif
33523
33524/*
33525** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
33526** file-control operation.  Enlarge the database to nBytes in size
33527** (rounded up to the next chunk-size).  If the database is already
33528** nBytes or larger, this routine is a no-op.
33529*/
33530static int fcntlSizeHint(unixFile *pFile, i64 nByte){
33531  if( pFile->szChunk>0 ){
33532    i64 nSize;                    /* Required file size */
33533    struct stat buf;              /* Used to hold return values of fstat() */
33534
33535    if( osFstat(pFile->h, &buf) ){
33536      return unixLogError(SQLITE_IOERR_FSTAT, "fstat", pFile->zPath);
33537    }
33538
33539    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
33540    if( nSize>(i64)buf.st_size ){
33541
33542#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
33543      /* The code below is handling the return value of osFallocate()
33544      ** correctly. posix_fallocate() is defined to "returns zero on success,
33545      ** or an error number on  failure". See the manpage for details. */
33546      int err;
33547      do{
33548        err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
33549      }while( err==EINTR );
33550      if( err ) return SQLITE_IOERR_WRITE;
33551#else
33552      /* If the OS does not have posix_fallocate(), fake it. Write a
33553      ** single byte to the last byte in each block that falls entirely
33554      ** within the extended region. Then, if required, a single byte
33555      ** at offset (nSize-1), to set the size of the file correctly.
33556      ** This is a similar technique to that used by glibc on systems
33557      ** that do not have a real fallocate() call.
33558      */
33559      int nBlk = buf.st_blksize;  /* File-system block size */
33560      int nWrite = 0;             /* Number of bytes written by seekAndWrite */
33561      i64 iWrite;                 /* Next offset to write to */
33562
33563      iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
33564      assert( iWrite>=buf.st_size );
33565      assert( ((iWrite+1)%nBlk)==0 );
33566      for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
33567        if( iWrite>=nSize ) iWrite = nSize - 1;
33568        nWrite = seekAndWrite(pFile, iWrite, "", 1);
33569        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
33570      }
33571#endif
33572    }
33573  }
33574
33575#if SQLITE_MAX_MMAP_SIZE>0
33576  if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
33577    int rc;
33578    if( pFile->szChunk<=0 ){
33579      if( robust_ftruncate(pFile->h, nByte) ){
33580        storeLastErrno(pFile, errno);
33581        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
33582      }
33583    }
33584
33585    rc = unixMapfile(pFile, nByte);
33586    return rc;
33587  }
33588#endif
33589
33590  return SQLITE_OK;
33591}
33592
33593/*
33594** If *pArg is initially negative then this is a query.  Set *pArg to
33595** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
33596**
33597** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
33598*/
33599static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
33600  if( *pArg<0 ){
33601    *pArg = (pFile->ctrlFlags & mask)!=0;
33602  }else if( (*pArg)==0 ){
33603    pFile->ctrlFlags &= ~mask;
33604  }else{
33605    pFile->ctrlFlags |= mask;
33606  }
33607}
33608
33609/* Forward declaration */
33610static int unixGetTempname(int nBuf, char *zBuf);
33611
33612/*
33613** Information and control of an open file handle.
33614*/
33615static int unixFileControl(sqlite3_file *id, int op, void *pArg){
33616  unixFile *pFile = (unixFile*)id;
33617  switch( op ){
33618    case SQLITE_FCNTL_LOCKSTATE: {
33619      *(int*)pArg = pFile->eFileLock;
33620      return SQLITE_OK;
33621    }
33622    case SQLITE_FCNTL_LAST_ERRNO: {
33623      *(int*)pArg = pFile->lastErrno;
33624      return SQLITE_OK;
33625    }
33626    case SQLITE_FCNTL_CHUNK_SIZE: {
33627      pFile->szChunk = *(int *)pArg;
33628      return SQLITE_OK;
33629    }
33630    case SQLITE_FCNTL_SIZE_HINT: {
33631      int rc;
33632      SimulateIOErrorBenign(1);
33633      rc = fcntlSizeHint(pFile, *(i64 *)pArg);
33634      SimulateIOErrorBenign(0);
33635      return rc;
33636    }
33637    case SQLITE_FCNTL_PERSIST_WAL: {
33638      unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
33639      return SQLITE_OK;
33640    }
33641    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
33642      unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
33643      return SQLITE_OK;
33644    }
33645    case SQLITE_FCNTL_VFSNAME: {
33646      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
33647      return SQLITE_OK;
33648    }
33649    case SQLITE_FCNTL_TEMPFILENAME: {
33650      char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
33651      if( zTFile ){
33652        unixGetTempname(pFile->pVfs->mxPathname, zTFile);
33653        *(char**)pArg = zTFile;
33654      }
33655      return SQLITE_OK;
33656    }
33657    case SQLITE_FCNTL_HAS_MOVED: {
33658      *(int*)pArg = fileHasMoved(pFile);
33659      return SQLITE_OK;
33660    }
33661#if SQLITE_MAX_MMAP_SIZE>0
33662    case SQLITE_FCNTL_MMAP_SIZE: {
33663      i64 newLimit = *(i64*)pArg;
33664      int rc = SQLITE_OK;
33665      if( newLimit>sqlite3GlobalConfig.mxMmap ){
33666        newLimit = sqlite3GlobalConfig.mxMmap;
33667      }
33668      *(i64*)pArg = pFile->mmapSizeMax;
33669      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
33670        pFile->mmapSizeMax = newLimit;
33671        if( pFile->mmapSize>0 ){
33672          unixUnmapfile(pFile);
33673          rc = unixMapfile(pFile, -1);
33674        }
33675      }
33676      return rc;
33677    }
33678#endif
33679#ifdef SQLITE_DEBUG
33680    /* The pager calls this method to signal that it has done
33681    ** a rollback and that the database is therefore unchanged and
33682    ** it hence it is OK for the transaction change counter to be
33683    ** unchanged.
33684    */
33685    case SQLITE_FCNTL_DB_UNCHANGED: {
33686      ((unixFile*)id)->dbUpdate = 0;
33687      return SQLITE_OK;
33688    }
33689#endif
33690#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
33691    case SQLITE_FCNTL_SET_LOCKPROXYFILE:
33692    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
33693      return proxyFileControl(id,op,pArg);
33694    }
33695#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
33696  }
33697  return SQLITE_NOTFOUND;
33698}
33699
33700/*
33701** Return the sector size in bytes of the underlying block device for
33702** the specified file. This is almost always 512 bytes, but may be
33703** larger for some devices.
33704**
33705** SQLite code assumes this function cannot fail. It also assumes that
33706** if two files are created in the same file-system directory (i.e.
33707** a database and its journal file) that the sector size will be the
33708** same for both.
33709*/
33710#ifndef __QNXNTO__
33711static int unixSectorSize(sqlite3_file *NotUsed){
33712  UNUSED_PARAMETER(NotUsed);
33713  return SQLITE_DEFAULT_SECTOR_SIZE;
33714}
33715#endif
33716
33717/*
33718** The following version of unixSectorSize() is optimized for QNX.
33719*/
33720#ifdef __QNXNTO__
33721#include <sys/dcmd_blk.h>
33722#include <sys/statvfs.h>
33723static int unixSectorSize(sqlite3_file *id){
33724  unixFile *pFile = (unixFile*)id;
33725  if( pFile->sectorSize == 0 ){
33726    struct statvfs fsInfo;
33727
33728    /* Set defaults for non-supported filesystems */
33729    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
33730    pFile->deviceCharacteristics = 0;
33731    if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
33732      return pFile->sectorSize;
33733    }
33734
33735    if( !strcmp(fsInfo.f_basetype, "tmp") ) {
33736      pFile->sectorSize = fsInfo.f_bsize;
33737      pFile->deviceCharacteristics =
33738        SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
33739        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
33740                                      ** the write succeeds */
33741        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33742                                      ** so it is ordered */
33743        0;
33744    }else if( strstr(fsInfo.f_basetype, "etfs") ){
33745      pFile->sectorSize = fsInfo.f_bsize;
33746      pFile->deviceCharacteristics =
33747        /* etfs cluster size writes are atomic */
33748        (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
33749        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
33750                                      ** the write succeeds */
33751        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33752                                      ** so it is ordered */
33753        0;
33754    }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
33755      pFile->sectorSize = fsInfo.f_bsize;
33756      pFile->deviceCharacteristics =
33757        SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
33758        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
33759                                      ** the write succeeds */
33760        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33761                                      ** so it is ordered */
33762        0;
33763    }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
33764      pFile->sectorSize = fsInfo.f_bsize;
33765      pFile->deviceCharacteristics =
33766        /* full bitset of atomics from max sector size and smaller */
33767        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
33768        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33769                                      ** so it is ordered */
33770        0;
33771    }else if( strstr(fsInfo.f_basetype, "dos") ){
33772      pFile->sectorSize = fsInfo.f_bsize;
33773      pFile->deviceCharacteristics =
33774        /* full bitset of atomics from max sector size and smaller */
33775        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
33776        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33777                                      ** so it is ordered */
33778        0;
33779    }else{
33780      pFile->deviceCharacteristics =
33781        SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
33782        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
33783                                      ** the write succeeds */
33784        0;
33785    }
33786  }
33787  /* Last chance verification.  If the sector size isn't a multiple of 512
33788  ** then it isn't valid.*/
33789  if( pFile->sectorSize % 512 != 0 ){
33790    pFile->deviceCharacteristics = 0;
33791    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
33792  }
33793  return pFile->sectorSize;
33794}
33795#endif /* __QNXNTO__ */
33796
33797/*
33798** Return the device characteristics for the file.
33799**
33800** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
33801** However, that choice is controversial since technically the underlying
33802** file system does not always provide powersafe overwrites.  (In other
33803** words, after a power-loss event, parts of the file that were never
33804** written might end up being altered.)  However, non-PSOW behavior is very,
33805** very rare.  And asserting PSOW makes a large reduction in the amount
33806** of required I/O for journaling, since a lot of padding is eliminated.
33807**  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
33808** available to turn it off and URI query parameter available to turn it off.
33809*/
33810static int unixDeviceCharacteristics(sqlite3_file *id){
33811  unixFile *p = (unixFile*)id;
33812  int rc = 0;
33813#ifdef __QNXNTO__
33814  if( p->sectorSize==0 ) unixSectorSize(id);
33815  rc = p->deviceCharacteristics;
33816#endif
33817  if( p->ctrlFlags & UNIXFILE_PSOW ){
33818    rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
33819  }
33820  return rc;
33821}
33822
33823#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
33824
33825/*
33826** Return the system page size.
33827**
33828** This function should not be called directly by other code in this file.
33829** Instead, it should be called via macro osGetpagesize().
33830*/
33831static int unixGetpagesize(void){
33832#if OS_VXWORKS
33833  return 1024;
33834#elif defined(_BSD_SOURCE)
33835  return getpagesize();
33836#else
33837  return (int)sysconf(_SC_PAGESIZE);
33838#endif
33839}
33840
33841#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
33842
33843#ifndef SQLITE_OMIT_WAL
33844
33845/*
33846** Object used to represent an shared memory buffer.
33847**
33848** When multiple threads all reference the same wal-index, each thread
33849** has its own unixShm object, but they all point to a single instance
33850** of this unixShmNode object.  In other words, each wal-index is opened
33851** only once per process.
33852**
33853** Each unixShmNode object is connected to a single unixInodeInfo object.
33854** We could coalesce this object into unixInodeInfo, but that would mean
33855** every open file that does not use shared memory (in other words, most
33856** open files) would have to carry around this extra information.  So
33857** the unixInodeInfo object contains a pointer to this unixShmNode object
33858** and the unixShmNode object is created only when needed.
33859**
33860** unixMutexHeld() must be true when creating or destroying
33861** this object or while reading or writing the following fields:
33862**
33863**      nRef
33864**
33865** The following fields are read-only after the object is created:
33866**
33867**      fid
33868**      zFilename
33869**
33870** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
33871** unixMutexHeld() is true when reading or writing any other field
33872** in this structure.
33873*/
33874struct unixShmNode {
33875  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
33876  sqlite3_mutex *mutex;      /* Mutex to access this object */
33877  char *zFilename;           /* Name of the mmapped file */
33878  int h;                     /* Open file descriptor */
33879  int szRegion;              /* Size of shared-memory regions */
33880  u16 nRegion;               /* Size of array apRegion */
33881  u8 isReadonly;             /* True if read-only */
33882  char **apRegion;           /* Array of mapped shared-memory regions */
33883  int nRef;                  /* Number of unixShm objects pointing to this */
33884  unixShm *pFirst;           /* All unixShm objects pointing to this */
33885#ifdef SQLITE_DEBUG
33886  u8 exclMask;               /* Mask of exclusive locks held */
33887  u8 sharedMask;             /* Mask of shared locks held */
33888  u8 nextShmId;              /* Next available unixShm.id value */
33889#endif
33890};
33891
33892/*
33893** Structure used internally by this VFS to record the state of an
33894** open shared memory connection.
33895**
33896** The following fields are initialized when this object is created and
33897** are read-only thereafter:
33898**
33899**    unixShm.pFile
33900**    unixShm.id
33901**
33902** All other fields are read/write.  The unixShm.pFile->mutex must be held
33903** while accessing any read/write fields.
33904*/
33905struct unixShm {
33906  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
33907  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
33908  u8 hasMutex;               /* True if holding the unixShmNode mutex */
33909  u8 id;                     /* Id of this connection within its unixShmNode */
33910  u16 sharedMask;            /* Mask of shared locks held */
33911  u16 exclMask;              /* Mask of exclusive locks held */
33912};
33913
33914/*
33915** Constants used for locking
33916*/
33917#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
33918#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
33919
33920/*
33921** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
33922**
33923** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
33924** otherwise.
33925*/
33926static int unixShmSystemLock(
33927  unixFile *pFile,       /* Open connection to the WAL file */
33928  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
33929  int ofst,              /* First byte of the locking range */
33930  int n                  /* Number of bytes to lock */
33931){
33932  unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
33933  struct flock f;        /* The posix advisory locking structure */
33934  int rc = SQLITE_OK;    /* Result code form fcntl() */
33935
33936  /* Access to the unixShmNode object is serialized by the caller */
33937  pShmNode = pFile->pInode->pShmNode;
33938  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
33939
33940  /* Shared locks never span more than one byte */
33941  assert( n==1 || lockType!=F_RDLCK );
33942
33943  /* Locks are within range */
33944  assert( n>=1 && n<=SQLITE_SHM_NLOCK );
33945
33946  if( pShmNode->h>=0 ){
33947    /* Initialize the locking parameters */
33948    memset(&f, 0, sizeof(f));
33949    f.l_type = lockType;
33950    f.l_whence = SEEK_SET;
33951    f.l_start = ofst;
33952    f.l_len = n;
33953
33954    rc = osFcntl(pShmNode->h, F_SETLK, &f);
33955    rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
33956  }
33957
33958  /* Update the global lock state and do debug tracing */
33959#ifdef SQLITE_DEBUG
33960  { u16 mask;
33961  OSTRACE(("SHM-LOCK "));
33962  mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
33963  if( rc==SQLITE_OK ){
33964    if( lockType==F_UNLCK ){
33965      OSTRACE(("unlock %d ok", ofst));
33966      pShmNode->exclMask &= ~mask;
33967      pShmNode->sharedMask &= ~mask;
33968    }else if( lockType==F_RDLCK ){
33969      OSTRACE(("read-lock %d ok", ofst));
33970      pShmNode->exclMask &= ~mask;
33971      pShmNode->sharedMask |= mask;
33972    }else{
33973      assert( lockType==F_WRLCK );
33974      OSTRACE(("write-lock %d ok", ofst));
33975      pShmNode->exclMask |= mask;
33976      pShmNode->sharedMask &= ~mask;
33977    }
33978  }else{
33979    if( lockType==F_UNLCK ){
33980      OSTRACE(("unlock %d failed", ofst));
33981    }else if( lockType==F_RDLCK ){
33982      OSTRACE(("read-lock failed"));
33983    }else{
33984      assert( lockType==F_WRLCK );
33985      OSTRACE(("write-lock %d failed", ofst));
33986    }
33987  }
33988  OSTRACE((" - afterwards %03x,%03x\n",
33989           pShmNode->sharedMask, pShmNode->exclMask));
33990  }
33991#endif
33992
33993  return rc;
33994}
33995
33996/*
33997** Return the minimum number of 32KB shm regions that should be mapped at
33998** a time, assuming that each mapping must be an integer multiple of the
33999** current system page-size.
34000**
34001** Usually, this is 1. The exception seems to be systems that are configured
34002** to use 64KB pages - in this case each mapping must cover at least two
34003** shm regions.
34004*/
34005static int unixShmRegionPerMap(void){
34006  int shmsz = 32*1024;            /* SHM region size */
34007  int pgsz = osGetpagesize();   /* System page size */
34008  assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
34009  if( pgsz<shmsz ) return 1;
34010  return pgsz/shmsz;
34011}
34012
34013/*
34014** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
34015**
34016** This is not a VFS shared-memory method; it is a utility function called
34017** by VFS shared-memory methods.
34018*/
34019static void unixShmPurge(unixFile *pFd){
34020  unixShmNode *p = pFd->pInode->pShmNode;
34021  assert( unixMutexHeld() );
34022  if( p && ALWAYS(p->nRef==0) ){
34023    int nShmPerMap = unixShmRegionPerMap();
34024    int i;
34025    assert( p->pInode==pFd->pInode );
34026    sqlite3_mutex_free(p->mutex);
34027    for(i=0; i<p->nRegion; i+=nShmPerMap){
34028      if( p->h>=0 ){
34029        osMunmap(p->apRegion[i], p->szRegion);
34030      }else{
34031        sqlite3_free(p->apRegion[i]);
34032      }
34033    }
34034    sqlite3_free(p->apRegion);
34035    if( p->h>=0 ){
34036      robust_close(pFd, p->h, __LINE__);
34037      p->h = -1;
34038    }
34039    p->pInode->pShmNode = 0;
34040    sqlite3_free(p);
34041  }
34042}
34043
34044/*
34045** Open a shared-memory area associated with open database file pDbFd.
34046** This particular implementation uses mmapped files.
34047**
34048** The file used to implement shared-memory is in the same directory
34049** as the open database file and has the same name as the open database
34050** file with the "-shm" suffix added.  For example, if the database file
34051** is "/home/user1/config.db" then the file that is created and mmapped
34052** for shared memory will be called "/home/user1/config.db-shm".
34053**
34054** Another approach to is to use files in /dev/shm or /dev/tmp or an
34055** some other tmpfs mount. But if a file in a different directory
34056** from the database file is used, then differing access permissions
34057** or a chroot() might cause two different processes on the same
34058** database to end up using different files for shared memory -
34059** meaning that their memory would not really be shared - resulting
34060** in database corruption.  Nevertheless, this tmpfs file usage
34061** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
34062** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
34063** option results in an incompatible build of SQLite;  builds of SQLite
34064** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
34065** same database file at the same time, database corruption will likely
34066** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
34067** "unsupported" and may go away in a future SQLite release.
34068**
34069** When opening a new shared-memory file, if no other instances of that
34070** file are currently open, in this process or in other processes, then
34071** the file must be truncated to zero length or have its header cleared.
34072**
34073** If the original database file (pDbFd) is using the "unix-excl" VFS
34074** that means that an exclusive lock is held on the database file and
34075** that no other processes are able to read or write the database.  In
34076** that case, we do not really need shared memory.  No shared memory
34077** file is created.  The shared memory will be simulated with heap memory.
34078*/
34079static int unixOpenSharedMemory(unixFile *pDbFd){
34080  struct unixShm *p = 0;          /* The connection to be opened */
34081  struct unixShmNode *pShmNode;   /* The underlying mmapped file */
34082  int rc;                         /* Result code */
34083  unixInodeInfo *pInode;          /* The inode of fd */
34084  char *zShmFilename;             /* Name of the file used for SHM */
34085  int nShmFilename;               /* Size of the SHM filename in bytes */
34086
34087  /* Allocate space for the new unixShm object. */
34088  p = sqlite3_malloc64( sizeof(*p) );
34089  if( p==0 ) return SQLITE_NOMEM_BKPT;
34090  memset(p, 0, sizeof(*p));
34091  assert( pDbFd->pShm==0 );
34092
34093  /* Check to see if a unixShmNode object already exists. Reuse an existing
34094  ** one if present. Create a new one if necessary.
34095  */
34096  unixEnterMutex();
34097  pInode = pDbFd->pInode;
34098  pShmNode = pInode->pShmNode;
34099  if( pShmNode==0 ){
34100    struct stat sStat;                 /* fstat() info for database file */
34101#ifndef SQLITE_SHM_DIRECTORY
34102    const char *zBasePath = pDbFd->zPath;
34103#endif
34104
34105    /* Call fstat() to figure out the permissions on the database file. If
34106    ** a new *-shm file is created, an attempt will be made to create it
34107    ** with the same permissions.
34108    */
34109    if( osFstat(pDbFd->h, &sStat) ){
34110      rc = unixLogError(SQLITE_IOERR_FSTAT, "fstat", pDbFd->zPath);
34111      goto shm_open_err;
34112    }
34113
34114#ifdef SQLITE_SHM_DIRECTORY
34115    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
34116#else
34117    nShmFilename = 6 + (int)strlen(zBasePath);
34118#endif
34119    pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
34120    if( pShmNode==0 ){
34121      rc = SQLITE_NOMEM_BKPT;
34122      goto shm_open_err;
34123    }
34124    memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
34125    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
34126#ifdef SQLITE_SHM_DIRECTORY
34127    sqlite3_snprintf(nShmFilename, zShmFilename,
34128                     SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
34129                     (u32)sStat.st_ino, (u32)sStat.st_dev);
34130#else
34131    sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
34132    sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
34133#endif
34134    pShmNode->h = -1;
34135    pDbFd->pInode->pShmNode = pShmNode;
34136    pShmNode->pInode = pDbFd->pInode;
34137    if( sqlite3GlobalConfig.bCoreMutex ){
34138      pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
34139      if( pShmNode->mutex==0 ){
34140        rc = SQLITE_NOMEM_BKPT;
34141        goto shm_open_err;
34142      }
34143    }
34144
34145    if( pInode->bProcessLock==0 ){
34146      int openFlags = O_RDWR | O_CREAT;
34147      if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
34148        openFlags = O_RDONLY;
34149        pShmNode->isReadonly = 1;
34150      }
34151      pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
34152      if( pShmNode->h<0 ){
34153        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
34154        goto shm_open_err;
34155      }
34156
34157      /* If this process is running as root, make sure that the SHM file
34158      ** is owned by the same user that owns the original database.  Otherwise,
34159      ** the original owner will not be able to connect.
34160      */
34161      robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
34162
34163      /* Check to see if another process is holding the dead-man switch.
34164      ** If not, truncate the file to zero length.
34165      */
34166      rc = SQLITE_OK;
34167      if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
34168        if( robust_ftruncate(pShmNode->h, 0) ){
34169          rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
34170        }
34171      }
34172      if( rc==SQLITE_OK ){
34173        rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
34174      }
34175      if( rc ) goto shm_open_err;
34176    }
34177  }
34178
34179  /* Make the new connection a child of the unixShmNode */
34180  p->pShmNode = pShmNode;
34181#ifdef SQLITE_DEBUG
34182  p->id = pShmNode->nextShmId++;
34183#endif
34184  pShmNode->nRef++;
34185  pDbFd->pShm = p;
34186  unixLeaveMutex();
34187
34188  /* The reference count on pShmNode has already been incremented under
34189  ** the cover of the unixEnterMutex() mutex and the pointer from the
34190  ** new (struct unixShm) object to the pShmNode has been set. All that is
34191  ** left to do is to link the new object into the linked list starting
34192  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
34193  ** mutex.
34194  */
34195  sqlite3_mutex_enter(pShmNode->mutex);
34196  p->pNext = pShmNode->pFirst;
34197  pShmNode->pFirst = p;
34198  sqlite3_mutex_leave(pShmNode->mutex);
34199  return SQLITE_OK;
34200
34201  /* Jump here on any error */
34202shm_open_err:
34203  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
34204  sqlite3_free(p);
34205  unixLeaveMutex();
34206  return rc;
34207}
34208
34209/*
34210** This function is called to obtain a pointer to region iRegion of the
34211** shared-memory associated with the database file fd. Shared-memory regions
34212** are numbered starting from zero. Each shared-memory region is szRegion
34213** bytes in size.
34214**
34215** If an error occurs, an error code is returned and *pp is set to NULL.
34216**
34217** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
34218** region has not been allocated (by any client, including one running in a
34219** separate process), then *pp is set to NULL and SQLITE_OK returned. If
34220** bExtend is non-zero and the requested shared-memory region has not yet
34221** been allocated, it is allocated by this function.
34222**
34223** If the shared-memory region has already been allocated or is allocated by
34224** this call as described above, then it is mapped into this processes
34225** address space (if it is not already), *pp is set to point to the mapped
34226** memory and SQLITE_OK returned.
34227*/
34228static int unixShmMap(
34229  sqlite3_file *fd,               /* Handle open on database file */
34230  int iRegion,                    /* Region to retrieve */
34231  int szRegion,                   /* Size of regions */
34232  int bExtend,                    /* True to extend file if necessary */
34233  void volatile **pp              /* OUT: Mapped memory */
34234){
34235  unixFile *pDbFd = (unixFile*)fd;
34236  unixShm *p;
34237  unixShmNode *pShmNode;
34238  int rc = SQLITE_OK;
34239  int nShmPerMap = unixShmRegionPerMap();
34240  int nReqRegion;
34241
34242  /* If the shared-memory file has not yet been opened, open it now. */
34243  if( pDbFd->pShm==0 ){
34244    rc = unixOpenSharedMemory(pDbFd);
34245    if( rc!=SQLITE_OK ) return rc;
34246  }
34247
34248  p = pDbFd->pShm;
34249  pShmNode = p->pShmNode;
34250  sqlite3_mutex_enter(pShmNode->mutex);
34251  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
34252  assert( pShmNode->pInode==pDbFd->pInode );
34253  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
34254  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
34255
34256  /* Minimum number of regions required to be mapped. */
34257  nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
34258
34259  if( pShmNode->nRegion<nReqRegion ){
34260    char **apNew;                      /* New apRegion[] array */
34261    int nByte = nReqRegion*szRegion;   /* Minimum required file size */
34262    struct stat sStat;                 /* Used by fstat() */
34263
34264    pShmNode->szRegion = szRegion;
34265
34266    if( pShmNode->h>=0 ){
34267      /* The requested region is not mapped into this processes address space.
34268      ** Check to see if it has been allocated (i.e. if the wal-index file is
34269      ** large enough to contain the requested region).
34270      */
34271      if( osFstat(pShmNode->h, &sStat) ){
34272        rc = SQLITE_IOERR_SHMSIZE;
34273        goto shmpage_out;
34274      }
34275
34276      if( sStat.st_size<nByte ){
34277        /* The requested memory region does not exist. If bExtend is set to
34278        ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
34279        */
34280        if( !bExtend ){
34281          goto shmpage_out;
34282        }
34283
34284        /* Alternatively, if bExtend is true, extend the file. Do this by
34285        ** writing a single byte to the end of each (OS) page being
34286        ** allocated or extended. Technically, we need only write to the
34287        ** last page in order to extend the file. But writing to all new
34288        ** pages forces the OS to allocate them immediately, which reduces
34289        ** the chances of SIGBUS while accessing the mapped region later on.
34290        */
34291        else{
34292          static const int pgsz = 4096;
34293          int iPg;
34294
34295          /* Write to the last byte of each newly allocated or extended page */
34296          assert( (nByte % pgsz)==0 );
34297          for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
34298            int x = 0;
34299            if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
34300              const char *zFile = pShmNode->zFilename;
34301              rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
34302              goto shmpage_out;
34303            }
34304          }
34305        }
34306      }
34307    }
34308
34309    /* Map the requested memory region into this processes address space. */
34310    apNew = (char **)sqlite3_realloc(
34311        pShmNode->apRegion, nReqRegion*sizeof(char *)
34312    );
34313    if( !apNew ){
34314      rc = SQLITE_IOERR_NOMEM_BKPT;
34315      goto shmpage_out;
34316    }
34317    pShmNode->apRegion = apNew;
34318    while( pShmNode->nRegion<nReqRegion ){
34319      int nMap = szRegion*nShmPerMap;
34320      int i;
34321      void *pMem;
34322      if( pShmNode->h>=0 ){
34323        pMem = osMmap(0, nMap,
34324            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
34325            MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
34326        );
34327        if( pMem==MAP_FAILED ){
34328          rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
34329          goto shmpage_out;
34330        }
34331      }else{
34332        pMem = sqlite3_malloc64(szRegion);
34333        if( pMem==0 ){
34334          rc = SQLITE_NOMEM_BKPT;
34335          goto shmpage_out;
34336        }
34337        memset(pMem, 0, szRegion);
34338      }
34339
34340      for(i=0; i<nShmPerMap; i++){
34341        pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
34342      }
34343      pShmNode->nRegion += nShmPerMap;
34344    }
34345  }
34346
34347shmpage_out:
34348  if( pShmNode->nRegion>iRegion ){
34349    *pp = pShmNode->apRegion[iRegion];
34350  }else{
34351    *pp = 0;
34352  }
34353  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
34354  sqlite3_mutex_leave(pShmNode->mutex);
34355  return rc;
34356}
34357
34358/*
34359** Change the lock state for a shared-memory segment.
34360**
34361** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
34362** different here than in posix.  In xShmLock(), one can go from unlocked
34363** to shared and back or from unlocked to exclusive and back.  But one may
34364** not go from shared to exclusive or from exclusive to shared.
34365*/
34366static int unixShmLock(
34367  sqlite3_file *fd,          /* Database file holding the shared memory */
34368  int ofst,                  /* First lock to acquire or release */
34369  int n,                     /* Number of locks to acquire or release */
34370  int flags                  /* What to do with the lock */
34371){
34372  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
34373  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
34374  unixShm *pX;                          /* For looping over all siblings */
34375  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
34376  int rc = SQLITE_OK;                   /* Result code */
34377  u16 mask;                             /* Mask of locks to take or release */
34378
34379  assert( pShmNode==pDbFd->pInode->pShmNode );
34380  assert( pShmNode->pInode==pDbFd->pInode );
34381  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
34382  assert( n>=1 );
34383  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
34384       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
34385       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
34386       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
34387  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
34388  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
34389  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
34390
34391  mask = (1<<(ofst+n)) - (1<<ofst);
34392  assert( n>1 || mask==(1<<ofst) );
34393  sqlite3_mutex_enter(pShmNode->mutex);
34394  if( flags & SQLITE_SHM_UNLOCK ){
34395    u16 allMask = 0; /* Mask of locks held by siblings */
34396
34397    /* See if any siblings hold this same lock */
34398    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34399      if( pX==p ) continue;
34400      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
34401      allMask |= pX->sharedMask;
34402    }
34403
34404    /* Unlock the system-level locks */
34405    if( (mask & allMask)==0 ){
34406      rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
34407    }else{
34408      rc = SQLITE_OK;
34409    }
34410
34411    /* Undo the local locks */
34412    if( rc==SQLITE_OK ){
34413      p->exclMask &= ~mask;
34414      p->sharedMask &= ~mask;
34415    }
34416  }else if( flags & SQLITE_SHM_SHARED ){
34417    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
34418
34419    /* Find out which shared locks are already held by sibling connections.
34420    ** If any sibling already holds an exclusive lock, go ahead and return
34421    ** SQLITE_BUSY.
34422    */
34423    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34424      if( (pX->exclMask & mask)!=0 ){
34425        rc = SQLITE_BUSY;
34426        break;
34427      }
34428      allShared |= pX->sharedMask;
34429    }
34430
34431    /* Get shared locks at the system level, if necessary */
34432    if( rc==SQLITE_OK ){
34433      if( (allShared & mask)==0 ){
34434        rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
34435      }else{
34436        rc = SQLITE_OK;
34437      }
34438    }
34439
34440    /* Get the local shared locks */
34441    if( rc==SQLITE_OK ){
34442      p->sharedMask |= mask;
34443    }
34444  }else{
34445    /* Make sure no sibling connections hold locks that will block this
34446    ** lock.  If any do, return SQLITE_BUSY right away.
34447    */
34448    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34449      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
34450        rc = SQLITE_BUSY;
34451        break;
34452      }
34453    }
34454
34455    /* Get the exclusive locks at the system level.  Then if successful
34456    ** also mark the local connection as being locked.
34457    */
34458    if( rc==SQLITE_OK ){
34459      rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
34460      if( rc==SQLITE_OK ){
34461        assert( (p->sharedMask & mask)==0 );
34462        p->exclMask |= mask;
34463      }
34464    }
34465  }
34466  sqlite3_mutex_leave(pShmNode->mutex);
34467  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
34468           p->id, osGetpid(0), p->sharedMask, p->exclMask));
34469  return rc;
34470}
34471
34472/*
34473** Implement a memory barrier or memory fence on shared memory.
34474**
34475** All loads and stores begun before the barrier must complete before
34476** any load or store begun after the barrier.
34477*/
34478static void unixShmBarrier(
34479  sqlite3_file *fd                /* Database file holding the shared memory */
34480){
34481  UNUSED_PARAMETER(fd);
34482  sqlite3MemoryBarrier();         /* compiler-defined memory barrier */
34483  unixEnterMutex();               /* Also mutex, for redundancy */
34484  unixLeaveMutex();
34485}
34486
34487/*
34488** Close a connection to shared-memory.  Delete the underlying
34489** storage if deleteFlag is true.
34490**
34491** If there is no shared memory associated with the connection then this
34492** routine is a harmless no-op.
34493*/
34494static int unixShmUnmap(
34495  sqlite3_file *fd,               /* The underlying database file */
34496  int deleteFlag                  /* Delete shared-memory if true */
34497){
34498  unixShm *p;                     /* The connection to be closed */
34499  unixShmNode *pShmNode;          /* The underlying shared-memory file */
34500  unixShm **pp;                   /* For looping over sibling connections */
34501  unixFile *pDbFd;                /* The underlying database file */
34502
34503  pDbFd = (unixFile*)fd;
34504  p = pDbFd->pShm;
34505  if( p==0 ) return SQLITE_OK;
34506  pShmNode = p->pShmNode;
34507
34508  assert( pShmNode==pDbFd->pInode->pShmNode );
34509  assert( pShmNode->pInode==pDbFd->pInode );
34510
34511  /* Remove connection p from the set of connections associated
34512  ** with pShmNode */
34513  sqlite3_mutex_enter(pShmNode->mutex);
34514  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
34515  *pp = p->pNext;
34516
34517  /* Free the connection p */
34518  sqlite3_free(p);
34519  pDbFd->pShm = 0;
34520  sqlite3_mutex_leave(pShmNode->mutex);
34521
34522  /* If pShmNode->nRef has reached 0, then close the underlying
34523  ** shared-memory file, too */
34524  unixEnterMutex();
34525  assert( pShmNode->nRef>0 );
34526  pShmNode->nRef--;
34527  if( pShmNode->nRef==0 ){
34528    if( deleteFlag && pShmNode->h>=0 ){
34529      osUnlink(pShmNode->zFilename);
34530    }
34531    unixShmPurge(pDbFd);
34532  }
34533  unixLeaveMutex();
34534
34535  return SQLITE_OK;
34536}
34537
34538
34539#else
34540# define unixShmMap     0
34541# define unixShmLock    0
34542# define unixShmBarrier 0
34543# define unixShmUnmap   0
34544#endif /* #ifndef SQLITE_OMIT_WAL */
34545
34546#if SQLITE_MAX_MMAP_SIZE>0
34547/*
34548** If it is currently memory mapped, unmap file pFd.
34549*/
34550static void unixUnmapfile(unixFile *pFd){
34551  assert( pFd->nFetchOut==0 );
34552  if( pFd->pMapRegion ){
34553    osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
34554    pFd->pMapRegion = 0;
34555    pFd->mmapSize = 0;
34556    pFd->mmapSizeActual = 0;
34557  }
34558}
34559
34560/*
34561** Attempt to set the size of the memory mapping maintained by file
34562** descriptor pFd to nNew bytes. Any existing mapping is discarded.
34563**
34564** If successful, this function sets the following variables:
34565**
34566**       unixFile.pMapRegion
34567**       unixFile.mmapSize
34568**       unixFile.mmapSizeActual
34569**
34570** If unsuccessful, an error message is logged via sqlite3_log() and
34571** the three variables above are zeroed. In this case SQLite should
34572** continue accessing the database using the xRead() and xWrite()
34573** methods.
34574*/
34575static void unixRemapfile(
34576  unixFile *pFd,                  /* File descriptor object */
34577  i64 nNew                        /* Required mapping size */
34578){
34579  const char *zErr = "mmap";
34580  int h = pFd->h;                      /* File descriptor open on db file */
34581  u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
34582  i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
34583  u8 *pNew = 0;                        /* Location of new mapping */
34584  int flags = PROT_READ;               /* Flags to pass to mmap() */
34585
34586  assert( pFd->nFetchOut==0 );
34587  assert( nNew>pFd->mmapSize );
34588  assert( nNew<=pFd->mmapSizeMax );
34589  assert( nNew>0 );
34590  assert( pFd->mmapSizeActual>=pFd->mmapSize );
34591  assert( MAP_FAILED!=0 );
34592
34593#ifdef SQLITE_MMAP_READWRITE
34594  if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
34595#endif
34596
34597  if( pOrig ){
34598#if HAVE_MREMAP
34599    i64 nReuse = pFd->mmapSize;
34600#else
34601    const int szSyspage = osGetpagesize();
34602    i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
34603#endif
34604    u8 *pReq = &pOrig[nReuse];
34605
34606    /* Unmap any pages of the existing mapping that cannot be reused. */
34607    if( nReuse!=nOrig ){
34608      osMunmap(pReq, nOrig-nReuse);
34609    }
34610
34611#if HAVE_MREMAP
34612    pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
34613    zErr = "mremap";
34614#else
34615    pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
34616    if( pNew!=MAP_FAILED ){
34617      if( pNew!=pReq ){
34618        osMunmap(pNew, nNew - nReuse);
34619        pNew = 0;
34620      }else{
34621        pNew = pOrig;
34622      }
34623    }
34624#endif
34625
34626    /* The attempt to extend the existing mapping failed. Free it. */
34627    if( pNew==MAP_FAILED || pNew==0 ){
34628      osMunmap(pOrig, nReuse);
34629    }
34630  }
34631
34632  /* If pNew is still NULL, try to create an entirely new mapping. */
34633  if( pNew==0 ){
34634    pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
34635  }
34636
34637  if( pNew==MAP_FAILED ){
34638    pNew = 0;
34639    nNew = 0;
34640    unixLogError(SQLITE_OK, zErr, pFd->zPath);
34641
34642    /* If the mmap() above failed, assume that all subsequent mmap() calls
34643    ** will probably fail too. Fall back to using xRead/xWrite exclusively
34644    ** in this case.  */
34645    pFd->mmapSizeMax = 0;
34646  }
34647  pFd->pMapRegion = (void *)pNew;
34648  pFd->mmapSize = pFd->mmapSizeActual = nNew;
34649}
34650
34651/*
34652** Memory map or remap the file opened by file-descriptor pFd (if the file
34653** is already mapped, the existing mapping is replaced by the new). Or, if
34654** there already exists a mapping for this file, and there are still
34655** outstanding xFetch() references to it, this function is a no-op.
34656**
34657** If parameter nByte is non-negative, then it is the requested size of
34658** the mapping to create. Otherwise, if nByte is less than zero, then the
34659** requested size is the size of the file on disk. The actual size of the
34660** created mapping is either the requested size or the value configured
34661** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
34662**
34663** SQLITE_OK is returned if no error occurs (even if the mapping is not
34664** recreated as a result of outstanding references) or an SQLite error
34665** code otherwise.
34666*/
34667static int unixMapfile(unixFile *pFd, i64 nMap){
34668  assert( nMap>=0 || pFd->nFetchOut==0 );
34669  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
34670  if( pFd->nFetchOut>0 ) return SQLITE_OK;
34671
34672  if( nMap<0 ){
34673    struct stat statbuf;          /* Low-level file information */
34674    if( osFstat(pFd->h, &statbuf) ){
34675      return SQLITE_IOERR_FSTAT;
34676    }
34677    nMap = statbuf.st_size;
34678  }
34679  if( nMap>pFd->mmapSizeMax ){
34680    nMap = pFd->mmapSizeMax;
34681  }
34682
34683  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
34684  if( nMap!=pFd->mmapSize ){
34685    unixRemapfile(pFd, nMap);
34686  }
34687
34688  return SQLITE_OK;
34689}
34690#endif /* SQLITE_MAX_MMAP_SIZE>0 */
34691
34692/*
34693** If possible, return a pointer to a mapping of file fd starting at offset
34694** iOff. The mapping must be valid for at least nAmt bytes.
34695**
34696** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
34697** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
34698** Finally, if an error does occur, return an SQLite error code. The final
34699** value of *pp is undefined in this case.
34700**
34701** If this function does return a pointer, the caller must eventually
34702** release the reference by calling unixUnfetch().
34703*/
34704static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
34705#if SQLITE_MAX_MMAP_SIZE>0
34706  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
34707#endif
34708  *pp = 0;
34709
34710#if SQLITE_MAX_MMAP_SIZE>0
34711  if( pFd->mmapSizeMax>0 ){
34712    if( pFd->pMapRegion==0 ){
34713      int rc = unixMapfile(pFd, -1);
34714      if( rc!=SQLITE_OK ) return rc;
34715    }
34716    if( pFd->mmapSize >= iOff+nAmt ){
34717      *pp = &((u8 *)pFd->pMapRegion)[iOff];
34718      pFd->nFetchOut++;
34719    }
34720  }
34721#endif
34722  return SQLITE_OK;
34723}
34724
34725/*
34726** If the third argument is non-NULL, then this function releases a
34727** reference obtained by an earlier call to unixFetch(). The second
34728** argument passed to this function must be the same as the corresponding
34729** argument that was passed to the unixFetch() invocation.
34730**
34731** Or, if the third argument is NULL, then this function is being called
34732** to inform the VFS layer that, according to POSIX, any existing mapping
34733** may now be invalid and should be unmapped.
34734*/
34735static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
34736#if SQLITE_MAX_MMAP_SIZE>0
34737  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
34738  UNUSED_PARAMETER(iOff);
34739
34740  /* If p==0 (unmap the entire file) then there must be no outstanding
34741  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
34742  ** then there must be at least one outstanding.  */
34743  assert( (p==0)==(pFd->nFetchOut==0) );
34744
34745  /* If p!=0, it must match the iOff value. */
34746  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
34747
34748  if( p ){
34749    pFd->nFetchOut--;
34750  }else{
34751    unixUnmapfile(pFd);
34752  }
34753
34754  assert( pFd->nFetchOut>=0 );
34755#else
34756  UNUSED_PARAMETER(fd);
34757  UNUSED_PARAMETER(p);
34758  UNUSED_PARAMETER(iOff);
34759#endif
34760  return SQLITE_OK;
34761}
34762
34763/*
34764** Here ends the implementation of all sqlite3_file methods.
34765**
34766********************** End sqlite3_file Methods *******************************
34767******************************************************************************/
34768
34769/*
34770** This division contains definitions of sqlite3_io_methods objects that
34771** implement various file locking strategies.  It also contains definitions
34772** of "finder" functions.  A finder-function is used to locate the appropriate
34773** sqlite3_io_methods object for a particular database file.  The pAppData
34774** field of the sqlite3_vfs VFS objects are initialized to be pointers to
34775** the correct finder-function for that VFS.
34776**
34777** Most finder functions return a pointer to a fixed sqlite3_io_methods
34778** object.  The only interesting finder-function is autolockIoFinder, which
34779** looks at the filesystem type and tries to guess the best locking
34780** strategy from that.
34781**
34782** For finder-function F, two objects are created:
34783**
34784**    (1) The real finder-function named "FImpt()".
34785**
34786**    (2) A constant pointer to this function named just "F".
34787**
34788**
34789** A pointer to the F pointer is used as the pAppData value for VFS
34790** objects.  We have to do this instead of letting pAppData point
34791** directly at the finder-function since C90 rules prevent a void*
34792** from be cast into a function pointer.
34793**
34794**
34795** Each instance of this macro generates two objects:
34796**
34797**   *  A constant sqlite3_io_methods object call METHOD that has locking
34798**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
34799**
34800**   *  An I/O method finder function called FINDER that returns a pointer
34801**      to the METHOD object in the previous bullet.
34802*/
34803#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP)     \
34804static const sqlite3_io_methods METHOD = {                                   \
34805   VERSION,                    /* iVersion */                                \
34806   CLOSE,                      /* xClose */                                  \
34807   unixRead,                   /* xRead */                                   \
34808   unixWrite,                  /* xWrite */                                  \
34809   unixTruncate,               /* xTruncate */                               \
34810   unixSync,                   /* xSync */                                   \
34811   unixFileSize,               /* xFileSize */                               \
34812   LOCK,                       /* xLock */                                   \
34813   UNLOCK,                     /* xUnlock */                                 \
34814   CKLOCK,                     /* xCheckReservedLock */                      \
34815   unixFileControl,            /* xFileControl */                            \
34816   unixSectorSize,             /* xSectorSize */                             \
34817   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
34818   SHMMAP,                     /* xShmMap */                                 \
34819   unixShmLock,                /* xShmLock */                                \
34820   unixShmBarrier,             /* xShmBarrier */                             \
34821   unixShmUnmap,               /* xShmUnmap */                               \
34822   unixFetch,                  /* xFetch */                                  \
34823   unixUnfetch,                /* xUnfetch */                                \
34824};                                                                           \
34825static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
34826  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
34827  return &METHOD;                                                            \
34828}                                                                            \
34829static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
34830    = FINDER##Impl;
34831
34832/*
34833** Here are all of the sqlite3_io_methods objects for each of the
34834** locking strategies.  Functions that return pointers to these methods
34835** are also created.
34836*/
34837IOMETHODS(
34838  posixIoFinder,            /* Finder function name */
34839  posixIoMethods,           /* sqlite3_io_methods object name */
34840  3,                        /* shared memory and mmap are enabled */
34841  unixClose,                /* xClose method */
34842  unixLock,                 /* xLock method */
34843  unixUnlock,               /* xUnlock method */
34844  unixCheckReservedLock,    /* xCheckReservedLock method */
34845  unixShmMap                /* xShmMap method */
34846)
34847IOMETHODS(
34848  nolockIoFinder,           /* Finder function name */
34849  nolockIoMethods,          /* sqlite3_io_methods object name */
34850  3,                        /* shared memory is disabled */
34851  nolockClose,              /* xClose method */
34852  nolockLock,               /* xLock method */
34853  nolockUnlock,             /* xUnlock method */
34854  nolockCheckReservedLock,  /* xCheckReservedLock method */
34855  0                         /* xShmMap method */
34856)
34857IOMETHODS(
34858  dotlockIoFinder,          /* Finder function name */
34859  dotlockIoMethods,         /* sqlite3_io_methods object name */
34860  1,                        /* shared memory is disabled */
34861  dotlockClose,             /* xClose method */
34862  dotlockLock,              /* xLock method */
34863  dotlockUnlock,            /* xUnlock method */
34864  dotlockCheckReservedLock, /* xCheckReservedLock method */
34865  0                         /* xShmMap method */
34866)
34867
34868#if SQLITE_ENABLE_LOCKING_STYLE
34869IOMETHODS(
34870  flockIoFinder,            /* Finder function name */
34871  flockIoMethods,           /* sqlite3_io_methods object name */
34872  1,                        /* shared memory is disabled */
34873  flockClose,               /* xClose method */
34874  flockLock,                /* xLock method */
34875  flockUnlock,              /* xUnlock method */
34876  flockCheckReservedLock,   /* xCheckReservedLock method */
34877  0                         /* xShmMap method */
34878)
34879#endif
34880
34881#if OS_VXWORKS
34882IOMETHODS(
34883  semIoFinder,              /* Finder function name */
34884  semIoMethods,             /* sqlite3_io_methods object name */
34885  1,                        /* shared memory is disabled */
34886  semXClose,                /* xClose method */
34887  semXLock,                 /* xLock method */
34888  semXUnlock,               /* xUnlock method */
34889  semXCheckReservedLock,    /* xCheckReservedLock method */
34890  0                         /* xShmMap method */
34891)
34892#endif
34893
34894#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34895IOMETHODS(
34896  afpIoFinder,              /* Finder function name */
34897  afpIoMethods,             /* sqlite3_io_methods object name */
34898  1,                        /* shared memory is disabled */
34899  afpClose,                 /* xClose method */
34900  afpLock,                  /* xLock method */
34901  afpUnlock,                /* xUnlock method */
34902  afpCheckReservedLock,     /* xCheckReservedLock method */
34903  0                         /* xShmMap method */
34904)
34905#endif
34906
34907/*
34908** The proxy locking method is a "super-method" in the sense that it
34909** opens secondary file descriptors for the conch and lock files and
34910** it uses proxy, dot-file, AFP, and flock() locking methods on those
34911** secondary files.  For this reason, the division that implements
34912** proxy locking is located much further down in the file.  But we need
34913** to go ahead and define the sqlite3_io_methods and finder function
34914** for proxy locking here.  So we forward declare the I/O methods.
34915*/
34916#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34917static int proxyClose(sqlite3_file*);
34918static int proxyLock(sqlite3_file*, int);
34919static int proxyUnlock(sqlite3_file*, int);
34920static int proxyCheckReservedLock(sqlite3_file*, int*);
34921IOMETHODS(
34922  proxyIoFinder,            /* Finder function name */
34923  proxyIoMethods,           /* sqlite3_io_methods object name */
34924  1,                        /* shared memory is disabled */
34925  proxyClose,               /* xClose method */
34926  proxyLock,                /* xLock method */
34927  proxyUnlock,              /* xUnlock method */
34928  proxyCheckReservedLock,   /* xCheckReservedLock method */
34929  0                         /* xShmMap method */
34930)
34931#endif
34932
34933/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
34934#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34935IOMETHODS(
34936  nfsIoFinder,               /* Finder function name */
34937  nfsIoMethods,              /* sqlite3_io_methods object name */
34938  1,                         /* shared memory is disabled */
34939  unixClose,                 /* xClose method */
34940  unixLock,                  /* xLock method */
34941  nfsUnlock,                 /* xUnlock method */
34942  unixCheckReservedLock,     /* xCheckReservedLock method */
34943  0                          /* xShmMap method */
34944)
34945#endif
34946
34947#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34948/*
34949** This "finder" function attempts to determine the best locking strategy
34950** for the database file "filePath".  It then returns the sqlite3_io_methods
34951** object that implements that strategy.
34952**
34953** This is for MacOSX only.
34954*/
34955static const sqlite3_io_methods *autolockIoFinderImpl(
34956  const char *filePath,    /* name of the database file */
34957  unixFile *pNew           /* open file object for the database file */
34958){
34959  static const struct Mapping {
34960    const char *zFilesystem;              /* Filesystem type name */
34961    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
34962  } aMap[] = {
34963    { "hfs",    &posixIoMethods },
34964    { "ufs",    &posixIoMethods },
34965    { "afpfs",  &afpIoMethods },
34966    { "smbfs",  &afpIoMethods },
34967    { "webdav", &nolockIoMethods },
34968    { 0, 0 }
34969  };
34970  int i;
34971  struct statfs fsInfo;
34972  struct flock lockInfo;
34973
34974  if( !filePath ){
34975    /* If filePath==NULL that means we are dealing with a transient file
34976    ** that does not need to be locked. */
34977    return &nolockIoMethods;
34978  }
34979  if( statfs(filePath, &fsInfo) != -1 ){
34980    if( fsInfo.f_flags & MNT_RDONLY ){
34981      return &nolockIoMethods;
34982    }
34983    for(i=0; aMap[i].zFilesystem; i++){
34984      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
34985        return aMap[i].pMethods;
34986      }
34987    }
34988  }
34989
34990  /* Default case. Handles, amongst others, "nfs".
34991  ** Test byte-range lock using fcntl(). If the call succeeds,
34992  ** assume that the file-system supports POSIX style locks.
34993  */
34994  lockInfo.l_len = 1;
34995  lockInfo.l_start = 0;
34996  lockInfo.l_whence = SEEK_SET;
34997  lockInfo.l_type = F_RDLCK;
34998  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
34999    if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
35000      return &nfsIoMethods;
35001    } else {
35002      return &posixIoMethods;
35003    }
35004  }else{
35005    return &dotlockIoMethods;
35006  }
35007}
35008static const sqlite3_io_methods
35009  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
35010
35011#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
35012
35013#if OS_VXWORKS
35014/*
35015** This "finder" function for VxWorks checks to see if posix advisory
35016** locking works.  If it does, then that is what is used.  If it does not
35017** work, then fallback to named semaphore locking.
35018*/
35019static const sqlite3_io_methods *vxworksIoFinderImpl(
35020  const char *filePath,    /* name of the database file */
35021  unixFile *pNew           /* the open file object */
35022){
35023  struct flock lockInfo;
35024
35025  if( !filePath ){
35026    /* If filePath==NULL that means we are dealing with a transient file
35027    ** that does not need to be locked. */
35028    return &nolockIoMethods;
35029  }
35030
35031  /* Test if fcntl() is supported and use POSIX style locks.
35032  ** Otherwise fall back to the named semaphore method.
35033  */
35034  lockInfo.l_len = 1;
35035  lockInfo.l_start = 0;
35036  lockInfo.l_whence = SEEK_SET;
35037  lockInfo.l_type = F_RDLCK;
35038  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
35039    return &posixIoMethods;
35040  }else{
35041    return &semIoMethods;
35042  }
35043}
35044static const sqlite3_io_methods
35045  *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
35046
35047#endif /* OS_VXWORKS */
35048
35049/*
35050** An abstract type for a pointer to an IO method finder function:
35051*/
35052typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
35053
35054
35055/****************************************************************************
35056**************************** sqlite3_vfs methods ****************************
35057**
35058** This division contains the implementation of methods on the
35059** sqlite3_vfs object.
35060*/
35061
35062/*
35063** Initialize the contents of the unixFile structure pointed to by pId.
35064*/
35065static int fillInUnixFile(
35066  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
35067  int h,                  /* Open file descriptor of file being opened */
35068  sqlite3_file *pId,      /* Write to the unixFile structure here */
35069  const char *zFilename,  /* Name of the file being opened */
35070  int ctrlFlags           /* Zero or more UNIXFILE_* values */
35071){
35072  const sqlite3_io_methods *pLockingStyle;
35073  unixFile *pNew = (unixFile *)pId;
35074  int rc = SQLITE_OK;
35075
35076  assert( pNew->pInode==NULL );
35077
35078  /* Usually the path zFilename should not be a relative pathname. The
35079  ** exception is when opening the proxy "conch" file in builds that
35080  ** include the special Apple locking styles.
35081  */
35082#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35083  assert( zFilename==0 || zFilename[0]=='/'
35084    || pVfs->pAppData==(void*)&autolockIoFinder );
35085#else
35086  assert( zFilename==0 || zFilename[0]=='/' );
35087#endif
35088
35089  /* No locking occurs in temporary files */
35090  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
35091
35092  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
35093  pNew->h = h;
35094  pNew->pVfs = pVfs;
35095  pNew->zPath = zFilename;
35096  pNew->ctrlFlags = (u8)ctrlFlags;
35097#if SQLITE_MAX_MMAP_SIZE>0
35098  pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
35099#endif
35100  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
35101                           "psow", SQLITE_POWERSAFE_OVERWRITE) ){
35102    pNew->ctrlFlags |= UNIXFILE_PSOW;
35103  }
35104  if( strcmp(pVfs->zName,"unix-excl")==0 ){
35105    pNew->ctrlFlags |= UNIXFILE_EXCL;
35106  }
35107
35108#if OS_VXWORKS
35109  pNew->pId = vxworksFindFileId(zFilename);
35110  if( pNew->pId==0 ){
35111    ctrlFlags |= UNIXFILE_NOLOCK;
35112    rc = SQLITE_NOMEM_BKPT;
35113  }
35114#endif
35115
35116  if( ctrlFlags & UNIXFILE_NOLOCK ){
35117    pLockingStyle = &nolockIoMethods;
35118  }else{
35119    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
35120#if SQLITE_ENABLE_LOCKING_STYLE
35121    /* Cache zFilename in the locking context (AFP and dotlock override) for
35122    ** proxyLock activation is possible (remote proxy is based on db name)
35123    ** zFilename remains valid until file is closed, to support */
35124    pNew->lockingContext = (void*)zFilename;
35125#endif
35126  }
35127
35128  if( pLockingStyle == &posixIoMethods
35129#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35130    || pLockingStyle == &nfsIoMethods
35131#endif
35132  ){
35133    unixEnterMutex();
35134    rc = findInodeInfo(pNew, &pNew->pInode);
35135    if( rc!=SQLITE_OK ){
35136      /* If an error occurred in findInodeInfo(), close the file descriptor
35137      ** immediately, before releasing the mutex. findInodeInfo() may fail
35138      ** in two scenarios:
35139      **
35140      **   (a) A call to fstat() failed.
35141      **   (b) A malloc failed.
35142      **
35143      ** Scenario (b) may only occur if the process is holding no other
35144      ** file descriptors open on the same file. If there were other file
35145      ** descriptors on this file, then no malloc would be required by
35146      ** findInodeInfo(). If this is the case, it is quite safe to close
35147      ** handle h - as it is guaranteed that no posix locks will be released
35148      ** by doing so.
35149      **
35150      ** If scenario (a) caused the error then things are not so safe. The
35151      ** implicit assumption here is that if fstat() fails, things are in
35152      ** such bad shape that dropping a lock or two doesn't matter much.
35153      */
35154      robust_close(pNew, h, __LINE__);
35155      h = -1;
35156    }
35157    unixLeaveMutex();
35158  }
35159
35160#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
35161  else if( pLockingStyle == &afpIoMethods ){
35162    /* AFP locking uses the file path so it needs to be included in
35163    ** the afpLockingContext.
35164    */
35165    afpLockingContext *pCtx;
35166    pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
35167    if( pCtx==0 ){
35168      rc = SQLITE_NOMEM_BKPT;
35169    }else{
35170      /* NB: zFilename exists and remains valid until the file is closed
35171      ** according to requirement F11141.  So we do not need to make a
35172      ** copy of the filename. */
35173      pCtx->dbPath = zFilename;
35174      pCtx->reserved = 0;
35175      srandomdev();
35176      unixEnterMutex();
35177      rc = findInodeInfo(pNew, &pNew->pInode);
35178      if( rc!=SQLITE_OK ){
35179        sqlite3_free(pNew->lockingContext);
35180        robust_close(pNew, h, __LINE__);
35181        h = -1;
35182      }
35183      unixLeaveMutex();
35184    }
35185  }
35186#endif
35187
35188  else if( pLockingStyle == &dotlockIoMethods ){
35189    /* Dotfile locking uses the file path so it needs to be included in
35190    ** the dotlockLockingContext
35191    */
35192    char *zLockFile;
35193    int nFilename;
35194    assert( zFilename!=0 );
35195    nFilename = (int)strlen(zFilename) + 6;
35196    zLockFile = (char *)sqlite3_malloc64(nFilename);
35197    if( zLockFile==0 ){
35198      rc = SQLITE_NOMEM_BKPT;
35199    }else{
35200      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
35201    }
35202    pNew->lockingContext = zLockFile;
35203  }
35204
35205#if OS_VXWORKS
35206  else if( pLockingStyle == &semIoMethods ){
35207    /* Named semaphore locking uses the file path so it needs to be
35208    ** included in the semLockingContext
35209    */
35210    unixEnterMutex();
35211    rc = findInodeInfo(pNew, &pNew->pInode);
35212    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
35213      char *zSemName = pNew->pInode->aSemName;
35214      int n;
35215      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
35216                       pNew->pId->zCanonicalName);
35217      for( n=1; zSemName[n]; n++ )
35218        if( zSemName[n]=='/' ) zSemName[n] = '_';
35219      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
35220      if( pNew->pInode->pSem == SEM_FAILED ){
35221        rc = SQLITE_NOMEM_BKPT;
35222        pNew->pInode->aSemName[0] = '\0';
35223      }
35224    }
35225    unixLeaveMutex();
35226  }
35227#endif
35228
35229  storeLastErrno(pNew, 0);
35230#if OS_VXWORKS
35231  if( rc!=SQLITE_OK ){
35232    if( h>=0 ) robust_close(pNew, h, __LINE__);
35233    h = -1;
35234    osUnlink(zFilename);
35235    pNew->ctrlFlags |= UNIXFILE_DELETE;
35236  }
35237#endif
35238  if( rc!=SQLITE_OK ){
35239    if( h>=0 ) robust_close(pNew, h, __LINE__);
35240  }else{
35241    pNew->pMethod = pLockingStyle;
35242    OpenCounter(+1);
35243    verifyDbFile(pNew);
35244  }
35245  return rc;
35246}
35247
35248/*
35249** Return the name of a directory in which to put temporary files.
35250** If no suitable temporary file directory can be found, return NULL.
35251*/
35252static const char *unixTempFileDir(void){
35253  static const char *azDirs[] = {
35254     0,
35255     0,
35256     "/var/tmp",
35257     "/usr/tmp",
35258     "/tmp",
35259     "."
35260  };
35261  unsigned int i = 0;
35262  struct stat buf;
35263  const char *zDir = sqlite3_temp_directory;
35264
35265  if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
35266  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
35267  while(1){
35268    if( zDir!=0
35269     && osStat(zDir, &buf)==0
35270     && S_ISDIR(buf.st_mode)
35271     && osAccess(zDir, 03)==0
35272    ){
35273      return zDir;
35274    }
35275    if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
35276    zDir = azDirs[i++];
35277  }
35278  return 0;
35279}
35280
35281/*
35282** Create a temporary file name in zBuf.  zBuf must be allocated
35283** by the calling process and must be big enough to hold at least
35284** pVfs->mxPathname bytes.
35285*/
35286static int unixGetTempname(int nBuf, char *zBuf){
35287  const char *zDir;
35288  int iLimit = 0;
35289
35290  /* It's odd to simulate an io-error here, but really this is just
35291  ** using the io-error infrastructure to test that SQLite handles this
35292  ** function failing.
35293  */
35294  zBuf[0] = 0;
35295  SimulateIOError( return SQLITE_IOERR );
35296
35297  zDir = unixTempFileDir();
35298  if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
35299  do{
35300    u64 r;
35301    sqlite3_randomness(sizeof(r), &r);
35302    assert( nBuf>2 );
35303    zBuf[nBuf-2] = 0;
35304    sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
35305                     zDir, r, 0);
35306    if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
35307  }while( osAccess(zBuf,0)==0 );
35308  return SQLITE_OK;
35309}
35310
35311#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
35312/*
35313** Routine to transform a unixFile into a proxy-locking unixFile.
35314** Implementation in the proxy-lock division, but used by unixOpen()
35315** if SQLITE_PREFER_PROXY_LOCKING is defined.
35316*/
35317static int proxyTransformUnixFile(unixFile*, const char*);
35318#endif
35319
35320/*
35321** Search for an unused file descriptor that was opened on the database
35322** file (not a journal or master-journal file) identified by pathname
35323** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
35324** argument to this function.
35325**
35326** Such a file descriptor may exist if a database connection was closed
35327** but the associated file descriptor could not be closed because some
35328** other file descriptor open on the same file is holding a file-lock.
35329** Refer to comments in the unixClose() function and the lengthy comment
35330** describing "Posix Advisory Locking" at the start of this file for
35331** further details. Also, ticket #4018.
35332**
35333** If a suitable file descriptor is found, then it is returned. If no
35334** such file descriptor is located, -1 is returned.
35335*/
35336static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
35337  UnixUnusedFd *pUnused = 0;
35338
35339  /* Do not search for an unused file descriptor on vxworks. Not because
35340  ** vxworks would not benefit from the change (it might, we're not sure),
35341  ** but because no way to test it is currently available. It is better
35342  ** not to risk breaking vxworks support for the sake of such an obscure
35343  ** feature.  */
35344#if !OS_VXWORKS
35345  struct stat sStat;                   /* Results of stat() call */
35346
35347  /* A stat() call may fail for various reasons. If this happens, it is
35348  ** almost certain that an open() call on the same path will also fail.
35349  ** For this reason, if an error occurs in the stat() call here, it is
35350  ** ignored and -1 is returned. The caller will try to open a new file
35351  ** descriptor on the same path, fail, and return an error to SQLite.
35352  **
35353  ** Even if a subsequent open() call does succeed, the consequences of
35354  ** not searching for a reusable file descriptor are not dire.  */
35355  if( 0==osStat(zPath, &sStat) ){
35356    unixInodeInfo *pInode;
35357
35358    unixEnterMutex();
35359    pInode = inodeList;
35360    while( pInode && (pInode->fileId.dev!=sStat.st_dev
35361                     || pInode->fileId.ino!=(u64)sStat.st_ino) ){
35362       pInode = pInode->pNext;
35363    }
35364    if( pInode ){
35365      UnixUnusedFd **pp;
35366      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
35367      pUnused = *pp;
35368      if( pUnused ){
35369        *pp = pUnused->pNext;
35370      }
35371    }
35372    unixLeaveMutex();
35373  }
35374#endif    /* if !OS_VXWORKS */
35375  return pUnused;
35376}
35377
35378/*
35379** Find the mode, uid and gid of file zFile.
35380*/
35381static int getFileMode(
35382  const char *zFile,              /* File name */
35383  mode_t *pMode,                  /* OUT: Permissions of zFile */
35384  uid_t *pUid,                    /* OUT: uid of zFile. */
35385  gid_t *pGid                     /* OUT: gid of zFile. */
35386){
35387  struct stat sStat;              /* Output of stat() on database file */
35388  int rc = SQLITE_OK;
35389  if( 0==osStat(zFile, &sStat) ){
35390    *pMode = sStat.st_mode & 0777;
35391    *pUid = sStat.st_uid;
35392    *pGid = sStat.st_gid;
35393  }else{
35394    rc = SQLITE_IOERR_FSTAT;
35395  }
35396  return rc;
35397}
35398
35399/*
35400** This function is called by unixOpen() to determine the unix permissions
35401** to create new files with. If no error occurs, then SQLITE_OK is returned
35402** and a value suitable for passing as the third argument to open(2) is
35403** written to *pMode. If an IO error occurs, an SQLite error code is
35404** returned and the value of *pMode is not modified.
35405**
35406** In most cases, this routine sets *pMode to 0, which will become
35407** an indication to robust_open() to create the file using
35408** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
35409** But if the file being opened is a WAL or regular journal file, then
35410** this function queries the file-system for the permissions on the
35411** corresponding database file and sets *pMode to this value. Whenever
35412** possible, WAL and journal files are created using the same permissions
35413** as the associated database file.
35414**
35415** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
35416** original filename is unavailable.  But 8_3_NAMES is only used for
35417** FAT filesystems and permissions do not matter there, so just use
35418** the default permissions.
35419*/
35420static int findCreateFileMode(
35421  const char *zPath,              /* Path of file (possibly) being created */
35422  int flags,                      /* Flags passed as 4th argument to xOpen() */
35423  mode_t *pMode,                  /* OUT: Permissions to open file with */
35424  uid_t *pUid,                    /* OUT: uid to set on the file */
35425  gid_t *pGid                     /* OUT: gid to set on the file */
35426){
35427  int rc = SQLITE_OK;             /* Return Code */
35428  *pMode = 0;
35429  *pUid = 0;
35430  *pGid = 0;
35431  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
35432    char zDb[MAX_PATHNAME+1];     /* Database file path */
35433    int nDb;                      /* Number of valid bytes in zDb */
35434
35435    /* zPath is a path to a WAL or journal file. The following block derives
35436    ** the path to the associated database file from zPath. This block handles
35437    ** the following naming conventions:
35438    **
35439    **   "<path to db>-journal"
35440    **   "<path to db>-wal"
35441    **   "<path to db>-journalNN"
35442    **   "<path to db>-walNN"
35443    **
35444    ** where NN is a decimal number. The NN naming schemes are
35445    ** used by the test_multiplex.c module.
35446    */
35447    nDb = sqlite3Strlen30(zPath) - 1;
35448    while( zPath[nDb]!='-' ){
35449#ifndef SQLITE_ENABLE_8_3_NAMES
35450      /* In the normal case (8+3 filenames disabled) the journal filename
35451      ** is guaranteed to contain a '-' character. */
35452      assert( nDb>0 );
35453      assert( sqlite3Isalnum(zPath[nDb]) );
35454#else
35455      /* If 8+3 names are possible, then the journal file might not contain
35456      ** a '-' character.  So check for that case and return early. */
35457      if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
35458#endif
35459      nDb--;
35460    }
35461    memcpy(zDb, zPath, nDb);
35462    zDb[nDb] = '\0';
35463
35464    rc = getFileMode(zDb, pMode, pUid, pGid);
35465  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
35466    *pMode = 0600;
35467  }else if( flags & SQLITE_OPEN_URI ){
35468    /* If this is a main database file and the file was opened using a URI
35469    ** filename, check for the "modeof" parameter. If present, interpret
35470    ** its value as a filename and try to copy the mode, uid and gid from
35471    ** that file.  */
35472    const char *z = sqlite3_uri_parameter(zPath, "modeof");
35473    if( z ){
35474      rc = getFileMode(z, pMode, pUid, pGid);
35475    }
35476  }
35477  return rc;
35478}
35479
35480/*
35481** Open the file zPath.
35482**
35483** Previously, the SQLite OS layer used three functions in place of this
35484** one:
35485**
35486**     sqlite3OsOpenReadWrite();
35487**     sqlite3OsOpenReadOnly();
35488**     sqlite3OsOpenExclusive();
35489**
35490** These calls correspond to the following combinations of flags:
35491**
35492**     ReadWrite() ->     (READWRITE | CREATE)
35493**     ReadOnly()  ->     (READONLY)
35494**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
35495**
35496** The old OpenExclusive() accepted a boolean argument - "delFlag". If
35497** true, the file was configured to be automatically deleted when the
35498** file handle closed. To achieve the same effect using this new
35499** interface, add the DELETEONCLOSE flag to those specified above for
35500** OpenExclusive().
35501*/
35502static int unixOpen(
35503  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
35504  const char *zPath,           /* Pathname of file to be opened */
35505  sqlite3_file *pFile,         /* The file descriptor to be filled in */
35506  int flags,                   /* Input flags to control the opening */
35507  int *pOutFlags               /* Output flags returned to SQLite core */
35508){
35509  unixFile *p = (unixFile *)pFile;
35510  int fd = -1;                   /* File descriptor returned by open() */
35511  int openFlags = 0;             /* Flags to pass to open() */
35512  int eType = flags&0xFFFFFF00;  /* Type of file to open */
35513  int noLock;                    /* True to omit locking primitives */
35514  int rc = SQLITE_OK;            /* Function Return Code */
35515  int ctrlFlags = 0;             /* UNIXFILE_* flags */
35516
35517  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
35518  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
35519  int isCreate     = (flags & SQLITE_OPEN_CREATE);
35520  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
35521  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
35522#if SQLITE_ENABLE_LOCKING_STYLE
35523  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
35524#endif
35525#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
35526  struct statfs fsInfo;
35527#endif
35528
35529  /* If creating a master or main-file journal, this function will open
35530  ** a file-descriptor on the directory too. The first time unixSync()
35531  ** is called the directory file descriptor will be fsync()ed and close()d.
35532  */
35533  int syncDir = (isCreate && (
35534        eType==SQLITE_OPEN_MASTER_JOURNAL
35535     || eType==SQLITE_OPEN_MAIN_JOURNAL
35536     || eType==SQLITE_OPEN_WAL
35537  ));
35538
35539  /* If argument zPath is a NULL pointer, this function is required to open
35540  ** a temporary file. Use this buffer to store the file name in.
35541  */
35542  char zTmpname[MAX_PATHNAME+2];
35543  const char *zName = zPath;
35544
35545  /* Check the following statements are true:
35546  **
35547  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
35548  **   (b) if CREATE is set, then READWRITE must also be set, and
35549  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
35550  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
35551  */
35552  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
35553  assert(isCreate==0 || isReadWrite);
35554  assert(isExclusive==0 || isCreate);
35555  assert(isDelete==0 || isCreate);
35556
35557  /* The main DB, main journal, WAL file and master journal are never
35558  ** automatically deleted. Nor are they ever temporary files.  */
35559  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
35560  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
35561  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
35562  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
35563
35564  /* Assert that the upper layer has set one of the "file-type" flags. */
35565  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
35566       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
35567       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
35568       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
35569  );
35570
35571  /* Detect a pid change and reset the PRNG.  There is a race condition
35572  ** here such that two or more threads all trying to open databases at
35573  ** the same instant might all reset the PRNG.  But multiple resets
35574  ** are harmless.
35575  */
35576  if( randomnessPid!=osGetpid(0) ){
35577    randomnessPid = osGetpid(0);
35578    sqlite3_randomness(0,0);
35579  }
35580
35581  memset(p, 0, sizeof(unixFile));
35582
35583  if( eType==SQLITE_OPEN_MAIN_DB ){
35584    UnixUnusedFd *pUnused;
35585    pUnused = findReusableFd(zName, flags);
35586    if( pUnused ){
35587      fd = pUnused->fd;
35588    }else{
35589      pUnused = sqlite3_malloc64(sizeof(*pUnused));
35590      if( !pUnused ){
35591        return SQLITE_NOMEM_BKPT;
35592      }
35593    }
35594    p->pUnused = pUnused;
35595
35596    /* Database filenames are double-zero terminated if they are not
35597    ** URIs with parameters.  Hence, they can always be passed into
35598    ** sqlite3_uri_parameter(). */
35599    assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
35600
35601  }else if( !zName ){
35602    /* If zName is NULL, the upper layer is requesting a temp file. */
35603    assert(isDelete && !syncDir);
35604    rc = unixGetTempname(pVfs->mxPathname, zTmpname);
35605    if( rc!=SQLITE_OK ){
35606      return rc;
35607    }
35608    zName = zTmpname;
35609
35610    /* Generated temporary filenames are always double-zero terminated
35611    ** for use by sqlite3_uri_parameter(). */
35612    assert( zName[strlen(zName)+1]==0 );
35613  }
35614
35615  /* Determine the value of the flags parameter passed to POSIX function
35616  ** open(). These must be calculated even if open() is not called, as
35617  ** they may be stored as part of the file handle and used by the
35618  ** 'conch file' locking functions later on.  */
35619  if( isReadonly )  openFlags |= O_RDONLY;
35620  if( isReadWrite ) openFlags |= O_RDWR;
35621  if( isCreate )    openFlags |= O_CREAT;
35622  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
35623  openFlags |= (O_LARGEFILE|O_BINARY);
35624
35625  if( fd<0 ){
35626    mode_t openMode;              /* Permissions to create file with */
35627    uid_t uid;                    /* Userid for the file */
35628    gid_t gid;                    /* Groupid for the file */
35629    rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
35630    if( rc!=SQLITE_OK ){
35631      assert( !p->pUnused );
35632      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
35633      return rc;
35634    }
35635    fd = robust_open(zName, openFlags, openMode);
35636    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
35637    assert( !isExclusive || (openFlags & O_CREAT)!=0 );
35638    if( fd<0 && errno!=EISDIR && isReadWrite ){
35639      /* Failed to open the file for read/write access. Try read-only. */
35640      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
35641      openFlags &= ~(O_RDWR|O_CREAT);
35642      flags |= SQLITE_OPEN_READONLY;
35643      openFlags |= O_RDONLY;
35644      isReadonly = 1;
35645      fd = robust_open(zName, openFlags, openMode);
35646    }
35647    if( fd<0 ){
35648      rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
35649      goto open_finished;
35650    }
35651
35652    /* If this process is running as root and if creating a new rollback
35653    ** journal or WAL file, set the ownership of the journal or WAL to be
35654    ** the same as the original database.
35655    */
35656    if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
35657      robustFchown(fd, uid, gid);
35658    }
35659  }
35660  assert( fd>=0 );
35661  if( pOutFlags ){
35662    *pOutFlags = flags;
35663  }
35664
35665  if( p->pUnused ){
35666    p->pUnused->fd = fd;
35667    p->pUnused->flags = flags;
35668  }
35669
35670  if( isDelete ){
35671#if OS_VXWORKS
35672    zPath = zName;
35673#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
35674    zPath = sqlite3_mprintf("%s", zName);
35675    if( zPath==0 ){
35676      robust_close(p, fd, __LINE__);
35677      return SQLITE_NOMEM_BKPT;
35678    }
35679#else
35680    osUnlink(zName);
35681#endif
35682  }
35683#if SQLITE_ENABLE_LOCKING_STYLE
35684  else{
35685    p->openFlags = openFlags;
35686  }
35687#endif
35688
35689#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
35690  if( fstatfs(fd, &fsInfo) == -1 ){
35691    storeLastErrno(p, errno);
35692    robust_close(p, fd, __LINE__);
35693    return SQLITE_IOERR_ACCESS;
35694  }
35695  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
35696    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
35697  }
35698  if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
35699    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
35700  }
35701#endif
35702
35703  /* Set up appropriate ctrlFlags */
35704  if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
35705  if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
35706  noLock = eType!=SQLITE_OPEN_MAIN_DB;
35707  if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
35708  if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
35709  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
35710
35711#if SQLITE_ENABLE_LOCKING_STYLE
35712#if SQLITE_PREFER_PROXY_LOCKING
35713  isAutoProxy = 1;
35714#endif
35715  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
35716    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
35717    int useProxy = 0;
35718
35719    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
35720    ** never use proxy, NULL means use proxy for non-local files only.  */
35721    if( envforce!=NULL ){
35722      useProxy = atoi(envforce)>0;
35723    }else{
35724      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
35725    }
35726    if( useProxy ){
35727      rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
35728      if( rc==SQLITE_OK ){
35729        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
35730        if( rc!=SQLITE_OK ){
35731          /* Use unixClose to clean up the resources added in fillInUnixFile
35732          ** and clear all the structure's references.  Specifically,
35733          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
35734          */
35735          unixClose(pFile);
35736          return rc;
35737        }
35738      }
35739      goto open_finished;
35740    }
35741  }
35742#endif
35743
35744  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
35745
35746open_finished:
35747  if( rc!=SQLITE_OK ){
35748    sqlite3_free(p->pUnused);
35749  }
35750  return rc;
35751}
35752
35753
35754/*
35755** Delete the file at zPath. If the dirSync argument is true, fsync()
35756** the directory after deleting the file.
35757*/
35758static int unixDelete(
35759  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
35760  const char *zPath,        /* Name of file to be deleted */
35761  int dirSync               /* If true, fsync() directory after deleting file */
35762){
35763  int rc = SQLITE_OK;
35764  UNUSED_PARAMETER(NotUsed);
35765  SimulateIOError(return SQLITE_IOERR_DELETE);
35766  if( osUnlink(zPath)==(-1) ){
35767    if( errno==ENOENT
35768#if OS_VXWORKS
35769        || osAccess(zPath,0)!=0
35770#endif
35771    ){
35772      rc = SQLITE_IOERR_DELETE_NOENT;
35773    }else{
35774      rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
35775    }
35776    return rc;
35777  }
35778#ifndef SQLITE_DISABLE_DIRSYNC
35779  if( (dirSync & 1)!=0 ){
35780    int fd;
35781    rc = osOpenDirectory(zPath, &fd);
35782    if( rc==SQLITE_OK ){
35783      if( full_fsync(fd,0,0) ){
35784        rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
35785      }
35786      robust_close(0, fd, __LINE__);
35787    }else{
35788      assert( rc==SQLITE_CANTOPEN );
35789      rc = SQLITE_OK;
35790    }
35791  }
35792#endif
35793  return rc;
35794}
35795
35796/*
35797** Test the existence of or access permissions of file zPath. The
35798** test performed depends on the value of flags:
35799**
35800**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
35801**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
35802**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
35803**
35804** Otherwise return 0.
35805*/
35806static int unixAccess(
35807  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
35808  const char *zPath,      /* Path of the file to examine */
35809  int flags,              /* What do we want to learn about the zPath file? */
35810  int *pResOut            /* Write result boolean here */
35811){
35812  UNUSED_PARAMETER(NotUsed);
35813  SimulateIOError( return SQLITE_IOERR_ACCESS; );
35814  assert( pResOut!=0 );
35815
35816  /* The spec says there are three possible values for flags.  But only
35817  ** two of them are actually used */
35818  assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
35819
35820  if( flags==SQLITE_ACCESS_EXISTS ){
35821    struct stat buf;
35822    *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
35823  }else{
35824    *pResOut = osAccess(zPath, W_OK|R_OK)==0;
35825  }
35826  return SQLITE_OK;
35827}
35828
35829/*
35830**
35831*/
35832static int mkFullPathname(
35833  const char *zPath,              /* Input path */
35834  char *zOut,                     /* Output buffer */
35835  int nOut                        /* Allocated size of buffer zOut */
35836){
35837  int nPath = sqlite3Strlen30(zPath);
35838  int iOff = 0;
35839  if( zPath[0]!='/' ){
35840    if( osGetcwd(zOut, nOut-2)==0 ){
35841      return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
35842    }
35843    iOff = sqlite3Strlen30(zOut);
35844    zOut[iOff++] = '/';
35845  }
35846  if( (iOff+nPath+1)>nOut ){
35847    /* SQLite assumes that xFullPathname() nul-terminates the output buffer
35848    ** even if it returns an error.  */
35849    zOut[iOff] = '\0';
35850    return SQLITE_CANTOPEN_BKPT;
35851  }
35852  sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
35853  return SQLITE_OK;
35854}
35855
35856/*
35857** Turn a relative pathname into a full pathname. The relative path
35858** is stored as a nul-terminated string in the buffer pointed to by
35859** zPath.
35860**
35861** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
35862** (in this case, MAX_PATHNAME bytes). The full-path is written to
35863** this buffer before returning.
35864*/
35865static int unixFullPathname(
35866  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
35867  const char *zPath,            /* Possibly relative input path */
35868  int nOut,                     /* Size of output buffer in bytes */
35869  char *zOut                    /* Output buffer */
35870){
35871#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
35872  return mkFullPathname(zPath, zOut, nOut);
35873#else
35874  int rc = SQLITE_OK;
35875  int nByte;
35876  int nLink = 1;                /* Number of symbolic links followed so far */
35877  const char *zIn = zPath;      /* Input path for each iteration of loop */
35878  char *zDel = 0;
35879
35880  assert( pVfs->mxPathname==MAX_PATHNAME );
35881  UNUSED_PARAMETER(pVfs);
35882
35883  /* It's odd to simulate an io-error here, but really this is just
35884  ** using the io-error infrastructure to test that SQLite handles this
35885  ** function failing. This function could fail if, for example, the
35886  ** current working directory has been unlinked.
35887  */
35888  SimulateIOError( return SQLITE_ERROR );
35889
35890  do {
35891
35892    /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
35893    ** link, or false otherwise.  */
35894    int bLink = 0;
35895    struct stat buf;
35896    if( osLstat(zIn, &buf)!=0 ){
35897      if( errno!=ENOENT ){
35898        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
35899      }
35900    }else{
35901      bLink = S_ISLNK(buf.st_mode);
35902    }
35903
35904    if( bLink ){
35905      if( zDel==0 ){
35906        zDel = sqlite3_malloc(nOut);
35907        if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
35908      }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
35909        rc = SQLITE_CANTOPEN_BKPT;
35910      }
35911
35912      if( rc==SQLITE_OK ){
35913        nByte = osReadlink(zIn, zDel, nOut-1);
35914        if( nByte<0 ){
35915          rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
35916        }else{
35917          if( zDel[0]!='/' ){
35918            int n;
35919            for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
35920            if( nByte+n+1>nOut ){
35921              rc = SQLITE_CANTOPEN_BKPT;
35922            }else{
35923              memmove(&zDel[n], zDel, nByte+1);
35924              memcpy(zDel, zIn, n);
35925              nByte += n;
35926            }
35927          }
35928          zDel[nByte] = '\0';
35929        }
35930      }
35931
35932      zIn = zDel;
35933    }
35934
35935    assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
35936    if( rc==SQLITE_OK && zIn!=zOut ){
35937      rc = mkFullPathname(zIn, zOut, nOut);
35938    }
35939    if( bLink==0 ) break;
35940    zIn = zOut;
35941  }while( rc==SQLITE_OK );
35942
35943  sqlite3_free(zDel);
35944  return rc;
35945#endif   /* HAVE_READLINK && HAVE_LSTAT */
35946}
35947
35948
35949#ifndef SQLITE_OMIT_LOAD_EXTENSION
35950/*
35951** Interfaces for opening a shared library, finding entry points
35952** within the shared library, and closing the shared library.
35953*/
35954#include <dlfcn.h>
35955static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
35956  UNUSED_PARAMETER(NotUsed);
35957  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
35958}
35959
35960/*
35961** SQLite calls this function immediately after a call to unixDlSym() or
35962** unixDlOpen() fails (returns a null pointer). If a more detailed error
35963** message is available, it is written to zBufOut. If no error message
35964** is available, zBufOut is left unmodified and SQLite uses a default
35965** error message.
35966*/
35967static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
35968  const char *zErr;
35969  UNUSED_PARAMETER(NotUsed);
35970  unixEnterMutex();
35971  zErr = dlerror();
35972  if( zErr ){
35973    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
35974  }
35975  unixLeaveMutex();
35976}
35977static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
35978  /*
35979  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
35980  ** cast into a pointer to a function.  And yet the library dlsym() routine
35981  ** returns a void* which is really a pointer to a function.  So how do we
35982  ** use dlsym() with -pedantic-errors?
35983  **
35984  ** Variable x below is defined to be a pointer to a function taking
35985  ** parameters void* and const char* and returning a pointer to a function.
35986  ** We initialize x by assigning it a pointer to the dlsym() function.
35987  ** (That assignment requires a cast.)  Then we call the function that
35988  ** x points to.
35989  **
35990  ** This work-around is unlikely to work correctly on any system where
35991  ** you really cannot cast a function pointer into void*.  But then, on the
35992  ** other hand, dlsym() will not work on such a system either, so we have
35993  ** not really lost anything.
35994  */
35995  void (*(*x)(void*,const char*))(void);
35996  UNUSED_PARAMETER(NotUsed);
35997  x = (void(*(*)(void*,const char*))(void))dlsym;
35998  return (*x)(p, zSym);
35999}
36000static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
36001  UNUSED_PARAMETER(NotUsed);
36002  dlclose(pHandle);
36003}
36004#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
36005  #define unixDlOpen  0
36006  #define unixDlError 0
36007  #define unixDlSym   0
36008  #define unixDlClose 0
36009#endif
36010
36011/*
36012** Write nBuf bytes of random data to the supplied buffer zBuf.
36013*/
36014static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
36015  UNUSED_PARAMETER(NotUsed);
36016  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
36017
36018  /* We have to initialize zBuf to prevent valgrind from reporting
36019  ** errors.  The reports issued by valgrind are incorrect - we would
36020  ** prefer that the randomness be increased by making use of the
36021  ** uninitialized space in zBuf - but valgrind errors tend to worry
36022  ** some users.  Rather than argue, it seems easier just to initialize
36023  ** the whole array and silence valgrind, even if that means less randomness
36024  ** in the random seed.
36025  **
36026  ** When testing, initializing zBuf[] to zero is all we do.  That means
36027  ** that we always use the same random number sequence.  This makes the
36028  ** tests repeatable.
36029  */
36030  memset(zBuf, 0, nBuf);
36031  randomnessPid = osGetpid(0);
36032#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
36033  {
36034    int fd, got;
36035    fd = robust_open("/dev/urandom", O_RDONLY, 0);
36036    if( fd<0 ){
36037      time_t t;
36038      time(&t);
36039      memcpy(zBuf, &t, sizeof(t));
36040      memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
36041      assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
36042      nBuf = sizeof(t) + sizeof(randomnessPid);
36043    }else{
36044      do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
36045      robust_close(0, fd, __LINE__);
36046    }
36047  }
36048#endif
36049  return nBuf;
36050}
36051
36052
36053/*
36054** Sleep for a little while.  Return the amount of time slept.
36055** The argument is the number of microseconds we want to sleep.
36056** The return value is the number of microseconds of sleep actually
36057** requested from the underlying operating system, a number which
36058** might be greater than or equal to the argument, but not less
36059** than the argument.
36060*/
36061static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
36062#if OS_VXWORKS
36063  struct timespec sp;
36064
36065  sp.tv_sec = microseconds / 1000000;
36066  sp.tv_nsec = (microseconds % 1000000) * 1000;
36067  nanosleep(&sp, NULL);
36068  UNUSED_PARAMETER(NotUsed);
36069  return microseconds;
36070#elif defined(HAVE_USLEEP) && HAVE_USLEEP
36071  usleep(microseconds);
36072  UNUSED_PARAMETER(NotUsed);
36073  return microseconds;
36074#else
36075  int seconds = (microseconds+999999)/1000000;
36076  sleep(seconds);
36077  UNUSED_PARAMETER(NotUsed);
36078  return seconds*1000000;
36079#endif
36080}
36081
36082/*
36083** The following variable, if set to a non-zero value, is interpreted as
36084** the number of seconds since 1970 and is used to set the result of
36085** sqlite3OsCurrentTime() during testing.
36086*/
36087#ifdef SQLITE_TEST
36088SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
36089#endif
36090
36091/*
36092** Find the current time (in Universal Coordinated Time).  Write into *piNow
36093** the current time and date as a Julian Day number times 86_400_000.  In
36094** other words, write into *piNow the number of milliseconds since the Julian
36095** epoch of noon in Greenwich on November 24, 4714 B.C according to the
36096** proleptic Gregorian calendar.
36097**
36098** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
36099** cannot be found.
36100*/
36101static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
36102  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
36103  int rc = SQLITE_OK;
36104#if defined(NO_GETTOD)
36105  time_t t;
36106  time(&t);
36107  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
36108#elif OS_VXWORKS
36109  struct timespec sNow;
36110  clock_gettime(CLOCK_REALTIME, &sNow);
36111  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
36112#else
36113  struct timeval sNow;
36114  (void)gettimeofday(&sNow, 0);  /* Cannot fail given valid arguments */
36115  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
36116#endif
36117
36118#ifdef SQLITE_TEST
36119  if( sqlite3_current_time ){
36120    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
36121  }
36122#endif
36123  UNUSED_PARAMETER(NotUsed);
36124  return rc;
36125}
36126
36127#ifndef SQLITE_OMIT_DEPRECATED
36128/*
36129** Find the current time (in Universal Coordinated Time).  Write the
36130** current time and date as a Julian Day number into *prNow and
36131** return 0.  Return 1 if the time and date cannot be found.
36132*/
36133static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
36134  sqlite3_int64 i = 0;
36135  int rc;
36136  UNUSED_PARAMETER(NotUsed);
36137  rc = unixCurrentTimeInt64(0, &i);
36138  *prNow = i/86400000.0;
36139  return rc;
36140}
36141#else
36142# define unixCurrentTime 0
36143#endif
36144
36145/*
36146** The xGetLastError() method is designed to return a better
36147** low-level error message when operating-system problems come up
36148** during SQLite operation.  Only the integer return code is currently
36149** used.
36150*/
36151static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
36152  UNUSED_PARAMETER(NotUsed);
36153  UNUSED_PARAMETER(NotUsed2);
36154  UNUSED_PARAMETER(NotUsed3);
36155  return errno;
36156}
36157
36158
36159/*
36160************************ End of sqlite3_vfs methods ***************************
36161******************************************************************************/
36162
36163/******************************************************************************
36164************************** Begin Proxy Locking ********************************
36165**
36166** Proxy locking is a "uber-locking-method" in this sense:  It uses the
36167** other locking methods on secondary lock files.  Proxy locking is a
36168** meta-layer over top of the primitive locking implemented above.  For
36169** this reason, the division that implements of proxy locking is deferred
36170** until late in the file (here) after all of the other I/O methods have
36171** been defined - so that the primitive locking methods are available
36172** as services to help with the implementation of proxy locking.
36173**
36174****
36175**
36176** The default locking schemes in SQLite use byte-range locks on the
36177** database file to coordinate safe, concurrent access by multiple readers
36178** and writers [http://sqlite.org/lockingv3.html].  The five file locking
36179** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
36180** as POSIX read & write locks over fixed set of locations (via fsctl),
36181** on AFP and SMB only exclusive byte-range locks are available via fsctl
36182** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
36183** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
36184** address in the shared range is taken for a SHARED lock, the entire
36185** shared range is taken for an EXCLUSIVE lock):
36186**
36187**      PENDING_BYTE        0x40000000
36188**      RESERVED_BYTE       0x40000001
36189**      SHARED_RANGE        0x40000002 -> 0x40000200
36190**
36191** This works well on the local file system, but shows a nearly 100x
36192** slowdown in read performance on AFP because the AFP client disables
36193** the read cache when byte-range locks are present.  Enabling the read
36194** cache exposes a cache coherency problem that is present on all OS X
36195** supported network file systems.  NFS and AFP both observe the
36196** close-to-open semantics for ensuring cache coherency
36197** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
36198** address the requirements for concurrent database access by multiple
36199** readers and writers
36200** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
36201**
36202** To address the performance and cache coherency issues, proxy file locking
36203** changes the way database access is controlled by limiting access to a
36204** single host at a time and moving file locks off of the database file
36205** and onto a proxy file on the local file system.
36206**
36207**
36208** Using proxy locks
36209** -----------------
36210**
36211** C APIs
36212**
36213**  sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
36214**                       <proxy_path> | ":auto:");
36215**  sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
36216**                       &<proxy_path>);
36217**
36218**
36219** SQL pragmas
36220**
36221**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
36222**  PRAGMA [database.]lock_proxy_file
36223**
36224** Specifying ":auto:" means that if there is a conch file with a matching
36225** host ID in it, the proxy path in the conch file will be used, otherwise
36226** a proxy path based on the user's temp dir
36227** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
36228** actual proxy file name is generated from the name and path of the
36229** database file.  For example:
36230**
36231**       For database path "/Users/me/foo.db"
36232**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
36233**
36234** Once a lock proxy is configured for a database connection, it can not
36235** be removed, however it may be switched to a different proxy path via
36236** the above APIs (assuming the conch file is not being held by another
36237** connection or process).
36238**
36239**
36240** How proxy locking works
36241** -----------------------
36242**
36243** Proxy file locking relies primarily on two new supporting files:
36244**
36245**   *  conch file to limit access to the database file to a single host
36246**      at a time
36247**
36248**   *  proxy file to act as a proxy for the advisory locks normally
36249**      taken on the database
36250**
36251** The conch file - to use a proxy file, sqlite must first "hold the conch"
36252** by taking an sqlite-style shared lock on the conch file, reading the
36253** contents and comparing the host's unique host ID (see below) and lock
36254** proxy path against the values stored in the conch.  The conch file is
36255** stored in the same directory as the database file and the file name
36256** is patterned after the database file name as ".<databasename>-conch".
36257** If the conch file does not exist, or its contents do not match the
36258** host ID and/or proxy path, then the lock is escalated to an exclusive
36259** lock and the conch file contents is updated with the host ID and proxy
36260** path and the lock is downgraded to a shared lock again.  If the conch
36261** is held by another process (with a shared lock), the exclusive lock
36262** will fail and SQLITE_BUSY is returned.
36263**
36264** The proxy file - a single-byte file used for all advisory file locks
36265** normally taken on the database file.   This allows for safe sharing
36266** of the database file for multiple readers and writers on the same
36267** host (the conch ensures that they all use the same local lock file).
36268**
36269** Requesting the lock proxy does not immediately take the conch, it is
36270** only taken when the first request to lock database file is made.
36271** This matches the semantics of the traditional locking behavior, where
36272** opening a connection to a database file does not take a lock on it.
36273** The shared lock and an open file descriptor are maintained until
36274** the connection to the database is closed.
36275**
36276** The proxy file and the lock file are never deleted so they only need
36277** to be created the first time they are used.
36278**
36279** Configuration options
36280** ---------------------
36281**
36282**  SQLITE_PREFER_PROXY_LOCKING
36283**
36284**       Database files accessed on non-local file systems are
36285**       automatically configured for proxy locking, lock files are
36286**       named automatically using the same logic as
36287**       PRAGMA lock_proxy_file=":auto:"
36288**
36289**  SQLITE_PROXY_DEBUG
36290**
36291**       Enables the logging of error messages during host id file
36292**       retrieval and creation
36293**
36294**  LOCKPROXYDIR
36295**
36296**       Overrides the default directory used for lock proxy files that
36297**       are named automatically via the ":auto:" setting
36298**
36299**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
36300**
36301**       Permissions to use when creating a directory for storing the
36302**       lock proxy files, only used when LOCKPROXYDIR is not set.
36303**
36304**
36305** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
36306** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
36307** force proxy locking to be used for every database file opened, and 0
36308** will force automatic proxy locking to be disabled for all database
36309** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
36310** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
36311*/
36312
36313/*
36314** Proxy locking is only available on MacOSX
36315*/
36316#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
36317
36318/*
36319** The proxyLockingContext has the path and file structures for the remote
36320** and local proxy files in it
36321*/
36322typedef struct proxyLockingContext proxyLockingContext;
36323struct proxyLockingContext {
36324  unixFile *conchFile;         /* Open conch file */
36325  char *conchFilePath;         /* Name of the conch file */
36326  unixFile *lockProxy;         /* Open proxy lock file */
36327  char *lockProxyPath;         /* Name of the proxy lock file */
36328  char *dbPath;                /* Name of the open file */
36329  int conchHeld;               /* 1 if the conch is held, -1 if lockless */
36330  int nFails;                  /* Number of conch taking failures */
36331  void *oldLockingContext;     /* Original lockingcontext to restore on close */
36332  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
36333};
36334
36335/*
36336** The proxy lock file path for the database at dbPath is written into lPath,
36337** which must point to valid, writable memory large enough for a maxLen length
36338** file path.
36339*/
36340static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
36341  int len;
36342  int dbLen;
36343  int i;
36344
36345#ifdef LOCKPROXYDIR
36346  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
36347#else
36348# ifdef _CS_DARWIN_USER_TEMP_DIR
36349  {
36350    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
36351      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
36352               lPath, errno, osGetpid(0)));
36353      return SQLITE_IOERR_LOCK;
36354    }
36355    len = strlcat(lPath, "sqliteplocks", maxLen);
36356  }
36357# else
36358  len = strlcpy(lPath, "/tmp/", maxLen);
36359# endif
36360#endif
36361
36362  if( lPath[len-1]!='/' ){
36363    len = strlcat(lPath, "/", maxLen);
36364  }
36365
36366  /* transform the db path to a unique cache name */
36367  dbLen = (int)strlen(dbPath);
36368  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
36369    char c = dbPath[i];
36370    lPath[i+len] = (c=='/')?'_':c;
36371  }
36372  lPath[i+len]='\0';
36373  strlcat(lPath, ":auto:", maxLen);
36374  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
36375  return SQLITE_OK;
36376}
36377
36378/*
36379 ** Creates the lock file and any missing directories in lockPath
36380 */
36381static int proxyCreateLockPath(const char *lockPath){
36382  int i, len;
36383  char buf[MAXPATHLEN];
36384  int start = 0;
36385
36386  assert(lockPath!=NULL);
36387  /* try to create all the intermediate directories */
36388  len = (int)strlen(lockPath);
36389  buf[0] = lockPath[0];
36390  for( i=1; i<len; i++ ){
36391    if( lockPath[i] == '/' && (i - start > 0) ){
36392      /* only mkdir if leaf dir != "." or "/" or ".." */
36393      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
36394         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
36395        buf[i]='\0';
36396        if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
36397          int err=errno;
36398          if( err!=EEXIST ) {
36399            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
36400                     "'%s' proxy lock path=%s pid=%d\n",
36401                     buf, strerror(err), lockPath, osGetpid(0)));
36402            return err;
36403          }
36404        }
36405      }
36406      start=i+1;
36407    }
36408    buf[i] = lockPath[i];
36409  }
36410  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
36411  return 0;
36412}
36413
36414/*
36415** Create a new VFS file descriptor (stored in memory obtained from
36416** sqlite3_malloc) and open the file named "path" in the file descriptor.
36417**
36418** The caller is responsible not only for closing the file descriptor
36419** but also for freeing the memory associated with the file descriptor.
36420*/
36421static int proxyCreateUnixFile(
36422    const char *path,        /* path for the new unixFile */
36423    unixFile **ppFile,       /* unixFile created and returned by ref */
36424    int islockfile           /* if non zero missing dirs will be created */
36425) {
36426  int fd = -1;
36427  unixFile *pNew;
36428  int rc = SQLITE_OK;
36429  int openFlags = O_RDWR | O_CREAT;
36430  sqlite3_vfs dummyVfs;
36431  int terrno = 0;
36432  UnixUnusedFd *pUnused = NULL;
36433
36434  /* 1. first try to open/create the file
36435  ** 2. if that fails, and this is a lock file (not-conch), try creating
36436  ** the parent directories and then try again.
36437  ** 3. if that fails, try to open the file read-only
36438  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
36439  */
36440  pUnused = findReusableFd(path, openFlags);
36441  if( pUnused ){
36442    fd = pUnused->fd;
36443  }else{
36444    pUnused = sqlite3_malloc64(sizeof(*pUnused));
36445    if( !pUnused ){
36446      return SQLITE_NOMEM_BKPT;
36447    }
36448  }
36449  if( fd<0 ){
36450    fd = robust_open(path, openFlags, 0);
36451    terrno = errno;
36452    if( fd<0 && errno==ENOENT && islockfile ){
36453      if( proxyCreateLockPath(path) == SQLITE_OK ){
36454        fd = robust_open(path, openFlags, 0);
36455      }
36456    }
36457  }
36458  if( fd<0 ){
36459    openFlags = O_RDONLY;
36460    fd = robust_open(path, openFlags, 0);
36461    terrno = errno;
36462  }
36463  if( fd<0 ){
36464    if( islockfile ){
36465      return SQLITE_BUSY;
36466    }
36467    switch (terrno) {
36468      case EACCES:
36469        return SQLITE_PERM;
36470      case EIO:
36471        return SQLITE_IOERR_LOCK; /* even though it is the conch */
36472      default:
36473        return SQLITE_CANTOPEN_BKPT;
36474    }
36475  }
36476
36477  pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
36478  if( pNew==NULL ){
36479    rc = SQLITE_NOMEM_BKPT;
36480    goto end_create_proxy;
36481  }
36482  memset(pNew, 0, sizeof(unixFile));
36483  pNew->openFlags = openFlags;
36484  memset(&dummyVfs, 0, sizeof(dummyVfs));
36485  dummyVfs.pAppData = (void*)&autolockIoFinder;
36486  dummyVfs.zName = "dummy";
36487  pUnused->fd = fd;
36488  pUnused->flags = openFlags;
36489  pNew->pUnused = pUnused;
36490
36491  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
36492  if( rc==SQLITE_OK ){
36493    *ppFile = pNew;
36494    return SQLITE_OK;
36495  }
36496end_create_proxy:
36497  robust_close(pNew, fd, __LINE__);
36498  sqlite3_free(pNew);
36499  sqlite3_free(pUnused);
36500  return rc;
36501}
36502
36503#ifdef SQLITE_TEST
36504/* simulate multiple hosts by creating unique hostid file paths */
36505SQLITE_API int sqlite3_hostid_num = 0;
36506#endif
36507
36508#define PROXY_HOSTIDLEN    16  /* conch file host id length */
36509
36510#ifdef HAVE_GETHOSTUUID
36511/* Not always defined in the headers as it ought to be */
36512extern int gethostuuid(uuid_t id, const struct timespec *wait);
36513#endif
36514
36515/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
36516** bytes of writable memory.
36517*/
36518static int proxyGetHostID(unsigned char *pHostID, int *pError){
36519  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
36520  memset(pHostID, 0, PROXY_HOSTIDLEN);
36521#ifdef HAVE_GETHOSTUUID
36522  {
36523    struct timespec timeout = {1, 0}; /* 1 sec timeout */
36524    if( gethostuuid(pHostID, &timeout) ){
36525      int err = errno;
36526      if( pError ){
36527        *pError = err;
36528      }
36529      return SQLITE_IOERR;
36530    }
36531  }
36532#else
36533  UNUSED_PARAMETER(pError);
36534#endif
36535#ifdef SQLITE_TEST
36536  /* simulate multiple hosts by creating unique hostid file paths */
36537  if( sqlite3_hostid_num != 0){
36538    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
36539  }
36540#endif
36541
36542  return SQLITE_OK;
36543}
36544
36545/* The conch file contains the header, host id and lock file path
36546 */
36547#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
36548#define PROXY_HEADERLEN    1   /* conch file header length */
36549#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
36550#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
36551
36552/*
36553** Takes an open conch file, copies the contents to a new path and then moves
36554** it back.  The newly created file's file descriptor is assigned to the
36555** conch file structure and finally the original conch file descriptor is
36556** closed.  Returns zero if successful.
36557*/
36558static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
36559  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36560  unixFile *conchFile = pCtx->conchFile;
36561  char tPath[MAXPATHLEN];
36562  char buf[PROXY_MAXCONCHLEN];
36563  char *cPath = pCtx->conchFilePath;
36564  size_t readLen = 0;
36565  size_t pathLen = 0;
36566  char errmsg[64] = "";
36567  int fd = -1;
36568  int rc = -1;
36569  UNUSED_PARAMETER(myHostID);
36570
36571  /* create a new path by replace the trailing '-conch' with '-break' */
36572  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
36573  if( pathLen>MAXPATHLEN || pathLen<6 ||
36574     (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
36575    sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
36576    goto end_breaklock;
36577  }
36578  /* read the conch content */
36579  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
36580  if( readLen<PROXY_PATHINDEX ){
36581    sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
36582    goto end_breaklock;
36583  }
36584  /* write it out to the temporary break file */
36585  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
36586  if( fd<0 ){
36587    sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
36588    goto end_breaklock;
36589  }
36590  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
36591    sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
36592    goto end_breaklock;
36593  }
36594  if( rename(tPath, cPath) ){
36595    sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
36596    goto end_breaklock;
36597  }
36598  rc = 0;
36599  fprintf(stderr, "broke stale lock on %s\n", cPath);
36600  robust_close(pFile, conchFile->h, __LINE__);
36601  conchFile->h = fd;
36602  conchFile->openFlags = O_RDWR | O_CREAT;
36603
36604end_breaklock:
36605  if( rc ){
36606    if( fd>=0 ){
36607      osUnlink(tPath);
36608      robust_close(pFile, fd, __LINE__);
36609    }
36610    fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
36611  }
36612  return rc;
36613}
36614
36615/* Take the requested lock on the conch file and break a stale lock if the
36616** host id matches.
36617*/
36618static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
36619  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36620  unixFile *conchFile = pCtx->conchFile;
36621  int rc = SQLITE_OK;
36622  int nTries = 0;
36623  struct timespec conchModTime;
36624
36625  memset(&conchModTime, 0, sizeof(conchModTime));
36626  do {
36627    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
36628    nTries ++;
36629    if( rc==SQLITE_BUSY ){
36630      /* If the lock failed (busy):
36631       * 1st try: get the mod time of the conch, wait 0.5s and try again.
36632       * 2nd try: fail if the mod time changed or host id is different, wait
36633       *           10 sec and try again
36634       * 3rd try: break the lock unless the mod time has changed.
36635       */
36636      struct stat buf;
36637      if( osFstat(conchFile->h, &buf) ){
36638        storeLastErrno(pFile, errno);
36639        return SQLITE_IOERR_LOCK;
36640      }
36641
36642      if( nTries==1 ){
36643        conchModTime = buf.st_mtimespec;
36644        usleep(500000); /* wait 0.5 sec and try the lock again*/
36645        continue;
36646      }
36647
36648      assert( nTries>1 );
36649      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
36650         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
36651        return SQLITE_BUSY;
36652      }
36653
36654      if( nTries==2 ){
36655        char tBuf[PROXY_MAXCONCHLEN];
36656        int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
36657        if( len<0 ){
36658          storeLastErrno(pFile, errno);
36659          return SQLITE_IOERR_LOCK;
36660        }
36661        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
36662          /* don't break the lock if the host id doesn't match */
36663          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
36664            return SQLITE_BUSY;
36665          }
36666        }else{
36667          /* don't break the lock on short read or a version mismatch */
36668          return SQLITE_BUSY;
36669        }
36670        usleep(10000000); /* wait 10 sec and try the lock again */
36671        continue;
36672      }
36673
36674      assert( nTries==3 );
36675      if( 0==proxyBreakConchLock(pFile, myHostID) ){
36676        rc = SQLITE_OK;
36677        if( lockType==EXCLUSIVE_LOCK ){
36678          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
36679        }
36680        if( !rc ){
36681          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
36682        }
36683      }
36684    }
36685  } while( rc==SQLITE_BUSY && nTries<3 );
36686
36687  return rc;
36688}
36689
36690/* Takes the conch by taking a shared lock and read the contents conch, if
36691** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
36692** lockPath means that the lockPath in the conch file will be used if the
36693** host IDs match, or a new lock path will be generated automatically
36694** and written to the conch file.
36695*/
36696static int proxyTakeConch(unixFile *pFile){
36697  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36698
36699  if( pCtx->conchHeld!=0 ){
36700    return SQLITE_OK;
36701  }else{
36702    unixFile *conchFile = pCtx->conchFile;
36703    uuid_t myHostID;
36704    int pError = 0;
36705    char readBuf[PROXY_MAXCONCHLEN];
36706    char lockPath[MAXPATHLEN];
36707    char *tempLockPath = NULL;
36708    int rc = SQLITE_OK;
36709    int createConch = 0;
36710    int hostIdMatch = 0;
36711    int readLen = 0;
36712    int tryOldLockPath = 0;
36713    int forceNewLockPath = 0;
36714
36715    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
36716             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
36717             osGetpid(0)));
36718
36719    rc = proxyGetHostID(myHostID, &pError);
36720    if( (rc&0xff)==SQLITE_IOERR ){
36721      storeLastErrno(pFile, pError);
36722      goto end_takeconch;
36723    }
36724    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
36725    if( rc!=SQLITE_OK ){
36726      goto end_takeconch;
36727    }
36728    /* read the existing conch file */
36729    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
36730    if( readLen<0 ){
36731      /* I/O error: lastErrno set by seekAndRead */
36732      storeLastErrno(pFile, conchFile->lastErrno);
36733      rc = SQLITE_IOERR_READ;
36734      goto end_takeconch;
36735    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
36736             readBuf[0]!=(char)PROXY_CONCHVERSION ){
36737      /* a short read or version format mismatch means we need to create a new
36738      ** conch file.
36739      */
36740      createConch = 1;
36741    }
36742    /* if the host id matches and the lock path already exists in the conch
36743    ** we'll try to use the path there, if we can't open that path, we'll
36744    ** retry with a new auto-generated path
36745    */
36746    do { /* in case we need to try again for an :auto: named lock file */
36747
36748      if( !createConch && !forceNewLockPath ){
36749        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
36750                                  PROXY_HOSTIDLEN);
36751        /* if the conch has data compare the contents */
36752        if( !pCtx->lockProxyPath ){
36753          /* for auto-named local lock file, just check the host ID and we'll
36754           ** use the local lock file path that's already in there
36755           */
36756          if( hostIdMatch ){
36757            size_t pathLen = (readLen - PROXY_PATHINDEX);
36758
36759            if( pathLen>=MAXPATHLEN ){
36760              pathLen=MAXPATHLEN-1;
36761            }
36762            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
36763            lockPath[pathLen] = 0;
36764            tempLockPath = lockPath;
36765            tryOldLockPath = 1;
36766            /* create a copy of the lock path if the conch is taken */
36767            goto end_takeconch;
36768          }
36769        }else if( hostIdMatch
36770               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
36771                           readLen-PROXY_PATHINDEX)
36772        ){
36773          /* conch host and lock path match */
36774          goto end_takeconch;
36775        }
36776      }
36777
36778      /* if the conch isn't writable and doesn't match, we can't take it */
36779      if( (conchFile->openFlags&O_RDWR) == 0 ){
36780        rc = SQLITE_BUSY;
36781        goto end_takeconch;
36782      }
36783
36784      /* either the conch didn't match or we need to create a new one */
36785      if( !pCtx->lockProxyPath ){
36786        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
36787        tempLockPath = lockPath;
36788        /* create a copy of the lock path _only_ if the conch is taken */
36789      }
36790
36791      /* update conch with host and path (this will fail if other process
36792      ** has a shared lock already), if the host id matches, use the big
36793      ** stick.
36794      */
36795      futimes(conchFile->h, NULL);
36796      if( hostIdMatch && !createConch ){
36797        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
36798          /* We are trying for an exclusive lock but another thread in this
36799           ** same process is still holding a shared lock. */
36800          rc = SQLITE_BUSY;
36801        } else {
36802          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
36803        }
36804      }else{
36805        rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
36806      }
36807      if( rc==SQLITE_OK ){
36808        char writeBuffer[PROXY_MAXCONCHLEN];
36809        int writeSize = 0;
36810
36811        writeBuffer[0] = (char)PROXY_CONCHVERSION;
36812        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
36813        if( pCtx->lockProxyPath!=NULL ){
36814          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
36815                  MAXPATHLEN);
36816        }else{
36817          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
36818        }
36819        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
36820        robust_ftruncate(conchFile->h, writeSize);
36821        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
36822        full_fsync(conchFile->h,0,0);
36823        /* If we created a new conch file (not just updated the contents of a
36824         ** valid conch file), try to match the permissions of the database
36825         */
36826        if( rc==SQLITE_OK && createConch ){
36827          struct stat buf;
36828          int err = osFstat(pFile->h, &buf);
36829          if( err==0 ){
36830            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
36831                                        S_IROTH|S_IWOTH);
36832            /* try to match the database file R/W permissions, ignore failure */
36833#ifndef SQLITE_PROXY_DEBUG
36834            osFchmod(conchFile->h, cmode);
36835#else
36836            do{
36837              rc = osFchmod(conchFile->h, cmode);
36838            }while( rc==(-1) && errno==EINTR );
36839            if( rc!=0 ){
36840              int code = errno;
36841              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
36842                      cmode, code, strerror(code));
36843            } else {
36844              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
36845            }
36846          }else{
36847            int code = errno;
36848            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
36849                    err, code, strerror(code));
36850#endif
36851          }
36852        }
36853      }
36854      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
36855
36856    end_takeconch:
36857      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
36858      if( rc==SQLITE_OK && pFile->openFlags ){
36859        int fd;
36860        if( pFile->h>=0 ){
36861          robust_close(pFile, pFile->h, __LINE__);
36862        }
36863        pFile->h = -1;
36864        fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
36865        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
36866        if( fd>=0 ){
36867          pFile->h = fd;
36868        }else{
36869          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
36870           during locking */
36871        }
36872      }
36873      if( rc==SQLITE_OK && !pCtx->lockProxy ){
36874        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
36875        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
36876        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
36877          /* we couldn't create the proxy lock file with the old lock file path
36878           ** so try again via auto-naming
36879           */
36880          forceNewLockPath = 1;
36881          tryOldLockPath = 0;
36882          continue; /* go back to the do {} while start point, try again */
36883        }
36884      }
36885      if( rc==SQLITE_OK ){
36886        /* Need to make a copy of path if we extracted the value
36887         ** from the conch file or the path was allocated on the stack
36888         */
36889        if( tempLockPath ){
36890          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
36891          if( !pCtx->lockProxyPath ){
36892            rc = SQLITE_NOMEM_BKPT;
36893          }
36894        }
36895      }
36896      if( rc==SQLITE_OK ){
36897        pCtx->conchHeld = 1;
36898
36899        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
36900          afpLockingContext *afpCtx;
36901          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
36902          afpCtx->dbPath = pCtx->lockProxyPath;
36903        }
36904      } else {
36905        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
36906      }
36907      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
36908               rc==SQLITE_OK?"ok":"failed"));
36909      return rc;
36910    } while (1); /* in case we need to retry the :auto: lock file -
36911                 ** we should never get here except via the 'continue' call. */
36912  }
36913}
36914
36915/*
36916** If pFile holds a lock on a conch file, then release that lock.
36917*/
36918static int proxyReleaseConch(unixFile *pFile){
36919  int rc = SQLITE_OK;         /* Subroutine return code */
36920  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
36921  unixFile *conchFile;        /* Name of the conch file */
36922
36923  pCtx = (proxyLockingContext *)pFile->lockingContext;
36924  conchFile = pCtx->conchFile;
36925  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
36926           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
36927           osGetpid(0)));
36928  if( pCtx->conchHeld>0 ){
36929    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
36930  }
36931  pCtx->conchHeld = 0;
36932  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
36933           (rc==SQLITE_OK ? "ok" : "failed")));
36934  return rc;
36935}
36936
36937/*
36938** Given the name of a database file, compute the name of its conch file.
36939** Store the conch filename in memory obtained from sqlite3_malloc64().
36940** Make *pConchPath point to the new name.  Return SQLITE_OK on success
36941** or SQLITE_NOMEM if unable to obtain memory.
36942**
36943** The caller is responsible for ensuring that the allocated memory
36944** space is eventually freed.
36945**
36946** *pConchPath is set to NULL if a memory allocation error occurs.
36947*/
36948static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
36949  int i;                        /* Loop counter */
36950  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
36951  char *conchPath;              /* buffer in which to construct conch name */
36952
36953  /* Allocate space for the conch filename and initialize the name to
36954  ** the name of the original database file. */
36955  *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
36956  if( conchPath==0 ){
36957    return SQLITE_NOMEM_BKPT;
36958  }
36959  memcpy(conchPath, dbPath, len+1);
36960
36961  /* now insert a "." before the last / character */
36962  for( i=(len-1); i>=0; i-- ){
36963    if( conchPath[i]=='/' ){
36964      i++;
36965      break;
36966    }
36967  }
36968  conchPath[i]='.';
36969  while ( i<len ){
36970    conchPath[i+1]=dbPath[i];
36971    i++;
36972  }
36973
36974  /* append the "-conch" suffix to the file */
36975  memcpy(&conchPath[i+1], "-conch", 7);
36976  assert( (int)strlen(conchPath) == len+7 );
36977
36978  return SQLITE_OK;
36979}
36980
36981
36982/* Takes a fully configured proxy locking-style unix file and switches
36983** the local lock file path
36984*/
36985static int switchLockProxyPath(unixFile *pFile, const char *path) {
36986  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
36987  char *oldPath = pCtx->lockProxyPath;
36988  int rc = SQLITE_OK;
36989
36990  if( pFile->eFileLock!=NO_LOCK ){
36991    return SQLITE_BUSY;
36992  }
36993
36994  /* nothing to do if the path is NULL, :auto: or matches the existing path */
36995  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
36996    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
36997    return SQLITE_OK;
36998  }else{
36999    unixFile *lockProxy = pCtx->lockProxy;
37000    pCtx->lockProxy=NULL;
37001    pCtx->conchHeld = 0;
37002    if( lockProxy!=NULL ){
37003      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
37004      if( rc ) return rc;
37005      sqlite3_free(lockProxy);
37006    }
37007    sqlite3_free(oldPath);
37008    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
37009  }
37010
37011  return rc;
37012}
37013
37014/*
37015** pFile is a file that has been opened by a prior xOpen call.  dbPath
37016** is a string buffer at least MAXPATHLEN+1 characters in size.
37017**
37018** This routine find the filename associated with pFile and writes it
37019** int dbPath.
37020*/
37021static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
37022#if defined(__APPLE__)
37023  if( pFile->pMethod == &afpIoMethods ){
37024    /* afp style keeps a reference to the db path in the filePath field
37025    ** of the struct */
37026    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
37027    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
37028            MAXPATHLEN);
37029  } else
37030#endif
37031  if( pFile->pMethod == &dotlockIoMethods ){
37032    /* dot lock style uses the locking context to store the dot lock
37033    ** file path */
37034    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
37035    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
37036  }else{
37037    /* all other styles use the locking context to store the db file path */
37038    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
37039    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
37040  }
37041  return SQLITE_OK;
37042}
37043
37044/*
37045** Takes an already filled in unix file and alters it so all file locking
37046** will be performed on the local proxy lock file.  The following fields
37047** are preserved in the locking context so that they can be restored and
37048** the unix structure properly cleaned up at close time:
37049**  ->lockingContext
37050**  ->pMethod
37051*/
37052static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
37053  proxyLockingContext *pCtx;
37054  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
37055  char *lockPath=NULL;
37056  int rc = SQLITE_OK;
37057
37058  if( pFile->eFileLock!=NO_LOCK ){
37059    return SQLITE_BUSY;
37060  }
37061  proxyGetDbPathForUnixFile(pFile, dbPath);
37062  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
37063    lockPath=NULL;
37064  }else{
37065    lockPath=(char *)path;
37066  }
37067
37068  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
37069           (lockPath ? lockPath : ":auto:"), osGetpid(0)));
37070
37071  pCtx = sqlite3_malloc64( sizeof(*pCtx) );
37072  if( pCtx==0 ){
37073    return SQLITE_NOMEM_BKPT;
37074  }
37075  memset(pCtx, 0, sizeof(*pCtx));
37076
37077  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
37078  if( rc==SQLITE_OK ){
37079    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
37080    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
37081      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
37082      ** (c) the file system is read-only, then enable no-locking access.
37083      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
37084      ** that openFlags will have only one of O_RDONLY or O_RDWR.
37085      */
37086      struct statfs fsInfo;
37087      struct stat conchInfo;
37088      int goLockless = 0;
37089
37090      if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
37091        int err = errno;
37092        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
37093          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
37094        }
37095      }
37096      if( goLockless ){
37097        pCtx->conchHeld = -1; /* read only FS/ lockless */
37098        rc = SQLITE_OK;
37099      }
37100    }
37101  }
37102  if( rc==SQLITE_OK && lockPath ){
37103    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
37104  }
37105
37106  if( rc==SQLITE_OK ){
37107    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
37108    if( pCtx->dbPath==NULL ){
37109      rc = SQLITE_NOMEM_BKPT;
37110    }
37111  }
37112  if( rc==SQLITE_OK ){
37113    /* all memory is allocated, proxys are created and assigned,
37114    ** switch the locking context and pMethod then return.
37115    */
37116    pCtx->oldLockingContext = pFile->lockingContext;
37117    pFile->lockingContext = pCtx;
37118    pCtx->pOldMethod = pFile->pMethod;
37119    pFile->pMethod = &proxyIoMethods;
37120  }else{
37121    if( pCtx->conchFile ){
37122      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
37123      sqlite3_free(pCtx->conchFile);
37124    }
37125    sqlite3DbFree(0, pCtx->lockProxyPath);
37126    sqlite3_free(pCtx->conchFilePath);
37127    sqlite3_free(pCtx);
37128  }
37129  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
37130           (rc==SQLITE_OK ? "ok" : "failed")));
37131  return rc;
37132}
37133
37134
37135/*
37136** This routine handles sqlite3_file_control() calls that are specific
37137** to proxy locking.
37138*/
37139static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
37140  switch( op ){
37141    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
37142      unixFile *pFile = (unixFile*)id;
37143      if( pFile->pMethod == &proxyIoMethods ){
37144        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
37145        proxyTakeConch(pFile);
37146        if( pCtx->lockProxyPath ){
37147          *(const char **)pArg = pCtx->lockProxyPath;
37148        }else{
37149          *(const char **)pArg = ":auto: (not held)";
37150        }
37151      } else {
37152        *(const char **)pArg = NULL;
37153      }
37154      return SQLITE_OK;
37155    }
37156    case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
37157      unixFile *pFile = (unixFile*)id;
37158      int rc = SQLITE_OK;
37159      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
37160      if( pArg==NULL || (const char *)pArg==0 ){
37161        if( isProxyStyle ){
37162          /* turn off proxy locking - not supported.  If support is added for
37163          ** switching proxy locking mode off then it will need to fail if
37164          ** the journal mode is WAL mode.
37165          */
37166          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
37167        }else{
37168          /* turn off proxy locking - already off - NOOP */
37169          rc = SQLITE_OK;
37170        }
37171      }else{
37172        const char *proxyPath = (const char *)pArg;
37173        if( isProxyStyle ){
37174          proxyLockingContext *pCtx =
37175            (proxyLockingContext*)pFile->lockingContext;
37176          if( !strcmp(pArg, ":auto:")
37177           || (pCtx->lockProxyPath &&
37178               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
37179          ){
37180            rc = SQLITE_OK;
37181          }else{
37182            rc = switchLockProxyPath(pFile, proxyPath);
37183          }
37184        }else{
37185          /* turn on proxy file locking */
37186          rc = proxyTransformUnixFile(pFile, proxyPath);
37187        }
37188      }
37189      return rc;
37190    }
37191    default: {
37192      assert( 0 );  /* The call assures that only valid opcodes are sent */
37193    }
37194  }
37195  /*NOTREACHED*/
37196  return SQLITE_ERROR;
37197}
37198
37199/*
37200** Within this division (the proxying locking implementation) the procedures
37201** above this point are all utilities.  The lock-related methods of the
37202** proxy-locking sqlite3_io_method object follow.
37203*/
37204
37205
37206/*
37207** This routine checks if there is a RESERVED lock held on the specified
37208** file by this or any other process. If such a lock is held, set *pResOut
37209** to a non-zero value otherwise *pResOut is set to zero.  The return value
37210** is set to SQLITE_OK unless an I/O error occurs during lock checking.
37211*/
37212static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
37213  unixFile *pFile = (unixFile*)id;
37214  int rc = proxyTakeConch(pFile);
37215  if( rc==SQLITE_OK ){
37216    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37217    if( pCtx->conchHeld>0 ){
37218      unixFile *proxy = pCtx->lockProxy;
37219      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
37220    }else{ /* conchHeld < 0 is lockless */
37221      pResOut=0;
37222    }
37223  }
37224  return rc;
37225}
37226
37227/*
37228** Lock the file with the lock specified by parameter eFileLock - one
37229** of the following:
37230**
37231**     (1) SHARED_LOCK
37232**     (2) RESERVED_LOCK
37233**     (3) PENDING_LOCK
37234**     (4) EXCLUSIVE_LOCK
37235**
37236** Sometimes when requesting one lock state, additional lock states
37237** are inserted in between.  The locking might fail on one of the later
37238** transitions leaving the lock state different from what it started but
37239** still short of its goal.  The following chart shows the allowed
37240** transitions and the inserted intermediate states:
37241**
37242**    UNLOCKED -> SHARED
37243**    SHARED -> RESERVED
37244**    SHARED -> (PENDING) -> EXCLUSIVE
37245**    RESERVED -> (PENDING) -> EXCLUSIVE
37246**    PENDING -> EXCLUSIVE
37247**
37248** This routine will only increase a lock.  Use the sqlite3OsUnlock()
37249** routine to lower a locking level.
37250*/
37251static int proxyLock(sqlite3_file *id, int eFileLock) {
37252  unixFile *pFile = (unixFile*)id;
37253  int rc = proxyTakeConch(pFile);
37254  if( rc==SQLITE_OK ){
37255    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37256    if( pCtx->conchHeld>0 ){
37257      unixFile *proxy = pCtx->lockProxy;
37258      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
37259      pFile->eFileLock = proxy->eFileLock;
37260    }else{
37261      /* conchHeld < 0 is lockless */
37262    }
37263  }
37264  return rc;
37265}
37266
37267
37268/*
37269** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
37270** must be either NO_LOCK or SHARED_LOCK.
37271**
37272** If the locking level of the file descriptor is already at or below
37273** the requested locking level, this routine is a no-op.
37274*/
37275static int proxyUnlock(sqlite3_file *id, int eFileLock) {
37276  unixFile *pFile = (unixFile*)id;
37277  int rc = proxyTakeConch(pFile);
37278  if( rc==SQLITE_OK ){
37279    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37280    if( pCtx->conchHeld>0 ){
37281      unixFile *proxy = pCtx->lockProxy;
37282      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
37283      pFile->eFileLock = proxy->eFileLock;
37284    }else{
37285      /* conchHeld < 0 is lockless */
37286    }
37287  }
37288  return rc;
37289}
37290
37291/*
37292** Close a file that uses proxy locks.
37293*/
37294static int proxyClose(sqlite3_file *id) {
37295  if( ALWAYS(id) ){
37296    unixFile *pFile = (unixFile*)id;
37297    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37298    unixFile *lockProxy = pCtx->lockProxy;
37299    unixFile *conchFile = pCtx->conchFile;
37300    int rc = SQLITE_OK;
37301
37302    if( lockProxy ){
37303      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
37304      if( rc ) return rc;
37305      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
37306      if( rc ) return rc;
37307      sqlite3_free(lockProxy);
37308      pCtx->lockProxy = 0;
37309    }
37310    if( conchFile ){
37311      if( pCtx->conchHeld ){
37312        rc = proxyReleaseConch(pFile);
37313        if( rc ) return rc;
37314      }
37315      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
37316      if( rc ) return rc;
37317      sqlite3_free(conchFile);
37318    }
37319    sqlite3DbFree(0, pCtx->lockProxyPath);
37320    sqlite3_free(pCtx->conchFilePath);
37321    sqlite3DbFree(0, pCtx->dbPath);
37322    /* restore the original locking context and pMethod then close it */
37323    pFile->lockingContext = pCtx->oldLockingContext;
37324    pFile->pMethod = pCtx->pOldMethod;
37325    sqlite3_free(pCtx);
37326    return pFile->pMethod->xClose(id);
37327  }
37328  return SQLITE_OK;
37329}
37330
37331
37332
37333#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
37334/*
37335** The proxy locking style is intended for use with AFP filesystems.
37336** And since AFP is only supported on MacOSX, the proxy locking is also
37337** restricted to MacOSX.
37338**
37339**
37340******************* End of the proxy lock implementation **********************
37341******************************************************************************/
37342
37343/*
37344** Initialize the operating system interface.
37345**
37346** This routine registers all VFS implementations for unix-like operating
37347** systems.  This routine, and the sqlite3_os_end() routine that follows,
37348** should be the only routines in this file that are visible from other
37349** files.
37350**
37351** This routine is called once during SQLite initialization and by a
37352** single thread.  The memory allocation and mutex subsystems have not
37353** necessarily been initialized when this routine is called, and so they
37354** should not be used.
37355*/
37356SQLITE_API int sqlite3_os_init(void){
37357  /*
37358  ** The following macro defines an initializer for an sqlite3_vfs object.
37359  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
37360  ** to the "finder" function.  (pAppData is a pointer to a pointer because
37361  ** silly C90 rules prohibit a void* from being cast to a function pointer
37362  ** and so we have to go through the intermediate pointer to avoid problems
37363  ** when compiling with -pedantic-errors on GCC.)
37364  **
37365  ** The FINDER parameter to this macro is the name of the pointer to the
37366  ** finder-function.  The finder-function returns a pointer to the
37367  ** sqlite_io_methods object that implements the desired locking
37368  ** behaviors.  See the division above that contains the IOMETHODS
37369  ** macro for addition information on finder-functions.
37370  **
37371  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
37372  ** object.  But the "autolockIoFinder" available on MacOSX does a little
37373  ** more than that; it looks at the filesystem type that hosts the
37374  ** database file and tries to choose an locking method appropriate for
37375  ** that filesystem time.
37376  */
37377  #define UNIXVFS(VFSNAME, FINDER) {                        \
37378    3,                    /* iVersion */                    \
37379    sizeof(unixFile),     /* szOsFile */                    \
37380    MAX_PATHNAME,         /* mxPathname */                  \
37381    0,                    /* pNext */                       \
37382    VFSNAME,              /* zName */                       \
37383    (void*)&FINDER,       /* pAppData */                    \
37384    unixOpen,             /* xOpen */                       \
37385    unixDelete,           /* xDelete */                     \
37386    unixAccess,           /* xAccess */                     \
37387    unixFullPathname,     /* xFullPathname */               \
37388    unixDlOpen,           /* xDlOpen */                     \
37389    unixDlError,          /* xDlError */                    \
37390    unixDlSym,            /* xDlSym */                      \
37391    unixDlClose,          /* xDlClose */                    \
37392    unixRandomness,       /* xRandomness */                 \
37393    unixSleep,            /* xSleep */                      \
37394    unixCurrentTime,      /* xCurrentTime */                \
37395    unixGetLastError,     /* xGetLastError */               \
37396    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
37397    unixSetSystemCall,    /* xSetSystemCall */              \
37398    unixGetSystemCall,    /* xGetSystemCall */              \
37399    unixNextSystemCall,   /* xNextSystemCall */             \
37400  }
37401
37402  /*
37403  ** All default VFSes for unix are contained in the following array.
37404  **
37405  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
37406  ** by the SQLite core when the VFS is registered.  So the following
37407  ** array cannot be const.
37408  */
37409  static sqlite3_vfs aVfs[] = {
37410#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
37411    UNIXVFS("unix",          autolockIoFinder ),
37412#elif OS_VXWORKS
37413    UNIXVFS("unix",          vxworksIoFinder ),
37414#else
37415    UNIXVFS("unix",          posixIoFinder ),
37416#endif
37417    UNIXVFS("unix-none",     nolockIoFinder ),
37418    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
37419    UNIXVFS("unix-excl",     posixIoFinder ),
37420#if OS_VXWORKS
37421    UNIXVFS("unix-namedsem", semIoFinder ),
37422#endif
37423#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
37424    UNIXVFS("unix-posix",    posixIoFinder ),
37425#endif
37426#if SQLITE_ENABLE_LOCKING_STYLE
37427    UNIXVFS("unix-flock",    flockIoFinder ),
37428#endif
37429#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
37430    UNIXVFS("unix-afp",      afpIoFinder ),
37431    UNIXVFS("unix-nfs",      nfsIoFinder ),
37432    UNIXVFS("unix-proxy",    proxyIoFinder ),
37433#endif
37434  };
37435  unsigned int i;          /* Loop counter */
37436
37437  /* Double-check that the aSyscall[] array has been constructed
37438  ** correctly.  See ticket [bb3a86e890c8e96ab] */
37439  assert( ArraySize(aSyscall)==28 );
37440
37441  /* Register all VFSes defined in the aVfs[] array */
37442  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
37443    sqlite3_vfs_register(&aVfs[i], i==0);
37444  }
37445  return SQLITE_OK;
37446}
37447
37448/*
37449** Shutdown the operating system interface.
37450**
37451** Some operating systems might need to do some cleanup in this routine,
37452** to release dynamically allocated objects.  But not on unix.
37453** This routine is a no-op for unix.
37454*/
37455SQLITE_API int sqlite3_os_end(void){
37456  return SQLITE_OK;
37457}
37458
37459#endif /* SQLITE_OS_UNIX */
37460
37461/************** End of os_unix.c *********************************************/
37462/************** Begin file os_win.c ******************************************/
37463/*
37464** 2004 May 22
37465**
37466** The author disclaims copyright to this source code.  In place of
37467** a legal notice, here is a blessing:
37468**
37469**    May you do good and not evil.
37470**    May you find forgiveness for yourself and forgive others.
37471**    May you share freely, never taking more than you give.
37472**
37473******************************************************************************
37474**
37475** This file contains code that is specific to Windows.
37476*/
37477/* #include "sqliteInt.h" */
37478#if SQLITE_OS_WIN               /* This file is used for Windows only */
37479
37480/*
37481** Include code that is common to all os_*.c files
37482*/
37483/************** Include os_common.h in the middle of os_win.c ****************/
37484/************** Begin file os_common.h ***************************************/
37485/*
37486** 2004 May 22
37487**
37488** The author disclaims copyright to this source code.  In place of
37489** a legal notice, here is a blessing:
37490**
37491**    May you do good and not evil.
37492**    May you find forgiveness for yourself and forgive others.
37493**    May you share freely, never taking more than you give.
37494**
37495******************************************************************************
37496**
37497** This file contains macros and a little bit of code that is common to
37498** all of the platform-specific files (os_*.c) and is #included into those
37499** files.
37500**
37501** This file should be #included by the os_*.c files only.  It is not a
37502** general purpose header file.
37503*/
37504#ifndef _OS_COMMON_H_
37505#define _OS_COMMON_H_
37506
37507/*
37508** At least two bugs have slipped in because we changed the MEMORY_DEBUG
37509** macro to SQLITE_DEBUG and some older makefiles have not yet made the
37510** switch.  The following code should catch this problem at compile-time.
37511*/
37512#ifdef MEMORY_DEBUG
37513# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
37514#endif
37515
37516/*
37517** Macros for performance tracing.  Normally turned off.  Only works
37518** on i486 hardware.
37519*/
37520#ifdef SQLITE_PERFORMANCE_TRACE
37521
37522/*
37523** hwtime.h contains inline assembler code for implementing
37524** high-performance timing routines.
37525*/
37526/************** Include hwtime.h in the middle of os_common.h ****************/
37527/************** Begin file hwtime.h ******************************************/
37528/*
37529** 2008 May 27
37530**
37531** The author disclaims copyright to this source code.  In place of
37532** a legal notice, here is a blessing:
37533**
37534**    May you do good and not evil.
37535**    May you find forgiveness for yourself and forgive others.
37536**    May you share freely, never taking more than you give.
37537**
37538******************************************************************************
37539**
37540** This file contains inline asm code for retrieving "high-performance"
37541** counters for x86 class CPUs.
37542*/
37543#ifndef SQLITE_HWTIME_H
37544#define SQLITE_HWTIME_H
37545
37546/*
37547** The following routine only works on pentium-class (or newer) processors.
37548** It uses the RDTSC opcode to read the cycle count value out of the
37549** processor and returns that value.  This can be used for high-res
37550** profiling.
37551*/
37552#if (defined(__GNUC__) || defined(_MSC_VER)) && \
37553      (defined(i386) || defined(__i386__) || defined(_M_IX86))
37554
37555  #if defined(__GNUC__)
37556
37557  __inline__ sqlite_uint64 sqlite3Hwtime(void){
37558     unsigned int lo, hi;
37559     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
37560     return (sqlite_uint64)hi << 32 | lo;
37561  }
37562
37563  #elif defined(_MSC_VER)
37564
37565  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
37566     __asm {
37567        rdtsc
37568        ret       ; return value at EDX:EAX
37569     }
37570  }
37571
37572  #endif
37573
37574#elif (defined(__GNUC__) && defined(__x86_64__))
37575
37576  __inline__ sqlite_uint64 sqlite3Hwtime(void){
37577      unsigned long val;
37578      __asm__ __volatile__ ("rdtsc" : "=A" (val));
37579      return val;
37580  }
37581
37582#elif (defined(__GNUC__) && defined(__ppc__))
37583
37584  __inline__ sqlite_uint64 sqlite3Hwtime(void){
37585      unsigned long long retval;
37586      unsigned long junk;
37587      __asm__ __volatile__ ("\n\
37588          1:      mftbu   %1\n\
37589                  mftb    %L0\n\
37590                  mftbu   %0\n\
37591                  cmpw    %0,%1\n\
37592                  bne     1b"
37593                  : "=r" (retval), "=r" (junk));
37594      return retval;
37595  }
37596
37597#else
37598
37599  #error Need implementation of sqlite3Hwtime() for your platform.
37600
37601  /*
37602  ** To compile without implementing sqlite3Hwtime() for your platform,
37603  ** you can remove the above #error and use the following
37604  ** stub function.  You will lose timing support for many
37605  ** of the debugging and testing utilities, but it should at
37606  ** least compile and run.
37607  */
37608SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
37609
37610#endif
37611
37612#endif /* !defined(SQLITE_HWTIME_H) */
37613
37614/************** End of hwtime.h **********************************************/
37615/************** Continuing where we left off in os_common.h ******************/
37616
37617static sqlite_uint64 g_start;
37618static sqlite_uint64 g_elapsed;
37619#define TIMER_START       g_start=sqlite3Hwtime()
37620#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
37621#define TIMER_ELAPSED     g_elapsed
37622#else
37623#define TIMER_START
37624#define TIMER_END
37625#define TIMER_ELAPSED     ((sqlite_uint64)0)
37626#endif
37627
37628/*
37629** If we compile with the SQLITE_TEST macro set, then the following block
37630** of code will give us the ability to simulate a disk I/O error.  This
37631** is used for testing the I/O recovery logic.
37632*/
37633#if defined(SQLITE_TEST)
37634SQLITE_API extern int sqlite3_io_error_hit;
37635SQLITE_API extern int sqlite3_io_error_hardhit;
37636SQLITE_API extern int sqlite3_io_error_pending;
37637SQLITE_API extern int sqlite3_io_error_persist;
37638SQLITE_API extern int sqlite3_io_error_benign;
37639SQLITE_API extern int sqlite3_diskfull_pending;
37640SQLITE_API extern int sqlite3_diskfull;
37641#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
37642#define SimulateIOError(CODE)  \
37643  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
37644       || sqlite3_io_error_pending-- == 1 )  \
37645              { local_ioerr(); CODE; }
37646static void local_ioerr(){
37647  IOTRACE(("IOERR\n"));
37648  sqlite3_io_error_hit++;
37649  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
37650}
37651#define SimulateDiskfullError(CODE) \
37652   if( sqlite3_diskfull_pending ){ \
37653     if( sqlite3_diskfull_pending == 1 ){ \
37654       local_ioerr(); \
37655       sqlite3_diskfull = 1; \
37656       sqlite3_io_error_hit = 1; \
37657       CODE; \
37658     }else{ \
37659       sqlite3_diskfull_pending--; \
37660     } \
37661   }
37662#else
37663#define SimulateIOErrorBenign(X)
37664#define SimulateIOError(A)
37665#define SimulateDiskfullError(A)
37666#endif /* defined(SQLITE_TEST) */
37667
37668/*
37669** When testing, keep a count of the number of open files.
37670*/
37671#if defined(SQLITE_TEST)
37672SQLITE_API extern int sqlite3_open_file_count;
37673#define OpenCounter(X)  sqlite3_open_file_count+=(X)
37674#else
37675#define OpenCounter(X)
37676#endif /* defined(SQLITE_TEST) */
37677
37678#endif /* !defined(_OS_COMMON_H_) */
37679
37680/************** End of os_common.h *******************************************/
37681/************** Continuing where we left off in os_win.c *********************/
37682
37683/*
37684** Include the header file for the Windows VFS.
37685*/
37686/* #include "os_win.h" */
37687
37688/*
37689** Compiling and using WAL mode requires several APIs that are only
37690** available in Windows platforms based on the NT kernel.
37691*/
37692#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
37693#  error "WAL mode requires support from the Windows NT kernel, compile\
37694 with SQLITE_OMIT_WAL."
37695#endif
37696
37697#if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
37698#  error "Memory mapped files require support from the Windows NT kernel,\
37699 compile with SQLITE_MAX_MMAP_SIZE=0."
37700#endif
37701
37702/*
37703** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
37704** based on the sub-platform)?
37705*/
37706#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
37707#  define SQLITE_WIN32_HAS_ANSI
37708#endif
37709
37710/*
37711** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
37712** based on the sub-platform)?
37713*/
37714#if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
37715    !defined(SQLITE_WIN32_NO_WIDE)
37716#  define SQLITE_WIN32_HAS_WIDE
37717#endif
37718
37719/*
37720** Make sure at least one set of Win32 APIs is available.
37721*/
37722#if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
37723#  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
37724 must be defined."
37725#endif
37726
37727/*
37728** Define the required Windows SDK version constants if they are not
37729** already available.
37730*/
37731#ifndef NTDDI_WIN8
37732#  define NTDDI_WIN8                        0x06020000
37733#endif
37734
37735#ifndef NTDDI_WINBLUE
37736#  define NTDDI_WINBLUE                     0x06030000
37737#endif
37738
37739#ifndef NTDDI_WINTHRESHOLD
37740#  define NTDDI_WINTHRESHOLD                0x06040000
37741#endif
37742
37743/*
37744** Check to see if the GetVersionEx[AW] functions are deprecated on the
37745** target system.  GetVersionEx was first deprecated in Win8.1.
37746*/
37747#ifndef SQLITE_WIN32_GETVERSIONEX
37748#  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
37749#    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
37750#  else
37751#    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
37752#  endif
37753#endif
37754
37755/*
37756** Check to see if the CreateFileMappingA function is supported on the
37757** target system.  It is unavailable when using "mincore.lib" on Win10.
37758** When compiling for Windows 10, always assume "mincore.lib" is in use.
37759*/
37760#ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
37761#  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
37762#    define SQLITE_WIN32_CREATEFILEMAPPINGA   0
37763#  else
37764#    define SQLITE_WIN32_CREATEFILEMAPPINGA   1
37765#  endif
37766#endif
37767
37768/*
37769** This constant should already be defined (in the "WinDef.h" SDK file).
37770*/
37771#ifndef MAX_PATH
37772#  define MAX_PATH                      (260)
37773#endif
37774
37775/*
37776** Maximum pathname length (in chars) for Win32.  This should normally be
37777** MAX_PATH.
37778*/
37779#ifndef SQLITE_WIN32_MAX_PATH_CHARS
37780#  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
37781#endif
37782
37783/*
37784** This constant should already be defined (in the "WinNT.h" SDK file).
37785*/
37786#ifndef UNICODE_STRING_MAX_CHARS
37787#  define UNICODE_STRING_MAX_CHARS      (32767)
37788#endif
37789
37790/*
37791** Maximum pathname length (in chars) for WinNT.  This should normally be
37792** UNICODE_STRING_MAX_CHARS.
37793*/
37794#ifndef SQLITE_WINNT_MAX_PATH_CHARS
37795#  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
37796#endif
37797
37798/*
37799** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
37800** characters, so we allocate 4 bytes per character assuming worst-case of
37801** 4-bytes-per-character for UTF8.
37802*/
37803#ifndef SQLITE_WIN32_MAX_PATH_BYTES
37804#  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
37805#endif
37806
37807/*
37808** Maximum pathname length (in bytes) for WinNT.  This should normally be
37809** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
37810*/
37811#ifndef SQLITE_WINNT_MAX_PATH_BYTES
37812#  define SQLITE_WINNT_MAX_PATH_BYTES   \
37813                            (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
37814#endif
37815
37816/*
37817** Maximum error message length (in chars) for WinRT.
37818*/
37819#ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
37820#  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
37821#endif
37822
37823/*
37824** Returns non-zero if the character should be treated as a directory
37825** separator.
37826*/
37827#ifndef winIsDirSep
37828#  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
37829#endif
37830
37831/*
37832** This macro is used when a local variable is set to a value that is
37833** [sometimes] not used by the code (e.g. via conditional compilation).
37834*/
37835#ifndef UNUSED_VARIABLE_VALUE
37836#  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
37837#endif
37838
37839/*
37840** Returns the character that should be used as the directory separator.
37841*/
37842#ifndef winGetDirSep
37843#  define winGetDirSep()                '\\'
37844#endif
37845
37846/*
37847** Do we need to manually define the Win32 file mapping APIs for use with WAL
37848** mode or memory mapped files (e.g. these APIs are available in the Windows
37849** CE SDK; however, they are not present in the header file)?
37850*/
37851#if SQLITE_WIN32_FILEMAPPING_API && \
37852        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
37853/*
37854** Two of the file mapping APIs are different under WinRT.  Figure out which
37855** set we need.
37856*/
37857#if SQLITE_OS_WINRT
37858WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
37859        LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
37860
37861WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
37862#else
37863#if defined(SQLITE_WIN32_HAS_ANSI)
37864WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
37865        DWORD, DWORD, DWORD, LPCSTR);
37866#endif /* defined(SQLITE_WIN32_HAS_ANSI) */
37867
37868#if defined(SQLITE_WIN32_HAS_WIDE)
37869WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
37870        DWORD, DWORD, DWORD, LPCWSTR);
37871#endif /* defined(SQLITE_WIN32_HAS_WIDE) */
37872
37873WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
37874#endif /* SQLITE_OS_WINRT */
37875
37876/*
37877** These file mapping APIs are common to both Win32 and WinRT.
37878*/
37879
37880WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
37881WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
37882#endif /* SQLITE_WIN32_FILEMAPPING_API */
37883
37884/*
37885** Some Microsoft compilers lack this definition.
37886*/
37887#ifndef INVALID_FILE_ATTRIBUTES
37888# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
37889#endif
37890
37891#ifndef FILE_FLAG_MASK
37892# define FILE_FLAG_MASK          (0xFF3C0000)
37893#endif
37894
37895#ifndef FILE_ATTRIBUTE_MASK
37896# define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
37897#endif
37898
37899#ifndef SQLITE_OMIT_WAL
37900/* Forward references to structures used for WAL */
37901typedef struct winShm winShm;           /* A connection to shared-memory */
37902typedef struct winShmNode winShmNode;   /* A region of shared-memory */
37903#endif
37904
37905/*
37906** WinCE lacks native support for file locking so we have to fake it
37907** with some code of our own.
37908*/
37909#if SQLITE_OS_WINCE
37910typedef struct winceLock {
37911  int nReaders;       /* Number of reader locks obtained */
37912  BOOL bPending;      /* Indicates a pending lock has been obtained */
37913  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
37914  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
37915} winceLock;
37916#endif
37917
37918/*
37919** The winFile structure is a subclass of sqlite3_file* specific to the win32
37920** portability layer.
37921*/
37922typedef struct winFile winFile;
37923struct winFile {
37924  const sqlite3_io_methods *pMethod; /*** Must be first ***/
37925  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
37926  HANDLE h;               /* Handle for accessing the file */
37927  u8 locktype;            /* Type of lock currently held on this file */
37928  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
37929  u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
37930  DWORD lastErrno;        /* The Windows errno from the last I/O error */
37931#ifndef SQLITE_OMIT_WAL
37932  winShm *pShm;           /* Instance of shared memory on this file */
37933#endif
37934  const char *zPath;      /* Full pathname of this file */
37935  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
37936#if SQLITE_OS_WINCE
37937  LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
37938  HANDLE hMutex;          /* Mutex used to control access to shared lock */
37939  HANDLE hShared;         /* Shared memory segment used for locking */
37940  winceLock local;        /* Locks obtained by this instance of winFile */
37941  winceLock *shared;      /* Global shared lock memory for the file  */
37942#endif
37943#if SQLITE_MAX_MMAP_SIZE>0
37944  int nFetchOut;                /* Number of outstanding xFetch references */
37945  HANDLE hMap;                  /* Handle for accessing memory mapping */
37946  void *pMapRegion;             /* Area memory mapped */
37947  sqlite3_int64 mmapSize;       /* Usable size of mapped region */
37948  sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
37949  sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
37950#endif
37951};
37952
37953/*
37954** The winVfsAppData structure is used for the pAppData member for all of the
37955** Win32 VFS variants.
37956*/
37957typedef struct winVfsAppData winVfsAppData;
37958struct winVfsAppData {
37959  const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
37960  void *pAppData;                    /* The extra pAppData, if any. */
37961  BOOL bNoLock;                      /* Non-zero if locking is disabled. */
37962};
37963
37964/*
37965** Allowed values for winFile.ctrlFlags
37966*/
37967#define WINFILE_RDONLY          0x02   /* Connection is read only */
37968#define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
37969#define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
37970
37971/*
37972 * The size of the buffer used by sqlite3_win32_write_debug().
37973 */
37974#ifndef SQLITE_WIN32_DBG_BUF_SIZE
37975#  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
37976#endif
37977
37978/*
37979 * The value used with sqlite3_win32_set_directory() to specify that
37980 * the data directory should be changed.
37981 */
37982#ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
37983#  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
37984#endif
37985
37986/*
37987 * The value used with sqlite3_win32_set_directory() to specify that
37988 * the temporary directory should be changed.
37989 */
37990#ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
37991#  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
37992#endif
37993
37994/*
37995 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
37996 * various Win32 API heap functions instead of our own.
37997 */
37998#ifdef SQLITE_WIN32_MALLOC
37999
38000/*
38001 * If this is non-zero, an isolated heap will be created by the native Win32
38002 * allocator subsystem; otherwise, the default process heap will be used.  This
38003 * setting has no effect when compiling for WinRT.  By default, this is enabled
38004 * and an isolated heap will be created to store all allocated data.
38005 *
38006 ******************************************************************************
38007 * WARNING: It is important to note that when this setting is non-zero and the
38008 *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
38009 *          function), all data that was allocated using the isolated heap will
38010 *          be freed immediately and any attempt to access any of that freed
38011 *          data will almost certainly result in an immediate access violation.
38012 ******************************************************************************
38013 */
38014#ifndef SQLITE_WIN32_HEAP_CREATE
38015#  define SQLITE_WIN32_HEAP_CREATE        (TRUE)
38016#endif
38017
38018/*
38019 * This is the maximum possible initial size of the Win32-specific heap, in
38020 * bytes.
38021 */
38022#ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
38023#  define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
38024#endif
38025
38026/*
38027 * This is the extra space for the initial size of the Win32-specific heap,
38028 * in bytes.  This value may be zero.
38029 */
38030#ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
38031#  define SQLITE_WIN32_HEAP_INIT_EXTRA  (4194304)
38032#endif
38033
38034/*
38035 * Calculate the maximum legal cache size, in pages, based on the maximum
38036 * possible initial heap size and the default page size, setting aside the
38037 * needed extra space.
38038 */
38039#ifndef SQLITE_WIN32_MAX_CACHE_SIZE
38040#  define SQLITE_WIN32_MAX_CACHE_SIZE   (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
38041                                          (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
38042                                         (SQLITE_DEFAULT_PAGE_SIZE))
38043#endif
38044
38045/*
38046 * This is cache size used in the calculation of the initial size of the
38047 * Win32-specific heap.  It cannot be negative.
38048 */
38049#ifndef SQLITE_WIN32_CACHE_SIZE
38050#  if SQLITE_DEFAULT_CACHE_SIZE>=0
38051#    define SQLITE_WIN32_CACHE_SIZE     (SQLITE_DEFAULT_CACHE_SIZE)
38052#  else
38053#    define SQLITE_WIN32_CACHE_SIZE     (-(SQLITE_DEFAULT_CACHE_SIZE))
38054#  endif
38055#endif
38056
38057/*
38058 * Make sure that the calculated cache size, in pages, cannot cause the
38059 * initial size of the Win32-specific heap to exceed the maximum amount
38060 * of memory that can be specified in the call to HeapCreate.
38061 */
38062#if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
38063#  undef SQLITE_WIN32_CACHE_SIZE
38064#  define SQLITE_WIN32_CACHE_SIZE       (2000)
38065#endif
38066
38067/*
38068 * The initial size of the Win32-specific heap.  This value may be zero.
38069 */
38070#ifndef SQLITE_WIN32_HEAP_INIT_SIZE
38071#  define SQLITE_WIN32_HEAP_INIT_SIZE   ((SQLITE_WIN32_CACHE_SIZE) * \
38072                                         (SQLITE_DEFAULT_PAGE_SIZE) + \
38073                                         (SQLITE_WIN32_HEAP_INIT_EXTRA))
38074#endif
38075
38076/*
38077 * The maximum size of the Win32-specific heap.  This value may be zero.
38078 */
38079#ifndef SQLITE_WIN32_HEAP_MAX_SIZE
38080#  define SQLITE_WIN32_HEAP_MAX_SIZE    (0)
38081#endif
38082
38083/*
38084 * The extra flags to use in calls to the Win32 heap APIs.  This value may be
38085 * zero for the default behavior.
38086 */
38087#ifndef SQLITE_WIN32_HEAP_FLAGS
38088#  define SQLITE_WIN32_HEAP_FLAGS       (0)
38089#endif
38090
38091
38092/*
38093** The winMemData structure stores information required by the Win32-specific
38094** sqlite3_mem_methods implementation.
38095*/
38096typedef struct winMemData winMemData;
38097struct winMemData {
38098#ifndef NDEBUG
38099  u32 magic1;   /* Magic number to detect structure corruption. */
38100#endif
38101  HANDLE hHeap; /* The handle to our heap. */
38102  BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
38103#ifndef NDEBUG
38104  u32 magic2;   /* Magic number to detect structure corruption. */
38105#endif
38106};
38107
38108#ifndef NDEBUG
38109#define WINMEM_MAGIC1     0x42b2830b
38110#define WINMEM_MAGIC2     0xbd4d7cf4
38111#endif
38112
38113static struct winMemData win_mem_data = {
38114#ifndef NDEBUG
38115  WINMEM_MAGIC1,
38116#endif
38117  NULL, FALSE
38118#ifndef NDEBUG
38119  ,WINMEM_MAGIC2
38120#endif
38121};
38122
38123#ifndef NDEBUG
38124#define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
38125#define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
38126#define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
38127#else
38128#define winMemAssertMagic()
38129#endif
38130
38131#define winMemGetDataPtr()  &win_mem_data
38132#define winMemGetHeap()     win_mem_data.hHeap
38133#define winMemGetOwned()    win_mem_data.bOwned
38134
38135static void *winMemMalloc(int nBytes);
38136static void winMemFree(void *pPrior);
38137static void *winMemRealloc(void *pPrior, int nBytes);
38138static int winMemSize(void *p);
38139static int winMemRoundup(int n);
38140static int winMemInit(void *pAppData);
38141static void winMemShutdown(void *pAppData);
38142
38143SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
38144#endif /* SQLITE_WIN32_MALLOC */
38145
38146/*
38147** The following variable is (normally) set once and never changes
38148** thereafter.  It records whether the operating system is Win9x
38149** or WinNT.
38150**
38151** 0:   Operating system unknown.
38152** 1:   Operating system is Win9x.
38153** 2:   Operating system is WinNT.
38154**
38155** In order to facilitate testing on a WinNT system, the test fixture
38156** can manually set this value to 1 to emulate Win98 behavior.
38157*/
38158#ifdef SQLITE_TEST
38159SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
38160#else
38161static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
38162#endif
38163
38164#ifndef SYSCALL
38165#  define SYSCALL sqlite3_syscall_ptr
38166#endif
38167
38168/*
38169** This function is not available on Windows CE or WinRT.
38170 */
38171
38172#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
38173#  define osAreFileApisANSI()       1
38174#endif
38175
38176/*
38177** Many system calls are accessed through pointer-to-functions so that
38178** they may be overridden at runtime to facilitate fault injection during
38179** testing and sandboxing.  The following array holds the names and pointers
38180** to all overrideable system calls.
38181*/
38182static struct win_syscall {
38183  const char *zName;            /* Name of the system call */
38184  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
38185  sqlite3_syscall_ptr pDefault; /* Default value */
38186} aSyscall[] = {
38187#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38188  { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
38189#else
38190  { "AreFileApisANSI",         (SYSCALL)0,                       0 },
38191#endif
38192
38193#ifndef osAreFileApisANSI
38194#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
38195#endif
38196
38197#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
38198  { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
38199#else
38200  { "CharLowerW",              (SYSCALL)0,                       0 },
38201#endif
38202
38203#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
38204
38205#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
38206  { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
38207#else
38208  { "CharUpperW",              (SYSCALL)0,                       0 },
38209#endif
38210
38211#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
38212
38213  { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
38214
38215#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
38216
38217#if defined(SQLITE_WIN32_HAS_ANSI)
38218  { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
38219#else
38220  { "CreateFileA",             (SYSCALL)0,                       0 },
38221#endif
38222
38223#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
38224        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
38225
38226#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38227  { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
38228#else
38229  { "CreateFileW",             (SYSCALL)0,                       0 },
38230#endif
38231
38232#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
38233        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
38234
38235#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
38236        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
38237        SQLITE_WIN32_CREATEFILEMAPPINGA
38238  { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
38239#else
38240  { "CreateFileMappingA",      (SYSCALL)0,                       0 },
38241#endif
38242
38243#define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
38244        DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
38245
38246#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
38247        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
38248  { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
38249#else
38250  { "CreateFileMappingW",      (SYSCALL)0,                       0 },
38251#endif
38252
38253#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
38254        DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
38255
38256#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38257  { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
38258#else
38259  { "CreateMutexW",            (SYSCALL)0,                       0 },
38260#endif
38261
38262#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
38263        LPCWSTR))aSyscall[8].pCurrent)
38264
38265#if defined(SQLITE_WIN32_HAS_ANSI)
38266  { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
38267#else
38268  { "DeleteFileA",             (SYSCALL)0,                       0 },
38269#endif
38270
38271#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
38272
38273#if defined(SQLITE_WIN32_HAS_WIDE)
38274  { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
38275#else
38276  { "DeleteFileW",             (SYSCALL)0,                       0 },
38277#endif
38278
38279#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
38280
38281#if SQLITE_OS_WINCE
38282  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
38283#else
38284  { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
38285#endif
38286
38287#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
38288        LPFILETIME))aSyscall[11].pCurrent)
38289
38290#if SQLITE_OS_WINCE
38291  { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
38292#else
38293  { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
38294#endif
38295
38296#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
38297        LPSYSTEMTIME))aSyscall[12].pCurrent)
38298
38299  { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
38300
38301#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
38302
38303#if defined(SQLITE_WIN32_HAS_ANSI)
38304  { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
38305#else
38306  { "FormatMessageA",          (SYSCALL)0,                       0 },
38307#endif
38308
38309#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
38310        DWORD,va_list*))aSyscall[14].pCurrent)
38311
38312#if defined(SQLITE_WIN32_HAS_WIDE)
38313  { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
38314#else
38315  { "FormatMessageW",          (SYSCALL)0,                       0 },
38316#endif
38317
38318#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
38319        DWORD,va_list*))aSyscall[15].pCurrent)
38320
38321#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
38322  { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
38323#else
38324  { "FreeLibrary",             (SYSCALL)0,                       0 },
38325#endif
38326
38327#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
38328
38329  { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
38330
38331#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
38332
38333#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
38334  { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
38335#else
38336  { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
38337#endif
38338
38339#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
38340        LPDWORD))aSyscall[18].pCurrent)
38341
38342#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38343  { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
38344#else
38345  { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
38346#endif
38347
38348#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
38349        LPDWORD))aSyscall[19].pCurrent)
38350
38351#if defined(SQLITE_WIN32_HAS_ANSI)
38352  { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
38353#else
38354  { "GetFileAttributesA",      (SYSCALL)0,                       0 },
38355#endif
38356
38357#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
38358
38359#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38360  { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
38361#else
38362  { "GetFileAttributesW",      (SYSCALL)0,                       0 },
38363#endif
38364
38365#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
38366
38367#if defined(SQLITE_WIN32_HAS_WIDE)
38368  { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
38369#else
38370  { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
38371#endif
38372
38373#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
38374        LPVOID))aSyscall[22].pCurrent)
38375
38376#if !SQLITE_OS_WINRT
38377  { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
38378#else
38379  { "GetFileSize",             (SYSCALL)0,                       0 },
38380#endif
38381
38382#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
38383
38384#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
38385  { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
38386#else
38387  { "GetFullPathNameA",        (SYSCALL)0,                       0 },
38388#endif
38389
38390#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
38391        LPSTR*))aSyscall[24].pCurrent)
38392
38393#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38394  { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
38395#else
38396  { "GetFullPathNameW",        (SYSCALL)0,                       0 },
38397#endif
38398
38399#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
38400        LPWSTR*))aSyscall[25].pCurrent)
38401
38402  { "GetLastError",            (SYSCALL)GetLastError,            0 },
38403
38404#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
38405
38406#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
38407#if SQLITE_OS_WINCE
38408  /* The GetProcAddressA() routine is only available on Windows CE. */
38409  { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
38410#else
38411  /* All other Windows platforms expect GetProcAddress() to take
38412  ** an ANSI string regardless of the _UNICODE setting */
38413  { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
38414#endif
38415#else
38416  { "GetProcAddressA",         (SYSCALL)0,                       0 },
38417#endif
38418
38419#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
38420        LPCSTR))aSyscall[27].pCurrent)
38421
38422#if !SQLITE_OS_WINRT
38423  { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
38424#else
38425  { "GetSystemInfo",           (SYSCALL)0,                       0 },
38426#endif
38427
38428#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
38429
38430  { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
38431
38432#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
38433
38434#if !SQLITE_OS_WINCE
38435  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
38436#else
38437  { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
38438#endif
38439
38440#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
38441        LPFILETIME))aSyscall[30].pCurrent)
38442
38443#if defined(SQLITE_WIN32_HAS_ANSI)
38444  { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
38445#else
38446  { "GetTempPathA",            (SYSCALL)0,                       0 },
38447#endif
38448
38449#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
38450
38451#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38452  { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
38453#else
38454  { "GetTempPathW",            (SYSCALL)0,                       0 },
38455#endif
38456
38457#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
38458
38459#if !SQLITE_OS_WINRT
38460  { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
38461#else
38462  { "GetTickCount",            (SYSCALL)0,                       0 },
38463#endif
38464
38465#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
38466
38467#if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
38468  { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
38469#else
38470  { "GetVersionExA",           (SYSCALL)0,                       0 },
38471#endif
38472
38473#define osGetVersionExA ((BOOL(WINAPI*)( \
38474        LPOSVERSIONINFOA))aSyscall[34].pCurrent)
38475
38476#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
38477        SQLITE_WIN32_GETVERSIONEX
38478  { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
38479#else
38480  { "GetVersionExW",           (SYSCALL)0,                       0 },
38481#endif
38482
38483#define osGetVersionExW ((BOOL(WINAPI*)( \
38484        LPOSVERSIONINFOW))aSyscall[35].pCurrent)
38485
38486  { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
38487
38488#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
38489        SIZE_T))aSyscall[36].pCurrent)
38490
38491#if !SQLITE_OS_WINRT
38492  { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
38493#else
38494  { "HeapCreate",              (SYSCALL)0,                       0 },
38495#endif
38496
38497#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
38498        SIZE_T))aSyscall[37].pCurrent)
38499
38500#if !SQLITE_OS_WINRT
38501  { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
38502#else
38503  { "HeapDestroy",             (SYSCALL)0,                       0 },
38504#endif
38505
38506#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
38507
38508  { "HeapFree",                (SYSCALL)HeapFree,                0 },
38509
38510#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
38511
38512  { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
38513
38514#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
38515        SIZE_T))aSyscall[40].pCurrent)
38516
38517  { "HeapSize",                (SYSCALL)HeapSize,                0 },
38518
38519#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
38520        LPCVOID))aSyscall[41].pCurrent)
38521
38522#if !SQLITE_OS_WINRT
38523  { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
38524#else
38525  { "HeapValidate",            (SYSCALL)0,                       0 },
38526#endif
38527
38528#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
38529        LPCVOID))aSyscall[42].pCurrent)
38530
38531#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38532  { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
38533#else
38534  { "HeapCompact",             (SYSCALL)0,                       0 },
38535#endif
38536
38537#define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
38538
38539#if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
38540  { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
38541#else
38542  { "LoadLibraryA",            (SYSCALL)0,                       0 },
38543#endif
38544
38545#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
38546
38547#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
38548        !defined(SQLITE_OMIT_LOAD_EXTENSION)
38549  { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
38550#else
38551  { "LoadLibraryW",            (SYSCALL)0,                       0 },
38552#endif
38553
38554#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
38555
38556#if !SQLITE_OS_WINRT
38557  { "LocalFree",               (SYSCALL)LocalFree,               0 },
38558#else
38559  { "LocalFree",               (SYSCALL)0,                       0 },
38560#endif
38561
38562#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
38563
38564#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38565  { "LockFile",                (SYSCALL)LockFile,                0 },
38566#else
38567  { "LockFile",                (SYSCALL)0,                       0 },
38568#endif
38569
38570#ifndef osLockFile
38571#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38572        DWORD))aSyscall[47].pCurrent)
38573#endif
38574
38575#if !SQLITE_OS_WINCE
38576  { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
38577#else
38578  { "LockFileEx",              (SYSCALL)0,                       0 },
38579#endif
38580
38581#ifndef osLockFileEx
38582#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
38583        LPOVERLAPPED))aSyscall[48].pCurrent)
38584#endif
38585
38586#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
38587        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
38588  { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
38589#else
38590  { "MapViewOfFile",           (SYSCALL)0,                       0 },
38591#endif
38592
38593#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38594        SIZE_T))aSyscall[49].pCurrent)
38595
38596  { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
38597
38598#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
38599        int))aSyscall[50].pCurrent)
38600
38601  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
38602
38603#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
38604        LARGE_INTEGER*))aSyscall[51].pCurrent)
38605
38606  { "ReadFile",                (SYSCALL)ReadFile,                0 },
38607
38608#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
38609        LPOVERLAPPED))aSyscall[52].pCurrent)
38610
38611  { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
38612
38613#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
38614
38615#if !SQLITE_OS_WINRT
38616  { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
38617#else
38618  { "SetFilePointer",          (SYSCALL)0,                       0 },
38619#endif
38620
38621#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
38622        DWORD))aSyscall[54].pCurrent)
38623
38624#if !SQLITE_OS_WINRT
38625  { "Sleep",                   (SYSCALL)Sleep,                   0 },
38626#else
38627  { "Sleep",                   (SYSCALL)0,                       0 },
38628#endif
38629
38630#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
38631
38632  { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
38633
38634#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
38635        LPFILETIME))aSyscall[56].pCurrent)
38636
38637#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38638  { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
38639#else
38640  { "UnlockFile",              (SYSCALL)0,                       0 },
38641#endif
38642
38643#ifndef osUnlockFile
38644#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38645        DWORD))aSyscall[57].pCurrent)
38646#endif
38647
38648#if !SQLITE_OS_WINCE
38649  { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
38650#else
38651  { "UnlockFileEx",            (SYSCALL)0,                       0 },
38652#endif
38653
38654#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38655        LPOVERLAPPED))aSyscall[58].pCurrent)
38656
38657#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
38658  { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
38659#else
38660  { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
38661#endif
38662
38663#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
38664
38665  { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
38666
38667#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
38668        LPCSTR,LPBOOL))aSyscall[60].pCurrent)
38669
38670  { "WriteFile",               (SYSCALL)WriteFile,               0 },
38671
38672#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
38673        LPOVERLAPPED))aSyscall[61].pCurrent)
38674
38675#if SQLITE_OS_WINRT
38676  { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
38677#else
38678  { "CreateEventExW",          (SYSCALL)0,                       0 },
38679#endif
38680
38681#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
38682        DWORD,DWORD))aSyscall[62].pCurrent)
38683
38684#if !SQLITE_OS_WINRT
38685  { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
38686#else
38687  { "WaitForSingleObject",     (SYSCALL)0,                       0 },
38688#endif
38689
38690#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
38691        DWORD))aSyscall[63].pCurrent)
38692
38693#if !SQLITE_OS_WINCE
38694  { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
38695#else
38696  { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
38697#endif
38698
38699#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
38700        BOOL))aSyscall[64].pCurrent)
38701
38702#if SQLITE_OS_WINRT
38703  { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
38704#else
38705  { "SetFilePointerEx",        (SYSCALL)0,                       0 },
38706#endif
38707
38708#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
38709        PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
38710
38711#if SQLITE_OS_WINRT
38712  { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
38713#else
38714  { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
38715#endif
38716
38717#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
38718        FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
38719
38720#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
38721  { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
38722#else
38723  { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
38724#endif
38725
38726#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
38727        SIZE_T))aSyscall[67].pCurrent)
38728
38729#if SQLITE_OS_WINRT
38730  { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
38731#else
38732  { "CreateFile2",             (SYSCALL)0,                       0 },
38733#endif
38734
38735#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
38736        LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
38737
38738#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
38739  { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
38740#else
38741  { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
38742#endif
38743
38744#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
38745        DWORD))aSyscall[69].pCurrent)
38746
38747#if SQLITE_OS_WINRT
38748  { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
38749#else
38750  { "GetTickCount64",          (SYSCALL)0,                       0 },
38751#endif
38752
38753#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
38754
38755#if SQLITE_OS_WINRT
38756  { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
38757#else
38758  { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
38759#endif
38760
38761#define osGetNativeSystemInfo ((VOID(WINAPI*)( \
38762        LPSYSTEM_INFO))aSyscall[71].pCurrent)
38763
38764#if defined(SQLITE_WIN32_HAS_ANSI)
38765  { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
38766#else
38767  { "OutputDebugStringA",      (SYSCALL)0,                       0 },
38768#endif
38769
38770#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
38771
38772#if defined(SQLITE_WIN32_HAS_WIDE)
38773  { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
38774#else
38775  { "OutputDebugStringW",      (SYSCALL)0,                       0 },
38776#endif
38777
38778#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
38779
38780  { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
38781
38782#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
38783
38784#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
38785  { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
38786#else
38787  { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
38788#endif
38789
38790#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
38791        LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
38792
38793/*
38794** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
38795**       is really just a macro that uses a compiler intrinsic (e.g. x64).
38796**       So do not try to make this is into a redefinable interface.
38797*/
38798#if defined(InterlockedCompareExchange)
38799  { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
38800
38801#define osInterlockedCompareExchange InterlockedCompareExchange
38802#else
38803  { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
38804
38805#define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
38806        SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
38807#endif /* defined(InterlockedCompareExchange) */
38808
38809#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
38810  { "UuidCreate",               (SYSCALL)UuidCreate,             0 },
38811#else
38812  { "UuidCreate",               (SYSCALL)0,                      0 },
38813#endif
38814
38815#define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
38816
38817#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
38818  { "UuidCreateSequential",     (SYSCALL)UuidCreateSequential,   0 },
38819#else
38820  { "UuidCreateSequential",     (SYSCALL)0,                      0 },
38821#endif
38822
38823#define osUuidCreateSequential \
38824        ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
38825
38826#if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
38827  { "FlushViewOfFile",          (SYSCALL)FlushViewOfFile,        0 },
38828#else
38829  { "FlushViewOfFile",          (SYSCALL)0,                      0 },
38830#endif
38831
38832#define osFlushViewOfFile \
38833        ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
38834
38835}; /* End of the overrideable system calls */
38836
38837/*
38838** This is the xSetSystemCall() method of sqlite3_vfs for all of the
38839** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
38840** system call pointer, or SQLITE_NOTFOUND if there is no configurable
38841** system call named zName.
38842*/
38843static int winSetSystemCall(
38844  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
38845  const char *zName,            /* Name of system call to override */
38846  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
38847){
38848  unsigned int i;
38849  int rc = SQLITE_NOTFOUND;
38850
38851  UNUSED_PARAMETER(pNotUsed);
38852  if( zName==0 ){
38853    /* If no zName is given, restore all system calls to their default
38854    ** settings and return NULL
38855    */
38856    rc = SQLITE_OK;
38857    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38858      if( aSyscall[i].pDefault ){
38859        aSyscall[i].pCurrent = aSyscall[i].pDefault;
38860      }
38861    }
38862  }else{
38863    /* If zName is specified, operate on only the one system call
38864    ** specified.
38865    */
38866    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38867      if( strcmp(zName, aSyscall[i].zName)==0 ){
38868        if( aSyscall[i].pDefault==0 ){
38869          aSyscall[i].pDefault = aSyscall[i].pCurrent;
38870        }
38871        rc = SQLITE_OK;
38872        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
38873        aSyscall[i].pCurrent = pNewFunc;
38874        break;
38875      }
38876    }
38877  }
38878  return rc;
38879}
38880
38881/*
38882** Return the value of a system call.  Return NULL if zName is not a
38883** recognized system call name.  NULL is also returned if the system call
38884** is currently undefined.
38885*/
38886static sqlite3_syscall_ptr winGetSystemCall(
38887  sqlite3_vfs *pNotUsed,
38888  const char *zName
38889){
38890  unsigned int i;
38891
38892  UNUSED_PARAMETER(pNotUsed);
38893  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38894    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
38895  }
38896  return 0;
38897}
38898
38899/*
38900** Return the name of the first system call after zName.  If zName==NULL
38901** then return the name of the first system call.  Return NULL if zName
38902** is the last system call or if zName is not the name of a valid
38903** system call.
38904*/
38905static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
38906  int i = -1;
38907
38908  UNUSED_PARAMETER(p);
38909  if( zName ){
38910    for(i=0; i<ArraySize(aSyscall)-1; i++){
38911      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
38912    }
38913  }
38914  for(i++; i<ArraySize(aSyscall); i++){
38915    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
38916  }
38917  return 0;
38918}
38919
38920#ifdef SQLITE_WIN32_MALLOC
38921/*
38922** If a Win32 native heap has been configured, this function will attempt to
38923** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
38924** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
38925** "pnLargest" argument, if non-zero, will be used to return the size of the
38926** largest committed free block in the heap, in bytes.
38927*/
38928SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
38929  int rc = SQLITE_OK;
38930  UINT nLargest = 0;
38931  HANDLE hHeap;
38932
38933  winMemAssertMagic();
38934  hHeap = winMemGetHeap();
38935  assert( hHeap!=0 );
38936  assert( hHeap!=INVALID_HANDLE_VALUE );
38937#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38938  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38939#endif
38940#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38941  if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
38942    DWORD lastErrno = osGetLastError();
38943    if( lastErrno==NO_ERROR ){
38944      sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
38945                  (void*)hHeap);
38946      rc = SQLITE_NOMEM_BKPT;
38947    }else{
38948      sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
38949                  osGetLastError(), (void*)hHeap);
38950      rc = SQLITE_ERROR;
38951    }
38952  }
38953#else
38954  sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
38955              (void*)hHeap);
38956  rc = SQLITE_NOTFOUND;
38957#endif
38958  if( pnLargest ) *pnLargest = nLargest;
38959  return rc;
38960}
38961
38962/*
38963** If a Win32 native heap has been configured, this function will attempt to
38964** destroy and recreate it.  If the Win32 native heap is not isolated and/or
38965** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
38966** be returned and no changes will be made to the Win32 native heap.
38967*/
38968SQLITE_API int sqlite3_win32_reset_heap(){
38969  int rc;
38970  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
38971  MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
38972  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
38973  MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
38974  sqlite3_mutex_enter(pMaster);
38975  sqlite3_mutex_enter(pMem);
38976  winMemAssertMagic();
38977  if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
38978    /*
38979    ** At this point, there should be no outstanding memory allocations on
38980    ** the heap.  Also, since both the master and memsys locks are currently
38981    ** being held by us, no other function (i.e. from another thread) should
38982    ** be able to even access the heap.  Attempt to destroy and recreate our
38983    ** isolated Win32 native heap now.
38984    */
38985    assert( winMemGetHeap()!=NULL );
38986    assert( winMemGetOwned() );
38987    assert( sqlite3_memory_used()==0 );
38988    winMemShutdown(winMemGetDataPtr());
38989    assert( winMemGetHeap()==NULL );
38990    assert( !winMemGetOwned() );
38991    assert( sqlite3_memory_used()==0 );
38992    rc = winMemInit(winMemGetDataPtr());
38993    assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
38994    assert( rc!=SQLITE_OK || winMemGetOwned() );
38995    assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
38996  }else{
38997    /*
38998    ** The Win32 native heap cannot be modified because it may be in use.
38999    */
39000    rc = SQLITE_BUSY;
39001  }
39002  sqlite3_mutex_leave(pMem);
39003  sqlite3_mutex_leave(pMaster);
39004  return rc;
39005}
39006#endif /* SQLITE_WIN32_MALLOC */
39007
39008/*
39009** This function outputs the specified (ANSI) string to the Win32 debugger
39010** (if available).
39011*/
39012
39013SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
39014  char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
39015  int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
39016  if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
39017  assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
39018#ifdef SQLITE_ENABLE_API_ARMOR
39019  if( !zBuf ){
39020    (void)SQLITE_MISUSE_BKPT;
39021    return;
39022  }
39023#endif
39024#if defined(SQLITE_WIN32_HAS_ANSI)
39025  if( nMin>0 ){
39026    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
39027    memcpy(zDbgBuf, zBuf, nMin);
39028    osOutputDebugStringA(zDbgBuf);
39029  }else{
39030    osOutputDebugStringA(zBuf);
39031  }
39032#elif defined(SQLITE_WIN32_HAS_WIDE)
39033  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
39034  if ( osMultiByteToWideChar(
39035          osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
39036          nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
39037    return;
39038  }
39039  osOutputDebugStringW((LPCWSTR)zDbgBuf);
39040#else
39041  if( nMin>0 ){
39042    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
39043    memcpy(zDbgBuf, zBuf, nMin);
39044    fprintf(stderr, "%s", zDbgBuf);
39045  }else{
39046    fprintf(stderr, "%s", zBuf);
39047  }
39048#endif
39049}
39050
39051/*
39052** The following routine suspends the current thread for at least ms
39053** milliseconds.  This is equivalent to the Win32 Sleep() interface.
39054*/
39055#if SQLITE_OS_WINRT
39056static HANDLE sleepObj = NULL;
39057#endif
39058
39059SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
39060#if SQLITE_OS_WINRT
39061  if ( sleepObj==NULL ){
39062    sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
39063                                SYNCHRONIZE);
39064  }
39065  assert( sleepObj!=NULL );
39066  osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
39067#else
39068  osSleep(milliseconds);
39069#endif
39070}
39071
39072#if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
39073        SQLITE_THREADSAFE>0
39074SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
39075  DWORD rc;
39076  while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
39077                                       TRUE))==WAIT_IO_COMPLETION ){}
39078  return rc;
39079}
39080#endif
39081
39082/*
39083** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
39084** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
39085**
39086** Here is an interesting observation:  Win95, Win98, and WinME lack
39087** the LockFileEx() API.  But we can still statically link against that
39088** API as long as we don't call it when running Win95/98/ME.  A call to
39089** this routine is used to determine if the host is Win95/98/ME or
39090** WinNT/2K/XP so that we will know whether or not we can safely call
39091** the LockFileEx() API.
39092*/
39093
39094#if !SQLITE_WIN32_GETVERSIONEX
39095# define osIsNT()  (1)
39096#elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
39097# define osIsNT()  (1)
39098#elif !defined(SQLITE_WIN32_HAS_WIDE)
39099# define osIsNT()  (0)
39100#else
39101# define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
39102#endif
39103
39104/*
39105** This function determines if the machine is running a version of Windows
39106** based on the NT kernel.
39107*/
39108SQLITE_API int sqlite3_win32_is_nt(void){
39109#if SQLITE_OS_WINRT
39110  /*
39111  ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
39112  **       kernel.
39113  */
39114  return 1;
39115#elif SQLITE_WIN32_GETVERSIONEX
39116  if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
39117#if defined(SQLITE_WIN32_HAS_ANSI)
39118    OSVERSIONINFOA sInfo;
39119    sInfo.dwOSVersionInfoSize = sizeof(sInfo);
39120    osGetVersionExA(&sInfo);
39121    osInterlockedCompareExchange(&sqlite3_os_type,
39122        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
39123#elif defined(SQLITE_WIN32_HAS_WIDE)
39124    OSVERSIONINFOW sInfo;
39125    sInfo.dwOSVersionInfoSize = sizeof(sInfo);
39126    osGetVersionExW(&sInfo);
39127    osInterlockedCompareExchange(&sqlite3_os_type,
39128        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
39129#endif
39130  }
39131  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
39132#elif SQLITE_TEST
39133  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
39134#else
39135  /*
39136  ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
39137  **       deprecated are always assumed to be based on the NT kernel.
39138  */
39139  return 1;
39140#endif
39141}
39142
39143#ifdef SQLITE_WIN32_MALLOC
39144/*
39145** Allocate nBytes of memory.
39146*/
39147static void *winMemMalloc(int nBytes){
39148  HANDLE hHeap;
39149  void *p;
39150
39151  winMemAssertMagic();
39152  hHeap = winMemGetHeap();
39153  assert( hHeap!=0 );
39154  assert( hHeap!=INVALID_HANDLE_VALUE );
39155#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39156  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
39157#endif
39158  assert( nBytes>=0 );
39159  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
39160  if( !p ){
39161    sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
39162                nBytes, osGetLastError(), (void*)hHeap);
39163  }
39164  return p;
39165}
39166
39167/*
39168** Free memory.
39169*/
39170static void winMemFree(void *pPrior){
39171  HANDLE hHeap;
39172
39173  winMemAssertMagic();
39174  hHeap = winMemGetHeap();
39175  assert( hHeap!=0 );
39176  assert( hHeap!=INVALID_HANDLE_VALUE );
39177#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39178  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
39179#endif
39180  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
39181  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
39182    sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
39183                pPrior, osGetLastError(), (void*)hHeap);
39184  }
39185}
39186
39187/*
39188** Change the size of an existing memory allocation
39189*/
39190static void *winMemRealloc(void *pPrior, int nBytes){
39191  HANDLE hHeap;
39192  void *p;
39193
39194  winMemAssertMagic();
39195  hHeap = winMemGetHeap();
39196  assert( hHeap!=0 );
39197  assert( hHeap!=INVALID_HANDLE_VALUE );
39198#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39199  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
39200#endif
39201  assert( nBytes>=0 );
39202  if( !pPrior ){
39203    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
39204  }else{
39205    p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
39206  }
39207  if( !p ){
39208    sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
39209                pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
39210                (void*)hHeap);
39211  }
39212  return p;
39213}
39214
39215/*
39216** Return the size of an outstanding allocation, in bytes.
39217*/
39218static int winMemSize(void *p){
39219  HANDLE hHeap;
39220  SIZE_T n;
39221
39222  winMemAssertMagic();
39223  hHeap = winMemGetHeap();
39224  assert( hHeap!=0 );
39225  assert( hHeap!=INVALID_HANDLE_VALUE );
39226#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39227  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
39228#endif
39229  if( !p ) return 0;
39230  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
39231  if( n==(SIZE_T)-1 ){
39232    sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
39233                p, osGetLastError(), (void*)hHeap);
39234    return 0;
39235  }
39236  return (int)n;
39237}
39238
39239/*
39240** Round up a request size to the next valid allocation size.
39241*/
39242static int winMemRoundup(int n){
39243  return n;
39244}
39245
39246/*
39247** Initialize this module.
39248*/
39249static int winMemInit(void *pAppData){
39250  winMemData *pWinMemData = (winMemData *)pAppData;
39251
39252  if( !pWinMemData ) return SQLITE_ERROR;
39253  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
39254  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
39255
39256#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
39257  if( !pWinMemData->hHeap ){
39258    DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
39259    DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
39260    if( dwMaximumSize==0 ){
39261      dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
39262    }else if( dwInitialSize>dwMaximumSize ){
39263      dwInitialSize = dwMaximumSize;
39264    }
39265    pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
39266                                      dwInitialSize, dwMaximumSize);
39267    if( !pWinMemData->hHeap ){
39268      sqlite3_log(SQLITE_NOMEM,
39269          "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
39270          osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
39271          dwMaximumSize);
39272      return SQLITE_NOMEM_BKPT;
39273    }
39274    pWinMemData->bOwned = TRUE;
39275    assert( pWinMemData->bOwned );
39276  }
39277#else
39278  pWinMemData->hHeap = osGetProcessHeap();
39279  if( !pWinMemData->hHeap ){
39280    sqlite3_log(SQLITE_NOMEM,
39281        "failed to GetProcessHeap (%lu)", osGetLastError());
39282    return SQLITE_NOMEM_BKPT;
39283  }
39284  pWinMemData->bOwned = FALSE;
39285  assert( !pWinMemData->bOwned );
39286#endif
39287  assert( pWinMemData->hHeap!=0 );
39288  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
39289#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39290  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
39291#endif
39292  return SQLITE_OK;
39293}
39294
39295/*
39296** Deinitialize this module.
39297*/
39298static void winMemShutdown(void *pAppData){
39299  winMemData *pWinMemData = (winMemData *)pAppData;
39300
39301  if( !pWinMemData ) return;
39302  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
39303  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
39304
39305  if( pWinMemData->hHeap ){
39306    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
39307#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39308    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
39309#endif
39310    if( pWinMemData->bOwned ){
39311      if( !osHeapDestroy(pWinMemData->hHeap) ){
39312        sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
39313                    osGetLastError(), (void*)pWinMemData->hHeap);
39314      }
39315      pWinMemData->bOwned = FALSE;
39316    }
39317    pWinMemData->hHeap = NULL;
39318  }
39319}
39320
39321/*
39322** Populate the low-level memory allocation function pointers in
39323** sqlite3GlobalConfig.m with pointers to the routines in this file. The
39324** arguments specify the block of memory to manage.
39325**
39326** This routine is only called by sqlite3_config(), and therefore
39327** is not required to be threadsafe (it is not).
39328*/
39329SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
39330  static const sqlite3_mem_methods winMemMethods = {
39331    winMemMalloc,
39332    winMemFree,
39333    winMemRealloc,
39334    winMemSize,
39335    winMemRoundup,
39336    winMemInit,
39337    winMemShutdown,
39338    &win_mem_data
39339  };
39340  return &winMemMethods;
39341}
39342
39343SQLITE_PRIVATE void sqlite3MemSetDefault(void){
39344  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
39345}
39346#endif /* SQLITE_WIN32_MALLOC */
39347
39348/*
39349** Convert a UTF-8 string to Microsoft Unicode.
39350**
39351** Space to hold the returned string is obtained from sqlite3_malloc().
39352*/
39353static LPWSTR winUtf8ToUnicode(const char *zText){
39354  int nChar;
39355  LPWSTR zWideText;
39356
39357  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
39358  if( nChar==0 ){
39359    return 0;
39360  }
39361  zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
39362  if( zWideText==0 ){
39363    return 0;
39364  }
39365  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
39366                                nChar);
39367  if( nChar==0 ){
39368    sqlite3_free(zWideText);
39369    zWideText = 0;
39370  }
39371  return zWideText;
39372}
39373
39374/*
39375** Convert a Microsoft Unicode string to UTF-8.
39376**
39377** Space to hold the returned string is obtained from sqlite3_malloc().
39378*/
39379static char *winUnicodeToUtf8(LPCWSTR zWideText){
39380  int nByte;
39381  char *zText;
39382
39383  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
39384  if( nByte == 0 ){
39385    return 0;
39386  }
39387  zText = sqlite3MallocZero( nByte );
39388  if( zText==0 ){
39389    return 0;
39390  }
39391  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
39392                                0, 0);
39393  if( nByte == 0 ){
39394    sqlite3_free(zText);
39395    zText = 0;
39396  }
39397  return zText;
39398}
39399
39400/*
39401** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
39402** code page.
39403**
39404** Space to hold the returned string is obtained from sqlite3_malloc().
39405*/
39406static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
39407  int nByte;
39408  LPWSTR zMbcsText;
39409  int codepage = useAnsi ? CP_ACP : CP_OEMCP;
39410
39411  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
39412                                0)*sizeof(WCHAR);
39413  if( nByte==0 ){
39414    return 0;
39415  }
39416  zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
39417  if( zMbcsText==0 ){
39418    return 0;
39419  }
39420  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
39421                                nByte);
39422  if( nByte==0 ){
39423    sqlite3_free(zMbcsText);
39424    zMbcsText = 0;
39425  }
39426  return zMbcsText;
39427}
39428
39429/*
39430** Convert a Microsoft Unicode string to a multi-byte character string,
39431** using the ANSI or OEM code page.
39432**
39433** Space to hold the returned string is obtained from sqlite3_malloc().
39434*/
39435static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
39436  int nByte;
39437  char *zText;
39438  int codepage = useAnsi ? CP_ACP : CP_OEMCP;
39439
39440  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
39441  if( nByte == 0 ){
39442    return 0;
39443  }
39444  zText = sqlite3MallocZero( nByte );
39445  if( zText==0 ){
39446    return 0;
39447  }
39448  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
39449                                nByte, 0, 0);
39450  if( nByte == 0 ){
39451    sqlite3_free(zText);
39452    zText = 0;
39453  }
39454  return zText;
39455}
39456
39457/*
39458** Convert a multi-byte character string to UTF-8.
39459**
39460** Space to hold the returned string is obtained from sqlite3_malloc().
39461*/
39462static char *winMbcsToUtf8(const char *zText, int useAnsi){
39463  char *zTextUtf8;
39464  LPWSTR zTmpWide;
39465
39466  zTmpWide = winMbcsToUnicode(zText, useAnsi);
39467  if( zTmpWide==0 ){
39468    return 0;
39469  }
39470  zTextUtf8 = winUnicodeToUtf8(zTmpWide);
39471  sqlite3_free(zTmpWide);
39472  return zTextUtf8;
39473}
39474
39475/*
39476** Convert a UTF-8 string to a multi-byte character string.
39477**
39478** Space to hold the returned string is obtained from sqlite3_malloc().
39479*/
39480static char *winUtf8ToMbcs(const char *zText, int useAnsi){
39481  char *zTextMbcs;
39482  LPWSTR zTmpWide;
39483
39484  zTmpWide = winUtf8ToUnicode(zText);
39485  if( zTmpWide==0 ){
39486    return 0;
39487  }
39488  zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
39489  sqlite3_free(zTmpWide);
39490  return zTextMbcs;
39491}
39492
39493/*
39494** This is a public wrapper for the winUtf8ToUnicode() function.
39495*/
39496SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
39497#ifdef SQLITE_ENABLE_API_ARMOR
39498  if( !zText ){
39499    (void)SQLITE_MISUSE_BKPT;
39500    return 0;
39501  }
39502#endif
39503#ifndef SQLITE_OMIT_AUTOINIT
39504  if( sqlite3_initialize() ) return 0;
39505#endif
39506  return winUtf8ToUnicode(zText);
39507}
39508
39509/*
39510** This is a public wrapper for the winUnicodeToUtf8() function.
39511*/
39512SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
39513#ifdef SQLITE_ENABLE_API_ARMOR
39514  if( !zWideText ){
39515    (void)SQLITE_MISUSE_BKPT;
39516    return 0;
39517  }
39518#endif
39519#ifndef SQLITE_OMIT_AUTOINIT
39520  if( sqlite3_initialize() ) return 0;
39521#endif
39522  return winUnicodeToUtf8(zWideText);
39523}
39524
39525/*
39526** This is a public wrapper for the winMbcsToUtf8() function.
39527*/
39528SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
39529#ifdef SQLITE_ENABLE_API_ARMOR
39530  if( !zText ){
39531    (void)SQLITE_MISUSE_BKPT;
39532    return 0;
39533  }
39534#endif
39535#ifndef SQLITE_OMIT_AUTOINIT
39536  if( sqlite3_initialize() ) return 0;
39537#endif
39538  return winMbcsToUtf8(zText, osAreFileApisANSI());
39539}
39540
39541/*
39542** This is a public wrapper for the winMbcsToUtf8() function.
39543*/
39544SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
39545#ifdef SQLITE_ENABLE_API_ARMOR
39546  if( !zText ){
39547    (void)SQLITE_MISUSE_BKPT;
39548    return 0;
39549  }
39550#endif
39551#ifndef SQLITE_OMIT_AUTOINIT
39552  if( sqlite3_initialize() ) return 0;
39553#endif
39554  return winMbcsToUtf8(zText, useAnsi);
39555}
39556
39557/*
39558** This is a public wrapper for the winUtf8ToMbcs() function.
39559*/
39560SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
39561#ifdef SQLITE_ENABLE_API_ARMOR
39562  if( !zText ){
39563    (void)SQLITE_MISUSE_BKPT;
39564    return 0;
39565  }
39566#endif
39567#ifndef SQLITE_OMIT_AUTOINIT
39568  if( sqlite3_initialize() ) return 0;
39569#endif
39570  return winUtf8ToMbcs(zText, osAreFileApisANSI());
39571}
39572
39573/*
39574** This is a public wrapper for the winUtf8ToMbcs() function.
39575*/
39576SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
39577#ifdef SQLITE_ENABLE_API_ARMOR
39578  if( !zText ){
39579    (void)SQLITE_MISUSE_BKPT;
39580    return 0;
39581  }
39582#endif
39583#ifndef SQLITE_OMIT_AUTOINIT
39584  if( sqlite3_initialize() ) return 0;
39585#endif
39586  return winUtf8ToMbcs(zText, useAnsi);
39587}
39588
39589/*
39590** This function sets the data directory or the temporary directory based on
39591** the provided arguments.  The type argument must be 1 in order to set the
39592** data directory or 2 in order to set the temporary directory.  The zValue
39593** argument is the name of the directory to use.  The return value will be
39594** SQLITE_OK if successful.
39595*/
39596SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
39597  char **ppDirectory = 0;
39598#ifndef SQLITE_OMIT_AUTOINIT
39599  int rc = sqlite3_initialize();
39600  if( rc ) return rc;
39601#endif
39602  if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
39603    ppDirectory = &sqlite3_data_directory;
39604  }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
39605    ppDirectory = &sqlite3_temp_directory;
39606  }
39607  assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
39608          || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
39609  );
39610  assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
39611  if( ppDirectory ){
39612    char *zValueUtf8 = 0;
39613    if( zValue && zValue[0] ){
39614      zValueUtf8 = winUnicodeToUtf8(zValue);
39615      if ( zValueUtf8==0 ){
39616        return SQLITE_NOMEM_BKPT;
39617      }
39618    }
39619    sqlite3_free(*ppDirectory);
39620    *ppDirectory = zValueUtf8;
39621    return SQLITE_OK;
39622  }
39623  return SQLITE_ERROR;
39624}
39625
39626/*
39627** The return value of winGetLastErrorMsg
39628** is zero if the error message fits in the buffer, or non-zero
39629** otherwise (if the message was truncated).
39630*/
39631static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
39632  /* FormatMessage returns 0 on failure.  Otherwise it
39633  ** returns the number of TCHARs written to the output
39634  ** buffer, excluding the terminating null char.
39635  */
39636  DWORD dwLen = 0;
39637  char *zOut = 0;
39638
39639  if( osIsNT() ){
39640#if SQLITE_OS_WINRT
39641    WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
39642    dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
39643                             FORMAT_MESSAGE_IGNORE_INSERTS,
39644                             NULL,
39645                             lastErrno,
39646                             0,
39647                             zTempWide,
39648                             SQLITE_WIN32_MAX_ERRMSG_CHARS,
39649                             0);
39650#else
39651    LPWSTR zTempWide = NULL;
39652    dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
39653                             FORMAT_MESSAGE_FROM_SYSTEM |
39654                             FORMAT_MESSAGE_IGNORE_INSERTS,
39655                             NULL,
39656                             lastErrno,
39657                             0,
39658                             (LPWSTR) &zTempWide,
39659                             0,
39660                             0);
39661#endif
39662    if( dwLen > 0 ){
39663      /* allocate a buffer and convert to UTF8 */
39664      sqlite3BeginBenignMalloc();
39665      zOut = winUnicodeToUtf8(zTempWide);
39666      sqlite3EndBenignMalloc();
39667#if !SQLITE_OS_WINRT
39668      /* free the system buffer allocated by FormatMessage */
39669      osLocalFree(zTempWide);
39670#endif
39671    }
39672  }
39673#ifdef SQLITE_WIN32_HAS_ANSI
39674  else{
39675    char *zTemp = NULL;
39676    dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
39677                             FORMAT_MESSAGE_FROM_SYSTEM |
39678                             FORMAT_MESSAGE_IGNORE_INSERTS,
39679                             NULL,
39680                             lastErrno,
39681                             0,
39682                             (LPSTR) &zTemp,
39683                             0,
39684                             0);
39685    if( dwLen > 0 ){
39686      /* allocate a buffer and convert to UTF8 */
39687      sqlite3BeginBenignMalloc();
39688      zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
39689      sqlite3EndBenignMalloc();
39690      /* free the system buffer allocated by FormatMessage */
39691      osLocalFree(zTemp);
39692    }
39693  }
39694#endif
39695  if( 0 == dwLen ){
39696    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
39697  }else{
39698    /* copy a maximum of nBuf chars to output buffer */
39699    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
39700    /* free the UTF8 buffer */
39701    sqlite3_free(zOut);
39702  }
39703  return 0;
39704}
39705
39706/*
39707**
39708** This function - winLogErrorAtLine() - is only ever called via the macro
39709** winLogError().
39710**
39711** This routine is invoked after an error occurs in an OS function.
39712** It logs a message using sqlite3_log() containing the current value of
39713** error code and, if possible, the human-readable equivalent from
39714** FormatMessage.
39715**
39716** The first argument passed to the macro should be the error code that
39717** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
39718** The two subsequent arguments should be the name of the OS function that
39719** failed and the associated file-system path, if any.
39720*/
39721#define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
39722static int winLogErrorAtLine(
39723  int errcode,                    /* SQLite error code */
39724  DWORD lastErrno,                /* Win32 last error */
39725  const char *zFunc,              /* Name of OS function that failed */
39726  const char *zPath,              /* File path associated with error */
39727  int iLine                       /* Source line number where error occurred */
39728){
39729  char zMsg[500];                 /* Human readable error text */
39730  int i;                          /* Loop counter */
39731
39732  zMsg[0] = 0;
39733  winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
39734  assert( errcode!=SQLITE_OK );
39735  if( zPath==0 ) zPath = "";
39736  for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
39737  zMsg[i] = 0;
39738  sqlite3_log(errcode,
39739      "os_win.c:%d: (%lu) %s(%s) - %s",
39740      iLine, lastErrno, zFunc, zPath, zMsg
39741  );
39742
39743  return errcode;
39744}
39745
39746/*
39747** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
39748** will be retried following a locking error - probably caused by
39749** antivirus software.  Also the initial delay before the first retry.
39750** The delay increases linearly with each retry.
39751*/
39752#ifndef SQLITE_WIN32_IOERR_RETRY
39753# define SQLITE_WIN32_IOERR_RETRY 10
39754#endif
39755#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
39756# define SQLITE_WIN32_IOERR_RETRY_DELAY 25
39757#endif
39758static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
39759static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
39760
39761/*
39762** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
39763** error code obtained via GetLastError() is eligible to be retried.  It
39764** must accept the error code DWORD as its only argument and should return
39765** non-zero if the error code is transient in nature and the operation
39766** responsible for generating the original error might succeed upon being
39767** retried.  The argument to this macro should be a variable.
39768**
39769** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
39770** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
39771** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
39772** may be used to include additional error codes in the set that should
39773** result in the failing I/O operation being retried by the caller.  If
39774** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
39775** identical to those of the "winIoerrCanRetry1" macro.
39776*/
39777#if !defined(winIoerrCanRetry1)
39778#define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
39779                              ((a)==ERROR_SHARING_VIOLATION)    || \
39780                              ((a)==ERROR_LOCK_VIOLATION)       || \
39781                              ((a)==ERROR_DEV_NOT_EXIST)        || \
39782                              ((a)==ERROR_NETNAME_DELETED)      || \
39783                              ((a)==ERROR_SEM_TIMEOUT)          || \
39784                              ((a)==ERROR_NETWORK_UNREACHABLE))
39785#endif
39786
39787/*
39788** If a ReadFile() or WriteFile() error occurs, invoke this routine
39789** to see if it should be retried.  Return TRUE to retry.  Return FALSE
39790** to give up with an error.
39791*/
39792static int winRetryIoerr(int *pnRetry, DWORD *pError){
39793  DWORD e = osGetLastError();
39794  if( *pnRetry>=winIoerrRetry ){
39795    if( pError ){
39796      *pError = e;
39797    }
39798    return 0;
39799  }
39800  if( winIoerrCanRetry1(e) ){
39801    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
39802    ++*pnRetry;
39803    return 1;
39804  }
39805#if defined(winIoerrCanRetry2)
39806  else if( winIoerrCanRetry2(e) ){
39807    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
39808    ++*pnRetry;
39809    return 1;
39810  }
39811#endif
39812  if( pError ){
39813    *pError = e;
39814  }
39815  return 0;
39816}
39817
39818/*
39819** Log a I/O error retry episode.
39820*/
39821static void winLogIoerr(int nRetry, int lineno){
39822  if( nRetry ){
39823    sqlite3_log(SQLITE_NOTICE,
39824      "delayed %dms for lock/sharing conflict at line %d",
39825      winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
39826    );
39827  }
39828}
39829
39830/*
39831** This #if does not rely on the SQLITE_OS_WINCE define because the
39832** corresponding section in "date.c" cannot use it.
39833*/
39834#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
39835    (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
39836/*
39837** The MSVC CRT on Windows CE may not have a localtime() function.
39838** So define a substitute.
39839*/
39840/* #  include <time.h> */
39841struct tm *__cdecl localtime(const time_t *t)
39842{
39843  static struct tm y;
39844  FILETIME uTm, lTm;
39845  SYSTEMTIME pTm;
39846  sqlite3_int64 t64;
39847  t64 = *t;
39848  t64 = (t64 + 11644473600)*10000000;
39849  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
39850  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
39851  osFileTimeToLocalFileTime(&uTm,&lTm);
39852  osFileTimeToSystemTime(&lTm,&pTm);
39853  y.tm_year = pTm.wYear - 1900;
39854  y.tm_mon = pTm.wMonth - 1;
39855  y.tm_wday = pTm.wDayOfWeek;
39856  y.tm_mday = pTm.wDay;
39857  y.tm_hour = pTm.wHour;
39858  y.tm_min = pTm.wMinute;
39859  y.tm_sec = pTm.wSecond;
39860  return &y;
39861}
39862#endif
39863
39864#if SQLITE_OS_WINCE
39865/*************************************************************************
39866** This section contains code for WinCE only.
39867*/
39868#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
39869
39870/*
39871** Acquire a lock on the handle h
39872*/
39873static void winceMutexAcquire(HANDLE h){
39874   DWORD dwErr;
39875   do {
39876     dwErr = osWaitForSingleObject(h, INFINITE);
39877   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
39878}
39879/*
39880** Release a lock acquired by winceMutexAcquire()
39881*/
39882#define winceMutexRelease(h) ReleaseMutex(h)
39883
39884/*
39885** Create the mutex and shared memory used for locking in the file
39886** descriptor pFile
39887*/
39888static int winceCreateLock(const char *zFilename, winFile *pFile){
39889  LPWSTR zTok;
39890  LPWSTR zName;
39891  DWORD lastErrno;
39892  BOOL bLogged = FALSE;
39893  BOOL bInit = TRUE;
39894
39895  zName = winUtf8ToUnicode(zFilename);
39896  if( zName==0 ){
39897    /* out of memory */
39898    return SQLITE_IOERR_NOMEM_BKPT;
39899  }
39900
39901  /* Initialize the local lockdata */
39902  memset(&pFile->local, 0, sizeof(pFile->local));
39903
39904  /* Replace the backslashes from the filename and lowercase it
39905  ** to derive a mutex name. */
39906  zTok = osCharLowerW(zName);
39907  for (;*zTok;zTok++){
39908    if (*zTok == '\\') *zTok = '_';
39909  }
39910
39911  /* Create/open the named mutex */
39912  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
39913  if (!pFile->hMutex){
39914    pFile->lastErrno = osGetLastError();
39915    sqlite3_free(zName);
39916    return winLogError(SQLITE_IOERR, pFile->lastErrno,
39917                       "winceCreateLock1", zFilename);
39918  }
39919
39920  /* Acquire the mutex before continuing */
39921  winceMutexAcquire(pFile->hMutex);
39922
39923  /* Since the names of named mutexes, semaphores, file mappings etc are
39924  ** case-sensitive, take advantage of that by uppercasing the mutex name
39925  ** and using that as the shared filemapping name.
39926  */
39927  osCharUpperW(zName);
39928  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
39929                                        PAGE_READWRITE, 0, sizeof(winceLock),
39930                                        zName);
39931
39932  /* Set a flag that indicates we're the first to create the memory so it
39933  ** must be zero-initialized */
39934  lastErrno = osGetLastError();
39935  if (lastErrno == ERROR_ALREADY_EXISTS){
39936    bInit = FALSE;
39937  }
39938
39939  sqlite3_free(zName);
39940
39941  /* If we succeeded in making the shared memory handle, map it. */
39942  if( pFile->hShared ){
39943    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
39944             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
39945    /* If mapping failed, close the shared memory handle and erase it */
39946    if( !pFile->shared ){
39947      pFile->lastErrno = osGetLastError();
39948      winLogError(SQLITE_IOERR, pFile->lastErrno,
39949                  "winceCreateLock2", zFilename);
39950      bLogged = TRUE;
39951      osCloseHandle(pFile->hShared);
39952      pFile->hShared = NULL;
39953    }
39954  }
39955
39956  /* If shared memory could not be created, then close the mutex and fail */
39957  if( pFile->hShared==NULL ){
39958    if( !bLogged ){
39959      pFile->lastErrno = lastErrno;
39960      winLogError(SQLITE_IOERR, pFile->lastErrno,
39961                  "winceCreateLock3", zFilename);
39962      bLogged = TRUE;
39963    }
39964    winceMutexRelease(pFile->hMutex);
39965    osCloseHandle(pFile->hMutex);
39966    pFile->hMutex = NULL;
39967    return SQLITE_IOERR;
39968  }
39969
39970  /* Initialize the shared memory if we're supposed to */
39971  if( bInit ){
39972    memset(pFile->shared, 0, sizeof(winceLock));
39973  }
39974
39975  winceMutexRelease(pFile->hMutex);
39976  return SQLITE_OK;
39977}
39978
39979/*
39980** Destroy the part of winFile that deals with wince locks
39981*/
39982static void winceDestroyLock(winFile *pFile){
39983  if (pFile->hMutex){
39984    /* Acquire the mutex */
39985    winceMutexAcquire(pFile->hMutex);
39986
39987    /* The following blocks should probably assert in debug mode, but they
39988       are to cleanup in case any locks remained open */
39989    if (pFile->local.nReaders){
39990      pFile->shared->nReaders --;
39991    }
39992    if (pFile->local.bReserved){
39993      pFile->shared->bReserved = FALSE;
39994    }
39995    if (pFile->local.bPending){
39996      pFile->shared->bPending = FALSE;
39997    }
39998    if (pFile->local.bExclusive){
39999      pFile->shared->bExclusive = FALSE;
40000    }
40001
40002    /* De-reference and close our copy of the shared memory handle */
40003    osUnmapViewOfFile(pFile->shared);
40004    osCloseHandle(pFile->hShared);
40005
40006    /* Done with the mutex */
40007    winceMutexRelease(pFile->hMutex);
40008    osCloseHandle(pFile->hMutex);
40009    pFile->hMutex = NULL;
40010  }
40011}
40012
40013/*
40014** An implementation of the LockFile() API of Windows for CE
40015*/
40016static BOOL winceLockFile(
40017  LPHANDLE phFile,
40018  DWORD dwFileOffsetLow,
40019  DWORD dwFileOffsetHigh,
40020  DWORD nNumberOfBytesToLockLow,
40021  DWORD nNumberOfBytesToLockHigh
40022){
40023  winFile *pFile = HANDLE_TO_WINFILE(phFile);
40024  BOOL bReturn = FALSE;
40025
40026  UNUSED_PARAMETER(dwFileOffsetHigh);
40027  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
40028
40029  if (!pFile->hMutex) return TRUE;
40030  winceMutexAcquire(pFile->hMutex);
40031
40032  /* Wanting an exclusive lock? */
40033  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
40034       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
40035    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
40036       pFile->shared->bExclusive = TRUE;
40037       pFile->local.bExclusive = TRUE;
40038       bReturn = TRUE;
40039    }
40040  }
40041
40042  /* Want a read-only lock? */
40043  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
40044           nNumberOfBytesToLockLow == 1){
40045    if (pFile->shared->bExclusive == 0){
40046      pFile->local.nReaders ++;
40047      if (pFile->local.nReaders == 1){
40048        pFile->shared->nReaders ++;
40049      }
40050      bReturn = TRUE;
40051    }
40052  }
40053
40054  /* Want a pending lock? */
40055  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
40056           && nNumberOfBytesToLockLow == 1){
40057    /* If no pending lock has been acquired, then acquire it */
40058    if (pFile->shared->bPending == 0) {
40059      pFile->shared->bPending = TRUE;
40060      pFile->local.bPending = TRUE;
40061      bReturn = TRUE;
40062    }
40063  }
40064
40065  /* Want a reserved lock? */
40066  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
40067           && nNumberOfBytesToLockLow == 1){
40068    if (pFile->shared->bReserved == 0) {
40069      pFile->shared->bReserved = TRUE;
40070      pFile->local.bReserved = TRUE;
40071      bReturn = TRUE;
40072    }
40073  }
40074
40075  winceMutexRelease(pFile->hMutex);
40076  return bReturn;
40077}
40078
40079/*
40080** An implementation of the UnlockFile API of Windows for CE
40081*/
40082static BOOL winceUnlockFile(
40083  LPHANDLE phFile,
40084  DWORD dwFileOffsetLow,
40085  DWORD dwFileOffsetHigh,
40086  DWORD nNumberOfBytesToUnlockLow,
40087  DWORD nNumberOfBytesToUnlockHigh
40088){
40089  winFile *pFile = HANDLE_TO_WINFILE(phFile);
40090  BOOL bReturn = FALSE;
40091
40092  UNUSED_PARAMETER(dwFileOffsetHigh);
40093  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
40094
40095  if (!pFile->hMutex) return TRUE;
40096  winceMutexAcquire(pFile->hMutex);
40097
40098  /* Releasing a reader lock or an exclusive lock */
40099  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
40100    /* Did we have an exclusive lock? */
40101    if (pFile->local.bExclusive){
40102      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
40103      pFile->local.bExclusive = FALSE;
40104      pFile->shared->bExclusive = FALSE;
40105      bReturn = TRUE;
40106    }
40107
40108    /* Did we just have a reader lock? */
40109    else if (pFile->local.nReaders){
40110      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
40111             || nNumberOfBytesToUnlockLow == 1);
40112      pFile->local.nReaders --;
40113      if (pFile->local.nReaders == 0)
40114      {
40115        pFile->shared->nReaders --;
40116      }
40117      bReturn = TRUE;
40118    }
40119  }
40120
40121  /* Releasing a pending lock */
40122  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
40123           && nNumberOfBytesToUnlockLow == 1){
40124    if (pFile->local.bPending){
40125      pFile->local.bPending = FALSE;
40126      pFile->shared->bPending = FALSE;
40127      bReturn = TRUE;
40128    }
40129  }
40130  /* Releasing a reserved lock */
40131  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
40132           && nNumberOfBytesToUnlockLow == 1){
40133    if (pFile->local.bReserved) {
40134      pFile->local.bReserved = FALSE;
40135      pFile->shared->bReserved = FALSE;
40136      bReturn = TRUE;
40137    }
40138  }
40139
40140  winceMutexRelease(pFile->hMutex);
40141  return bReturn;
40142}
40143/*
40144** End of the special code for wince
40145*****************************************************************************/
40146#endif /* SQLITE_OS_WINCE */
40147
40148/*
40149** Lock a file region.
40150*/
40151static BOOL winLockFile(
40152  LPHANDLE phFile,
40153  DWORD flags,
40154  DWORD offsetLow,
40155  DWORD offsetHigh,
40156  DWORD numBytesLow,
40157  DWORD numBytesHigh
40158){
40159#if SQLITE_OS_WINCE
40160  /*
40161  ** NOTE: Windows CE is handled differently here due its lack of the Win32
40162  **       API LockFile.
40163  */
40164  return winceLockFile(phFile, offsetLow, offsetHigh,
40165                       numBytesLow, numBytesHigh);
40166#else
40167  if( osIsNT() ){
40168    OVERLAPPED ovlp;
40169    memset(&ovlp, 0, sizeof(OVERLAPPED));
40170    ovlp.Offset = offsetLow;
40171    ovlp.OffsetHigh = offsetHigh;
40172    return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
40173  }else{
40174    return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
40175                      numBytesHigh);
40176  }
40177#endif
40178}
40179
40180/*
40181** Unlock a file region.
40182 */
40183static BOOL winUnlockFile(
40184  LPHANDLE phFile,
40185  DWORD offsetLow,
40186  DWORD offsetHigh,
40187  DWORD numBytesLow,
40188  DWORD numBytesHigh
40189){
40190#if SQLITE_OS_WINCE
40191  /*
40192  ** NOTE: Windows CE is handled differently here due its lack of the Win32
40193  **       API UnlockFile.
40194  */
40195  return winceUnlockFile(phFile, offsetLow, offsetHigh,
40196                         numBytesLow, numBytesHigh);
40197#else
40198  if( osIsNT() ){
40199    OVERLAPPED ovlp;
40200    memset(&ovlp, 0, sizeof(OVERLAPPED));
40201    ovlp.Offset = offsetLow;
40202    ovlp.OffsetHigh = offsetHigh;
40203    return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
40204  }else{
40205    return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
40206                        numBytesHigh);
40207  }
40208#endif
40209}
40210
40211/*****************************************************************************
40212** The next group of routines implement the I/O methods specified
40213** by the sqlite3_io_methods object.
40214******************************************************************************/
40215
40216/*
40217** Some Microsoft compilers lack this definition.
40218*/
40219#ifndef INVALID_SET_FILE_POINTER
40220# define INVALID_SET_FILE_POINTER ((DWORD)-1)
40221#endif
40222
40223/*
40224** Move the current position of the file handle passed as the first
40225** argument to offset iOffset within the file. If successful, return 0.
40226** Otherwise, set pFile->lastErrno and return non-zero.
40227*/
40228static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
40229#if !SQLITE_OS_WINRT
40230  LONG upperBits;                 /* Most sig. 32 bits of new offset */
40231  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
40232  DWORD dwRet;                    /* Value returned by SetFilePointer() */
40233  DWORD lastErrno;                /* Value returned by GetLastError() */
40234
40235  OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
40236
40237  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
40238  lowerBits = (LONG)(iOffset & 0xffffffff);
40239
40240  /* API oddity: If successful, SetFilePointer() returns a dword
40241  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
40242  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
40243  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
40244  ** whether an error has actually occurred, it is also necessary to call
40245  ** GetLastError().
40246  */
40247  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
40248
40249  if( (dwRet==INVALID_SET_FILE_POINTER
40250      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
40251    pFile->lastErrno = lastErrno;
40252    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
40253                "winSeekFile", pFile->zPath);
40254    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
40255    return 1;
40256  }
40257
40258  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
40259  return 0;
40260#else
40261  /*
40262  ** Same as above, except that this implementation works for WinRT.
40263  */
40264
40265  LARGE_INTEGER x;                /* The new offset */
40266  BOOL bRet;                      /* Value returned by SetFilePointerEx() */
40267
40268  x.QuadPart = iOffset;
40269  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
40270
40271  if(!bRet){
40272    pFile->lastErrno = osGetLastError();
40273    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
40274                "winSeekFile", pFile->zPath);
40275    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
40276    return 1;
40277  }
40278
40279  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
40280  return 0;
40281#endif
40282}
40283
40284#if SQLITE_MAX_MMAP_SIZE>0
40285/* Forward references to VFS helper methods used for memory mapped files */
40286static int winMapfile(winFile*, sqlite3_int64);
40287static int winUnmapfile(winFile*);
40288#endif
40289
40290/*
40291** Close a file.
40292**
40293** It is reported that an attempt to close a handle might sometimes
40294** fail.  This is a very unreasonable result, but Windows is notorious
40295** for being unreasonable so I do not doubt that it might happen.  If
40296** the close fails, we pause for 100 milliseconds and try again.  As
40297** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
40298** giving up and returning an error.
40299*/
40300#define MX_CLOSE_ATTEMPT 3
40301static int winClose(sqlite3_file *id){
40302  int rc, cnt = 0;
40303  winFile *pFile = (winFile*)id;
40304
40305  assert( id!=0 );
40306#ifndef SQLITE_OMIT_WAL
40307  assert( pFile->pShm==0 );
40308#endif
40309  assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
40310  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
40311           osGetCurrentProcessId(), pFile, pFile->h));
40312
40313#if SQLITE_MAX_MMAP_SIZE>0
40314  winUnmapfile(pFile);
40315#endif
40316
40317  do{
40318    rc = osCloseHandle(pFile->h);
40319    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
40320  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
40321#if SQLITE_OS_WINCE
40322#define WINCE_DELETION_ATTEMPTS 3
40323  {
40324    winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
40325    if( pAppData==NULL || !pAppData->bNoLock ){
40326      winceDestroyLock(pFile);
40327    }
40328  }
40329  if( pFile->zDeleteOnClose ){
40330    int cnt = 0;
40331    while(
40332           osDeleteFileW(pFile->zDeleteOnClose)==0
40333        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
40334        && cnt++ < WINCE_DELETION_ATTEMPTS
40335    ){
40336       sqlite3_win32_sleep(100);  /* Wait a little before trying again */
40337    }
40338    sqlite3_free(pFile->zDeleteOnClose);
40339  }
40340#endif
40341  if( rc ){
40342    pFile->h = NULL;
40343  }
40344  OpenCounter(-1);
40345  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
40346           osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
40347  return rc ? SQLITE_OK
40348            : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
40349                          "winClose", pFile->zPath);
40350}
40351
40352/*
40353** Read data from a file into a buffer.  Return SQLITE_OK if all
40354** bytes were read successfully and SQLITE_IOERR if anything goes
40355** wrong.
40356*/
40357static int winRead(
40358  sqlite3_file *id,          /* File to read from */
40359  void *pBuf,                /* Write content into this buffer */
40360  int amt,                   /* Number of bytes to read */
40361  sqlite3_int64 offset       /* Begin reading at this offset */
40362){
40363#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
40364  OVERLAPPED overlapped;          /* The offset for ReadFile. */
40365#endif
40366  winFile *pFile = (winFile*)id;  /* file handle */
40367  DWORD nRead;                    /* Number of bytes actually read from file */
40368  int nRetry = 0;                 /* Number of retrys */
40369
40370  assert( id!=0 );
40371  assert( amt>0 );
40372  assert( offset>=0 );
40373  SimulateIOError(return SQLITE_IOERR_READ);
40374  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
40375           "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
40376           pFile->h, pBuf, amt, offset, pFile->locktype));
40377
40378#if SQLITE_MAX_MMAP_SIZE>0
40379  /* Deal with as much of this read request as possible by transfering
40380  ** data from the memory mapping using memcpy().  */
40381  if( offset<pFile->mmapSize ){
40382    if( offset+amt <= pFile->mmapSize ){
40383      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
40384      OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40385               osGetCurrentProcessId(), pFile, pFile->h));
40386      return SQLITE_OK;
40387    }else{
40388      int nCopy = (int)(pFile->mmapSize - offset);
40389      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
40390      pBuf = &((u8 *)pBuf)[nCopy];
40391      amt -= nCopy;
40392      offset += nCopy;
40393    }
40394  }
40395#endif
40396
40397#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
40398  if( winSeekFile(pFile, offset) ){
40399    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
40400             osGetCurrentProcessId(), pFile, pFile->h));
40401    return SQLITE_FULL;
40402  }
40403  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
40404#else
40405  memset(&overlapped, 0, sizeof(OVERLAPPED));
40406  overlapped.Offset = (LONG)(offset & 0xffffffff);
40407  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
40408  while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
40409         osGetLastError()!=ERROR_HANDLE_EOF ){
40410#endif
40411    DWORD lastErrno;
40412    if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
40413    pFile->lastErrno = lastErrno;
40414    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
40415             osGetCurrentProcessId(), pFile, pFile->h));
40416    return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
40417                       "winRead", pFile->zPath);
40418  }
40419  winLogIoerr(nRetry, __LINE__);
40420  if( nRead<(DWORD)amt ){
40421    /* Unread parts of the buffer must be zero-filled */
40422    memset(&((char*)pBuf)[nRead], 0, amt-nRead);
40423    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
40424             osGetCurrentProcessId(), pFile, pFile->h));
40425    return SQLITE_IOERR_SHORT_READ;
40426  }
40427
40428  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40429           osGetCurrentProcessId(), pFile, pFile->h));
40430  return SQLITE_OK;
40431}
40432
40433/*
40434** Write data from a buffer into a file.  Return SQLITE_OK on success
40435** or some other error code on failure.
40436*/
40437static int winWrite(
40438  sqlite3_file *id,               /* File to write into */
40439  const void *pBuf,               /* The bytes to be written */
40440  int amt,                        /* Number of bytes to write */
40441  sqlite3_int64 offset            /* Offset into the file to begin writing at */
40442){
40443  int rc = 0;                     /* True if error has occurred, else false */
40444  winFile *pFile = (winFile*)id;  /* File handle */
40445  int nRetry = 0;                 /* Number of retries */
40446
40447  assert( amt>0 );
40448  assert( pFile );
40449  SimulateIOError(return SQLITE_IOERR_WRITE);
40450  SimulateDiskfullError(return SQLITE_FULL);
40451
40452  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
40453           "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
40454           pFile->h, pBuf, amt, offset, pFile->locktype));
40455
40456#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
40457  /* Deal with as much of this write request as possible by transfering
40458  ** data from the memory mapping using memcpy().  */
40459  if( offset<pFile->mmapSize ){
40460    if( offset+amt <= pFile->mmapSize ){
40461      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
40462      OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40463               osGetCurrentProcessId(), pFile, pFile->h));
40464      return SQLITE_OK;
40465    }else{
40466      int nCopy = (int)(pFile->mmapSize - offset);
40467      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
40468      pBuf = &((u8 *)pBuf)[nCopy];
40469      amt -= nCopy;
40470      offset += nCopy;
40471    }
40472  }
40473#endif
40474
40475#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
40476  rc = winSeekFile(pFile, offset);
40477  if( rc==0 ){
40478#else
40479  {
40480#endif
40481#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
40482    OVERLAPPED overlapped;        /* The offset for WriteFile. */
40483#endif
40484    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
40485    int nRem = amt;               /* Number of bytes yet to be written */
40486    DWORD nWrite;                 /* Bytes written by each WriteFile() call */
40487    DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
40488
40489#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
40490    memset(&overlapped, 0, sizeof(OVERLAPPED));
40491    overlapped.Offset = (LONG)(offset & 0xffffffff);
40492    overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
40493#endif
40494
40495    while( nRem>0 ){
40496#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
40497      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
40498#else
40499      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
40500#endif
40501        if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
40502        break;
40503      }
40504      assert( nWrite==0 || nWrite<=(DWORD)nRem );
40505      if( nWrite==0 || nWrite>(DWORD)nRem ){
40506        lastErrno = osGetLastError();
40507        break;
40508      }
40509#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
40510      offset += nWrite;
40511      overlapped.Offset = (LONG)(offset & 0xffffffff);
40512      overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
40513#endif
40514      aRem += nWrite;
40515      nRem -= nWrite;
40516    }
40517    if( nRem>0 ){
40518      pFile->lastErrno = lastErrno;
40519      rc = 1;
40520    }
40521  }
40522
40523  if( rc ){
40524    if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
40525       || ( pFile->lastErrno==ERROR_DISK_FULL )){
40526      OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
40527               osGetCurrentProcessId(), pFile, pFile->h));
40528      return winLogError(SQLITE_FULL, pFile->lastErrno,
40529                         "winWrite1", pFile->zPath);
40530    }
40531    OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
40532             osGetCurrentProcessId(), pFile, pFile->h));
40533    return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
40534                       "winWrite2", pFile->zPath);
40535  }else{
40536    winLogIoerr(nRetry, __LINE__);
40537  }
40538  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40539           osGetCurrentProcessId(), pFile, pFile->h));
40540  return SQLITE_OK;
40541}
40542
40543/*
40544** Truncate an open file to a specified size
40545*/
40546static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
40547  winFile *pFile = (winFile*)id;  /* File handle object */
40548  int rc = SQLITE_OK;             /* Return code for this function */
40549  DWORD lastErrno;
40550
40551  assert( pFile );
40552  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
40553  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
40554           osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
40555
40556  /* If the user has configured a chunk-size for this file, truncate the
40557  ** file so that it consists of an integer number of chunks (i.e. the
40558  ** actual file size after the operation may be larger than the requested
40559  ** size).
40560  */
40561  if( pFile->szChunk>0 ){
40562    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
40563  }
40564
40565  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
40566  if( winSeekFile(pFile, nByte) ){
40567    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
40568                     "winTruncate1", pFile->zPath);
40569  }else if( 0==osSetEndOfFile(pFile->h) &&
40570            ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
40571    pFile->lastErrno = lastErrno;
40572    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
40573                     "winTruncate2", pFile->zPath);
40574  }
40575
40576#if SQLITE_MAX_MMAP_SIZE>0
40577  /* If the file was truncated to a size smaller than the currently
40578  ** mapped region, reduce the effective mapping size as well. SQLite will
40579  ** use read() and write() to access data beyond this point from now on.
40580  */
40581  if( pFile->pMapRegion && nByte<pFile->mmapSize ){
40582    pFile->mmapSize = nByte;
40583  }
40584#endif
40585
40586  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
40587           osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
40588  return rc;
40589}
40590
40591#ifdef SQLITE_TEST
40592/*
40593** Count the number of fullsyncs and normal syncs.  This is used to test
40594** that syncs and fullsyncs are occuring at the right times.
40595*/
40596SQLITE_API int sqlite3_sync_count = 0;
40597SQLITE_API int sqlite3_fullsync_count = 0;
40598#endif
40599
40600/*
40601** Make sure all writes to a particular file are committed to disk.
40602*/
40603static int winSync(sqlite3_file *id, int flags){
40604#ifndef SQLITE_NO_SYNC
40605  /*
40606  ** Used only when SQLITE_NO_SYNC is not defined.
40607   */
40608  BOOL rc;
40609#endif
40610#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
40611    defined(SQLITE_HAVE_OS_TRACE)
40612  /*
40613  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
40614  ** OSTRACE() macros.
40615   */
40616  winFile *pFile = (winFile*)id;
40617#else
40618  UNUSED_PARAMETER(id);
40619#endif
40620
40621  assert( pFile );
40622  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
40623  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
40624      || (flags&0x0F)==SQLITE_SYNC_FULL
40625  );
40626
40627  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
40628  ** line is to test that doing so does not cause any problems.
40629  */
40630  SimulateDiskfullError( return SQLITE_FULL );
40631
40632  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
40633           osGetCurrentProcessId(), pFile, pFile->h, flags,
40634           pFile->locktype));
40635
40636#ifndef SQLITE_TEST
40637  UNUSED_PARAMETER(flags);
40638#else
40639  if( (flags&0x0F)==SQLITE_SYNC_FULL ){
40640    sqlite3_fullsync_count++;
40641  }
40642  sqlite3_sync_count++;
40643#endif
40644
40645  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
40646  ** no-op
40647  */
40648#ifdef SQLITE_NO_SYNC
40649  OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40650           osGetCurrentProcessId(), pFile, pFile->h));
40651  return SQLITE_OK;
40652#else
40653#if SQLITE_MAX_MMAP_SIZE>0
40654  if( pFile->pMapRegion ){
40655    if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
40656      OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
40657               "rc=SQLITE_OK\n", osGetCurrentProcessId(),
40658               pFile, pFile->pMapRegion));
40659    }else{
40660      pFile->lastErrno = osGetLastError();
40661      OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
40662               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
40663               pFile, pFile->pMapRegion));
40664      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
40665                         "winSync1", pFile->zPath);
40666    }
40667  }
40668#endif
40669  rc = osFlushFileBuffers(pFile->h);
40670  SimulateIOError( rc=FALSE );
40671  if( rc ){
40672    OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40673             osGetCurrentProcessId(), pFile, pFile->h));
40674    return SQLITE_OK;
40675  }else{
40676    pFile->lastErrno = osGetLastError();
40677    OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
40678             osGetCurrentProcessId(), pFile, pFile->h));
40679    return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
40680                       "winSync2", pFile->zPath);
40681  }
40682#endif
40683}
40684
40685/*
40686** Determine the current size of a file in bytes
40687*/
40688static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
40689  winFile *pFile = (winFile*)id;
40690  int rc = SQLITE_OK;
40691
40692  assert( id!=0 );
40693  assert( pSize!=0 );
40694  SimulateIOError(return SQLITE_IOERR_FSTAT);
40695  OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
40696
40697#if SQLITE_OS_WINRT
40698  {
40699    FILE_STANDARD_INFO info;
40700    if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
40701                                     &info, sizeof(info)) ){
40702      *pSize = info.EndOfFile.QuadPart;
40703    }else{
40704      pFile->lastErrno = osGetLastError();
40705      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
40706                       "winFileSize", pFile->zPath);
40707    }
40708  }
40709#else
40710  {
40711    DWORD upperBits;
40712    DWORD lowerBits;
40713    DWORD lastErrno;
40714
40715    lowerBits = osGetFileSize(pFile->h, &upperBits);
40716    *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
40717    if(   (lowerBits == INVALID_FILE_SIZE)
40718       && ((lastErrno = osGetLastError())!=NO_ERROR) ){
40719      pFile->lastErrno = lastErrno;
40720      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
40721                       "winFileSize", pFile->zPath);
40722    }
40723  }
40724#endif
40725  OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
40726           pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
40727  return rc;
40728}
40729
40730/*
40731** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
40732*/
40733#ifndef LOCKFILE_FAIL_IMMEDIATELY
40734# define LOCKFILE_FAIL_IMMEDIATELY 1
40735#endif
40736
40737#ifndef LOCKFILE_EXCLUSIVE_LOCK
40738# define LOCKFILE_EXCLUSIVE_LOCK 2
40739#endif
40740
40741/*
40742** Historically, SQLite has used both the LockFile and LockFileEx functions.
40743** When the LockFile function was used, it was always expected to fail
40744** immediately if the lock could not be obtained.  Also, it always expected to
40745** obtain an exclusive lock.  These flags are used with the LockFileEx function
40746** and reflect those expectations; therefore, they should not be changed.
40747*/
40748#ifndef SQLITE_LOCKFILE_FLAGS
40749# define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
40750                                  LOCKFILE_EXCLUSIVE_LOCK)
40751#endif
40752
40753/*
40754** Currently, SQLite never calls the LockFileEx function without wanting the
40755** call to fail immediately if the lock cannot be obtained.
40756*/
40757#ifndef SQLITE_LOCKFILEEX_FLAGS
40758# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
40759#endif
40760
40761/*
40762** Acquire a reader lock.
40763** Different API routines are called depending on whether or not this
40764** is Win9x or WinNT.
40765*/
40766static int winGetReadLock(winFile *pFile){
40767  int res;
40768  OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
40769  if( osIsNT() ){
40770#if SQLITE_OS_WINCE
40771    /*
40772    ** NOTE: Windows CE is handled differently here due its lack of the Win32
40773    **       API LockFileEx.
40774    */
40775    res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
40776#else
40777    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
40778                      SHARED_SIZE, 0);
40779#endif
40780  }
40781#ifdef SQLITE_WIN32_HAS_ANSI
40782  else{
40783    int lk;
40784    sqlite3_randomness(sizeof(lk), &lk);
40785    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
40786    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
40787                      SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
40788  }
40789#endif
40790  if( res == 0 ){
40791    pFile->lastErrno = osGetLastError();
40792    /* No need to log a failure to lock */
40793  }
40794  OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
40795  return res;
40796}
40797
40798/*
40799** Undo a readlock
40800*/
40801static int winUnlockReadLock(winFile *pFile){
40802  int res;
40803  DWORD lastErrno;
40804  OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
40805  if( osIsNT() ){
40806    res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
40807  }
40808#ifdef SQLITE_WIN32_HAS_ANSI
40809  else{
40810    res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
40811  }
40812#endif
40813  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
40814    pFile->lastErrno = lastErrno;
40815    winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
40816                "winUnlockReadLock", pFile->zPath);
40817  }
40818  OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
40819  return res;
40820}
40821
40822/*
40823** Lock the file with the lock specified by parameter locktype - one
40824** of the following:
40825**
40826**     (1) SHARED_LOCK
40827**     (2) RESERVED_LOCK
40828**     (3) PENDING_LOCK
40829**     (4) EXCLUSIVE_LOCK
40830**
40831** Sometimes when requesting one lock state, additional lock states
40832** are inserted in between.  The locking might fail on one of the later
40833** transitions leaving the lock state different from what it started but
40834** still short of its goal.  The following chart shows the allowed
40835** transitions and the inserted intermediate states:
40836**
40837**    UNLOCKED -> SHARED
40838**    SHARED -> RESERVED
40839**    SHARED -> (PENDING) -> EXCLUSIVE
40840**    RESERVED -> (PENDING) -> EXCLUSIVE
40841**    PENDING -> EXCLUSIVE
40842**
40843** This routine will only increase a lock.  The winUnlock() routine
40844** erases all locks at once and returns us immediately to locking level 0.
40845** It is not possible to lower the locking level one step at a time.  You
40846** must go straight to locking level 0.
40847*/
40848static int winLock(sqlite3_file *id, int locktype){
40849  int rc = SQLITE_OK;    /* Return code from subroutines */
40850  int res = 1;           /* Result of a Windows lock call */
40851  int newLocktype;       /* Set pFile->locktype to this value before exiting */
40852  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
40853  winFile *pFile = (winFile*)id;
40854  DWORD lastErrno = NO_ERROR;
40855
40856  assert( id!=0 );
40857  OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
40858           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
40859
40860  /* If there is already a lock of this type or more restrictive on the
40861  ** OsFile, do nothing. Don't use the end_lock: exit path, as
40862  ** sqlite3OsEnterMutex() hasn't been called yet.
40863  */
40864  if( pFile->locktype>=locktype ){
40865    OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
40866    return SQLITE_OK;
40867  }
40868
40869  /* Do not allow any kind of write-lock on a read-only database
40870  */
40871  if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
40872    return SQLITE_IOERR_LOCK;
40873  }
40874
40875  /* Make sure the locking sequence is correct
40876  */
40877  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
40878  assert( locktype!=PENDING_LOCK );
40879  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
40880
40881  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
40882  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
40883  ** the PENDING_LOCK byte is temporary.
40884  */
40885  newLocktype = pFile->locktype;
40886  if( pFile->locktype==NO_LOCK
40887   || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
40888  ){
40889    int cnt = 3;
40890    while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
40891                                         PENDING_BYTE, 0, 1, 0))==0 ){
40892      /* Try 3 times to get the pending lock.  This is needed to work
40893      ** around problems caused by indexing and/or anti-virus software on
40894      ** Windows systems.
40895      ** If you are using this code as a model for alternative VFSes, do not
40896      ** copy this retry logic.  It is a hack intended for Windows only.
40897      */
40898      lastErrno = osGetLastError();
40899      OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
40900               pFile->h, cnt, res));
40901      if( lastErrno==ERROR_INVALID_HANDLE ){
40902        pFile->lastErrno = lastErrno;
40903        rc = SQLITE_IOERR_LOCK;
40904        OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
40905                 pFile->h, cnt, sqlite3ErrName(rc)));
40906        return rc;
40907      }
40908      if( cnt ) sqlite3_win32_sleep(1);
40909    }
40910    gotPendingLock = res;
40911    if( !res ){
40912      lastErrno = osGetLastError();
40913    }
40914  }
40915
40916  /* Acquire a shared lock
40917  */
40918  if( locktype==SHARED_LOCK && res ){
40919    assert( pFile->locktype==NO_LOCK );
40920    res = winGetReadLock(pFile);
40921    if( res ){
40922      newLocktype = SHARED_LOCK;
40923    }else{
40924      lastErrno = osGetLastError();
40925    }
40926  }
40927
40928  /* Acquire a RESERVED lock
40929  */
40930  if( locktype==RESERVED_LOCK && res ){
40931    assert( pFile->locktype==SHARED_LOCK );
40932    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
40933    if( res ){
40934      newLocktype = RESERVED_LOCK;
40935    }else{
40936      lastErrno = osGetLastError();
40937    }
40938  }
40939
40940  /* Acquire a PENDING lock
40941  */
40942  if( locktype==EXCLUSIVE_LOCK && res ){
40943    newLocktype = PENDING_LOCK;
40944    gotPendingLock = 0;
40945  }
40946
40947  /* Acquire an EXCLUSIVE lock
40948  */
40949  if( locktype==EXCLUSIVE_LOCK && res ){
40950    assert( pFile->locktype>=SHARED_LOCK );
40951    res = winUnlockReadLock(pFile);
40952    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
40953                      SHARED_SIZE, 0);
40954    if( res ){
40955      newLocktype = EXCLUSIVE_LOCK;
40956    }else{
40957      lastErrno = osGetLastError();
40958      winGetReadLock(pFile);
40959    }
40960  }
40961
40962  /* If we are holding a PENDING lock that ought to be released, then
40963  ** release it now.
40964  */
40965  if( gotPendingLock && locktype==SHARED_LOCK ){
40966    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
40967  }
40968
40969  /* Update the state of the lock has held in the file descriptor then
40970  ** return the appropriate result code.
40971  */
40972  if( res ){
40973    rc = SQLITE_OK;
40974  }else{
40975    pFile->lastErrno = lastErrno;
40976    rc = SQLITE_BUSY;
40977    OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
40978             pFile->h, locktype, newLocktype));
40979  }
40980  pFile->locktype = (u8)newLocktype;
40981  OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
40982           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
40983  return rc;
40984}
40985
40986/*
40987** This routine checks if there is a RESERVED lock held on the specified
40988** file by this or any other process. If such a lock is held, return
40989** non-zero, otherwise zero.
40990*/
40991static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
40992  int res;
40993  winFile *pFile = (winFile*)id;
40994
40995  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
40996  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
40997
40998  assert( id!=0 );
40999  if( pFile->locktype>=RESERVED_LOCK ){
41000    res = 1;
41001    OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
41002  }else{
41003    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
41004    if( res ){
41005      winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
41006    }
41007    res = !res;
41008    OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
41009  }
41010  *pResOut = res;
41011  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
41012           pFile->h, pResOut, *pResOut));
41013  return SQLITE_OK;
41014}
41015
41016/*
41017** Lower the locking level on file descriptor id to locktype.  locktype
41018** must be either NO_LOCK or SHARED_LOCK.
41019**
41020** If the locking level of the file descriptor is already at or below
41021** the requested locking level, this routine is a no-op.
41022**
41023** It is not possible for this routine to fail if the second argument
41024** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
41025** might return SQLITE_IOERR;
41026*/
41027static int winUnlock(sqlite3_file *id, int locktype){
41028  int type;
41029  winFile *pFile = (winFile*)id;
41030  int rc = SQLITE_OK;
41031  assert( pFile!=0 );
41032  assert( locktype<=SHARED_LOCK );
41033  OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
41034           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
41035  type = pFile->locktype;
41036  if( type>=EXCLUSIVE_LOCK ){
41037    winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
41038    if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
41039      /* This should never happen.  We should always be able to
41040      ** reacquire the read lock */
41041      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
41042                       "winUnlock", pFile->zPath);
41043    }
41044  }
41045  if( type>=RESERVED_LOCK ){
41046    winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
41047  }
41048  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
41049    winUnlockReadLock(pFile);
41050  }
41051  if( type>=PENDING_LOCK ){
41052    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
41053  }
41054  pFile->locktype = (u8)locktype;
41055  OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
41056           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
41057  return rc;
41058}
41059
41060/******************************************************************************
41061****************************** No-op Locking **********************************
41062**
41063** Of the various locking implementations available, this is by far the
41064** simplest:  locking is ignored.  No attempt is made to lock the database
41065** file for reading or writing.
41066**
41067** This locking mode is appropriate for use on read-only databases
41068** (ex: databases that are burned into CD-ROM, for example.)  It can
41069** also be used if the application employs some external mechanism to
41070** prevent simultaneous access of the same database by two or more
41071** database connections.  But there is a serious risk of database
41072** corruption if this locking mode is used in situations where multiple
41073** database connections are accessing the same database file at the same
41074** time and one or more of those connections are writing.
41075*/
41076
41077static int winNolockLock(sqlite3_file *id, int locktype){
41078  UNUSED_PARAMETER(id);
41079  UNUSED_PARAMETER(locktype);
41080  return SQLITE_OK;
41081}
41082
41083static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
41084  UNUSED_PARAMETER(id);
41085  UNUSED_PARAMETER(pResOut);
41086  return SQLITE_OK;
41087}
41088
41089static int winNolockUnlock(sqlite3_file *id, int locktype){
41090  UNUSED_PARAMETER(id);
41091  UNUSED_PARAMETER(locktype);
41092  return SQLITE_OK;
41093}
41094
41095/******************* End of the no-op lock implementation *********************
41096******************************************************************************/
41097
41098/*
41099** If *pArg is initially negative then this is a query.  Set *pArg to
41100** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
41101**
41102** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
41103*/
41104static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
41105  if( *pArg<0 ){
41106    *pArg = (pFile->ctrlFlags & mask)!=0;
41107  }else if( (*pArg)==0 ){
41108    pFile->ctrlFlags &= ~mask;
41109  }else{
41110    pFile->ctrlFlags |= mask;
41111  }
41112}
41113
41114/* Forward references to VFS helper methods used for temporary files */
41115static int winGetTempname(sqlite3_vfs *, char **);
41116static int winIsDir(const void *);
41117static BOOL winIsDriveLetterAndColon(const char *);
41118
41119/*
41120** Control and query of the open file handle.
41121*/
41122static int winFileControl(sqlite3_file *id, int op, void *pArg){
41123  winFile *pFile = (winFile*)id;
41124  OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
41125  switch( op ){
41126    case SQLITE_FCNTL_LOCKSTATE: {
41127      *(int*)pArg = pFile->locktype;
41128      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41129      return SQLITE_OK;
41130    }
41131    case SQLITE_FCNTL_LAST_ERRNO: {
41132      *(int*)pArg = (int)pFile->lastErrno;
41133      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41134      return SQLITE_OK;
41135    }
41136    case SQLITE_FCNTL_CHUNK_SIZE: {
41137      pFile->szChunk = *(int *)pArg;
41138      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41139      return SQLITE_OK;
41140    }
41141    case SQLITE_FCNTL_SIZE_HINT: {
41142      if( pFile->szChunk>0 ){
41143        sqlite3_int64 oldSz;
41144        int rc = winFileSize(id, &oldSz);
41145        if( rc==SQLITE_OK ){
41146          sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
41147          if( newSz>oldSz ){
41148            SimulateIOErrorBenign(1);
41149            rc = winTruncate(id, newSz);
41150            SimulateIOErrorBenign(0);
41151          }
41152        }
41153        OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
41154        return rc;
41155      }
41156      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41157      return SQLITE_OK;
41158    }
41159    case SQLITE_FCNTL_PERSIST_WAL: {
41160      winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
41161      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41162      return SQLITE_OK;
41163    }
41164    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
41165      winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
41166      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41167      return SQLITE_OK;
41168    }
41169    case SQLITE_FCNTL_VFSNAME: {
41170      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
41171      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41172      return SQLITE_OK;
41173    }
41174    case SQLITE_FCNTL_WIN32_AV_RETRY: {
41175      int *a = (int*)pArg;
41176      if( a[0]>0 ){
41177        winIoerrRetry = a[0];
41178      }else{
41179        a[0] = winIoerrRetry;
41180      }
41181      if( a[1]>0 ){
41182        winIoerrRetryDelay = a[1];
41183      }else{
41184        a[1] = winIoerrRetryDelay;
41185      }
41186      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41187      return SQLITE_OK;
41188    }
41189    case SQLITE_FCNTL_WIN32_GET_HANDLE: {
41190      LPHANDLE phFile = (LPHANDLE)pArg;
41191      *phFile = pFile->h;
41192      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41193      return SQLITE_OK;
41194    }
41195#ifdef SQLITE_TEST
41196    case SQLITE_FCNTL_WIN32_SET_HANDLE: {
41197      LPHANDLE phFile = (LPHANDLE)pArg;
41198      HANDLE hOldFile = pFile->h;
41199      pFile->h = *phFile;
41200      *phFile = hOldFile;
41201      OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
41202               hOldFile, pFile->h));
41203      return SQLITE_OK;
41204    }
41205#endif
41206    case SQLITE_FCNTL_TEMPFILENAME: {
41207      char *zTFile = 0;
41208      int rc = winGetTempname(pFile->pVfs, &zTFile);
41209      if( rc==SQLITE_OK ){
41210        *(char**)pArg = zTFile;
41211      }
41212      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
41213      return rc;
41214    }
41215#if SQLITE_MAX_MMAP_SIZE>0
41216    case SQLITE_FCNTL_MMAP_SIZE: {
41217      i64 newLimit = *(i64*)pArg;
41218      int rc = SQLITE_OK;
41219      if( newLimit>sqlite3GlobalConfig.mxMmap ){
41220        newLimit = sqlite3GlobalConfig.mxMmap;
41221      }
41222      *(i64*)pArg = pFile->mmapSizeMax;
41223      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
41224        pFile->mmapSizeMax = newLimit;
41225        if( pFile->mmapSize>0 ){
41226          winUnmapfile(pFile);
41227          rc = winMapfile(pFile, -1);
41228        }
41229      }
41230      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
41231      return rc;
41232    }
41233#endif
41234  }
41235  OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
41236  return SQLITE_NOTFOUND;
41237}
41238
41239/*
41240** Return the sector size in bytes of the underlying block device for
41241** the specified file. This is almost always 512 bytes, but may be
41242** larger for some devices.
41243**
41244** SQLite code assumes this function cannot fail. It also assumes that
41245** if two files are created in the same file-system directory (i.e.
41246** a database and its journal file) that the sector size will be the
41247** same for both.
41248*/
41249static int winSectorSize(sqlite3_file *id){
41250  (void)id;
41251  return SQLITE_DEFAULT_SECTOR_SIZE;
41252}
41253
41254/*
41255** Return a vector of device characteristics.
41256*/
41257static int winDeviceCharacteristics(sqlite3_file *id){
41258  winFile *p = (winFile*)id;
41259  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
41260         ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
41261}
41262
41263/*
41264** Windows will only let you create file view mappings
41265** on allocation size granularity boundaries.
41266** During sqlite3_os_init() we do a GetSystemInfo()
41267** to get the granularity size.
41268*/
41269static SYSTEM_INFO winSysInfo;
41270
41271#ifndef SQLITE_OMIT_WAL
41272
41273/*
41274** Helper functions to obtain and relinquish the global mutex. The
41275** global mutex is used to protect the winLockInfo objects used by
41276** this file, all of which may be shared by multiple threads.
41277**
41278** Function winShmMutexHeld() is used to assert() that the global mutex
41279** is held when required. This function is only used as part of assert()
41280** statements. e.g.
41281**
41282**   winShmEnterMutex()
41283**     assert( winShmMutexHeld() );
41284**   winShmLeaveMutex()
41285*/
41286static void winShmEnterMutex(void){
41287  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
41288}
41289static void winShmLeaveMutex(void){
41290  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
41291}
41292#ifndef NDEBUG
41293static int winShmMutexHeld(void) {
41294  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
41295}
41296#endif
41297
41298/*
41299** Object used to represent a single file opened and mmapped to provide
41300** shared memory.  When multiple threads all reference the same
41301** log-summary, each thread has its own winFile object, but they all
41302** point to a single instance of this object.  In other words, each
41303** log-summary is opened only once per process.
41304**
41305** winShmMutexHeld() must be true when creating or destroying
41306** this object or while reading or writing the following fields:
41307**
41308**      nRef
41309**      pNext
41310**
41311** The following fields are read-only after the object is created:
41312**
41313**      fid
41314**      zFilename
41315**
41316** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
41317** winShmMutexHeld() is true when reading or writing any other field
41318** in this structure.
41319**
41320*/
41321struct winShmNode {
41322  sqlite3_mutex *mutex;      /* Mutex to access this object */
41323  char *zFilename;           /* Name of the file */
41324  winFile hFile;             /* File handle from winOpen */
41325
41326  int szRegion;              /* Size of shared-memory regions */
41327  int nRegion;               /* Size of array apRegion */
41328  struct ShmRegion {
41329    HANDLE hMap;             /* File handle from CreateFileMapping */
41330    void *pMap;
41331  } *aRegion;
41332  DWORD lastErrno;           /* The Windows errno from the last I/O error */
41333
41334  int nRef;                  /* Number of winShm objects pointing to this */
41335  winShm *pFirst;            /* All winShm objects pointing to this */
41336  winShmNode *pNext;         /* Next in list of all winShmNode objects */
41337#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
41338  u8 nextShmId;              /* Next available winShm.id value */
41339#endif
41340};
41341
41342/*
41343** A global array of all winShmNode objects.
41344**
41345** The winShmMutexHeld() must be true while reading or writing this list.
41346*/
41347static winShmNode *winShmNodeList = 0;
41348
41349/*
41350** Structure used internally by this VFS to record the state of an
41351** open shared memory connection.
41352**
41353** The following fields are initialized when this object is created and
41354** are read-only thereafter:
41355**
41356**    winShm.pShmNode
41357**    winShm.id
41358**
41359** All other fields are read/write.  The winShm.pShmNode->mutex must be held
41360** while accessing any read/write fields.
41361*/
41362struct winShm {
41363  winShmNode *pShmNode;      /* The underlying winShmNode object */
41364  winShm *pNext;             /* Next winShm with the same winShmNode */
41365  u8 hasMutex;               /* True if holding the winShmNode mutex */
41366  u16 sharedMask;            /* Mask of shared locks held */
41367  u16 exclMask;              /* Mask of exclusive locks held */
41368#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
41369  u8 id;                     /* Id of this connection with its winShmNode */
41370#endif
41371};
41372
41373/*
41374** Constants used for locking
41375*/
41376#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
41377#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
41378
41379/*
41380** Apply advisory locks for all n bytes beginning at ofst.
41381*/
41382#define WINSHM_UNLCK  1
41383#define WINSHM_RDLCK  2
41384#define WINSHM_WRLCK  3
41385static int winShmSystemLock(
41386  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
41387  int lockType,         /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
41388  int ofst,             /* Offset to first byte to be locked/unlocked */
41389  int nByte             /* Number of bytes to lock or unlock */
41390){
41391  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
41392
41393  /* Access to the winShmNode object is serialized by the caller */
41394  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
41395
41396  OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
41397           pFile->hFile.h, lockType, ofst, nByte));
41398
41399  /* Release/Acquire the system-level lock */
41400  if( lockType==WINSHM_UNLCK ){
41401    rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
41402  }else{
41403    /* Initialize the locking parameters */
41404    DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
41405    if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
41406    rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
41407  }
41408
41409  if( rc!= 0 ){
41410    rc = SQLITE_OK;
41411  }else{
41412    pFile->lastErrno =  osGetLastError();
41413    rc = SQLITE_BUSY;
41414  }
41415
41416  OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
41417           pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
41418           "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
41419
41420  return rc;
41421}
41422
41423/* Forward references to VFS methods */
41424static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
41425static int winDelete(sqlite3_vfs *,const char*,int);
41426
41427/*
41428** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
41429**
41430** This is not a VFS shared-memory method; it is a utility function called
41431** by VFS shared-memory methods.
41432*/
41433static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
41434  winShmNode **pp;
41435  winShmNode *p;
41436  assert( winShmMutexHeld() );
41437  OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
41438           osGetCurrentProcessId(), deleteFlag));
41439  pp = &winShmNodeList;
41440  while( (p = *pp)!=0 ){
41441    if( p->nRef==0 ){
41442      int i;
41443      if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
41444      for(i=0; i<p->nRegion; i++){
41445        BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
41446        OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
41447                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
41448        UNUSED_VARIABLE_VALUE(bRc);
41449        bRc = osCloseHandle(p->aRegion[i].hMap);
41450        OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
41451                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
41452        UNUSED_VARIABLE_VALUE(bRc);
41453      }
41454      if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
41455        SimulateIOErrorBenign(1);
41456        winClose((sqlite3_file *)&p->hFile);
41457        SimulateIOErrorBenign(0);
41458      }
41459      if( deleteFlag ){
41460        SimulateIOErrorBenign(1);
41461        sqlite3BeginBenignMalloc();
41462        winDelete(pVfs, p->zFilename, 0);
41463        sqlite3EndBenignMalloc();
41464        SimulateIOErrorBenign(0);
41465      }
41466      *pp = p->pNext;
41467      sqlite3_free(p->aRegion);
41468      sqlite3_free(p);
41469    }else{
41470      pp = &p->pNext;
41471    }
41472  }
41473}
41474
41475/*
41476** Open the shared-memory area associated with database file pDbFd.
41477**
41478** When opening a new shared-memory file, if no other instances of that
41479** file are currently open, in this process or in other processes, then
41480** the file must be truncated to zero length or have its header cleared.
41481*/
41482static int winOpenSharedMemory(winFile *pDbFd){
41483  struct winShm *p;                  /* The connection to be opened */
41484  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
41485  int rc;                            /* Result code */
41486  struct winShmNode *pNew;           /* Newly allocated winShmNode */
41487  int nName;                         /* Size of zName in bytes */
41488
41489  assert( pDbFd->pShm==0 );    /* Not previously opened */
41490
41491  /* Allocate space for the new sqlite3_shm object.  Also speculatively
41492  ** allocate space for a new winShmNode and filename.
41493  */
41494  p = sqlite3MallocZero( sizeof(*p) );
41495  if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
41496  nName = sqlite3Strlen30(pDbFd->zPath);
41497  pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
41498  if( pNew==0 ){
41499    sqlite3_free(p);
41500    return SQLITE_IOERR_NOMEM_BKPT;
41501  }
41502  pNew->zFilename = (char*)&pNew[1];
41503  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
41504  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
41505
41506  /* Look to see if there is an existing winShmNode that can be used.
41507  ** If no matching winShmNode currently exists, create a new one.
41508  */
41509  winShmEnterMutex();
41510  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
41511    /* TBD need to come up with better match here.  Perhaps
41512    ** use FILE_ID_BOTH_DIR_INFO Structure.
41513    */
41514    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
41515  }
41516  if( pShmNode ){
41517    sqlite3_free(pNew);
41518  }else{
41519    pShmNode = pNew;
41520    pNew = 0;
41521    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
41522    pShmNode->pNext = winShmNodeList;
41523    winShmNodeList = pShmNode;
41524
41525    if( sqlite3GlobalConfig.bCoreMutex ){
41526      pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
41527      if( pShmNode->mutex==0 ){
41528        rc = SQLITE_IOERR_NOMEM_BKPT;
41529        goto shm_open_err;
41530      }
41531    }
41532
41533    rc = winOpen(pDbFd->pVfs,
41534                 pShmNode->zFilename,             /* Name of the file (UTF-8) */
41535                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
41536                 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
41537                 0);
41538    if( SQLITE_OK!=rc ){
41539      goto shm_open_err;
41540    }
41541
41542    /* Check to see if another process is holding the dead-man switch.
41543    ** If not, truncate the file to zero length.
41544    */
41545    if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
41546      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
41547      if( rc!=SQLITE_OK ){
41548        rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
41549                         "winOpenShm", pDbFd->zPath);
41550      }
41551    }
41552    if( rc==SQLITE_OK ){
41553      winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
41554      rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
41555    }
41556    if( rc ) goto shm_open_err;
41557  }
41558
41559  /* Make the new connection a child of the winShmNode */
41560  p->pShmNode = pShmNode;
41561#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
41562  p->id = pShmNode->nextShmId++;
41563#endif
41564  pShmNode->nRef++;
41565  pDbFd->pShm = p;
41566  winShmLeaveMutex();
41567
41568  /* The reference count on pShmNode has already been incremented under
41569  ** the cover of the winShmEnterMutex() mutex and the pointer from the
41570  ** new (struct winShm) object to the pShmNode has been set. All that is
41571  ** left to do is to link the new object into the linked list starting
41572  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
41573  ** mutex.
41574  */
41575  sqlite3_mutex_enter(pShmNode->mutex);
41576  p->pNext = pShmNode->pFirst;
41577  pShmNode->pFirst = p;
41578  sqlite3_mutex_leave(pShmNode->mutex);
41579  return SQLITE_OK;
41580
41581  /* Jump here on any error */
41582shm_open_err:
41583  winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
41584  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
41585  sqlite3_free(p);
41586  sqlite3_free(pNew);
41587  winShmLeaveMutex();
41588  return rc;
41589}
41590
41591/*
41592** Close a connection to shared-memory.  Delete the underlying
41593** storage if deleteFlag is true.
41594*/
41595static int winShmUnmap(
41596  sqlite3_file *fd,          /* Database holding shared memory */
41597  int deleteFlag             /* Delete after closing if true */
41598){
41599  winFile *pDbFd;       /* Database holding shared-memory */
41600  winShm *p;            /* The connection to be closed */
41601  winShmNode *pShmNode; /* The underlying shared-memory file */
41602  winShm **pp;          /* For looping over sibling connections */
41603
41604  pDbFd = (winFile*)fd;
41605  p = pDbFd->pShm;
41606  if( p==0 ) return SQLITE_OK;
41607  pShmNode = p->pShmNode;
41608
41609  /* Remove connection p from the set of connections associated
41610  ** with pShmNode */
41611  sqlite3_mutex_enter(pShmNode->mutex);
41612  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
41613  *pp = p->pNext;
41614
41615  /* Free the connection p */
41616  sqlite3_free(p);
41617  pDbFd->pShm = 0;
41618  sqlite3_mutex_leave(pShmNode->mutex);
41619
41620  /* If pShmNode->nRef has reached 0, then close the underlying
41621  ** shared-memory file, too */
41622  winShmEnterMutex();
41623  assert( pShmNode->nRef>0 );
41624  pShmNode->nRef--;
41625  if( pShmNode->nRef==0 ){
41626    winShmPurge(pDbFd->pVfs, deleteFlag);
41627  }
41628  winShmLeaveMutex();
41629
41630  return SQLITE_OK;
41631}
41632
41633/*
41634** Change the lock state for a shared-memory segment.
41635*/
41636static int winShmLock(
41637  sqlite3_file *fd,          /* Database file holding the shared memory */
41638  int ofst,                  /* First lock to acquire or release */
41639  int n,                     /* Number of locks to acquire or release */
41640  int flags                  /* What to do with the lock */
41641){
41642  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
41643  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
41644  winShm *pX;                           /* For looping over all siblings */
41645  winShmNode *pShmNode = p->pShmNode;
41646  int rc = SQLITE_OK;                   /* Result code */
41647  u16 mask;                             /* Mask of locks to take or release */
41648
41649  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
41650  assert( n>=1 );
41651  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
41652       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
41653       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
41654       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
41655  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
41656
41657  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
41658  assert( n>1 || mask==(1<<ofst) );
41659  sqlite3_mutex_enter(pShmNode->mutex);
41660  if( flags & SQLITE_SHM_UNLOCK ){
41661    u16 allMask = 0; /* Mask of locks held by siblings */
41662
41663    /* See if any siblings hold this same lock */
41664    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41665      if( pX==p ) continue;
41666      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
41667      allMask |= pX->sharedMask;
41668    }
41669
41670    /* Unlock the system-level locks */
41671    if( (mask & allMask)==0 ){
41672      rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
41673    }else{
41674      rc = SQLITE_OK;
41675    }
41676
41677    /* Undo the local locks */
41678    if( rc==SQLITE_OK ){
41679      p->exclMask &= ~mask;
41680      p->sharedMask &= ~mask;
41681    }
41682  }else if( flags & SQLITE_SHM_SHARED ){
41683    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
41684
41685    /* Find out which shared locks are already held by sibling connections.
41686    ** If any sibling already holds an exclusive lock, go ahead and return
41687    ** SQLITE_BUSY.
41688    */
41689    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41690      if( (pX->exclMask & mask)!=0 ){
41691        rc = SQLITE_BUSY;
41692        break;
41693      }
41694      allShared |= pX->sharedMask;
41695    }
41696
41697    /* Get shared locks at the system level, if necessary */
41698    if( rc==SQLITE_OK ){
41699      if( (allShared & mask)==0 ){
41700        rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
41701      }else{
41702        rc = SQLITE_OK;
41703      }
41704    }
41705
41706    /* Get the local shared locks */
41707    if( rc==SQLITE_OK ){
41708      p->sharedMask |= mask;
41709    }
41710  }else{
41711    /* Make sure no sibling connections hold locks that will block this
41712    ** lock.  If any do, return SQLITE_BUSY right away.
41713    */
41714    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41715      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
41716        rc = SQLITE_BUSY;
41717        break;
41718      }
41719    }
41720
41721    /* Get the exclusive locks at the system level.  Then if successful
41722    ** also mark the local connection as being locked.
41723    */
41724    if( rc==SQLITE_OK ){
41725      rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
41726      if( rc==SQLITE_OK ){
41727        assert( (p->sharedMask & mask)==0 );
41728        p->exclMask |= mask;
41729      }
41730    }
41731  }
41732  sqlite3_mutex_leave(pShmNode->mutex);
41733  OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
41734           osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
41735           sqlite3ErrName(rc)));
41736  return rc;
41737}
41738
41739/*
41740** Implement a memory barrier or memory fence on shared memory.
41741**
41742** All loads and stores begun before the barrier must complete before
41743** any load or store begun after the barrier.
41744*/
41745static void winShmBarrier(
41746  sqlite3_file *fd          /* Database holding the shared memory */
41747){
41748  UNUSED_PARAMETER(fd);
41749  sqlite3MemoryBarrier();   /* compiler-defined memory barrier */
41750  winShmEnterMutex();       /* Also mutex, for redundancy */
41751  winShmLeaveMutex();
41752}
41753
41754/*
41755** This function is called to obtain a pointer to region iRegion of the
41756** shared-memory associated with the database file fd. Shared-memory regions
41757** are numbered starting from zero. Each shared-memory region is szRegion
41758** bytes in size.
41759**
41760** If an error occurs, an error code is returned and *pp is set to NULL.
41761**
41762** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
41763** region has not been allocated (by any client, including one running in a
41764** separate process), then *pp is set to NULL and SQLITE_OK returned. If
41765** isWrite is non-zero and the requested shared-memory region has not yet
41766** been allocated, it is allocated by this function.
41767**
41768** If the shared-memory region has already been allocated or is allocated by
41769** this call as described above, then it is mapped into this processes
41770** address space (if it is not already), *pp is set to point to the mapped
41771** memory and SQLITE_OK returned.
41772*/
41773static int winShmMap(
41774  sqlite3_file *fd,               /* Handle open on database file */
41775  int iRegion,                    /* Region to retrieve */
41776  int szRegion,                   /* Size of regions */
41777  int isWrite,                    /* True to extend file if necessary */
41778  void volatile **pp              /* OUT: Mapped memory */
41779){
41780  winFile *pDbFd = (winFile*)fd;
41781  winShm *pShm = pDbFd->pShm;
41782  winShmNode *pShmNode;
41783  int rc = SQLITE_OK;
41784
41785  if( !pShm ){
41786    rc = winOpenSharedMemory(pDbFd);
41787    if( rc!=SQLITE_OK ) return rc;
41788    pShm = pDbFd->pShm;
41789  }
41790  pShmNode = pShm->pShmNode;
41791
41792  sqlite3_mutex_enter(pShmNode->mutex);
41793  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
41794
41795  if( pShmNode->nRegion<=iRegion ){
41796    struct ShmRegion *apNew;           /* New aRegion[] array */
41797    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
41798    sqlite3_int64 sz;                  /* Current size of wal-index file */
41799
41800    pShmNode->szRegion = szRegion;
41801
41802    /* The requested region is not mapped into this processes address space.
41803    ** Check to see if it has been allocated (i.e. if the wal-index file is
41804    ** large enough to contain the requested region).
41805    */
41806    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
41807    if( rc!=SQLITE_OK ){
41808      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
41809                       "winShmMap1", pDbFd->zPath);
41810      goto shmpage_out;
41811    }
41812
41813    if( sz<nByte ){
41814      /* The requested memory region does not exist. If isWrite is set to
41815      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
41816      **
41817      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
41818      ** the requested memory region.
41819      */
41820      if( !isWrite ) goto shmpage_out;
41821      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
41822      if( rc!=SQLITE_OK ){
41823        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
41824                         "winShmMap2", pDbFd->zPath);
41825        goto shmpage_out;
41826      }
41827    }
41828
41829    /* Map the requested memory region into this processes address space. */
41830    apNew = (struct ShmRegion *)sqlite3_realloc64(
41831        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
41832    );
41833    if( !apNew ){
41834      rc = SQLITE_IOERR_NOMEM_BKPT;
41835      goto shmpage_out;
41836    }
41837    pShmNode->aRegion = apNew;
41838
41839    while( pShmNode->nRegion<=iRegion ){
41840      HANDLE hMap = NULL;         /* file-mapping handle */
41841      void *pMap = 0;             /* Mapped memory region */
41842
41843#if SQLITE_OS_WINRT
41844      hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
41845          NULL, PAGE_READWRITE, nByte, NULL
41846      );
41847#elif defined(SQLITE_WIN32_HAS_WIDE)
41848      hMap = osCreateFileMappingW(pShmNode->hFile.h,
41849          NULL, PAGE_READWRITE, 0, nByte, NULL
41850      );
41851#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
41852      hMap = osCreateFileMappingA(pShmNode->hFile.h,
41853          NULL, PAGE_READWRITE, 0, nByte, NULL
41854      );
41855#endif
41856      OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
41857               osGetCurrentProcessId(), pShmNode->nRegion, nByte,
41858               hMap ? "ok" : "failed"));
41859      if( hMap ){
41860        int iOffset = pShmNode->nRegion*szRegion;
41861        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
41862#if SQLITE_OS_WINRT
41863        pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
41864            iOffset - iOffsetShift, szRegion + iOffsetShift
41865        );
41866#else
41867        pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
41868            0, iOffset - iOffsetShift, szRegion + iOffsetShift
41869        );
41870#endif
41871        OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
41872                 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
41873                 szRegion, pMap ? "ok" : "failed"));
41874      }
41875      if( !pMap ){
41876        pShmNode->lastErrno = osGetLastError();
41877        rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
41878                         "winShmMap3", pDbFd->zPath);
41879        if( hMap ) osCloseHandle(hMap);
41880        goto shmpage_out;
41881      }
41882
41883      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
41884      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
41885      pShmNode->nRegion++;
41886    }
41887  }
41888
41889shmpage_out:
41890  if( pShmNode->nRegion>iRegion ){
41891    int iOffset = iRegion*szRegion;
41892    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
41893    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
41894    *pp = (void *)&p[iOffsetShift];
41895  }else{
41896    *pp = 0;
41897  }
41898  sqlite3_mutex_leave(pShmNode->mutex);
41899  return rc;
41900}
41901
41902#else
41903# define winShmMap     0
41904# define winShmLock    0
41905# define winShmBarrier 0
41906# define winShmUnmap   0
41907#endif /* #ifndef SQLITE_OMIT_WAL */
41908
41909/*
41910** Cleans up the mapped region of the specified file, if any.
41911*/
41912#if SQLITE_MAX_MMAP_SIZE>0
41913static int winUnmapfile(winFile *pFile){
41914  assert( pFile!=0 );
41915  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
41916           "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
41917           osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
41918           pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
41919  if( pFile->pMapRegion ){
41920    if( !osUnmapViewOfFile(pFile->pMapRegion) ){
41921      pFile->lastErrno = osGetLastError();
41922      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
41923               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
41924               pFile->pMapRegion));
41925      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
41926                         "winUnmapfile1", pFile->zPath);
41927    }
41928    pFile->pMapRegion = 0;
41929    pFile->mmapSize = 0;
41930    pFile->mmapSizeActual = 0;
41931  }
41932  if( pFile->hMap!=NULL ){
41933    if( !osCloseHandle(pFile->hMap) ){
41934      pFile->lastErrno = osGetLastError();
41935      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
41936               osGetCurrentProcessId(), pFile, pFile->hMap));
41937      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
41938                         "winUnmapfile2", pFile->zPath);
41939    }
41940    pFile->hMap = NULL;
41941  }
41942  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41943           osGetCurrentProcessId(), pFile));
41944  return SQLITE_OK;
41945}
41946
41947/*
41948** Memory map or remap the file opened by file-descriptor pFd (if the file
41949** is already mapped, the existing mapping is replaced by the new). Or, if
41950** there already exists a mapping for this file, and there are still
41951** outstanding xFetch() references to it, this function is a no-op.
41952**
41953** If parameter nByte is non-negative, then it is the requested size of
41954** the mapping to create. Otherwise, if nByte is less than zero, then the
41955** requested size is the size of the file on disk. The actual size of the
41956** created mapping is either the requested size or the value configured
41957** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
41958**
41959** SQLITE_OK is returned if no error occurs (even if the mapping is not
41960** recreated as a result of outstanding references) or an SQLite error
41961** code otherwise.
41962*/
41963static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
41964  sqlite3_int64 nMap = nByte;
41965  int rc;
41966
41967  assert( nMap>=0 || pFd->nFetchOut==0 );
41968  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
41969           osGetCurrentProcessId(), pFd, nByte));
41970
41971  if( pFd->nFetchOut>0 ) return SQLITE_OK;
41972
41973  if( nMap<0 ){
41974    rc = winFileSize((sqlite3_file*)pFd, &nMap);
41975    if( rc ){
41976      OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
41977               osGetCurrentProcessId(), pFd));
41978      return SQLITE_IOERR_FSTAT;
41979    }
41980  }
41981  if( nMap>pFd->mmapSizeMax ){
41982    nMap = pFd->mmapSizeMax;
41983  }
41984  nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
41985
41986  if( nMap==0 && pFd->mmapSize>0 ){
41987    winUnmapfile(pFd);
41988  }
41989  if( nMap!=pFd->mmapSize ){
41990    void *pNew = 0;
41991    DWORD protect = PAGE_READONLY;
41992    DWORD flags = FILE_MAP_READ;
41993
41994    winUnmapfile(pFd);
41995#ifdef SQLITE_MMAP_READWRITE
41996    if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
41997      protect = PAGE_READWRITE;
41998      flags |= FILE_MAP_WRITE;
41999    }
42000#endif
42001#if SQLITE_OS_WINRT
42002    pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
42003#elif defined(SQLITE_WIN32_HAS_WIDE)
42004    pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
42005                                (DWORD)((nMap>>32) & 0xffffffff),
42006                                (DWORD)(nMap & 0xffffffff), NULL);
42007#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
42008    pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
42009                                (DWORD)((nMap>>32) & 0xffffffff),
42010                                (DWORD)(nMap & 0xffffffff), NULL);
42011#endif
42012    if( pFd->hMap==NULL ){
42013      pFd->lastErrno = osGetLastError();
42014      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
42015                       "winMapfile1", pFd->zPath);
42016      /* Log the error, but continue normal operation using xRead/xWrite */
42017      OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
42018               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
42019      return SQLITE_OK;
42020    }
42021    assert( (nMap % winSysInfo.dwPageSize)==0 );
42022    assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
42023#if SQLITE_OS_WINRT
42024    pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
42025#else
42026    pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
42027#endif
42028    if( pNew==NULL ){
42029      osCloseHandle(pFd->hMap);
42030      pFd->hMap = NULL;
42031      pFd->lastErrno = osGetLastError();
42032      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
42033                       "winMapfile2", pFd->zPath);
42034      /* Log the error, but continue normal operation using xRead/xWrite */
42035      OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
42036               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
42037      return SQLITE_OK;
42038    }
42039    pFd->pMapRegion = pNew;
42040    pFd->mmapSize = nMap;
42041    pFd->mmapSizeActual = nMap;
42042  }
42043
42044  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
42045           osGetCurrentProcessId(), pFd));
42046  return SQLITE_OK;
42047}
42048#endif /* SQLITE_MAX_MMAP_SIZE>0 */
42049
42050/*
42051** If possible, return a pointer to a mapping of file fd starting at offset
42052** iOff. The mapping must be valid for at least nAmt bytes.
42053**
42054** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
42055** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
42056** Finally, if an error does occur, return an SQLite error code. The final
42057** value of *pp is undefined in this case.
42058**
42059** If this function does return a pointer, the caller must eventually
42060** release the reference by calling winUnfetch().
42061*/
42062static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
42063#if SQLITE_MAX_MMAP_SIZE>0
42064  winFile *pFd = (winFile*)fd;   /* The underlying database file */
42065#endif
42066  *pp = 0;
42067
42068  OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
42069           osGetCurrentProcessId(), fd, iOff, nAmt, pp));
42070
42071#if SQLITE_MAX_MMAP_SIZE>0
42072  if( pFd->mmapSizeMax>0 ){
42073    if( pFd->pMapRegion==0 ){
42074      int rc = winMapfile(pFd, -1);
42075      if( rc!=SQLITE_OK ){
42076        OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
42077                 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
42078        return rc;
42079      }
42080    }
42081    if( pFd->mmapSize >= iOff+nAmt ){
42082      *pp = &((u8 *)pFd->pMapRegion)[iOff];
42083      pFd->nFetchOut++;
42084    }
42085  }
42086#endif
42087
42088  OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
42089           osGetCurrentProcessId(), fd, pp, *pp));
42090  return SQLITE_OK;
42091}
42092
42093/*
42094** If the third argument is non-NULL, then this function releases a
42095** reference obtained by an earlier call to winFetch(). The second
42096** argument passed to this function must be the same as the corresponding
42097** argument that was passed to the winFetch() invocation.
42098**
42099** Or, if the third argument is NULL, then this function is being called
42100** to inform the VFS layer that, according to POSIX, any existing mapping
42101** may now be invalid and should be unmapped.
42102*/
42103static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
42104#if SQLITE_MAX_MMAP_SIZE>0
42105  winFile *pFd = (winFile*)fd;   /* The underlying database file */
42106
42107  /* If p==0 (unmap the entire file) then there must be no outstanding
42108  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
42109  ** then there must be at least one outstanding.  */
42110  assert( (p==0)==(pFd->nFetchOut==0) );
42111
42112  /* If p!=0, it must match the iOff value. */
42113  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
42114
42115  OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
42116           osGetCurrentProcessId(), pFd, iOff, p));
42117
42118  if( p ){
42119    pFd->nFetchOut--;
42120  }else{
42121    /* FIXME:  If Windows truly always prevents truncating or deleting a
42122    ** file while a mapping is held, then the following winUnmapfile() call
42123    ** is unnecessary can be omitted - potentially improving
42124    ** performance.  */
42125    winUnmapfile(pFd);
42126  }
42127
42128  assert( pFd->nFetchOut>=0 );
42129#endif
42130
42131  OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
42132           osGetCurrentProcessId(), fd));
42133  return SQLITE_OK;
42134}
42135
42136/*
42137** Here ends the implementation of all sqlite3_file methods.
42138**
42139********************** End sqlite3_file Methods *******************************
42140******************************************************************************/
42141
42142/*
42143** This vector defines all the methods that can operate on an
42144** sqlite3_file for win32.
42145*/
42146static const sqlite3_io_methods winIoMethod = {
42147  3,                              /* iVersion */
42148  winClose,                       /* xClose */
42149  winRead,                        /* xRead */
42150  winWrite,                       /* xWrite */
42151  winTruncate,                    /* xTruncate */
42152  winSync,                        /* xSync */
42153  winFileSize,                    /* xFileSize */
42154  winLock,                        /* xLock */
42155  winUnlock,                      /* xUnlock */
42156  winCheckReservedLock,           /* xCheckReservedLock */
42157  winFileControl,                 /* xFileControl */
42158  winSectorSize,                  /* xSectorSize */
42159  winDeviceCharacteristics,       /* xDeviceCharacteristics */
42160  winShmMap,                      /* xShmMap */
42161  winShmLock,                     /* xShmLock */
42162  winShmBarrier,                  /* xShmBarrier */
42163  winShmUnmap,                    /* xShmUnmap */
42164  winFetch,                       /* xFetch */
42165  winUnfetch                      /* xUnfetch */
42166};
42167
42168/*
42169** This vector defines all the methods that can operate on an
42170** sqlite3_file for win32 without performing any locking.
42171*/
42172static const sqlite3_io_methods winIoNolockMethod = {
42173  3,                              /* iVersion */
42174  winClose,                       /* xClose */
42175  winRead,                        /* xRead */
42176  winWrite,                       /* xWrite */
42177  winTruncate,                    /* xTruncate */
42178  winSync,                        /* xSync */
42179  winFileSize,                    /* xFileSize */
42180  winNolockLock,                  /* xLock */
42181  winNolockUnlock,                /* xUnlock */
42182  winNolockCheckReservedLock,     /* xCheckReservedLock */
42183  winFileControl,                 /* xFileControl */
42184  winSectorSize,                  /* xSectorSize */
42185  winDeviceCharacteristics,       /* xDeviceCharacteristics */
42186  winShmMap,                      /* xShmMap */
42187  winShmLock,                     /* xShmLock */
42188  winShmBarrier,                  /* xShmBarrier */
42189  winShmUnmap,                    /* xShmUnmap */
42190  winFetch,                       /* xFetch */
42191  winUnfetch                      /* xUnfetch */
42192};
42193
42194static winVfsAppData winAppData = {
42195  &winIoMethod,       /* pMethod */
42196  0,                  /* pAppData */
42197  0                   /* bNoLock */
42198};
42199
42200static winVfsAppData winNolockAppData = {
42201  &winIoNolockMethod, /* pMethod */
42202  0,                  /* pAppData */
42203  1                   /* bNoLock */
42204};
42205
42206/****************************************************************************
42207**************************** sqlite3_vfs methods ****************************
42208**
42209** This division contains the implementation of methods on the
42210** sqlite3_vfs object.
42211*/
42212
42213#if defined(__CYGWIN__)
42214/*
42215** Convert a filename from whatever the underlying operating system
42216** supports for filenames into UTF-8.  Space to hold the result is
42217** obtained from malloc and must be freed by the calling function.
42218*/
42219static char *winConvertToUtf8Filename(const void *zFilename){
42220  char *zConverted = 0;
42221  if( osIsNT() ){
42222    zConverted = winUnicodeToUtf8(zFilename);
42223  }
42224#ifdef SQLITE_WIN32_HAS_ANSI
42225  else{
42226    zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
42227  }
42228#endif
42229  /* caller will handle out of memory */
42230  return zConverted;
42231}
42232#endif
42233
42234/*
42235** Convert a UTF-8 filename into whatever form the underlying
42236** operating system wants filenames in.  Space to hold the result
42237** is obtained from malloc and must be freed by the calling
42238** function.
42239*/
42240static void *winConvertFromUtf8Filename(const char *zFilename){
42241  void *zConverted = 0;
42242  if( osIsNT() ){
42243    zConverted = winUtf8ToUnicode(zFilename);
42244  }
42245#ifdef SQLITE_WIN32_HAS_ANSI
42246  else{
42247    zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
42248  }
42249#endif
42250  /* caller will handle out of memory */
42251  return zConverted;
42252}
42253
42254/*
42255** This function returns non-zero if the specified UTF-8 string buffer
42256** ends with a directory separator character or one was successfully
42257** added to it.
42258*/
42259static int winMakeEndInDirSep(int nBuf, char *zBuf){
42260  if( zBuf ){
42261    int nLen = sqlite3Strlen30(zBuf);
42262    if( nLen>0 ){
42263      if( winIsDirSep(zBuf[nLen-1]) ){
42264        return 1;
42265      }else if( nLen+1<nBuf ){
42266        zBuf[nLen] = winGetDirSep();
42267        zBuf[nLen+1] = '\0';
42268        return 1;
42269      }
42270    }
42271  }
42272  return 0;
42273}
42274
42275/*
42276** Create a temporary file name and store the resulting pointer into pzBuf.
42277** The pointer returned in pzBuf must be freed via sqlite3_free().
42278*/
42279static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
42280  static char zChars[] =
42281    "abcdefghijklmnopqrstuvwxyz"
42282    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
42283    "0123456789";
42284  size_t i, j;
42285  int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
42286  int nMax, nBuf, nDir, nLen;
42287  char *zBuf;
42288
42289  /* It's odd to simulate an io-error here, but really this is just
42290  ** using the io-error infrastructure to test that SQLite handles this
42291  ** function failing.
42292  */
42293  SimulateIOError( return SQLITE_IOERR );
42294
42295  /* Allocate a temporary buffer to store the fully qualified file
42296  ** name for the temporary file.  If this fails, we cannot continue.
42297  */
42298  nMax = pVfs->mxPathname; nBuf = nMax + 2;
42299  zBuf = sqlite3MallocZero( nBuf );
42300  if( !zBuf ){
42301    OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42302    return SQLITE_IOERR_NOMEM_BKPT;
42303  }
42304
42305  /* Figure out the effective temporary directory.  First, check if one
42306  ** has been explicitly set by the application; otherwise, use the one
42307  ** configured by the operating system.
42308  */
42309  nDir = nMax - (nPre + 15);
42310  assert( nDir>0 );
42311  if( sqlite3_temp_directory ){
42312    int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
42313    if( nDirLen>0 ){
42314      if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
42315        nDirLen++;
42316      }
42317      if( nDirLen>nDir ){
42318        sqlite3_free(zBuf);
42319        OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
42320        return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
42321      }
42322      sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
42323    }
42324  }
42325#if defined(__CYGWIN__)
42326  else{
42327    static const char *azDirs[] = {
42328       0, /* getenv("SQLITE_TMPDIR") */
42329       0, /* getenv("TMPDIR") */
42330       0, /* getenv("TMP") */
42331       0, /* getenv("TEMP") */
42332       0, /* getenv("USERPROFILE") */
42333       "/var/tmp",
42334       "/usr/tmp",
42335       "/tmp",
42336       ".",
42337       0        /* List terminator */
42338    };
42339    unsigned int i;
42340    const char *zDir = 0;
42341
42342    if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
42343    if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
42344    if( !azDirs[2] ) azDirs[2] = getenv("TMP");
42345    if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
42346    if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
42347    for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
42348      void *zConverted;
42349      if( zDir==0 ) continue;
42350      /* If the path starts with a drive letter followed by the colon
42351      ** character, assume it is already a native Win32 path; otherwise,
42352      ** it must be converted to a native Win32 path via the Cygwin API
42353      ** prior to using it.
42354      */
42355      if( winIsDriveLetterAndColon(zDir) ){
42356        zConverted = winConvertFromUtf8Filename(zDir);
42357        if( !zConverted ){
42358          sqlite3_free(zBuf);
42359          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42360          return SQLITE_IOERR_NOMEM_BKPT;
42361        }
42362        if( winIsDir(zConverted) ){
42363          sqlite3_snprintf(nMax, zBuf, "%s", zDir);
42364          sqlite3_free(zConverted);
42365          break;
42366        }
42367        sqlite3_free(zConverted);
42368      }else{
42369        zConverted = sqlite3MallocZero( nMax+1 );
42370        if( !zConverted ){
42371          sqlite3_free(zBuf);
42372          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42373          return SQLITE_IOERR_NOMEM_BKPT;
42374        }
42375        if( cygwin_conv_path(
42376                osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
42377                zConverted, nMax+1)<0 ){
42378          sqlite3_free(zConverted);
42379          sqlite3_free(zBuf);
42380          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
42381          return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
42382                             "winGetTempname2", zDir);
42383        }
42384        if( winIsDir(zConverted) ){
42385          /* At this point, we know the candidate directory exists and should
42386          ** be used.  However, we may need to convert the string containing
42387          ** its name into UTF-8 (i.e. if it is UTF-16 right now).
42388          */
42389          char *zUtf8 = winConvertToUtf8Filename(zConverted);
42390          if( !zUtf8 ){
42391            sqlite3_free(zConverted);
42392            sqlite3_free(zBuf);
42393            OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42394            return SQLITE_IOERR_NOMEM_BKPT;
42395          }
42396          sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
42397          sqlite3_free(zUtf8);
42398          sqlite3_free(zConverted);
42399          break;
42400        }
42401        sqlite3_free(zConverted);
42402      }
42403    }
42404  }
42405#elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
42406  else if( osIsNT() ){
42407    char *zMulti;
42408    LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
42409    if( !zWidePath ){
42410      sqlite3_free(zBuf);
42411      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42412      return SQLITE_IOERR_NOMEM_BKPT;
42413    }
42414    if( osGetTempPathW(nMax, zWidePath)==0 ){
42415      sqlite3_free(zWidePath);
42416      sqlite3_free(zBuf);
42417      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
42418      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
42419                         "winGetTempname2", 0);
42420    }
42421    zMulti = winUnicodeToUtf8(zWidePath);
42422    if( zMulti ){
42423      sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
42424      sqlite3_free(zMulti);
42425      sqlite3_free(zWidePath);
42426    }else{
42427      sqlite3_free(zWidePath);
42428      sqlite3_free(zBuf);
42429      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42430      return SQLITE_IOERR_NOMEM_BKPT;
42431    }
42432  }
42433#ifdef SQLITE_WIN32_HAS_ANSI
42434  else{
42435    char *zUtf8;
42436    char *zMbcsPath = sqlite3MallocZero( nMax );
42437    if( !zMbcsPath ){
42438      sqlite3_free(zBuf);
42439      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42440      return SQLITE_IOERR_NOMEM_BKPT;
42441    }
42442    if( osGetTempPathA(nMax, zMbcsPath)==0 ){
42443      sqlite3_free(zBuf);
42444      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
42445      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
42446                         "winGetTempname3", 0);
42447    }
42448    zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
42449    if( zUtf8 ){
42450      sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
42451      sqlite3_free(zUtf8);
42452    }else{
42453      sqlite3_free(zBuf);
42454      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42455      return SQLITE_IOERR_NOMEM_BKPT;
42456    }
42457  }
42458#endif /* SQLITE_WIN32_HAS_ANSI */
42459#endif /* !SQLITE_OS_WINRT */
42460
42461  /*
42462  ** Check to make sure the temporary directory ends with an appropriate
42463  ** separator.  If it does not and there is not enough space left to add
42464  ** one, fail.
42465  */
42466  if( !winMakeEndInDirSep(nDir+1, zBuf) ){
42467    sqlite3_free(zBuf);
42468    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
42469    return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
42470  }
42471
42472  /*
42473  ** Check that the output buffer is large enough for the temporary file
42474  ** name in the following format:
42475  **
42476  **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
42477  **
42478  ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
42479  ** account for the space used by the 15 character random suffix and the
42480  ** two trailing NUL characters.  The final directory separator character
42481  ** has already added if it was not already present.
42482  */
42483  nLen = sqlite3Strlen30(zBuf);
42484  if( (nLen + nPre + 17) > nBuf ){
42485    sqlite3_free(zBuf);
42486    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
42487    return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
42488  }
42489
42490  sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
42491
42492  j = sqlite3Strlen30(zBuf);
42493  sqlite3_randomness(15, &zBuf[j]);
42494  for(i=0; i<15; i++, j++){
42495    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
42496  }
42497  zBuf[j] = 0;
42498  zBuf[j+1] = 0;
42499  *pzBuf = zBuf;
42500
42501  OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
42502  return SQLITE_OK;
42503}
42504
42505/*
42506** Return TRUE if the named file is really a directory.  Return false if
42507** it is something other than a directory, or if there is any kind of memory
42508** allocation failure.
42509*/
42510static int winIsDir(const void *zConverted){
42511  DWORD attr;
42512  int rc = 0;
42513  DWORD lastErrno;
42514
42515  if( osIsNT() ){
42516    int cnt = 0;
42517    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
42518    memset(&sAttrData, 0, sizeof(sAttrData));
42519    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
42520                             GetFileExInfoStandard,
42521                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
42522    if( !rc ){
42523      return 0; /* Invalid name? */
42524    }
42525    attr = sAttrData.dwFileAttributes;
42526#if SQLITE_OS_WINCE==0
42527  }else{
42528    attr = osGetFileAttributesA((char*)zConverted);
42529#endif
42530  }
42531  return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
42532}
42533
42534/*
42535** Open a file.
42536*/
42537static int winOpen(
42538  sqlite3_vfs *pVfs,        /* Used to get maximum path length and AppData */
42539  const char *zName,        /* Name of the file (UTF-8) */
42540  sqlite3_file *id,         /* Write the SQLite file handle here */
42541  int flags,                /* Open mode flags */
42542  int *pOutFlags            /* Status return flags */
42543){
42544  HANDLE h;
42545  DWORD lastErrno = 0;
42546  DWORD dwDesiredAccess;
42547  DWORD dwShareMode;
42548  DWORD dwCreationDisposition;
42549  DWORD dwFlagsAndAttributes = 0;
42550#if SQLITE_OS_WINCE
42551  int isTemp = 0;
42552#endif
42553  winVfsAppData *pAppData;
42554  winFile *pFile = (winFile*)id;
42555  void *zConverted;              /* Filename in OS encoding */
42556  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
42557  int cnt = 0;
42558
42559  /* If argument zPath is a NULL pointer, this function is required to open
42560  ** a temporary file. Use this buffer to store the file name in.
42561  */
42562  char *zTmpname = 0; /* For temporary filename, if necessary. */
42563
42564  int rc = SQLITE_OK;            /* Function Return Code */
42565#if !defined(NDEBUG) || SQLITE_OS_WINCE
42566  int eType = flags&0xFFFFFF00;  /* Type of file to open */
42567#endif
42568
42569  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
42570  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
42571  int isCreate     = (flags & SQLITE_OPEN_CREATE);
42572  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
42573  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
42574
42575#ifndef NDEBUG
42576  int isOpenJournal = (isCreate && (
42577        eType==SQLITE_OPEN_MASTER_JOURNAL
42578     || eType==SQLITE_OPEN_MAIN_JOURNAL
42579     || eType==SQLITE_OPEN_WAL
42580  ));
42581#endif
42582
42583  OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
42584           zUtf8Name, id, flags, pOutFlags));
42585
42586  /* Check the following statements are true:
42587  **
42588  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
42589  **   (b) if CREATE is set, then READWRITE must also be set, and
42590  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
42591  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
42592  */
42593  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
42594  assert(isCreate==0 || isReadWrite);
42595  assert(isExclusive==0 || isCreate);
42596  assert(isDelete==0 || isCreate);
42597
42598  /* The main DB, main journal, WAL file and master journal are never
42599  ** automatically deleted. Nor are they ever temporary files.  */
42600  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
42601  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
42602  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
42603  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
42604
42605  /* Assert that the upper layer has set one of the "file-type" flags. */
42606  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
42607       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
42608       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
42609       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
42610  );
42611
42612  assert( pFile!=0 );
42613  memset(pFile, 0, sizeof(winFile));
42614  pFile->h = INVALID_HANDLE_VALUE;
42615
42616#if SQLITE_OS_WINRT
42617  if( !zUtf8Name && !sqlite3_temp_directory ){
42618    sqlite3_log(SQLITE_ERROR,
42619        "sqlite3_temp_directory variable should be set for WinRT");
42620  }
42621#endif
42622
42623  /* If the second argument to this function is NULL, generate a
42624  ** temporary file name to use
42625  */
42626  if( !zUtf8Name ){
42627    assert( isDelete && !isOpenJournal );
42628    rc = winGetTempname(pVfs, &zTmpname);
42629    if( rc!=SQLITE_OK ){
42630      OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
42631      return rc;
42632    }
42633    zUtf8Name = zTmpname;
42634  }
42635
42636  /* Database filenames are double-zero terminated if they are not
42637  ** URIs with parameters.  Hence, they can always be passed into
42638  ** sqlite3_uri_parameter().
42639  */
42640  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
42641       zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
42642
42643  /* Convert the filename to the system encoding. */
42644  zConverted = winConvertFromUtf8Filename(zUtf8Name);
42645  if( zConverted==0 ){
42646    sqlite3_free(zTmpname);
42647    OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
42648    return SQLITE_IOERR_NOMEM_BKPT;
42649  }
42650
42651  if( winIsDir(zConverted) ){
42652    sqlite3_free(zConverted);
42653    sqlite3_free(zTmpname);
42654    OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
42655    return SQLITE_CANTOPEN_ISDIR;
42656  }
42657
42658  if( isReadWrite ){
42659    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
42660  }else{
42661    dwDesiredAccess = GENERIC_READ;
42662  }
42663
42664  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
42665  ** created. SQLite doesn't use it to indicate "exclusive access"
42666  ** as it is usually understood.
42667  */
42668  if( isExclusive ){
42669    /* Creates a new file, only if it does not already exist. */
42670    /* If the file exists, it fails. */
42671    dwCreationDisposition = CREATE_NEW;
42672  }else if( isCreate ){
42673    /* Open existing file, or create if it doesn't exist */
42674    dwCreationDisposition = OPEN_ALWAYS;
42675  }else{
42676    /* Opens a file, only if it exists. */
42677    dwCreationDisposition = OPEN_EXISTING;
42678  }
42679
42680  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
42681
42682  if( isDelete ){
42683#if SQLITE_OS_WINCE
42684    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
42685    isTemp = 1;
42686#else
42687    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
42688                               | FILE_ATTRIBUTE_HIDDEN
42689                               | FILE_FLAG_DELETE_ON_CLOSE;
42690#endif
42691  }else{
42692    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
42693  }
42694  /* Reports from the internet are that performance is always
42695  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
42696#if SQLITE_OS_WINCE
42697  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
42698#endif
42699
42700  if( osIsNT() ){
42701#if SQLITE_OS_WINRT
42702    CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
42703    extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
42704    extendedParameters.dwFileAttributes =
42705            dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
42706    extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
42707    extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
42708    extendedParameters.lpSecurityAttributes = NULL;
42709    extendedParameters.hTemplateFile = NULL;
42710    while( (h = osCreateFile2((LPCWSTR)zConverted,
42711                              dwDesiredAccess,
42712                              dwShareMode,
42713                              dwCreationDisposition,
42714                              &extendedParameters))==INVALID_HANDLE_VALUE &&
42715                              winRetryIoerr(&cnt, &lastErrno) ){
42716               /* Noop */
42717    }
42718#else
42719    while( (h = osCreateFileW((LPCWSTR)zConverted,
42720                              dwDesiredAccess,
42721                              dwShareMode, NULL,
42722                              dwCreationDisposition,
42723                              dwFlagsAndAttributes,
42724                              NULL))==INVALID_HANDLE_VALUE &&
42725                              winRetryIoerr(&cnt, &lastErrno) ){
42726               /* Noop */
42727    }
42728#endif
42729  }
42730#ifdef SQLITE_WIN32_HAS_ANSI
42731  else{
42732    while( (h = osCreateFileA((LPCSTR)zConverted,
42733                              dwDesiredAccess,
42734                              dwShareMode, NULL,
42735                              dwCreationDisposition,
42736                              dwFlagsAndAttributes,
42737                              NULL))==INVALID_HANDLE_VALUE &&
42738                              winRetryIoerr(&cnt, &lastErrno) ){
42739               /* Noop */
42740    }
42741  }
42742#endif
42743  winLogIoerr(cnt, __LINE__);
42744
42745  OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
42746           dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
42747
42748  if( h==INVALID_HANDLE_VALUE ){
42749    pFile->lastErrno = lastErrno;
42750    winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
42751    sqlite3_free(zConverted);
42752    sqlite3_free(zTmpname);
42753    if( isReadWrite && !isExclusive ){
42754      return winOpen(pVfs, zName, id,
42755         ((flags|SQLITE_OPEN_READONLY) &
42756                     ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
42757         pOutFlags);
42758    }else{
42759      return SQLITE_CANTOPEN_BKPT;
42760    }
42761  }
42762
42763  if( pOutFlags ){
42764    if( isReadWrite ){
42765      *pOutFlags = SQLITE_OPEN_READWRITE;
42766    }else{
42767      *pOutFlags = SQLITE_OPEN_READONLY;
42768    }
42769  }
42770
42771  OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
42772           "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
42773           *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
42774
42775  pAppData = (winVfsAppData*)pVfs->pAppData;
42776
42777#if SQLITE_OS_WINCE
42778  {
42779    if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
42780         && ((pAppData==NULL) || !pAppData->bNoLock)
42781         && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
42782    ){
42783      osCloseHandle(h);
42784      sqlite3_free(zConverted);
42785      sqlite3_free(zTmpname);
42786      OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
42787      return rc;
42788    }
42789  }
42790  if( isTemp ){
42791    pFile->zDeleteOnClose = zConverted;
42792  }else
42793#endif
42794  {
42795    sqlite3_free(zConverted);
42796  }
42797
42798  sqlite3_free(zTmpname);
42799  pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
42800  pFile->pVfs = pVfs;
42801  pFile->h = h;
42802  if( isReadonly ){
42803    pFile->ctrlFlags |= WINFILE_RDONLY;
42804  }
42805  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
42806    pFile->ctrlFlags |= WINFILE_PSOW;
42807  }
42808  pFile->lastErrno = NO_ERROR;
42809  pFile->zPath = zName;
42810#if SQLITE_MAX_MMAP_SIZE>0
42811  pFile->hMap = NULL;
42812  pFile->pMapRegion = 0;
42813  pFile->mmapSize = 0;
42814  pFile->mmapSizeActual = 0;
42815  pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
42816#endif
42817
42818  OpenCounter(+1);
42819  return rc;
42820}
42821
42822/*
42823** Delete the named file.
42824**
42825** Note that Windows does not allow a file to be deleted if some other
42826** process has it open.  Sometimes a virus scanner or indexing program
42827** will open a journal file shortly after it is created in order to do
42828** whatever it does.  While this other process is holding the
42829** file open, we will be unable to delete it.  To work around this
42830** problem, we delay 100 milliseconds and try to delete again.  Up
42831** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
42832** up and returning an error.
42833*/
42834static int winDelete(
42835  sqlite3_vfs *pVfs,          /* Not used on win32 */
42836  const char *zFilename,      /* Name of file to delete */
42837  int syncDir                 /* Not used on win32 */
42838){
42839  int cnt = 0;
42840  int rc;
42841  DWORD attr;
42842  DWORD lastErrno = 0;
42843  void *zConverted;
42844  UNUSED_PARAMETER(pVfs);
42845  UNUSED_PARAMETER(syncDir);
42846
42847  SimulateIOError(return SQLITE_IOERR_DELETE);
42848  OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
42849
42850  zConverted = winConvertFromUtf8Filename(zFilename);
42851  if( zConverted==0 ){
42852    OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
42853    return SQLITE_IOERR_NOMEM_BKPT;
42854  }
42855  if( osIsNT() ){
42856    do {
42857#if SQLITE_OS_WINRT
42858      WIN32_FILE_ATTRIBUTE_DATA sAttrData;
42859      memset(&sAttrData, 0, sizeof(sAttrData));
42860      if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
42861                                  &sAttrData) ){
42862        attr = sAttrData.dwFileAttributes;
42863      }else{
42864        lastErrno = osGetLastError();
42865        if( lastErrno==ERROR_FILE_NOT_FOUND
42866         || lastErrno==ERROR_PATH_NOT_FOUND ){
42867          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42868        }else{
42869          rc = SQLITE_ERROR;
42870        }
42871        break;
42872      }
42873#else
42874      attr = osGetFileAttributesW(zConverted);
42875#endif
42876      if ( attr==INVALID_FILE_ATTRIBUTES ){
42877        lastErrno = osGetLastError();
42878        if( lastErrno==ERROR_FILE_NOT_FOUND
42879         || lastErrno==ERROR_PATH_NOT_FOUND ){
42880          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42881        }else{
42882          rc = SQLITE_ERROR;
42883        }
42884        break;
42885      }
42886      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
42887        rc = SQLITE_ERROR; /* Files only. */
42888        break;
42889      }
42890      if ( osDeleteFileW(zConverted) ){
42891        rc = SQLITE_OK; /* Deleted OK. */
42892        break;
42893      }
42894      if ( !winRetryIoerr(&cnt, &lastErrno) ){
42895        rc = SQLITE_ERROR; /* No more retries. */
42896        break;
42897      }
42898    } while(1);
42899  }
42900#ifdef SQLITE_WIN32_HAS_ANSI
42901  else{
42902    do {
42903      attr = osGetFileAttributesA(zConverted);
42904      if ( attr==INVALID_FILE_ATTRIBUTES ){
42905        lastErrno = osGetLastError();
42906        if( lastErrno==ERROR_FILE_NOT_FOUND
42907         || lastErrno==ERROR_PATH_NOT_FOUND ){
42908          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42909        }else{
42910          rc = SQLITE_ERROR;
42911        }
42912        break;
42913      }
42914      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
42915        rc = SQLITE_ERROR; /* Files only. */
42916        break;
42917      }
42918      if ( osDeleteFileA(zConverted) ){
42919        rc = SQLITE_OK; /* Deleted OK. */
42920        break;
42921      }
42922      if ( !winRetryIoerr(&cnt, &lastErrno) ){
42923        rc = SQLITE_ERROR; /* No more retries. */
42924        break;
42925      }
42926    } while(1);
42927  }
42928#endif
42929  if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
42930    rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
42931  }else{
42932    winLogIoerr(cnt, __LINE__);
42933  }
42934  sqlite3_free(zConverted);
42935  OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
42936  return rc;
42937}
42938
42939/*
42940** Check the existence and status of a file.
42941*/
42942static int winAccess(
42943  sqlite3_vfs *pVfs,         /* Not used on win32 */
42944  const char *zFilename,     /* Name of file to check */
42945  int flags,                 /* Type of test to make on this file */
42946  int *pResOut               /* OUT: Result */
42947){
42948  DWORD attr;
42949  int rc = 0;
42950  DWORD lastErrno = 0;
42951  void *zConverted;
42952  UNUSED_PARAMETER(pVfs);
42953
42954  SimulateIOError( return SQLITE_IOERR_ACCESS; );
42955  OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
42956           zFilename, flags, pResOut));
42957
42958  zConverted = winConvertFromUtf8Filename(zFilename);
42959  if( zConverted==0 ){
42960    OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
42961    return SQLITE_IOERR_NOMEM_BKPT;
42962  }
42963  if( osIsNT() ){
42964    int cnt = 0;
42965    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
42966    memset(&sAttrData, 0, sizeof(sAttrData));
42967    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
42968                             GetFileExInfoStandard,
42969                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
42970    if( rc ){
42971      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
42972      ** as if it does not exist.
42973      */
42974      if(    flags==SQLITE_ACCESS_EXISTS
42975          && sAttrData.nFileSizeHigh==0
42976          && sAttrData.nFileSizeLow==0 ){
42977        attr = INVALID_FILE_ATTRIBUTES;
42978      }else{
42979        attr = sAttrData.dwFileAttributes;
42980      }
42981    }else{
42982      winLogIoerr(cnt, __LINE__);
42983      if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
42984        sqlite3_free(zConverted);
42985        return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
42986                           zFilename);
42987      }else{
42988        attr = INVALID_FILE_ATTRIBUTES;
42989      }
42990    }
42991  }
42992#ifdef SQLITE_WIN32_HAS_ANSI
42993  else{
42994    attr = osGetFileAttributesA((char*)zConverted);
42995  }
42996#endif
42997  sqlite3_free(zConverted);
42998  switch( flags ){
42999    case SQLITE_ACCESS_READ:
43000    case SQLITE_ACCESS_EXISTS:
43001      rc = attr!=INVALID_FILE_ATTRIBUTES;
43002      break;
43003    case SQLITE_ACCESS_READWRITE:
43004      rc = attr!=INVALID_FILE_ATTRIBUTES &&
43005             (attr & FILE_ATTRIBUTE_READONLY)==0;
43006      break;
43007    default:
43008      assert(!"Invalid flags argument");
43009  }
43010  *pResOut = rc;
43011  OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
43012           zFilename, pResOut, *pResOut));
43013  return SQLITE_OK;
43014}
43015
43016/*
43017** Returns non-zero if the specified path name starts with a drive letter
43018** followed by a colon character.
43019*/
43020static BOOL winIsDriveLetterAndColon(
43021  const char *zPathname
43022){
43023  return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
43024}
43025
43026/*
43027** Returns non-zero if the specified path name should be used verbatim.  If
43028** non-zero is returned from this function, the calling function must simply
43029** use the provided path name verbatim -OR- resolve it into a full path name
43030** using the GetFullPathName Win32 API function (if available).
43031*/
43032static BOOL winIsVerbatimPathname(
43033  const char *zPathname
43034){
43035  /*
43036  ** If the path name starts with a forward slash or a backslash, it is either
43037  ** a legal UNC name, a volume relative path, or an absolute path name in the
43038  ** "Unix" format on Windows.  There is no easy way to differentiate between
43039  ** the final two cases; therefore, we return the safer return value of TRUE
43040  ** so that callers of this function will simply use it verbatim.
43041  */
43042  if ( winIsDirSep(zPathname[0]) ){
43043    return TRUE;
43044  }
43045
43046  /*
43047  ** If the path name starts with a letter and a colon it is either a volume
43048  ** relative path or an absolute path.  Callers of this function must not
43049  ** attempt to treat it as a relative path name (i.e. they should simply use
43050  ** it verbatim).
43051  */
43052  if ( winIsDriveLetterAndColon(zPathname) ){
43053    return TRUE;
43054  }
43055
43056  /*
43057  ** If we get to this point, the path name should almost certainly be a purely
43058  ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
43059  */
43060  return FALSE;
43061}
43062
43063/*
43064** Turn a relative pathname into a full pathname.  Write the full
43065** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
43066** bytes in size.
43067*/
43068static int winFullPathname(
43069  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
43070  const char *zRelative,        /* Possibly relative input path */
43071  int nFull,                    /* Size of output buffer in bytes */
43072  char *zFull                   /* Output buffer */
43073){
43074#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
43075  DWORD nByte;
43076  void *zConverted;
43077  char *zOut;
43078#endif
43079
43080  /* If this path name begins with "/X:", where "X" is any alphabetic
43081  ** character, discard the initial "/" from the pathname.
43082  */
43083  if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
43084    zRelative++;
43085  }
43086
43087#if defined(__CYGWIN__)
43088  SimulateIOError( return SQLITE_ERROR );
43089  UNUSED_PARAMETER(nFull);
43090  assert( nFull>=pVfs->mxPathname );
43091  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
43092    /*
43093    ** NOTE: We are dealing with a relative path name and the data
43094    **       directory has been set.  Therefore, use it as the basis
43095    **       for converting the relative path name to an absolute
43096    **       one by prepending the data directory and a slash.
43097    */
43098    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
43099    if( !zOut ){
43100      return SQLITE_IOERR_NOMEM_BKPT;
43101    }
43102    if( cygwin_conv_path(
43103            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
43104            CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
43105      sqlite3_free(zOut);
43106      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
43107                         "winFullPathname1", zRelative);
43108    }else{
43109      char *zUtf8 = winConvertToUtf8Filename(zOut);
43110      if( !zUtf8 ){
43111        sqlite3_free(zOut);
43112        return SQLITE_IOERR_NOMEM_BKPT;
43113      }
43114      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
43115                       sqlite3_data_directory, winGetDirSep(), zUtf8);
43116      sqlite3_free(zUtf8);
43117      sqlite3_free(zOut);
43118    }
43119  }else{
43120    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
43121    if( !zOut ){
43122      return SQLITE_IOERR_NOMEM_BKPT;
43123    }
43124    if( cygwin_conv_path(
43125            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
43126            zRelative, zOut, pVfs->mxPathname+1)<0 ){
43127      sqlite3_free(zOut);
43128      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
43129                         "winFullPathname2", zRelative);
43130    }else{
43131      char *zUtf8 = winConvertToUtf8Filename(zOut);
43132      if( !zUtf8 ){
43133        sqlite3_free(zOut);
43134        return SQLITE_IOERR_NOMEM_BKPT;
43135      }
43136      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
43137      sqlite3_free(zUtf8);
43138      sqlite3_free(zOut);
43139    }
43140  }
43141  return SQLITE_OK;
43142#endif
43143
43144#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
43145  SimulateIOError( return SQLITE_ERROR );
43146  /* WinCE has no concept of a relative pathname, or so I am told. */
43147  /* WinRT has no way to convert a relative path to an absolute one. */
43148  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
43149    /*
43150    ** NOTE: We are dealing with a relative path name and the data
43151    **       directory has been set.  Therefore, use it as the basis
43152    **       for converting the relative path name to an absolute
43153    **       one by prepending the data directory and a backslash.
43154    */
43155    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
43156                     sqlite3_data_directory, winGetDirSep(), zRelative);
43157  }else{
43158    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
43159  }
43160  return SQLITE_OK;
43161#endif
43162
43163#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
43164  /* It's odd to simulate an io-error here, but really this is just
43165  ** using the io-error infrastructure to test that SQLite handles this
43166  ** function failing. This function could fail if, for example, the
43167  ** current working directory has been unlinked.
43168  */
43169  SimulateIOError( return SQLITE_ERROR );
43170  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
43171    /*
43172    ** NOTE: We are dealing with a relative path name and the data
43173    **       directory has been set.  Therefore, use it as the basis
43174    **       for converting the relative path name to an absolute
43175    **       one by prepending the data directory and a backslash.
43176    */
43177    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
43178                     sqlite3_data_directory, winGetDirSep(), zRelative);
43179    return SQLITE_OK;
43180  }
43181  zConverted = winConvertFromUtf8Filename(zRelative);
43182  if( zConverted==0 ){
43183    return SQLITE_IOERR_NOMEM_BKPT;
43184  }
43185  if( osIsNT() ){
43186    LPWSTR zTemp;
43187    nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
43188    if( nByte==0 ){
43189      sqlite3_free(zConverted);
43190      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
43191                         "winFullPathname1", zRelative);
43192    }
43193    nByte += 3;
43194    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
43195    if( zTemp==0 ){
43196      sqlite3_free(zConverted);
43197      return SQLITE_IOERR_NOMEM_BKPT;
43198    }
43199    nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
43200    if( nByte==0 ){
43201      sqlite3_free(zConverted);
43202      sqlite3_free(zTemp);
43203      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
43204                         "winFullPathname2", zRelative);
43205    }
43206    sqlite3_free(zConverted);
43207    zOut = winUnicodeToUtf8(zTemp);
43208    sqlite3_free(zTemp);
43209  }
43210#ifdef SQLITE_WIN32_HAS_ANSI
43211  else{
43212    char *zTemp;
43213    nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
43214    if( nByte==0 ){
43215      sqlite3_free(zConverted);
43216      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
43217                         "winFullPathname3", zRelative);
43218    }
43219    nByte += 3;
43220    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
43221    if( zTemp==0 ){
43222      sqlite3_free(zConverted);
43223      return SQLITE_IOERR_NOMEM_BKPT;
43224    }
43225    nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
43226    if( nByte==0 ){
43227      sqlite3_free(zConverted);
43228      sqlite3_free(zTemp);
43229      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
43230                         "winFullPathname4", zRelative);
43231    }
43232    sqlite3_free(zConverted);
43233    zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
43234    sqlite3_free(zTemp);
43235  }
43236#endif
43237  if( zOut ){
43238    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
43239    sqlite3_free(zOut);
43240    return SQLITE_OK;
43241  }else{
43242    return SQLITE_IOERR_NOMEM_BKPT;
43243  }
43244#endif
43245}
43246
43247#ifndef SQLITE_OMIT_LOAD_EXTENSION
43248/*
43249** Interfaces for opening a shared library, finding entry points
43250** within the shared library, and closing the shared library.
43251*/
43252static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
43253  HANDLE h;
43254#if defined(__CYGWIN__)
43255  int nFull = pVfs->mxPathname+1;
43256  char *zFull = sqlite3MallocZero( nFull );
43257  void *zConverted = 0;
43258  if( zFull==0 ){
43259    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
43260    return 0;
43261  }
43262  if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
43263    sqlite3_free(zFull);
43264    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
43265    return 0;
43266  }
43267  zConverted = winConvertFromUtf8Filename(zFull);
43268  sqlite3_free(zFull);
43269#else
43270  void *zConverted = winConvertFromUtf8Filename(zFilename);
43271  UNUSED_PARAMETER(pVfs);
43272#endif
43273  if( zConverted==0 ){
43274    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
43275    return 0;
43276  }
43277  if( osIsNT() ){
43278#if SQLITE_OS_WINRT
43279    h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
43280#else
43281    h = osLoadLibraryW((LPCWSTR)zConverted);
43282#endif
43283  }
43284#ifdef SQLITE_WIN32_HAS_ANSI
43285  else{
43286    h = osLoadLibraryA((char*)zConverted);
43287  }
43288#endif
43289  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
43290  sqlite3_free(zConverted);
43291  return (void*)h;
43292}
43293static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
43294  UNUSED_PARAMETER(pVfs);
43295  winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
43296}
43297static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
43298  FARPROC proc;
43299  UNUSED_PARAMETER(pVfs);
43300  proc = osGetProcAddressA((HANDLE)pH, zSym);
43301  OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
43302           (void*)pH, zSym, (void*)proc));
43303  return (void(*)(void))proc;
43304}
43305static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
43306  UNUSED_PARAMETER(pVfs);
43307  osFreeLibrary((HANDLE)pHandle);
43308  OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
43309}
43310#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
43311  #define winDlOpen  0
43312  #define winDlError 0
43313  #define winDlSym   0
43314  #define winDlClose 0
43315#endif
43316
43317/* State information for the randomness gatherer. */
43318typedef struct EntropyGatherer EntropyGatherer;
43319struct EntropyGatherer {
43320  unsigned char *a;   /* Gather entropy into this buffer */
43321  int na;             /* Size of a[] in bytes */
43322  int i;              /* XOR next input into a[i] */
43323  int nXor;           /* Number of XOR operations done */
43324};
43325
43326#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
43327/* Mix sz bytes of entropy into p. */
43328static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
43329  int j, k;
43330  for(j=0, k=p->i; j<sz; j++){
43331    p->a[k++] ^= x[j];
43332    if( k>=p->na ) k = 0;
43333  }
43334  p->i = k;
43335  p->nXor += sz;
43336}
43337#endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
43338
43339/*
43340** Write up to nBuf bytes of randomness into zBuf.
43341*/
43342static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
43343#if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
43344  UNUSED_PARAMETER(pVfs);
43345  memset(zBuf, 0, nBuf);
43346  return nBuf;
43347#else
43348  EntropyGatherer e;
43349  UNUSED_PARAMETER(pVfs);
43350  memset(zBuf, 0, nBuf);
43351#if defined(_MSC_VER) && _MSC_VER>=1400 && !SQLITE_OS_WINCE
43352  rand_s((unsigned int*)zBuf); /* rand_s() is not available with MinGW */
43353#endif /* defined(_MSC_VER) && _MSC_VER>=1400 */
43354  e.a = (unsigned char*)zBuf;
43355  e.na = nBuf;
43356  e.nXor = 0;
43357  e.i = 0;
43358  {
43359    SYSTEMTIME x;
43360    osGetSystemTime(&x);
43361    xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
43362  }
43363  {
43364    DWORD pid = osGetCurrentProcessId();
43365    xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
43366  }
43367#if SQLITE_OS_WINRT
43368  {
43369    ULONGLONG cnt = osGetTickCount64();
43370    xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
43371  }
43372#else
43373  {
43374    DWORD cnt = osGetTickCount();
43375    xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
43376  }
43377#endif /* SQLITE_OS_WINRT */
43378  {
43379    LARGE_INTEGER i;
43380    osQueryPerformanceCounter(&i);
43381    xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
43382  }
43383#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
43384  {
43385    UUID id;
43386    memset(&id, 0, sizeof(UUID));
43387    osUuidCreate(&id);
43388    xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
43389    memset(&id, 0, sizeof(UUID));
43390    osUuidCreateSequential(&id);
43391    xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
43392  }
43393#endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
43394  return e.nXor>nBuf ? nBuf : e.nXor;
43395#endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
43396}
43397
43398
43399/*
43400** Sleep for a little while.  Return the amount of time slept.
43401*/
43402static int winSleep(sqlite3_vfs *pVfs, int microsec){
43403  sqlite3_win32_sleep((microsec+999)/1000);
43404  UNUSED_PARAMETER(pVfs);
43405  return ((microsec+999)/1000)*1000;
43406}
43407
43408/*
43409** The following variable, if set to a non-zero value, is interpreted as
43410** the number of seconds since 1970 and is used to set the result of
43411** sqlite3OsCurrentTime() during testing.
43412*/
43413#ifdef SQLITE_TEST
43414SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
43415#endif
43416
43417/*
43418** Find the current time (in Universal Coordinated Time).  Write into *piNow
43419** the current time and date as a Julian Day number times 86_400_000.  In
43420** other words, write into *piNow the number of milliseconds since the Julian
43421** epoch of noon in Greenwich on November 24, 4714 B.C according to the
43422** proleptic Gregorian calendar.
43423**
43424** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
43425** cannot be found.
43426*/
43427static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
43428  /* FILETIME structure is a 64-bit value representing the number of
43429     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
43430  */
43431  FILETIME ft;
43432  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
43433#ifdef SQLITE_TEST
43434  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
43435#endif
43436  /* 2^32 - to avoid use of LL and warnings in gcc */
43437  static const sqlite3_int64 max32BitValue =
43438      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
43439      (sqlite3_int64)294967296;
43440
43441#if SQLITE_OS_WINCE
43442  SYSTEMTIME time;
43443  osGetSystemTime(&time);
43444  /* if SystemTimeToFileTime() fails, it returns zero. */
43445  if (!osSystemTimeToFileTime(&time,&ft)){
43446    return SQLITE_ERROR;
43447  }
43448#else
43449  osGetSystemTimeAsFileTime( &ft );
43450#endif
43451
43452  *piNow = winFiletimeEpoch +
43453            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
43454               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
43455
43456#ifdef SQLITE_TEST
43457  if( sqlite3_current_time ){
43458    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
43459  }
43460#endif
43461  UNUSED_PARAMETER(pVfs);
43462  return SQLITE_OK;
43463}
43464
43465/*
43466** Find the current time (in Universal Coordinated Time).  Write the
43467** current time and date as a Julian Day number into *prNow and
43468** return 0.  Return 1 if the time and date cannot be found.
43469*/
43470static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
43471  int rc;
43472  sqlite3_int64 i;
43473  rc = winCurrentTimeInt64(pVfs, &i);
43474  if( !rc ){
43475    *prNow = i/86400000.0;
43476  }
43477  return rc;
43478}
43479
43480/*
43481** The idea is that this function works like a combination of
43482** GetLastError() and FormatMessage() on Windows (or errno and
43483** strerror_r() on Unix). After an error is returned by an OS
43484** function, SQLite calls this function with zBuf pointing to
43485** a buffer of nBuf bytes. The OS layer should populate the
43486** buffer with a nul-terminated UTF-8 encoded error message
43487** describing the last IO error to have occurred within the calling
43488** thread.
43489**
43490** If the error message is too large for the supplied buffer,
43491** it should be truncated. The return value of xGetLastError
43492** is zero if the error message fits in the buffer, or non-zero
43493** otherwise (if the message was truncated). If non-zero is returned,
43494** then it is not necessary to include the nul-terminator character
43495** in the output buffer.
43496**
43497** Not supplying an error message will have no adverse effect
43498** on SQLite. It is fine to have an implementation that never
43499** returns an error message:
43500**
43501**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
43502**     assert(zBuf[0]=='\0');
43503**     return 0;
43504**   }
43505**
43506** However if an error message is supplied, it will be incorporated
43507** by sqlite into the error message available to the user using
43508** sqlite3_errmsg(), possibly making IO errors easier to debug.
43509*/
43510static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
43511  DWORD e = osGetLastError();
43512  UNUSED_PARAMETER(pVfs);
43513  if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
43514  return e;
43515}
43516
43517/*
43518** Initialize and deinitialize the operating system interface.
43519*/
43520SQLITE_API int sqlite3_os_init(void){
43521  static sqlite3_vfs winVfs = {
43522    3,                     /* iVersion */
43523    sizeof(winFile),       /* szOsFile */
43524    SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
43525    0,                     /* pNext */
43526    "win32",               /* zName */
43527    &winAppData,           /* pAppData */
43528    winOpen,               /* xOpen */
43529    winDelete,             /* xDelete */
43530    winAccess,             /* xAccess */
43531    winFullPathname,       /* xFullPathname */
43532    winDlOpen,             /* xDlOpen */
43533    winDlError,            /* xDlError */
43534    winDlSym,              /* xDlSym */
43535    winDlClose,            /* xDlClose */
43536    winRandomness,         /* xRandomness */
43537    winSleep,              /* xSleep */
43538    winCurrentTime,        /* xCurrentTime */
43539    winGetLastError,       /* xGetLastError */
43540    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
43541    winSetSystemCall,      /* xSetSystemCall */
43542    winGetSystemCall,      /* xGetSystemCall */
43543    winNextSystemCall,     /* xNextSystemCall */
43544  };
43545#if defined(SQLITE_WIN32_HAS_WIDE)
43546  static sqlite3_vfs winLongPathVfs = {
43547    3,                     /* iVersion */
43548    sizeof(winFile),       /* szOsFile */
43549    SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
43550    0,                     /* pNext */
43551    "win32-longpath",      /* zName */
43552    &winAppData,           /* pAppData */
43553    winOpen,               /* xOpen */
43554    winDelete,             /* xDelete */
43555    winAccess,             /* xAccess */
43556    winFullPathname,       /* xFullPathname */
43557    winDlOpen,             /* xDlOpen */
43558    winDlError,            /* xDlError */
43559    winDlSym,              /* xDlSym */
43560    winDlClose,            /* xDlClose */
43561    winRandomness,         /* xRandomness */
43562    winSleep,              /* xSleep */
43563    winCurrentTime,        /* xCurrentTime */
43564    winGetLastError,       /* xGetLastError */
43565    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
43566    winSetSystemCall,      /* xSetSystemCall */
43567    winGetSystemCall,      /* xGetSystemCall */
43568    winNextSystemCall,     /* xNextSystemCall */
43569  };
43570#endif
43571  static sqlite3_vfs winNolockVfs = {
43572    3,                     /* iVersion */
43573    sizeof(winFile),       /* szOsFile */
43574    SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
43575    0,                     /* pNext */
43576    "win32-none",          /* zName */
43577    &winNolockAppData,     /* pAppData */
43578    winOpen,               /* xOpen */
43579    winDelete,             /* xDelete */
43580    winAccess,             /* xAccess */
43581    winFullPathname,       /* xFullPathname */
43582    winDlOpen,             /* xDlOpen */
43583    winDlError,            /* xDlError */
43584    winDlSym,              /* xDlSym */
43585    winDlClose,            /* xDlClose */
43586    winRandomness,         /* xRandomness */
43587    winSleep,              /* xSleep */
43588    winCurrentTime,        /* xCurrentTime */
43589    winGetLastError,       /* xGetLastError */
43590    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
43591    winSetSystemCall,      /* xSetSystemCall */
43592    winGetSystemCall,      /* xGetSystemCall */
43593    winNextSystemCall,     /* xNextSystemCall */
43594  };
43595#if defined(SQLITE_WIN32_HAS_WIDE)
43596  static sqlite3_vfs winLongPathNolockVfs = {
43597    3,                     /* iVersion */
43598    sizeof(winFile),       /* szOsFile */
43599    SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
43600    0,                     /* pNext */
43601    "win32-longpath-none", /* zName */
43602    &winNolockAppData,     /* pAppData */
43603    winOpen,               /* xOpen */
43604    winDelete,             /* xDelete */
43605    winAccess,             /* xAccess */
43606    winFullPathname,       /* xFullPathname */
43607    winDlOpen,             /* xDlOpen */
43608    winDlError,            /* xDlError */
43609    winDlSym,              /* xDlSym */
43610    winDlClose,            /* xDlClose */
43611    winRandomness,         /* xRandomness */
43612    winSleep,              /* xSleep */
43613    winCurrentTime,        /* xCurrentTime */
43614    winGetLastError,       /* xGetLastError */
43615    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
43616    winSetSystemCall,      /* xSetSystemCall */
43617    winGetSystemCall,      /* xGetSystemCall */
43618    winNextSystemCall,     /* xNextSystemCall */
43619  };
43620#endif
43621
43622  /* Double-check that the aSyscall[] array has been constructed
43623  ** correctly.  See ticket [bb3a86e890c8e96ab] */
43624  assert( ArraySize(aSyscall)==80 );
43625
43626  /* get memory map allocation granularity */
43627  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
43628#if SQLITE_OS_WINRT
43629  osGetNativeSystemInfo(&winSysInfo);
43630#else
43631  osGetSystemInfo(&winSysInfo);
43632#endif
43633  assert( winSysInfo.dwAllocationGranularity>0 );
43634  assert( winSysInfo.dwPageSize>0 );
43635
43636  sqlite3_vfs_register(&winVfs, 1);
43637
43638#if defined(SQLITE_WIN32_HAS_WIDE)
43639  sqlite3_vfs_register(&winLongPathVfs, 0);
43640#endif
43641
43642  sqlite3_vfs_register(&winNolockVfs, 0);
43643
43644#if defined(SQLITE_WIN32_HAS_WIDE)
43645  sqlite3_vfs_register(&winLongPathNolockVfs, 0);
43646#endif
43647
43648  return SQLITE_OK;
43649}
43650
43651SQLITE_API int sqlite3_os_end(void){
43652#if SQLITE_OS_WINRT
43653  if( sleepObj!=NULL ){
43654    osCloseHandle(sleepObj);
43655    sleepObj = NULL;
43656  }
43657#endif
43658  return SQLITE_OK;
43659}
43660
43661#endif /* SQLITE_OS_WIN */
43662
43663/************** End of os_win.c **********************************************/
43664/************** Begin file bitvec.c ******************************************/
43665/*
43666** 2008 February 16
43667**
43668** The author disclaims copyright to this source code.  In place of
43669** a legal notice, here is a blessing:
43670**
43671**    May you do good and not evil.
43672**    May you find forgiveness for yourself and forgive others.
43673**    May you share freely, never taking more than you give.
43674**
43675*************************************************************************
43676** This file implements an object that represents a fixed-length
43677** bitmap.  Bits are numbered starting with 1.
43678**
43679** A bitmap is used to record which pages of a database file have been
43680** journalled during a transaction, or which pages have the "dont-write"
43681** property.  Usually only a few pages are meet either condition.
43682** So the bitmap is usually sparse and has low cardinality.
43683** But sometimes (for example when during a DROP of a large table) most
43684** or all of the pages in a database can get journalled.  In those cases,
43685** the bitmap becomes dense with high cardinality.  The algorithm needs
43686** to handle both cases well.
43687**
43688** The size of the bitmap is fixed when the object is created.
43689**
43690** All bits are clear when the bitmap is created.  Individual bits
43691** may be set or cleared one at a time.
43692**
43693** Test operations are about 100 times more common that set operations.
43694** Clear operations are exceedingly rare.  There are usually between
43695** 5 and 500 set operations per Bitvec object, though the number of sets can
43696** sometimes grow into tens of thousands or larger.  The size of the
43697** Bitvec object is the number of pages in the database file at the
43698** start of a transaction, and is thus usually less than a few thousand,
43699** but can be as large as 2 billion for a really big database.
43700*/
43701/* #include "sqliteInt.h" */
43702
43703/* Size of the Bitvec structure in bytes. */
43704#define BITVEC_SZ        512
43705
43706/* Round the union size down to the nearest pointer boundary, since that's how
43707** it will be aligned within the Bitvec struct. */
43708#define BITVEC_USIZE \
43709    (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
43710
43711/* Type of the array "element" for the bitmap representation.
43712** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
43713** Setting this to the "natural word" size of your CPU may improve
43714** performance. */
43715#define BITVEC_TELEM     u8
43716/* Size, in bits, of the bitmap element. */
43717#define BITVEC_SZELEM    8
43718/* Number of elements in a bitmap array. */
43719#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
43720/* Number of bits in the bitmap array. */
43721#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
43722
43723/* Number of u32 values in hash table. */
43724#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
43725/* Maximum number of entries in hash table before
43726** sub-dividing and re-hashing. */
43727#define BITVEC_MXHASH    (BITVEC_NINT/2)
43728/* Hashing function for the aHash representation.
43729** Empirical testing showed that the *37 multiplier
43730** (an arbitrary prime)in the hash function provided
43731** no fewer collisions than the no-op *1. */
43732#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
43733
43734#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
43735
43736
43737/*
43738** A bitmap is an instance of the following structure.
43739**
43740** This bitmap records the existence of zero or more bits
43741** with values between 1 and iSize, inclusive.
43742**
43743** There are three possible representations of the bitmap.
43744** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
43745** bitmap.  The least significant bit is bit 1.
43746**
43747** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
43748** a hash table that will hold up to BITVEC_MXHASH distinct values.
43749**
43750** Otherwise, the value i is redirected into one of BITVEC_NPTR
43751** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
43752** handles up to iDivisor separate values of i.  apSub[0] holds
43753** values between 1 and iDivisor.  apSub[1] holds values between
43754** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
43755** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
43756** to hold deal with values between 1 and iDivisor.
43757*/
43758struct Bitvec {
43759  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
43760  u32 nSet;       /* Number of bits that are set - only valid for aHash
43761                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
43762                  ** this would be 125. */
43763  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
43764                  /* Should >=0 for apSub element. */
43765                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
43766                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
43767  union {
43768    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
43769    u32 aHash[BITVEC_NINT];      /* Hash table representation */
43770    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
43771  } u;
43772};
43773
43774/*
43775** Create a new bitmap object able to handle bits between 0 and iSize,
43776** inclusive.  Return a pointer to the new object.  Return NULL if
43777** malloc fails.
43778*/
43779SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
43780  Bitvec *p;
43781  assert( sizeof(*p)==BITVEC_SZ );
43782  p = sqlite3MallocZero( sizeof(*p) );
43783  if( p ){
43784    p->iSize = iSize;
43785  }
43786  return p;
43787}
43788
43789/*
43790** Check to see if the i-th bit is set.  Return true or false.
43791** If p is NULL (if the bitmap has not been created) or if
43792** i is out of range, then return false.
43793*/
43794SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
43795  assert( p!=0 );
43796  i--;
43797  if( i>=p->iSize ) return 0;
43798  while( p->iDivisor ){
43799    u32 bin = i/p->iDivisor;
43800    i = i%p->iDivisor;
43801    p = p->u.apSub[bin];
43802    if (!p) {
43803      return 0;
43804    }
43805  }
43806  if( p->iSize<=BITVEC_NBIT ){
43807    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
43808  } else{
43809    u32 h = BITVEC_HASH(i++);
43810    while( p->u.aHash[h] ){
43811      if( p->u.aHash[h]==i ) return 1;
43812      h = (h+1) % BITVEC_NINT;
43813    }
43814    return 0;
43815  }
43816}
43817SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
43818  return p!=0 && sqlite3BitvecTestNotNull(p,i);
43819}
43820
43821/*
43822** Set the i-th bit.  Return 0 on success and an error code if
43823** anything goes wrong.
43824**
43825** This routine might cause sub-bitmaps to be allocated.  Failing
43826** to get the memory needed to hold the sub-bitmap is the only
43827** that can go wrong with an insert, assuming p and i are valid.
43828**
43829** The calling function must ensure that p is a valid Bitvec object
43830** and that the value for "i" is within range of the Bitvec object.
43831** Otherwise the behavior is undefined.
43832*/
43833SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
43834  u32 h;
43835  if( p==0 ) return SQLITE_OK;
43836  assert( i>0 );
43837  assert( i<=p->iSize );
43838  i--;
43839  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
43840    u32 bin = i/p->iDivisor;
43841    i = i%p->iDivisor;
43842    if( p->u.apSub[bin]==0 ){
43843      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
43844      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
43845    }
43846    p = p->u.apSub[bin];
43847  }
43848  if( p->iSize<=BITVEC_NBIT ){
43849    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
43850    return SQLITE_OK;
43851  }
43852  h = BITVEC_HASH(i++);
43853  /* if there wasn't a hash collision, and this doesn't */
43854  /* completely fill the hash, then just add it without */
43855  /* worring about sub-dividing and re-hashing. */
43856  if( !p->u.aHash[h] ){
43857    if (p->nSet<(BITVEC_NINT-1)) {
43858      goto bitvec_set_end;
43859    } else {
43860      goto bitvec_set_rehash;
43861    }
43862  }
43863  /* there was a collision, check to see if it's already */
43864  /* in hash, if not, try to find a spot for it */
43865  do {
43866    if( p->u.aHash[h]==i ) return SQLITE_OK;
43867    h++;
43868    if( h>=BITVEC_NINT ) h = 0;
43869  } while( p->u.aHash[h] );
43870  /* we didn't find it in the hash.  h points to the first */
43871  /* available free spot. check to see if this is going to */
43872  /* make our hash too "full".  */
43873bitvec_set_rehash:
43874  if( p->nSet>=BITVEC_MXHASH ){
43875    unsigned int j;
43876    int rc;
43877    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
43878    if( aiValues==0 ){
43879      return SQLITE_NOMEM_BKPT;
43880    }else{
43881      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
43882      memset(p->u.apSub, 0, sizeof(p->u.apSub));
43883      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
43884      rc = sqlite3BitvecSet(p, i);
43885      for(j=0; j<BITVEC_NINT; j++){
43886        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
43887      }
43888      sqlite3StackFree(0, aiValues);
43889      return rc;
43890    }
43891  }
43892bitvec_set_end:
43893  p->nSet++;
43894  p->u.aHash[h] = i;
43895  return SQLITE_OK;
43896}
43897
43898/*
43899** Clear the i-th bit.
43900**
43901** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
43902** that BitvecClear can use to rebuilt its hash table.
43903*/
43904SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
43905  if( p==0 ) return;
43906  assert( i>0 );
43907  i--;
43908  while( p->iDivisor ){
43909    u32 bin = i/p->iDivisor;
43910    i = i%p->iDivisor;
43911    p = p->u.apSub[bin];
43912    if (!p) {
43913      return;
43914    }
43915  }
43916  if( p->iSize<=BITVEC_NBIT ){
43917    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
43918  }else{
43919    unsigned int j;
43920    u32 *aiValues = pBuf;
43921    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
43922    memset(p->u.aHash, 0, sizeof(p->u.aHash));
43923    p->nSet = 0;
43924    for(j=0; j<BITVEC_NINT; j++){
43925      if( aiValues[j] && aiValues[j]!=(i+1) ){
43926        u32 h = BITVEC_HASH(aiValues[j]-1);
43927        p->nSet++;
43928        while( p->u.aHash[h] ){
43929          h++;
43930          if( h>=BITVEC_NINT ) h = 0;
43931        }
43932        p->u.aHash[h] = aiValues[j];
43933      }
43934    }
43935  }
43936}
43937
43938/*
43939** Destroy a bitmap object.  Reclaim all memory used.
43940*/
43941SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
43942  if( p==0 ) return;
43943  if( p->iDivisor ){
43944    unsigned int i;
43945    for(i=0; i<BITVEC_NPTR; i++){
43946      sqlite3BitvecDestroy(p->u.apSub[i]);
43947    }
43948  }
43949  sqlite3_free(p);
43950}
43951
43952/*
43953** Return the value of the iSize parameter specified when Bitvec *p
43954** was created.
43955*/
43956SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
43957  return p->iSize;
43958}
43959
43960#ifndef SQLITE_UNTESTABLE
43961/*
43962** Let V[] be an array of unsigned characters sufficient to hold
43963** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
43964** Then the following macros can be used to set, clear, or test
43965** individual bits within V.
43966*/
43967#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
43968#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
43969#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
43970
43971/*
43972** This routine runs an extensive test of the Bitvec code.
43973**
43974** The input is an array of integers that acts as a program
43975** to test the Bitvec.  The integers are opcodes followed
43976** by 0, 1, or 3 operands, depending on the opcode.  Another
43977** opcode follows immediately after the last operand.
43978**
43979** There are 6 opcodes numbered from 0 through 5.  0 is the
43980** "halt" opcode and causes the test to end.
43981**
43982**    0          Halt and return the number of errors
43983**    1 N S X    Set N bits beginning with S and incrementing by X
43984**    2 N S X    Clear N bits beginning with S and incrementing by X
43985**    3 N        Set N randomly chosen bits
43986**    4 N        Clear N randomly chosen bits
43987**    5 N S X    Set N bits from S increment X in array only, not in bitvec
43988**
43989** The opcodes 1 through 4 perform set and clear operations are performed
43990** on both a Bitvec object and on a linear array of bits obtained from malloc.
43991** Opcode 5 works on the linear array only, not on the Bitvec.
43992** Opcode 5 is used to deliberately induce a fault in order to
43993** confirm that error detection works.
43994**
43995** At the conclusion of the test the linear array is compared
43996** against the Bitvec object.  If there are any differences,
43997** an error is returned.  If they are the same, zero is returned.
43998**
43999** If a memory allocation error occurs, return -1.
44000*/
44001SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
44002  Bitvec *pBitvec = 0;
44003  unsigned char *pV = 0;
44004  int rc = -1;
44005  int i, nx, pc, op;
44006  void *pTmpSpace;
44007
44008  /* Allocate the Bitvec to be tested and a linear array of
44009  ** bits to act as the reference */
44010  pBitvec = sqlite3BitvecCreate( sz );
44011  pV = sqlite3MallocZero( (sz+7)/8 + 1 );
44012  pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
44013  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
44014
44015  /* NULL pBitvec tests */
44016  sqlite3BitvecSet(0, 1);
44017  sqlite3BitvecClear(0, 1, pTmpSpace);
44018
44019  /* Run the program */
44020  pc = 0;
44021  while( (op = aOp[pc])!=0 ){
44022    switch( op ){
44023      case 1:
44024      case 2:
44025      case 5: {
44026        nx = 4;
44027        i = aOp[pc+2] - 1;
44028        aOp[pc+2] += aOp[pc+3];
44029        break;
44030      }
44031      case 3:
44032      case 4:
44033      default: {
44034        nx = 2;
44035        sqlite3_randomness(sizeof(i), &i);
44036        break;
44037      }
44038    }
44039    if( (--aOp[pc+1]) > 0 ) nx = 0;
44040    pc += nx;
44041    i = (i & 0x7fffffff)%sz;
44042    if( (op & 1)!=0 ){
44043      SETBIT(pV, (i+1));
44044      if( op!=5 ){
44045        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
44046      }
44047    }else{
44048      CLEARBIT(pV, (i+1));
44049      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
44050    }
44051  }
44052
44053  /* Test to make sure the linear array exactly matches the
44054  ** Bitvec object.  Start with the assumption that they do
44055  ** match (rc==0).  Change rc to non-zero if a discrepancy
44056  ** is found.
44057  */
44058  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
44059          + sqlite3BitvecTest(pBitvec, 0)
44060          + (sqlite3BitvecSize(pBitvec) - sz);
44061  for(i=1; i<=sz; i++){
44062    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
44063      rc = i;
44064      break;
44065    }
44066  }
44067
44068  /* Free allocated structure */
44069bitvec_end:
44070  sqlite3_free(pTmpSpace);
44071  sqlite3_free(pV);
44072  sqlite3BitvecDestroy(pBitvec);
44073  return rc;
44074}
44075#endif /* SQLITE_UNTESTABLE */
44076
44077/************** End of bitvec.c **********************************************/
44078/************** Begin file pcache.c ******************************************/
44079/*
44080** 2008 August 05
44081**
44082** The author disclaims copyright to this source code.  In place of
44083** a legal notice, here is a blessing:
44084**
44085**    May you do good and not evil.
44086**    May you find forgiveness for yourself and forgive others.
44087**    May you share freely, never taking more than you give.
44088**
44089*************************************************************************
44090** This file implements that page cache.
44091*/
44092/* #include "sqliteInt.h" */
44093
44094/*
44095** A complete page cache is an instance of this structure.  Every
44096** entry in the cache holds a single page of the database file.  The
44097** btree layer only operates on the cached copy of the database pages.
44098**
44099** A page cache entry is "clean" if it exactly matches what is currently
44100** on disk.  A page is "dirty" if it has been modified and needs to be
44101** persisted to disk.
44102**
44103** pDirty, pDirtyTail, pSynced:
44104**   All dirty pages are linked into the doubly linked list using
44105**   PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
44106**   such that p was added to the list more recently than p->pDirtyNext.
44107**   PCache.pDirty points to the first (newest) element in the list and
44108**   pDirtyTail to the last (oldest).
44109**
44110**   The PCache.pSynced variable is used to optimize searching for a dirty
44111**   page to eject from the cache mid-transaction. It is better to eject
44112**   a page that does not require a journal sync than one that does.
44113**   Therefore, pSynced is maintained to that it *almost* always points
44114**   to either the oldest page in the pDirty/pDirtyTail list that has a
44115**   clear PGHDR_NEED_SYNC flag or to a page that is older than this one
44116**   (so that the right page to eject can be found by following pDirtyPrev
44117**   pointers).
44118*/
44119struct PCache {
44120  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
44121  PgHdr *pSynced;                     /* Last synced page in dirty page list */
44122  int nRefSum;                        /* Sum of ref counts over all pages */
44123  int szCache;                        /* Configured cache size */
44124  int szSpill;                        /* Size before spilling occurs */
44125  int szPage;                         /* Size of every page in this cache */
44126  int szExtra;                        /* Size of extra space for each page */
44127  u8 bPurgeable;                      /* True if pages are on backing store */
44128  u8 eCreate;                         /* eCreate value for for xFetch() */
44129  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
44130  void *pStress;                      /* Argument to xStress */
44131  sqlite3_pcache *pCache;             /* Pluggable cache module */
44132};
44133
44134/********************************** Test and Debug Logic **********************/
44135/*
44136** Debug tracing macros.  Enable by by changing the "0" to "1" and
44137** recompiling.
44138**
44139** When sqlite3PcacheTrace is 1, single line trace messages are issued.
44140** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
44141** is displayed for many operations, resulting in a lot of output.
44142*/
44143#if defined(SQLITE_DEBUG) && 0
44144  int sqlite3PcacheTrace = 2;       /* 0: off  1: simple  2: cache dumps */
44145  int sqlite3PcacheMxDump = 9999;   /* Max cache entries for pcacheDump() */
44146# define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
44147  void pcacheDump(PCache *pCache){
44148    int N;
44149    int i, j;
44150    sqlite3_pcache_page *pLower;
44151    PgHdr *pPg;
44152    unsigned char *a;
44153
44154    if( sqlite3PcacheTrace<2 ) return;
44155    if( pCache->pCache==0 ) return;
44156    N = sqlite3PcachePagecount(pCache);
44157    if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
44158    for(i=1; i<=N; i++){
44159       pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
44160       if( pLower==0 ) continue;
44161       pPg = (PgHdr*)pLower->pExtra;
44162       printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
44163       a = (unsigned char *)pLower->pBuf;
44164       for(j=0; j<12; j++) printf("%02x", a[j]);
44165       printf("\n");
44166       if( pPg->pPage==0 ){
44167         sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
44168       }
44169    }
44170  }
44171  #else
44172# define pcacheTrace(X)
44173# define pcacheDump(X)
44174#endif
44175
44176/*
44177** Check invariants on a PgHdr entry.  Return true if everything is OK.
44178** Return false if any invariant is violated.
44179**
44180** This routine is for use inside of assert() statements only.  For
44181** example:
44182**
44183**          assert( sqlite3PcachePageSanity(pPg) );
44184*/
44185#ifdef SQLITE_DEBUG
44186SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
44187  PCache *pCache;
44188  assert( pPg!=0 );
44189  assert( pPg->pgno>0 || pPg->pPager==0 );    /* Page number is 1 or more */
44190  pCache = pPg->pCache;
44191  assert( pCache!=0 );      /* Every page has an associated PCache */
44192  if( pPg->flags & PGHDR_CLEAN ){
44193    assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
44194    assert( pCache->pDirty!=pPg );          /* CLEAN pages not on dirty list */
44195    assert( pCache->pDirtyTail!=pPg );
44196  }
44197  /* WRITEABLE pages must also be DIRTY */
44198  if( pPg->flags & PGHDR_WRITEABLE ){
44199    assert( pPg->flags & PGHDR_DIRTY );     /* WRITEABLE implies DIRTY */
44200  }
44201  /* NEED_SYNC can be set independently of WRITEABLE.  This can happen,
44202  ** for example, when using the sqlite3PagerDontWrite() optimization:
44203  **    (1)  Page X is journalled, and gets WRITEABLE and NEED_SEEK.
44204  **    (2)  Page X moved to freelist, WRITEABLE is cleared
44205  **    (3)  Page X reused, WRITEABLE is set again
44206  ** If NEED_SYNC had been cleared in step 2, then it would not be reset
44207  ** in step 3, and page might be written into the database without first
44208  ** syncing the rollback journal, which might cause corruption on a power
44209  ** loss.
44210  **
44211  ** Another example is when the database page size is smaller than the
44212  ** disk sector size.  When any page of a sector is journalled, all pages
44213  ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
44214  ** in case they are later modified, since all pages in the same sector
44215  ** must be journalled and synced before any of those pages can be safely
44216  ** written.
44217  */
44218  return 1;
44219}
44220#endif /* SQLITE_DEBUG */
44221
44222
44223/********************************** Linked List Management ********************/
44224
44225/* Allowed values for second argument to pcacheManageDirtyList() */
44226#define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
44227#define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
44228#define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
44229
44230/*
44231** Manage pPage's participation on the dirty list.  Bits of the addRemove
44232** argument determines what operation to do.  The 0x01 bit means first
44233** remove pPage from the dirty list.  The 0x02 means add pPage back to
44234** the dirty list.  Doing both moves pPage to the front of the dirty list.
44235*/
44236static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
44237  PCache *p = pPage->pCache;
44238
44239  pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
44240                addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
44241                pPage->pgno));
44242  if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
44243    assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
44244    assert( pPage->pDirtyPrev || pPage==p->pDirty );
44245
44246    /* Update the PCache1.pSynced variable if necessary. */
44247    if( p->pSynced==pPage ){
44248      p->pSynced = pPage->pDirtyPrev;
44249    }
44250
44251    if( pPage->pDirtyNext ){
44252      pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
44253    }else{
44254      assert( pPage==p->pDirtyTail );
44255      p->pDirtyTail = pPage->pDirtyPrev;
44256    }
44257    if( pPage->pDirtyPrev ){
44258      pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
44259    }else{
44260      /* If there are now no dirty pages in the cache, set eCreate to 2.
44261      ** This is an optimization that allows sqlite3PcacheFetch() to skip
44262      ** searching for a dirty page to eject from the cache when it might
44263      ** otherwise have to.  */
44264      assert( pPage==p->pDirty );
44265      p->pDirty = pPage->pDirtyNext;
44266      assert( p->bPurgeable || p->eCreate==2 );
44267      if( p->pDirty==0 ){         /*OPTIMIZATION-IF-TRUE*/
44268        assert( p->bPurgeable==0 || p->eCreate==1 );
44269        p->eCreate = 2;
44270      }
44271    }
44272    pPage->pDirtyNext = 0;
44273    pPage->pDirtyPrev = 0;
44274  }
44275  if( addRemove & PCACHE_DIRTYLIST_ADD ){
44276    assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
44277
44278    pPage->pDirtyNext = p->pDirty;
44279    if( pPage->pDirtyNext ){
44280      assert( pPage->pDirtyNext->pDirtyPrev==0 );
44281      pPage->pDirtyNext->pDirtyPrev = pPage;
44282    }else{
44283      p->pDirtyTail = pPage;
44284      if( p->bPurgeable ){
44285        assert( p->eCreate==2 );
44286        p->eCreate = 1;
44287      }
44288    }
44289    p->pDirty = pPage;
44290
44291    /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
44292    ** pSynced to point to it. Checking the NEED_SYNC flag is an
44293    ** optimization, as if pSynced points to a page with the NEED_SYNC
44294    ** flag set sqlite3PcacheFetchStress() searches through all newer
44295    ** entries of the dirty-list for a page with NEED_SYNC clear anyway.  */
44296    if( !p->pSynced
44297     && 0==(pPage->flags&PGHDR_NEED_SYNC)   /*OPTIMIZATION-IF-FALSE*/
44298    ){
44299      p->pSynced = pPage;
44300    }
44301  }
44302  pcacheDump(p);
44303}
44304
44305/*
44306** Wrapper around the pluggable caches xUnpin method. If the cache is
44307** being used for an in-memory database, this function is a no-op.
44308*/
44309static void pcacheUnpin(PgHdr *p){
44310  if( p->pCache->bPurgeable ){
44311    pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
44312    sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
44313    pcacheDump(p->pCache);
44314  }
44315}
44316
44317/*
44318** Compute the number of pages of cache requested.   p->szCache is the
44319** cache size requested by the "PRAGMA cache_size" statement.
44320*/
44321static int numberOfCachePages(PCache *p){
44322  if( p->szCache>=0 ){
44323    /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
44324    ** suggested cache size is set to N. */
44325    return p->szCache;
44326  }else{
44327    /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
44328    ** the number of cache pages is adjusted to use approximately abs(N*1024)
44329    ** bytes of memory. */
44330    return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
44331  }
44332}
44333
44334/*************************************************** General Interfaces ******
44335**
44336** Initialize and shutdown the page cache subsystem. Neither of these
44337** functions are threadsafe.
44338*/
44339SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
44340  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
44341    /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
44342    ** built-in default page cache is used instead of the application defined
44343    ** page cache. */
44344    sqlite3PCacheSetDefault();
44345  }
44346  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
44347}
44348SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
44349  if( sqlite3GlobalConfig.pcache2.xShutdown ){
44350    /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
44351    sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
44352  }
44353}
44354
44355/*
44356** Return the size in bytes of a PCache object.
44357*/
44358SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
44359
44360/*
44361** Create a new PCache object. Storage space to hold the object
44362** has already been allocated and is passed in as the p pointer.
44363** The caller discovers how much space needs to be allocated by
44364** calling sqlite3PcacheSize().
44365**
44366** szExtra is some extra space allocated for each page.  The first
44367** 8 bytes of the extra space will be zeroed as the page is allocated,
44368** but remaining content will be uninitialized.  Though it is opaque
44369** to this module, the extra space really ends up being the MemPage
44370** structure in the pager.
44371*/
44372SQLITE_PRIVATE int sqlite3PcacheOpen(
44373  int szPage,                  /* Size of every page */
44374  int szExtra,                 /* Extra space associated with each page */
44375  int bPurgeable,              /* True if pages are on backing store */
44376  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
44377  void *pStress,               /* Argument to xStress */
44378  PCache *p                    /* Preallocated space for the PCache */
44379){
44380  memset(p, 0, sizeof(PCache));
44381  p->szPage = 1;
44382  p->szExtra = szExtra;
44383  assert( szExtra>=8 );  /* First 8 bytes will be zeroed */
44384  p->bPurgeable = bPurgeable;
44385  p->eCreate = 2;
44386  p->xStress = xStress;
44387  p->pStress = pStress;
44388  p->szCache = 100;
44389  p->szSpill = 1;
44390  pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
44391  return sqlite3PcacheSetPageSize(p, szPage);
44392}
44393
44394/*
44395** Change the page size for PCache object. The caller must ensure that there
44396** are no outstanding page references when this function is called.
44397*/
44398SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
44399  assert( pCache->nRefSum==0 && pCache->pDirty==0 );
44400  if( pCache->szPage ){
44401    sqlite3_pcache *pNew;
44402    pNew = sqlite3GlobalConfig.pcache2.xCreate(
44403                szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
44404                pCache->bPurgeable
44405    );
44406    if( pNew==0 ) return SQLITE_NOMEM_BKPT;
44407    sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
44408    if( pCache->pCache ){
44409      sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
44410    }
44411    pCache->pCache = pNew;
44412    pCache->szPage = szPage;
44413    pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
44414  }
44415  return SQLITE_OK;
44416}
44417
44418/*
44419** Try to obtain a page from the cache.
44420**
44421** This routine returns a pointer to an sqlite3_pcache_page object if
44422** such an object is already in cache, or if a new one is created.
44423** This routine returns a NULL pointer if the object was not in cache
44424** and could not be created.
44425**
44426** The createFlags should be 0 to check for existing pages and should
44427** be 3 (not 1, but 3) to try to create a new page.
44428**
44429** If the createFlag is 0, then NULL is always returned if the page
44430** is not already in the cache.  If createFlag is 1, then a new page
44431** is created only if that can be done without spilling dirty pages
44432** and without exceeding the cache size limit.
44433**
44434** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
44435** initialize the sqlite3_pcache_page object and convert it into a
44436** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
44437** routines are split this way for performance reasons. When separated
44438** they can both (usually) operate without having to push values to
44439** the stack on entry and pop them back off on exit, which saves a
44440** lot of pushing and popping.
44441*/
44442SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
44443  PCache *pCache,       /* Obtain the page from this cache */
44444  Pgno pgno,            /* Page number to obtain */
44445  int createFlag        /* If true, create page if it does not exist already */
44446){
44447  int eCreate;
44448  sqlite3_pcache_page *pRes;
44449
44450  assert( pCache!=0 );
44451  assert( pCache->pCache!=0 );
44452  assert( createFlag==3 || createFlag==0 );
44453  assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
44454
44455  /* eCreate defines what to do if the page does not exist.
44456  **    0     Do not allocate a new page.  (createFlag==0)
44457  **    1     Allocate a new page if doing so is inexpensive.
44458  **          (createFlag==1 AND bPurgeable AND pDirty)
44459  **    2     Allocate a new page even it doing so is difficult.
44460  **          (createFlag==1 AND !(bPurgeable AND pDirty)
44461  */
44462  eCreate = createFlag & pCache->eCreate;
44463  assert( eCreate==0 || eCreate==1 || eCreate==2 );
44464  assert( createFlag==0 || pCache->eCreate==eCreate );
44465  assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
44466  pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
44467  pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
44468               createFlag?" create":"",pRes));
44469  return pRes;
44470}
44471
44472/*
44473** If the sqlite3PcacheFetch() routine is unable to allocate a new
44474** page because no clean pages are available for reuse and the cache
44475** size limit has been reached, then this routine can be invoked to
44476** try harder to allocate a page.  This routine might invoke the stress
44477** callback to spill dirty pages to the journal.  It will then try to
44478** allocate the new page and will only fail to allocate a new page on
44479** an OOM error.
44480**
44481** This routine should be invoked only after sqlite3PcacheFetch() fails.
44482*/
44483SQLITE_PRIVATE int sqlite3PcacheFetchStress(
44484  PCache *pCache,                 /* Obtain the page from this cache */
44485  Pgno pgno,                      /* Page number to obtain */
44486  sqlite3_pcache_page **ppPage    /* Write result here */
44487){
44488  PgHdr *pPg;
44489  if( pCache->eCreate==2 ) return 0;
44490
44491  if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
44492    /* Find a dirty page to write-out and recycle. First try to find a
44493    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
44494    ** cleared), but if that is not possible settle for any other
44495    ** unreferenced dirty page.
44496    **
44497    ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
44498    ** flag is currently referenced, then the following may leave pSynced
44499    ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
44500    ** cleared). This is Ok, as pSynced is just an optimization.  */
44501    for(pPg=pCache->pSynced;
44502        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
44503        pPg=pPg->pDirtyPrev
44504    );
44505    pCache->pSynced = pPg;
44506    if( !pPg ){
44507      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
44508    }
44509    if( pPg ){
44510      int rc;
44511#ifdef SQLITE_LOG_CACHE_SPILL
44512      sqlite3_log(SQLITE_FULL,
44513                  "spill page %d making room for %d - cache used: %d/%d",
44514                  pPg->pgno, pgno,
44515                  sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
44516                numberOfCachePages(pCache));
44517#endif
44518      pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
44519      rc = pCache->xStress(pCache->pStress, pPg);
44520      pcacheDump(pCache);
44521      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
44522        return rc;
44523      }
44524    }
44525  }
44526  *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
44527  return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
44528}
44529
44530/*
44531** This is a helper routine for sqlite3PcacheFetchFinish()
44532**
44533** In the uncommon case where the page being fetched has not been
44534** initialized, this routine is invoked to do the initialization.
44535** This routine is broken out into a separate function since it
44536** requires extra stack manipulation that can be avoided in the common
44537** case.
44538*/
44539static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
44540  PCache *pCache,             /* Obtain the page from this cache */
44541  Pgno pgno,                  /* Page number obtained */
44542  sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
44543){
44544  PgHdr *pPgHdr;
44545  assert( pPage!=0 );
44546  pPgHdr = (PgHdr*)pPage->pExtra;
44547  assert( pPgHdr->pPage==0 );
44548  memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
44549  pPgHdr->pPage = pPage;
44550  pPgHdr->pData = pPage->pBuf;
44551  pPgHdr->pExtra = (void *)&pPgHdr[1];
44552  memset(pPgHdr->pExtra, 0, 8);
44553  pPgHdr->pCache = pCache;
44554  pPgHdr->pgno = pgno;
44555  pPgHdr->flags = PGHDR_CLEAN;
44556  return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
44557}
44558
44559/*
44560** This routine converts the sqlite3_pcache_page object returned by
44561** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
44562** must be called after sqlite3PcacheFetch() in order to get a usable
44563** result.
44564*/
44565SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
44566  PCache *pCache,             /* Obtain the page from this cache */
44567  Pgno pgno,                  /* Page number obtained */
44568  sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
44569){
44570  PgHdr *pPgHdr;
44571
44572  assert( pPage!=0 );
44573  pPgHdr = (PgHdr *)pPage->pExtra;
44574
44575  if( !pPgHdr->pPage ){
44576    return pcacheFetchFinishWithInit(pCache, pgno, pPage);
44577  }
44578  pCache->nRefSum++;
44579  pPgHdr->nRef++;
44580  assert( sqlite3PcachePageSanity(pPgHdr) );
44581  return pPgHdr;
44582}
44583
44584/*
44585** Decrement the reference count on a page. If the page is clean and the
44586** reference count drops to 0, then it is made eligible for recycling.
44587*/
44588SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
44589  assert( p->nRef>0 );
44590  p->pCache->nRefSum--;
44591  if( (--p->nRef)==0 ){
44592    if( p->flags&PGHDR_CLEAN ){
44593      pcacheUnpin(p);
44594    }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/
44595      /* Move the page to the head of the dirty list. If p->pDirtyPrev==0,
44596      ** then page p is already at the head of the dirty list and the
44597      ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE
44598      ** tag above.  */
44599      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
44600    }
44601  }
44602}
44603
44604/*
44605** Increase the reference count of a supplied page by 1.
44606*/
44607SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
44608  assert(p->nRef>0);
44609  assert( sqlite3PcachePageSanity(p) );
44610  p->nRef++;
44611  p->pCache->nRefSum++;
44612}
44613
44614/*
44615** Drop a page from the cache. There must be exactly one reference to the
44616** page. This function deletes that reference, so after it returns the
44617** page pointed to by p is invalid.
44618*/
44619SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
44620  assert( p->nRef==1 );
44621  assert( sqlite3PcachePageSanity(p) );
44622  if( p->flags&PGHDR_DIRTY ){
44623    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
44624  }
44625  p->pCache->nRefSum--;
44626  sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
44627}
44628
44629/*
44630** Make sure the page is marked as dirty. If it isn't dirty already,
44631** make it so.
44632*/
44633SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
44634  assert( p->nRef>0 );
44635  assert( sqlite3PcachePageSanity(p) );
44636  if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){    /*OPTIMIZATION-IF-FALSE*/
44637    p->flags &= ~PGHDR_DONT_WRITE;
44638    if( p->flags & PGHDR_CLEAN ){
44639      p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
44640      pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
44641      assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
44642      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
44643    }
44644    assert( sqlite3PcachePageSanity(p) );
44645  }
44646}
44647
44648/*
44649** Make sure the page is marked as clean. If it isn't clean already,
44650** make it so.
44651*/
44652SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
44653  assert( sqlite3PcachePageSanity(p) );
44654  if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
44655    assert( (p->flags & PGHDR_CLEAN)==0 );
44656    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
44657    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
44658    p->flags |= PGHDR_CLEAN;
44659    pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
44660    assert( sqlite3PcachePageSanity(p) );
44661    if( p->nRef==0 ){
44662      pcacheUnpin(p);
44663    }
44664  }
44665}
44666
44667/*
44668** Make every page in the cache clean.
44669*/
44670SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
44671  PgHdr *p;
44672  pcacheTrace(("%p.CLEAN-ALL\n",pCache));
44673  while( (p = pCache->pDirty)!=0 ){
44674    sqlite3PcacheMakeClean(p);
44675  }
44676}
44677
44678/*
44679** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
44680*/
44681SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
44682  PgHdr *p;
44683  pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
44684  for(p=pCache->pDirty; p; p=p->pDirtyNext){
44685    p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
44686  }
44687  pCache->pSynced = pCache->pDirtyTail;
44688}
44689
44690/*
44691** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
44692*/
44693SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
44694  PgHdr *p;
44695  for(p=pCache->pDirty; p; p=p->pDirtyNext){
44696    p->flags &= ~PGHDR_NEED_SYNC;
44697  }
44698  pCache->pSynced = pCache->pDirtyTail;
44699}
44700
44701/*
44702** Change the page number of page p to newPgno.
44703*/
44704SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
44705  PCache *pCache = p->pCache;
44706  assert( p->nRef>0 );
44707  assert( newPgno>0 );
44708  assert( sqlite3PcachePageSanity(p) );
44709  pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
44710  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
44711  p->pgno = newPgno;
44712  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
44713    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
44714  }
44715}
44716
44717/*
44718** Drop every cache entry whose page number is greater than "pgno". The
44719** caller must ensure that there are no outstanding references to any pages
44720** other than page 1 with a page number greater than pgno.
44721**
44722** If there is a reference to page 1 and the pgno parameter passed to this
44723** function is 0, then the data area associated with page 1 is zeroed, but
44724** the page object is not dropped.
44725*/
44726SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
44727  if( pCache->pCache ){
44728    PgHdr *p;
44729    PgHdr *pNext;
44730    pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
44731    for(p=pCache->pDirty; p; p=pNext){
44732      pNext = p->pDirtyNext;
44733      /* This routine never gets call with a positive pgno except right
44734      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
44735      ** it must be that pgno==0.
44736      */
44737      assert( p->pgno>0 );
44738      if( p->pgno>pgno ){
44739        assert( p->flags&PGHDR_DIRTY );
44740        sqlite3PcacheMakeClean(p);
44741      }
44742    }
44743    if( pgno==0 && pCache->nRefSum ){
44744      sqlite3_pcache_page *pPage1;
44745      pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
44746      if( ALWAYS(pPage1) ){  /* Page 1 is always available in cache, because
44747                             ** pCache->nRefSum>0 */
44748        memset(pPage1->pBuf, 0, pCache->szPage);
44749        pgno = 1;
44750      }
44751    }
44752    sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
44753  }
44754}
44755
44756/*
44757** Close a cache.
44758*/
44759SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
44760  assert( pCache->pCache!=0 );
44761  pcacheTrace(("%p.CLOSE\n",pCache));
44762  sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
44763}
44764
44765/*
44766** Discard the contents of the cache.
44767*/
44768SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
44769  sqlite3PcacheTruncate(pCache, 0);
44770}
44771
44772/*
44773** Merge two lists of pages connected by pDirty and in pgno order.
44774** Do not bother fixing the pDirtyPrev pointers.
44775*/
44776static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
44777  PgHdr result, *pTail;
44778  pTail = &result;
44779  assert( pA!=0 && pB!=0 );
44780  for(;;){
44781    if( pA->pgno<pB->pgno ){
44782      pTail->pDirty = pA;
44783      pTail = pA;
44784      pA = pA->pDirty;
44785      if( pA==0 ){
44786        pTail->pDirty = pB;
44787        break;
44788      }
44789    }else{
44790      pTail->pDirty = pB;
44791      pTail = pB;
44792      pB = pB->pDirty;
44793      if( pB==0 ){
44794        pTail->pDirty = pA;
44795        break;
44796      }
44797    }
44798  }
44799  return result.pDirty;
44800}
44801
44802/*
44803** Sort the list of pages in accending order by pgno.  Pages are
44804** connected by pDirty pointers.  The pDirtyPrev pointers are
44805** corrupted by this sort.
44806**
44807** Since there cannot be more than 2^31 distinct pages in a database,
44808** there cannot be more than 31 buckets required by the merge sorter.
44809** One extra bucket is added to catch overflow in case something
44810** ever changes to make the previous sentence incorrect.
44811*/
44812#define N_SORT_BUCKET  32
44813static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
44814  PgHdr *a[N_SORT_BUCKET], *p;
44815  int i;
44816  memset(a, 0, sizeof(a));
44817  while( pIn ){
44818    p = pIn;
44819    pIn = p->pDirty;
44820    p->pDirty = 0;
44821    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
44822      if( a[i]==0 ){
44823        a[i] = p;
44824        break;
44825      }else{
44826        p = pcacheMergeDirtyList(a[i], p);
44827        a[i] = 0;
44828      }
44829    }
44830    if( NEVER(i==N_SORT_BUCKET-1) ){
44831      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
44832      ** the input list.  But that is impossible.
44833      */
44834      a[i] = pcacheMergeDirtyList(a[i], p);
44835    }
44836  }
44837  p = a[0];
44838  for(i=1; i<N_SORT_BUCKET; i++){
44839    if( a[i]==0 ) continue;
44840    p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
44841  }
44842  return p;
44843}
44844
44845/*
44846** Return a list of all dirty pages in the cache, sorted by page number.
44847*/
44848SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
44849  PgHdr *p;
44850  for(p=pCache->pDirty; p; p=p->pDirtyNext){
44851    p->pDirty = p->pDirtyNext;
44852  }
44853  return pcacheSortDirtyList(pCache->pDirty);
44854}
44855
44856/*
44857** Return the total number of references to all pages held by the cache.
44858**
44859** This is not the total number of pages referenced, but the sum of the
44860** reference count for all pages.
44861*/
44862SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
44863  return pCache->nRefSum;
44864}
44865
44866/*
44867** Return the number of references to the page supplied as an argument.
44868*/
44869SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
44870  return p->nRef;
44871}
44872
44873/*
44874** Return the total number of pages in the cache.
44875*/
44876SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
44877  assert( pCache->pCache!=0 );
44878  return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
44879}
44880
44881#ifdef SQLITE_TEST
44882/*
44883** Get the suggested cache-size value.
44884*/
44885SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
44886  return numberOfCachePages(pCache);
44887}
44888#endif
44889
44890/*
44891** Set the suggested cache-size value.
44892*/
44893SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
44894  assert( pCache->pCache!=0 );
44895  pCache->szCache = mxPage;
44896  sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
44897                                         numberOfCachePages(pCache));
44898}
44899
44900/*
44901** Set the suggested cache-spill value.  Make no changes if if the
44902** argument is zero.  Return the effective cache-spill size, which will
44903** be the larger of the szSpill and szCache.
44904*/
44905SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
44906  int res;
44907  assert( p->pCache!=0 );
44908  if( mxPage ){
44909    if( mxPage<0 ){
44910      mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
44911    }
44912    p->szSpill = mxPage;
44913  }
44914  res = numberOfCachePages(p);
44915  if( res<p->szSpill ) res = p->szSpill;
44916  return res;
44917}
44918
44919/*
44920** Free up as much memory as possible from the page cache.
44921*/
44922SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
44923  assert( pCache->pCache!=0 );
44924  sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
44925}
44926
44927/*
44928** Return the size of the header added by this middleware layer
44929** in the page-cache hierarchy.
44930*/
44931SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
44932
44933/*
44934** Return the number of dirty pages currently in the cache, as a percentage
44935** of the configured cache size.
44936*/
44937SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
44938  PgHdr *pDirty;
44939  int nDirty = 0;
44940  int nCache = numberOfCachePages(pCache);
44941  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
44942  return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
44943}
44944
44945#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
44946/*
44947** For all dirty pages currently in the cache, invoke the specified
44948** callback. This is only used if the SQLITE_CHECK_PAGES macro is
44949** defined.
44950*/
44951SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
44952  PgHdr *pDirty;
44953  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
44954    xIter(pDirty);
44955  }
44956}
44957#endif
44958
44959/************** End of pcache.c **********************************************/
44960/************** Begin file pcache1.c *****************************************/
44961/*
44962** 2008 November 05
44963**
44964** The author disclaims copyright to this source code.  In place of
44965** a legal notice, here is a blessing:
44966**
44967**    May you do good and not evil.
44968**    May you find forgiveness for yourself and forgive others.
44969**    May you share freely, never taking more than you give.
44970**
44971*************************************************************************
44972**
44973** This file implements the default page cache implementation (the
44974** sqlite3_pcache interface). It also contains part of the implementation
44975** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
44976** If the default page cache implementation is overridden, then neither of
44977** these two features are available.
44978**
44979** A Page cache line looks like this:
44980**
44981**  -------------------------------------------------------------
44982**  |  database page content   |  PgHdr1  |  MemPage  |  PgHdr  |
44983**  -------------------------------------------------------------
44984**
44985** The database page content is up front (so that buffer overreads tend to
44986** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions).   MemPage
44987** is the extension added by the btree.c module containing information such
44988** as the database page number and how that database page is used.  PgHdr
44989** is added by the pcache.c layer and contains information used to keep track
44990** of which pages are "dirty".  PgHdr1 is an extension added by this
44991** module (pcache1.c).  The PgHdr1 header is a subclass of sqlite3_pcache_page.
44992** PgHdr1 contains information needed to look up a page by its page number.
44993** The superclass sqlite3_pcache_page.pBuf points to the start of the
44994** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
44995**
44996** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
44997** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size).  The
44998** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
44999** size can vary according to architecture, compile-time options, and
45000** SQLite library version number.
45001**
45002** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
45003** using a separate memory allocation from the database page content.  This
45004** seeks to overcome the "clownshoe" problem (also called "internal
45005** fragmentation" in academic literature) of allocating a few bytes more
45006** than a power of two with the memory allocator rounding up to the next
45007** power of two, and leaving the rounded-up space unused.
45008**
45009** This module tracks pointers to PgHdr1 objects.  Only pcache.c communicates
45010** with this module.  Information is passed back and forth as PgHdr1 pointers.
45011**
45012** The pcache.c and pager.c modules deal pointers to PgHdr objects.
45013** The btree.c module deals with pointers to MemPage objects.
45014**
45015** SOURCE OF PAGE CACHE MEMORY:
45016**
45017** Memory for a page might come from any of three sources:
45018**
45019**    (1)  The general-purpose memory allocator - sqlite3Malloc()
45020**    (2)  Global page-cache memory provided using sqlite3_config() with
45021**         SQLITE_CONFIG_PAGECACHE.
45022**    (3)  PCache-local bulk allocation.
45023**
45024** The third case is a chunk of heap memory (defaulting to 100 pages worth)
45025** that is allocated when the page cache is created.  The size of the local
45026** bulk allocation can be adjusted using
45027**
45028**     sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
45029**
45030** If N is positive, then N pages worth of memory are allocated using a single
45031** sqlite3Malloc() call and that memory is used for the first N pages allocated.
45032** Or if N is negative, then -1024*N bytes of memory are allocated and used
45033** for as many pages as can be accomodated.
45034**
45035** Only one of (2) or (3) can be used.  Once the memory available to (2) or
45036** (3) is exhausted, subsequent allocations fail over to the general-purpose
45037** memory allocator (1).
45038**
45039** Earlier versions of SQLite used only methods (1) and (2).  But experiments
45040** show that method (3) with N==100 provides about a 5% performance boost for
45041** common workloads.
45042*/
45043/* #include "sqliteInt.h" */
45044
45045typedef struct PCache1 PCache1;
45046typedef struct PgHdr1 PgHdr1;
45047typedef struct PgFreeslot PgFreeslot;
45048typedef struct PGroup PGroup;
45049
45050/*
45051** Each cache entry is represented by an instance of the following
45052** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
45053** PgHdr1.pCache->szPage bytes is allocated directly before this structure
45054** in memory.
45055*/
45056struct PgHdr1 {
45057  sqlite3_pcache_page page;      /* Base class. Must be first. pBuf & pExtra */
45058  unsigned int iKey;             /* Key value (page number) */
45059  u8 isPinned;                   /* Page in use, not on the LRU list */
45060  u8 isBulkLocal;                /* This page from bulk local storage */
45061  u8 isAnchor;                   /* This is the PGroup.lru element */
45062  PgHdr1 *pNext;                 /* Next in hash table chain */
45063  PCache1 *pCache;               /* Cache that currently owns this page */
45064  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
45065  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
45066};
45067
45068/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
45069** of one or more PCaches that are able to recycle each other's unpinned
45070** pages when they are under memory pressure.  A PGroup is an instance of
45071** the following object.
45072**
45073** This page cache implementation works in one of two modes:
45074**
45075**   (1)  Every PCache is the sole member of its own PGroup.  There is
45076**        one PGroup per PCache.
45077**
45078**   (2)  There is a single global PGroup that all PCaches are a member
45079**        of.
45080**
45081** Mode 1 uses more memory (since PCache instances are not able to rob
45082** unused pages from other PCaches) but it also operates without a mutex,
45083** and is therefore often faster.  Mode 2 requires a mutex in order to be
45084** threadsafe, but recycles pages more efficiently.
45085**
45086** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
45087** PGroup which is the pcache1.grp global variable and its mutex is
45088** SQLITE_MUTEX_STATIC_LRU.
45089*/
45090struct PGroup {
45091  sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
45092  unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
45093  unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
45094  unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
45095  unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
45096  PgHdr1 lru;                    /* The beginning and end of the LRU list */
45097};
45098
45099/* Each page cache is an instance of the following object.  Every
45100** open database file (including each in-memory database and each
45101** temporary or transient database) has a single page cache which
45102** is an instance of this object.
45103**
45104** Pointers to structures of this type are cast and returned as
45105** opaque sqlite3_pcache* handles.
45106*/
45107struct PCache1 {
45108  /* Cache configuration parameters. Page size (szPage) and the purgeable
45109  ** flag (bPurgeable) are set when the cache is created. nMax may be
45110  ** modified at any time by a call to the pcache1Cachesize() method.
45111  ** The PGroup mutex must be held when accessing nMax.
45112  */
45113  PGroup *pGroup;                     /* PGroup this cache belongs to */
45114  int szPage;                         /* Size of database content section */
45115  int szExtra;                        /* sizeof(MemPage)+sizeof(PgHdr) */
45116  int szAlloc;                        /* Total size of one pcache line */
45117  int bPurgeable;                     /* True if cache is purgeable */
45118  unsigned int nMin;                  /* Minimum number of pages reserved */
45119  unsigned int nMax;                  /* Configured "cache_size" value */
45120  unsigned int n90pct;                /* nMax*9/10 */
45121  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
45122
45123  /* Hash table of all pages. The following variables may only be accessed
45124  ** when the accessor is holding the PGroup mutex.
45125  */
45126  unsigned int nRecyclable;           /* Number of pages in the LRU list */
45127  unsigned int nPage;                 /* Total number of pages in apHash */
45128  unsigned int nHash;                 /* Number of slots in apHash[] */
45129  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
45130  PgHdr1 *pFree;                      /* List of unused pcache-local pages */
45131  void *pBulk;                        /* Bulk memory used by pcache-local */
45132};
45133
45134/*
45135** Free slots in the allocator used to divide up the global page cache
45136** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
45137*/
45138struct PgFreeslot {
45139  PgFreeslot *pNext;  /* Next free slot */
45140};
45141
45142/*
45143** Global data used by this cache.
45144*/
45145static SQLITE_WSD struct PCacheGlobal {
45146  PGroup grp;                    /* The global PGroup for mode (2) */
45147
45148  /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
45149  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
45150  ** fixed at sqlite3_initialize() time and do not require mutex protection.
45151  ** The nFreeSlot and pFree values do require mutex protection.
45152  */
45153  int isInit;                    /* True if initialized */
45154  int separateCache;             /* Use a new PGroup for each PCache */
45155  int nInitPage;                 /* Initial bulk allocation size */
45156  int szSlot;                    /* Size of each free slot */
45157  int nSlot;                     /* The number of pcache slots */
45158  int nReserve;                  /* Try to keep nFreeSlot above this */
45159  void *pStart, *pEnd;           /* Bounds of global page cache memory */
45160  /* Above requires no mutex.  Use mutex below for variable that follow. */
45161  sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
45162  PgFreeslot *pFree;             /* Free page blocks */
45163  int nFreeSlot;                 /* Number of unused pcache slots */
45164  /* The following value requires a mutex to change.  We skip the mutex on
45165  ** reading because (1) most platforms read a 32-bit integer atomically and
45166  ** (2) even if an incorrect value is read, no great harm is done since this
45167  ** is really just an optimization. */
45168  int bUnderPressure;            /* True if low on PAGECACHE memory */
45169} pcache1_g;
45170
45171/*
45172** All code in this file should access the global structure above via the
45173** alias "pcache1". This ensures that the WSD emulation is used when
45174** compiling for systems that do not support real WSD.
45175*/
45176#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
45177
45178/*
45179** Macros to enter and leave the PCache LRU mutex.
45180*/
45181#if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
45182# define pcache1EnterMutex(X)  assert((X)->mutex==0)
45183# define pcache1LeaveMutex(X)  assert((X)->mutex==0)
45184# define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
45185#else
45186# define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
45187# define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
45188# define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
45189#endif
45190
45191/******************************************************************************/
45192/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
45193
45194
45195/*
45196** This function is called during initialization if a static buffer is
45197** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
45198** verb to sqlite3_config(). Parameter pBuf points to an allocation large
45199** enough to contain 'n' buffers of 'sz' bytes each.
45200**
45201** This routine is called from sqlite3_initialize() and so it is guaranteed
45202** to be serialized already.  There is no need for further mutexing.
45203*/
45204SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
45205  if( pcache1.isInit ){
45206    PgFreeslot *p;
45207    if( pBuf==0 ) sz = n = 0;
45208    sz = ROUNDDOWN8(sz);
45209    pcache1.szSlot = sz;
45210    pcache1.nSlot = pcache1.nFreeSlot = n;
45211    pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
45212    pcache1.pStart = pBuf;
45213    pcache1.pFree = 0;
45214    pcache1.bUnderPressure = 0;
45215    while( n-- ){
45216      p = (PgFreeslot*)pBuf;
45217      p->pNext = pcache1.pFree;
45218      pcache1.pFree = p;
45219      pBuf = (void*)&((char*)pBuf)[sz];
45220    }
45221    pcache1.pEnd = pBuf;
45222  }
45223}
45224
45225/*
45226** Try to initialize the pCache->pFree and pCache->pBulk fields.  Return
45227** true if pCache->pFree ends up containing one or more free pages.
45228*/
45229static int pcache1InitBulk(PCache1 *pCache){
45230  i64 szBulk;
45231  char *zBulk;
45232  if( pcache1.nInitPage==0 ) return 0;
45233  /* Do not bother with a bulk allocation if the cache size very small */
45234  if( pCache->nMax<3 ) return 0;
45235  sqlite3BeginBenignMalloc();
45236  if( pcache1.nInitPage>0 ){
45237    szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
45238  }else{
45239    szBulk = -1024 * (i64)pcache1.nInitPage;
45240  }
45241  if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
45242    szBulk = pCache->szAlloc*(i64)pCache->nMax;
45243  }
45244  zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
45245  sqlite3EndBenignMalloc();
45246  if( zBulk ){
45247    int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
45248    int i;
45249    for(i=0; i<nBulk; i++){
45250      PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
45251      pX->page.pBuf = zBulk;
45252      pX->page.pExtra = &pX[1];
45253      pX->isBulkLocal = 1;
45254      pX->isAnchor = 0;
45255      pX->pNext = pCache->pFree;
45256      pCache->pFree = pX;
45257      zBulk += pCache->szAlloc;
45258    }
45259  }
45260  return pCache->pFree!=0;
45261}
45262
45263/*
45264** Malloc function used within this file to allocate space from the buffer
45265** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
45266** such buffer exists or there is no space left in it, this function falls
45267** back to sqlite3Malloc().
45268**
45269** Multiple threads can run this routine at the same time.  Global variables
45270** in pcache1 need to be protected via mutex.
45271*/
45272static void *pcache1Alloc(int nByte){
45273  void *p = 0;
45274  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
45275  if( nByte<=pcache1.szSlot ){
45276    sqlite3_mutex_enter(pcache1.mutex);
45277    p = (PgHdr1 *)pcache1.pFree;
45278    if( p ){
45279      pcache1.pFree = pcache1.pFree->pNext;
45280      pcache1.nFreeSlot--;
45281      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
45282      assert( pcache1.nFreeSlot>=0 );
45283      sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
45284      sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
45285    }
45286    sqlite3_mutex_leave(pcache1.mutex);
45287  }
45288  if( p==0 ){
45289    /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
45290    ** it from sqlite3Malloc instead.
45291    */
45292    p = sqlite3Malloc(nByte);
45293#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
45294    if( p ){
45295      int sz = sqlite3MallocSize(p);
45296      sqlite3_mutex_enter(pcache1.mutex);
45297      sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
45298      sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
45299      sqlite3_mutex_leave(pcache1.mutex);
45300    }
45301#endif
45302    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
45303  }
45304  return p;
45305}
45306
45307/*
45308** Free an allocated buffer obtained from pcache1Alloc().
45309*/
45310static void pcache1Free(void *p){
45311  if( p==0 ) return;
45312  if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
45313    PgFreeslot *pSlot;
45314    sqlite3_mutex_enter(pcache1.mutex);
45315    sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
45316    pSlot = (PgFreeslot*)p;
45317    pSlot->pNext = pcache1.pFree;
45318    pcache1.pFree = pSlot;
45319    pcache1.nFreeSlot++;
45320    pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
45321    assert( pcache1.nFreeSlot<=pcache1.nSlot );
45322    sqlite3_mutex_leave(pcache1.mutex);
45323  }else{
45324    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
45325    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
45326#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
45327    {
45328      int nFreed = 0;
45329      nFreed = sqlite3MallocSize(p);
45330      sqlite3_mutex_enter(pcache1.mutex);
45331      sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
45332      sqlite3_mutex_leave(pcache1.mutex);
45333    }
45334#endif
45335    sqlite3_free(p);
45336  }
45337}
45338
45339#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
45340/*
45341** Return the size of a pcache allocation
45342*/
45343static int pcache1MemSize(void *p){
45344  if( p>=pcache1.pStart && p<pcache1.pEnd ){
45345    return pcache1.szSlot;
45346  }else{
45347    int iSize;
45348    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
45349    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
45350    iSize = sqlite3MallocSize(p);
45351    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
45352    return iSize;
45353  }
45354}
45355#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
45356
45357/*
45358** Allocate a new page object initially associated with cache pCache.
45359*/
45360static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
45361  PgHdr1 *p = 0;
45362  void *pPg;
45363
45364  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45365  if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
45366    p = pCache->pFree;
45367    pCache->pFree = p->pNext;
45368    p->pNext = 0;
45369  }else{
45370#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
45371    /* The group mutex must be released before pcache1Alloc() is called. This
45372    ** is because it might call sqlite3_release_memory(), which assumes that
45373    ** this mutex is not held. */
45374    assert( pcache1.separateCache==0 );
45375    assert( pCache->pGroup==&pcache1.grp );
45376    pcache1LeaveMutex(pCache->pGroup);
45377#endif
45378    if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
45379#ifdef SQLITE_PCACHE_SEPARATE_HEADER
45380    pPg = pcache1Alloc(pCache->szPage);
45381    p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
45382    if( !pPg || !p ){
45383      pcache1Free(pPg);
45384      sqlite3_free(p);
45385      pPg = 0;
45386    }
45387#else
45388    pPg = pcache1Alloc(pCache->szAlloc);
45389    p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
45390#endif
45391    if( benignMalloc ){ sqlite3EndBenignMalloc(); }
45392#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
45393    pcache1EnterMutex(pCache->pGroup);
45394#endif
45395    if( pPg==0 ) return 0;
45396    p->page.pBuf = pPg;
45397    p->page.pExtra = &p[1];
45398    p->isBulkLocal = 0;
45399    p->isAnchor = 0;
45400  }
45401  if( pCache->bPurgeable ){
45402    pCache->pGroup->nCurrentPage++;
45403  }
45404  return p;
45405}
45406
45407/*
45408** Free a page object allocated by pcache1AllocPage().
45409*/
45410static void pcache1FreePage(PgHdr1 *p){
45411  PCache1 *pCache;
45412  assert( p!=0 );
45413  pCache = p->pCache;
45414  assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
45415  if( p->isBulkLocal ){
45416    p->pNext = pCache->pFree;
45417    pCache->pFree = p;
45418  }else{
45419    pcache1Free(p->page.pBuf);
45420#ifdef SQLITE_PCACHE_SEPARATE_HEADER
45421    sqlite3_free(p);
45422#endif
45423  }
45424  if( pCache->bPurgeable ){
45425    pCache->pGroup->nCurrentPage--;
45426  }
45427}
45428
45429/*
45430** Malloc function used by SQLite to obtain space from the buffer configured
45431** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
45432** exists, this function falls back to sqlite3Malloc().
45433*/
45434SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
45435  return pcache1Alloc(sz);
45436}
45437
45438/*
45439** Free an allocated buffer obtained from sqlite3PageMalloc().
45440*/
45441SQLITE_PRIVATE void sqlite3PageFree(void *p){
45442  pcache1Free(p);
45443}
45444
45445
45446/*
45447** Return true if it desirable to avoid allocating a new page cache
45448** entry.
45449**
45450** If memory was allocated specifically to the page cache using
45451** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
45452** it is desirable to avoid allocating a new page cache entry because
45453** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
45454** for all page cache needs and we should not need to spill the
45455** allocation onto the heap.
45456**
45457** Or, the heap is used for all page cache memory but the heap is
45458** under memory pressure, then again it is desirable to avoid
45459** allocating a new page cache entry in order to avoid stressing
45460** the heap even further.
45461*/
45462static int pcache1UnderMemoryPressure(PCache1 *pCache){
45463  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
45464    return pcache1.bUnderPressure;
45465  }else{
45466    return sqlite3HeapNearlyFull();
45467  }
45468}
45469
45470/******************************************************************************/
45471/******** General Implementation Functions ************************************/
45472
45473/*
45474** This function is used to resize the hash table used by the cache passed
45475** as the first argument.
45476**
45477** The PCache mutex must be held when this function is called.
45478*/
45479static void pcache1ResizeHash(PCache1 *p){
45480  PgHdr1 **apNew;
45481  unsigned int nNew;
45482  unsigned int i;
45483
45484  assert( sqlite3_mutex_held(p->pGroup->mutex) );
45485
45486  nNew = p->nHash*2;
45487  if( nNew<256 ){
45488    nNew = 256;
45489  }
45490
45491  pcache1LeaveMutex(p->pGroup);
45492  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
45493  apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
45494  if( p->nHash ){ sqlite3EndBenignMalloc(); }
45495  pcache1EnterMutex(p->pGroup);
45496  if( apNew ){
45497    for(i=0; i<p->nHash; i++){
45498      PgHdr1 *pPage;
45499      PgHdr1 *pNext = p->apHash[i];
45500      while( (pPage = pNext)!=0 ){
45501        unsigned int h = pPage->iKey % nNew;
45502        pNext = pPage->pNext;
45503        pPage->pNext = apNew[h];
45504        apNew[h] = pPage;
45505      }
45506    }
45507    sqlite3_free(p->apHash);
45508    p->apHash = apNew;
45509    p->nHash = nNew;
45510  }
45511}
45512
45513/*
45514** This function is used internally to remove the page pPage from the
45515** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
45516** LRU list, then this function is a no-op.
45517**
45518** The PGroup mutex must be held when this function is called.
45519*/
45520static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
45521  PCache1 *pCache;
45522
45523  assert( pPage!=0 );
45524  assert( pPage->isPinned==0 );
45525  pCache = pPage->pCache;
45526  assert( pPage->pLruNext );
45527  assert( pPage->pLruPrev );
45528  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45529  pPage->pLruPrev->pLruNext = pPage->pLruNext;
45530  pPage->pLruNext->pLruPrev = pPage->pLruPrev;
45531  pPage->pLruNext = 0;
45532  pPage->pLruPrev = 0;
45533  pPage->isPinned = 1;
45534  assert( pPage->isAnchor==0 );
45535  assert( pCache->pGroup->lru.isAnchor==1 );
45536  pCache->nRecyclable--;
45537  return pPage;
45538}
45539
45540
45541/*
45542** Remove the page supplied as an argument from the hash table
45543** (PCache1.apHash structure) that it is currently stored in.
45544** Also free the page if freePage is true.
45545**
45546** The PGroup mutex must be held when this function is called.
45547*/
45548static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
45549  unsigned int h;
45550  PCache1 *pCache = pPage->pCache;
45551  PgHdr1 **pp;
45552
45553  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45554  h = pPage->iKey % pCache->nHash;
45555  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
45556  *pp = (*pp)->pNext;
45557
45558  pCache->nPage--;
45559  if( freeFlag ) pcache1FreePage(pPage);
45560}
45561
45562/*
45563** If there are currently more than nMaxPage pages allocated, try
45564** to recycle pages to reduce the number allocated to nMaxPage.
45565*/
45566static void pcache1EnforceMaxPage(PCache1 *pCache){
45567  PGroup *pGroup = pCache->pGroup;
45568  PgHdr1 *p;
45569  assert( sqlite3_mutex_held(pGroup->mutex) );
45570  while( pGroup->nCurrentPage>pGroup->nMaxPage
45571      && (p=pGroup->lru.pLruPrev)->isAnchor==0
45572  ){
45573    assert( p->pCache->pGroup==pGroup );
45574    assert( p->isPinned==0 );
45575    pcache1PinPage(p);
45576    pcache1RemoveFromHash(p, 1);
45577  }
45578  if( pCache->nPage==0 && pCache->pBulk ){
45579    sqlite3_free(pCache->pBulk);
45580    pCache->pBulk = pCache->pFree = 0;
45581  }
45582}
45583
45584/*
45585** Discard all pages from cache pCache with a page number (key value)
45586** greater than or equal to iLimit. Any pinned pages that meet this
45587** criteria are unpinned before they are discarded.
45588**
45589** The PCache mutex must be held when this function is called.
45590*/
45591static void pcache1TruncateUnsafe(
45592  PCache1 *pCache,             /* The cache to truncate */
45593  unsigned int iLimit          /* Drop pages with this pgno or larger */
45594){
45595  TESTONLY( int nPage = 0; )  /* To assert pCache->nPage is correct */
45596  unsigned int h, iStop;
45597  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45598  assert( pCache->iMaxKey >= iLimit );
45599  assert( pCache->nHash > 0 );
45600  if( pCache->iMaxKey - iLimit < pCache->nHash ){
45601    /* If we are just shaving the last few pages off the end of the
45602    ** cache, then there is no point in scanning the entire hash table.
45603    ** Only scan those hash slots that might contain pages that need to
45604    ** be removed. */
45605    h = iLimit % pCache->nHash;
45606    iStop = pCache->iMaxKey % pCache->nHash;
45607    TESTONLY( nPage = -10; )  /* Disable the pCache->nPage validity check */
45608  }else{
45609    /* This is the general case where many pages are being removed.
45610    ** It is necessary to scan the entire hash table */
45611    h = pCache->nHash/2;
45612    iStop = h - 1;
45613  }
45614  for(;;){
45615    PgHdr1 **pp;
45616    PgHdr1 *pPage;
45617    assert( h<pCache->nHash );
45618    pp = &pCache->apHash[h];
45619    while( (pPage = *pp)!=0 ){
45620      if( pPage->iKey>=iLimit ){
45621        pCache->nPage--;
45622        *pp = pPage->pNext;
45623        if( !pPage->isPinned ) pcache1PinPage(pPage);
45624        pcache1FreePage(pPage);
45625      }else{
45626        pp = &pPage->pNext;
45627        TESTONLY( if( nPage>=0 ) nPage++; )
45628      }
45629    }
45630    if( h==iStop ) break;
45631    h = (h+1) % pCache->nHash;
45632  }
45633  assert( nPage<0 || pCache->nPage==(unsigned)nPage );
45634}
45635
45636/******************************************************************************/
45637/******** sqlite3_pcache Methods **********************************************/
45638
45639/*
45640** Implementation of the sqlite3_pcache.xInit method.
45641*/
45642static int pcache1Init(void *NotUsed){
45643  UNUSED_PARAMETER(NotUsed);
45644  assert( pcache1.isInit==0 );
45645  memset(&pcache1, 0, sizeof(pcache1));
45646
45647
45648  /*
45649  ** The pcache1.separateCache variable is true if each PCache has its own
45650  ** private PGroup (mode-1).  pcache1.separateCache is false if the single
45651  ** PGroup in pcache1.grp is used for all page caches (mode-2).
45652  **
45653  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
45654  **
45655  **   *  Use a unified cache in single-threaded applications that have
45656  **      configured a start-time buffer for use as page-cache memory using
45657  **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
45658  **      pBuf argument.
45659  **
45660  **   *  Otherwise use separate caches (mode-1)
45661  */
45662#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
45663  pcache1.separateCache = 0;
45664#elif SQLITE_THREADSAFE
45665  pcache1.separateCache = sqlite3GlobalConfig.pPage==0
45666                          || sqlite3GlobalConfig.bCoreMutex>0;
45667#else
45668  pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
45669#endif
45670
45671#if SQLITE_THREADSAFE
45672  if( sqlite3GlobalConfig.bCoreMutex ){
45673    pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
45674    pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
45675  }
45676#endif
45677  if( pcache1.separateCache
45678   && sqlite3GlobalConfig.nPage!=0
45679   && sqlite3GlobalConfig.pPage==0
45680  ){
45681    pcache1.nInitPage = sqlite3GlobalConfig.nPage;
45682  }else{
45683    pcache1.nInitPage = 0;
45684  }
45685  pcache1.grp.mxPinned = 10;
45686  pcache1.isInit = 1;
45687  return SQLITE_OK;
45688}
45689
45690/*
45691** Implementation of the sqlite3_pcache.xShutdown method.
45692** Note that the static mutex allocated in xInit does
45693** not need to be freed.
45694*/
45695static void pcache1Shutdown(void *NotUsed){
45696  UNUSED_PARAMETER(NotUsed);
45697  assert( pcache1.isInit!=0 );
45698  memset(&pcache1, 0, sizeof(pcache1));
45699}
45700
45701/* forward declaration */
45702static void pcache1Destroy(sqlite3_pcache *p);
45703
45704/*
45705** Implementation of the sqlite3_pcache.xCreate method.
45706**
45707** Allocate a new cache.
45708*/
45709static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
45710  PCache1 *pCache;      /* The newly created page cache */
45711  PGroup *pGroup;       /* The group the new page cache will belong to */
45712  int sz;               /* Bytes of memory required to allocate the new cache */
45713
45714  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
45715  assert( szExtra < 300 );
45716
45717  sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
45718  pCache = (PCache1 *)sqlite3MallocZero(sz);
45719  if( pCache ){
45720    if( pcache1.separateCache ){
45721      pGroup = (PGroup*)&pCache[1];
45722      pGroup->mxPinned = 10;
45723    }else{
45724      pGroup = &pcache1.grp;
45725    }
45726    if( pGroup->lru.isAnchor==0 ){
45727      pGroup->lru.isAnchor = 1;
45728      pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
45729    }
45730    pCache->pGroup = pGroup;
45731    pCache->szPage = szPage;
45732    pCache->szExtra = szExtra;
45733    pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
45734    pCache->bPurgeable = (bPurgeable ? 1 : 0);
45735    pcache1EnterMutex(pGroup);
45736    pcache1ResizeHash(pCache);
45737    if( bPurgeable ){
45738      pCache->nMin = 10;
45739      pGroup->nMinPage += pCache->nMin;
45740      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45741    }
45742    pcache1LeaveMutex(pGroup);
45743    if( pCache->nHash==0 ){
45744      pcache1Destroy((sqlite3_pcache*)pCache);
45745      pCache = 0;
45746    }
45747  }
45748  return (sqlite3_pcache *)pCache;
45749}
45750
45751/*
45752** Implementation of the sqlite3_pcache.xCachesize method.
45753**
45754** Configure the cache_size limit for a cache.
45755*/
45756static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
45757  PCache1 *pCache = (PCache1 *)p;
45758  if( pCache->bPurgeable ){
45759    PGroup *pGroup = pCache->pGroup;
45760    pcache1EnterMutex(pGroup);
45761    pGroup->nMaxPage += (nMax - pCache->nMax);
45762    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45763    pCache->nMax = nMax;
45764    pCache->n90pct = pCache->nMax*9/10;
45765    pcache1EnforceMaxPage(pCache);
45766    pcache1LeaveMutex(pGroup);
45767  }
45768}
45769
45770/*
45771** Implementation of the sqlite3_pcache.xShrink method.
45772**
45773** Free up as much memory as possible.
45774*/
45775static void pcache1Shrink(sqlite3_pcache *p){
45776  PCache1 *pCache = (PCache1*)p;
45777  if( pCache->bPurgeable ){
45778    PGroup *pGroup = pCache->pGroup;
45779    int savedMaxPage;
45780    pcache1EnterMutex(pGroup);
45781    savedMaxPage = pGroup->nMaxPage;
45782    pGroup->nMaxPage = 0;
45783    pcache1EnforceMaxPage(pCache);
45784    pGroup->nMaxPage = savedMaxPage;
45785    pcache1LeaveMutex(pGroup);
45786  }
45787}
45788
45789/*
45790** Implementation of the sqlite3_pcache.xPagecount method.
45791*/
45792static int pcache1Pagecount(sqlite3_pcache *p){
45793  int n;
45794  PCache1 *pCache = (PCache1*)p;
45795  pcache1EnterMutex(pCache->pGroup);
45796  n = pCache->nPage;
45797  pcache1LeaveMutex(pCache->pGroup);
45798  return n;
45799}
45800
45801
45802/*
45803** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
45804** in the header of the pcache1Fetch() procedure.
45805**
45806** This steps are broken out into a separate procedure because they are
45807** usually not needed, and by avoiding the stack initialization required
45808** for these steps, the main pcache1Fetch() procedure can run faster.
45809*/
45810static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
45811  PCache1 *pCache,
45812  unsigned int iKey,
45813  int createFlag
45814){
45815  unsigned int nPinned;
45816  PGroup *pGroup = pCache->pGroup;
45817  PgHdr1 *pPage = 0;
45818
45819  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
45820  assert( pCache->nPage >= pCache->nRecyclable );
45821  nPinned = pCache->nPage - pCache->nRecyclable;
45822  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
45823  assert( pCache->n90pct == pCache->nMax*9/10 );
45824  if( createFlag==1 && (
45825        nPinned>=pGroup->mxPinned
45826     || nPinned>=pCache->n90pct
45827     || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
45828  )){
45829    return 0;
45830  }
45831
45832  if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
45833  assert( pCache->nHash>0 && pCache->apHash );
45834
45835  /* Step 4. Try to recycle a page. */
45836  if( pCache->bPurgeable
45837   && !pGroup->lru.pLruPrev->isAnchor
45838   && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
45839  ){
45840    PCache1 *pOther;
45841    pPage = pGroup->lru.pLruPrev;
45842    assert( pPage->isPinned==0 );
45843    pcache1RemoveFromHash(pPage, 0);
45844    pcache1PinPage(pPage);
45845    pOther = pPage->pCache;
45846    if( pOther->szAlloc != pCache->szAlloc ){
45847      pcache1FreePage(pPage);
45848      pPage = 0;
45849    }else{
45850      pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
45851    }
45852  }
45853
45854  /* Step 5. If a usable page buffer has still not been found,
45855  ** attempt to allocate a new one.
45856  */
45857  if( !pPage ){
45858    pPage = pcache1AllocPage(pCache, createFlag==1);
45859  }
45860
45861  if( pPage ){
45862    unsigned int h = iKey % pCache->nHash;
45863    pCache->nPage++;
45864    pPage->iKey = iKey;
45865    pPage->pNext = pCache->apHash[h];
45866    pPage->pCache = pCache;
45867    pPage->pLruPrev = 0;
45868    pPage->pLruNext = 0;
45869    pPage->isPinned = 1;
45870    *(void **)pPage->page.pExtra = 0;
45871    pCache->apHash[h] = pPage;
45872    if( iKey>pCache->iMaxKey ){
45873      pCache->iMaxKey = iKey;
45874    }
45875  }
45876  return pPage;
45877}
45878
45879/*
45880** Implementation of the sqlite3_pcache.xFetch method.
45881**
45882** Fetch a page by key value.
45883**
45884** Whether or not a new page may be allocated by this function depends on
45885** the value of the createFlag argument.  0 means do not allocate a new
45886** page.  1 means allocate a new page if space is easily available.  2
45887** means to try really hard to allocate a new page.
45888**
45889** For a non-purgeable cache (a cache used as the storage for an in-memory
45890** database) there is really no difference between createFlag 1 and 2.  So
45891** the calling function (pcache.c) will never have a createFlag of 1 on
45892** a non-purgeable cache.
45893**
45894** There are three different approaches to obtaining space for a page,
45895** depending on the value of parameter createFlag (which may be 0, 1 or 2).
45896**
45897**   1. Regardless of the value of createFlag, the cache is searched for a
45898**      copy of the requested page. If one is found, it is returned.
45899**
45900**   2. If createFlag==0 and the page is not already in the cache, NULL is
45901**      returned.
45902**
45903**   3. If createFlag is 1, and the page is not already in the cache, then
45904**      return NULL (do not allocate a new page) if any of the following
45905**      conditions are true:
45906**
45907**       (a) the number of pages pinned by the cache is greater than
45908**           PCache1.nMax, or
45909**
45910**       (b) the number of pages pinned by the cache is greater than
45911**           the sum of nMax for all purgeable caches, less the sum of
45912**           nMin for all other purgeable caches, or
45913**
45914**   4. If none of the first three conditions apply and the cache is marked
45915**      as purgeable, and if one of the following is true:
45916**
45917**       (a) The number of pages allocated for the cache is already
45918**           PCache1.nMax, or
45919**
45920**       (b) The number of pages allocated for all purgeable caches is
45921**           already equal to or greater than the sum of nMax for all
45922**           purgeable caches,
45923**
45924**       (c) The system is under memory pressure and wants to avoid
45925**           unnecessary pages cache entry allocations
45926**
45927**      then attempt to recycle a page from the LRU list. If it is the right
45928**      size, return the recycled buffer. Otherwise, free the buffer and
45929**      proceed to step 5.
45930**
45931**   5. Otherwise, allocate and return a new page buffer.
45932**
45933** There are two versions of this routine.  pcache1FetchWithMutex() is
45934** the general case.  pcache1FetchNoMutex() is a faster implementation for
45935** the common case where pGroup->mutex is NULL.  The pcache1Fetch() wrapper
45936** invokes the appropriate routine.
45937*/
45938static PgHdr1 *pcache1FetchNoMutex(
45939  sqlite3_pcache *p,
45940  unsigned int iKey,
45941  int createFlag
45942){
45943  PCache1 *pCache = (PCache1 *)p;
45944  PgHdr1 *pPage = 0;
45945
45946  /* Step 1: Search the hash table for an existing entry. */
45947  pPage = pCache->apHash[iKey % pCache->nHash];
45948  while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
45949
45950  /* Step 2: If the page was found in the hash table, then return it.
45951  ** If the page was not in the hash table and createFlag is 0, abort.
45952  ** Otherwise (page not in hash and createFlag!=0) continue with
45953  ** subsequent steps to try to create the page. */
45954  if( pPage ){
45955    if( !pPage->isPinned ){
45956      return pcache1PinPage(pPage);
45957    }else{
45958      return pPage;
45959    }
45960  }else if( createFlag ){
45961    /* Steps 3, 4, and 5 implemented by this subroutine */
45962    return pcache1FetchStage2(pCache, iKey, createFlag);
45963  }else{
45964    return 0;
45965  }
45966}
45967#if PCACHE1_MIGHT_USE_GROUP_MUTEX
45968static PgHdr1 *pcache1FetchWithMutex(
45969  sqlite3_pcache *p,
45970  unsigned int iKey,
45971  int createFlag
45972){
45973  PCache1 *pCache = (PCache1 *)p;
45974  PgHdr1 *pPage;
45975
45976  pcache1EnterMutex(pCache->pGroup);
45977  pPage = pcache1FetchNoMutex(p, iKey, createFlag);
45978  assert( pPage==0 || pCache->iMaxKey>=iKey );
45979  pcache1LeaveMutex(pCache->pGroup);
45980  return pPage;
45981}
45982#endif
45983static sqlite3_pcache_page *pcache1Fetch(
45984  sqlite3_pcache *p,
45985  unsigned int iKey,
45986  int createFlag
45987){
45988#if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
45989  PCache1 *pCache = (PCache1 *)p;
45990#endif
45991
45992  assert( offsetof(PgHdr1,page)==0 );
45993  assert( pCache->bPurgeable || createFlag!=1 );
45994  assert( pCache->bPurgeable || pCache->nMin==0 );
45995  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
45996  assert( pCache->nMin==0 || pCache->bPurgeable );
45997  assert( pCache->nHash>0 );
45998#if PCACHE1_MIGHT_USE_GROUP_MUTEX
45999  if( pCache->pGroup->mutex ){
46000    return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
46001  }else
46002#endif
46003  {
46004    return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
46005  }
46006}
46007
46008
46009/*
46010** Implementation of the sqlite3_pcache.xUnpin method.
46011**
46012** Mark a page as unpinned (eligible for asynchronous recycling).
46013*/
46014static void pcache1Unpin(
46015  sqlite3_pcache *p,
46016  sqlite3_pcache_page *pPg,
46017  int reuseUnlikely
46018){
46019  PCache1 *pCache = (PCache1 *)p;
46020  PgHdr1 *pPage = (PgHdr1 *)pPg;
46021  PGroup *pGroup = pCache->pGroup;
46022
46023  assert( pPage->pCache==pCache );
46024  pcache1EnterMutex(pGroup);
46025
46026  /* It is an error to call this function if the page is already
46027  ** part of the PGroup LRU list.
46028  */
46029  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
46030  assert( pPage->isPinned==1 );
46031
46032  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
46033    pcache1RemoveFromHash(pPage, 1);
46034  }else{
46035    /* Add the page to the PGroup LRU list. */
46036    PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
46037    pPage->pLruPrev = &pGroup->lru;
46038    (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
46039    *ppFirst = pPage;
46040    pCache->nRecyclable++;
46041    pPage->isPinned = 0;
46042  }
46043
46044  pcache1LeaveMutex(pCache->pGroup);
46045}
46046
46047/*
46048** Implementation of the sqlite3_pcache.xRekey method.
46049*/
46050static void pcache1Rekey(
46051  sqlite3_pcache *p,
46052  sqlite3_pcache_page *pPg,
46053  unsigned int iOld,
46054  unsigned int iNew
46055){
46056  PCache1 *pCache = (PCache1 *)p;
46057  PgHdr1 *pPage = (PgHdr1 *)pPg;
46058  PgHdr1 **pp;
46059  unsigned int h;
46060  assert( pPage->iKey==iOld );
46061  assert( pPage->pCache==pCache );
46062
46063  pcache1EnterMutex(pCache->pGroup);
46064
46065  h = iOld%pCache->nHash;
46066  pp = &pCache->apHash[h];
46067  while( (*pp)!=pPage ){
46068    pp = &(*pp)->pNext;
46069  }
46070  *pp = pPage->pNext;
46071
46072  h = iNew%pCache->nHash;
46073  pPage->iKey = iNew;
46074  pPage->pNext = pCache->apHash[h];
46075  pCache->apHash[h] = pPage;
46076  if( iNew>pCache->iMaxKey ){
46077    pCache->iMaxKey = iNew;
46078  }
46079
46080  pcache1LeaveMutex(pCache->pGroup);
46081}
46082
46083/*
46084** Implementation of the sqlite3_pcache.xTruncate method.
46085**
46086** Discard all unpinned pages in the cache with a page number equal to
46087** or greater than parameter iLimit. Any pinned pages with a page number
46088** equal to or greater than iLimit are implicitly unpinned.
46089*/
46090static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
46091  PCache1 *pCache = (PCache1 *)p;
46092  pcache1EnterMutex(pCache->pGroup);
46093  if( iLimit<=pCache->iMaxKey ){
46094    pcache1TruncateUnsafe(pCache, iLimit);
46095    pCache->iMaxKey = iLimit-1;
46096  }
46097  pcache1LeaveMutex(pCache->pGroup);
46098}
46099
46100/*
46101** Implementation of the sqlite3_pcache.xDestroy method.
46102**
46103** Destroy a cache allocated using pcache1Create().
46104*/
46105static void pcache1Destroy(sqlite3_pcache *p){
46106  PCache1 *pCache = (PCache1 *)p;
46107  PGroup *pGroup = pCache->pGroup;
46108  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
46109  pcache1EnterMutex(pGroup);
46110  if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
46111  assert( pGroup->nMaxPage >= pCache->nMax );
46112  pGroup->nMaxPage -= pCache->nMax;
46113  assert( pGroup->nMinPage >= pCache->nMin );
46114  pGroup->nMinPage -= pCache->nMin;
46115  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
46116  pcache1EnforceMaxPage(pCache);
46117  pcache1LeaveMutex(pGroup);
46118  sqlite3_free(pCache->pBulk);
46119  sqlite3_free(pCache->apHash);
46120  sqlite3_free(pCache);
46121}
46122
46123/*
46124** This function is called during initialization (sqlite3_initialize()) to
46125** install the default pluggable cache module, assuming the user has not
46126** already provided an alternative.
46127*/
46128SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
46129  static const sqlite3_pcache_methods2 defaultMethods = {
46130    1,                       /* iVersion */
46131    0,                       /* pArg */
46132    pcache1Init,             /* xInit */
46133    pcache1Shutdown,         /* xShutdown */
46134    pcache1Create,           /* xCreate */
46135    pcache1Cachesize,        /* xCachesize */
46136    pcache1Pagecount,        /* xPagecount */
46137    pcache1Fetch,            /* xFetch */
46138    pcache1Unpin,            /* xUnpin */
46139    pcache1Rekey,            /* xRekey */
46140    pcache1Truncate,         /* xTruncate */
46141    pcache1Destroy,          /* xDestroy */
46142    pcache1Shrink            /* xShrink */
46143  };
46144  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
46145}
46146
46147/*
46148** Return the size of the header on each page of this PCACHE implementation.
46149*/
46150SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
46151
46152/*
46153** Return the global mutex used by this PCACHE implementation.  The
46154** sqlite3_status() routine needs access to this mutex.
46155*/
46156SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
46157  return pcache1.mutex;
46158}
46159
46160#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
46161/*
46162** This function is called to free superfluous dynamically allocated memory
46163** held by the pager system. Memory in use by any SQLite pager allocated
46164** by the current thread may be sqlite3_free()ed.
46165**
46166** nReq is the number of bytes of memory required. Once this much has
46167** been released, the function returns. The return value is the total number
46168** of bytes of memory released.
46169*/
46170SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
46171  int nFree = 0;
46172  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
46173  assert( sqlite3_mutex_notheld(pcache1.mutex) );
46174  if( sqlite3GlobalConfig.nPage==0 ){
46175    PgHdr1 *p;
46176    pcache1EnterMutex(&pcache1.grp);
46177    while( (nReq<0 || nFree<nReq)
46178       &&  (p=pcache1.grp.lru.pLruPrev)!=0
46179       &&  p->isAnchor==0
46180    ){
46181      nFree += pcache1MemSize(p->page.pBuf);
46182#ifdef SQLITE_PCACHE_SEPARATE_HEADER
46183      nFree += sqlite3MemSize(p);
46184#endif
46185      assert( p->isPinned==0 );
46186      pcache1PinPage(p);
46187      pcache1RemoveFromHash(p, 1);
46188    }
46189    pcache1LeaveMutex(&pcache1.grp);
46190  }
46191  return nFree;
46192}
46193#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
46194
46195#ifdef SQLITE_TEST
46196/*
46197** This function is used by test procedures to inspect the internal state
46198** of the global cache.
46199*/
46200SQLITE_PRIVATE void sqlite3PcacheStats(
46201  int *pnCurrent,      /* OUT: Total number of pages cached */
46202  int *pnMax,          /* OUT: Global maximum cache size */
46203  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
46204  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
46205){
46206  PgHdr1 *p;
46207  int nRecyclable = 0;
46208  for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
46209    assert( p->isPinned==0 );
46210    nRecyclable++;
46211  }
46212  *pnCurrent = pcache1.grp.nCurrentPage;
46213  *pnMax = (int)pcache1.grp.nMaxPage;
46214  *pnMin = (int)pcache1.grp.nMinPage;
46215  *pnRecyclable = nRecyclable;
46216}
46217#endif
46218
46219/************** End of pcache1.c *********************************************/
46220/************** Begin file rowset.c ******************************************/
46221/*
46222** 2008 December 3
46223**
46224** The author disclaims copyright to this source code.  In place of
46225** a legal notice, here is a blessing:
46226**
46227**    May you do good and not evil.
46228**    May you find forgiveness for yourself and forgive others.
46229**    May you share freely, never taking more than you give.
46230**
46231*************************************************************************
46232**
46233** This module implements an object we call a "RowSet".
46234**
46235** The RowSet object is a collection of rowids.  Rowids
46236** are inserted into the RowSet in an arbitrary order.  Inserts
46237** can be intermixed with tests to see if a given rowid has been
46238** previously inserted into the RowSet.
46239**
46240** After all inserts are finished, it is possible to extract the
46241** elements of the RowSet in sorted order.  Once this extraction
46242** process has started, no new elements may be inserted.
46243**
46244** Hence, the primitive operations for a RowSet are:
46245**
46246**    CREATE
46247**    INSERT
46248**    TEST
46249**    SMALLEST
46250**    DESTROY
46251**
46252** The CREATE and DESTROY primitives are the constructor and destructor,
46253** obviously.  The INSERT primitive adds a new element to the RowSet.
46254** TEST checks to see if an element is already in the RowSet.  SMALLEST
46255** extracts the least value from the RowSet.
46256**
46257** The INSERT primitive might allocate additional memory.  Memory is
46258** allocated in chunks so most INSERTs do no allocation.  There is an
46259** upper bound on the size of allocated memory.  No memory is freed
46260** until DESTROY.
46261**
46262** The TEST primitive includes a "batch" number.  The TEST primitive
46263** will only see elements that were inserted before the last change
46264** in the batch number.  In other words, if an INSERT occurs between
46265** two TESTs where the TESTs have the same batch nubmer, then the
46266** value added by the INSERT will not be visible to the second TEST.
46267** The initial batch number is zero, so if the very first TEST contains
46268** a non-zero batch number, it will see all prior INSERTs.
46269**
46270** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
46271** that is attempted.
46272**
46273** The cost of an INSERT is roughly constant.  (Sometimes new memory
46274** has to be allocated on an INSERT.)  The cost of a TEST with a new
46275** batch number is O(NlogN) where N is the number of elements in the RowSet.
46276** The cost of a TEST using the same batch number is O(logN).  The cost
46277** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
46278** primitives are constant time.  The cost of DESTROY is O(N).
46279**
46280** TEST and SMALLEST may not be used by the same RowSet.  This used to
46281** be possible, but the feature was not used, so it was removed in order
46282** to simplify the code.
46283*/
46284/* #include "sqliteInt.h" */
46285
46286
46287/*
46288** Target size for allocation chunks.
46289*/
46290#define ROWSET_ALLOCATION_SIZE 1024
46291
46292/*
46293** The number of rowset entries per allocation chunk.
46294*/
46295#define ROWSET_ENTRY_PER_CHUNK  \
46296                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
46297
46298/*
46299** Each entry in a RowSet is an instance of the following object.
46300**
46301** This same object is reused to store a linked list of trees of RowSetEntry
46302** objects.  In that alternative use, pRight points to the next entry
46303** in the list, pLeft points to the tree, and v is unused.  The
46304** RowSet.pForest value points to the head of this forest list.
46305*/
46306struct RowSetEntry {
46307  i64 v;                        /* ROWID value for this entry */
46308  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
46309  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
46310};
46311
46312/*
46313** RowSetEntry objects are allocated in large chunks (instances of the
46314** following structure) to reduce memory allocation overhead.  The
46315** chunks are kept on a linked list so that they can be deallocated
46316** when the RowSet is destroyed.
46317*/
46318struct RowSetChunk {
46319  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
46320  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
46321};
46322
46323/*
46324** A RowSet in an instance of the following structure.
46325**
46326** A typedef of this structure if found in sqliteInt.h.
46327*/
46328struct RowSet {
46329  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
46330  sqlite3 *db;                   /* The database connection */
46331  struct RowSetEntry *pEntry;    /* List of entries using pRight */
46332  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
46333  struct RowSetEntry *pFresh;    /* Source of new entry objects */
46334  struct RowSetEntry *pForest;   /* List of binary trees of entries */
46335  u16 nFresh;                    /* Number of objects on pFresh */
46336  u16 rsFlags;                   /* Various flags */
46337  int iBatch;                    /* Current insert batch */
46338};
46339
46340/*
46341** Allowed values for RowSet.rsFlags
46342*/
46343#define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
46344#define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
46345
46346/*
46347** Turn bulk memory into a RowSet object.  N bytes of memory
46348** are available at pSpace.  The db pointer is used as a memory context
46349** for any subsequent allocations that need to occur.
46350** Return a pointer to the new RowSet object.
46351**
46352** It must be the case that N is sufficient to make a Rowset.  If not
46353** an assertion fault occurs.
46354**
46355** If N is larger than the minimum, use the surplus as an initial
46356** allocation of entries available to be filled.
46357*/
46358SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
46359  RowSet *p;
46360  assert( N >= ROUND8(sizeof(*p)) );
46361  p = pSpace;
46362  p->pChunk = 0;
46363  p->db = db;
46364  p->pEntry = 0;
46365  p->pLast = 0;
46366  p->pForest = 0;
46367  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
46368  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
46369  p->rsFlags = ROWSET_SORTED;
46370  p->iBatch = 0;
46371  return p;
46372}
46373
46374/*
46375** Deallocate all chunks from a RowSet.  This frees all memory that
46376** the RowSet has allocated over its lifetime.  This routine is
46377** the destructor for the RowSet.
46378*/
46379SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
46380  struct RowSetChunk *pChunk, *pNextChunk;
46381  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
46382    pNextChunk = pChunk->pNextChunk;
46383    sqlite3DbFree(p->db, pChunk);
46384  }
46385  p->pChunk = 0;
46386  p->nFresh = 0;
46387  p->pEntry = 0;
46388  p->pLast = 0;
46389  p->pForest = 0;
46390  p->rsFlags = ROWSET_SORTED;
46391}
46392
46393/*
46394** Allocate a new RowSetEntry object that is associated with the
46395** given RowSet.  Return a pointer to the new and completely uninitialized
46396** objected.
46397**
46398** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
46399** routine returns NULL.
46400*/
46401static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
46402  assert( p!=0 );
46403  if( p->nFresh==0 ){  /*OPTIMIZATION-IF-FALSE*/
46404    /* We could allocate a fresh RowSetEntry each time one is needed, but it
46405    ** is more efficient to pull a preallocated entry from the pool */
46406    struct RowSetChunk *pNew;
46407    pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
46408    if( pNew==0 ){
46409      return 0;
46410    }
46411    pNew->pNextChunk = p->pChunk;
46412    p->pChunk = pNew;
46413    p->pFresh = pNew->aEntry;
46414    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
46415  }
46416  p->nFresh--;
46417  return p->pFresh++;
46418}
46419
46420/*
46421** Insert a new value into a RowSet.
46422**
46423** The mallocFailed flag of the database connection is set if a
46424** memory allocation fails.
46425*/
46426SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
46427  struct RowSetEntry *pEntry;  /* The new entry */
46428  struct RowSetEntry *pLast;   /* The last prior entry */
46429
46430  /* This routine is never called after sqlite3RowSetNext() */
46431  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
46432
46433  pEntry = rowSetEntryAlloc(p);
46434  if( pEntry==0 ) return;
46435  pEntry->v = rowid;
46436  pEntry->pRight = 0;
46437  pLast = p->pLast;
46438  if( pLast ){
46439    if( rowid<=pLast->v ){  /*OPTIMIZATION-IF-FALSE*/
46440      /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
46441      ** where possible */
46442      p->rsFlags &= ~ROWSET_SORTED;
46443    }
46444    pLast->pRight = pEntry;
46445  }else{
46446    p->pEntry = pEntry;
46447  }
46448  p->pLast = pEntry;
46449}
46450
46451/*
46452** Merge two lists of RowSetEntry objects.  Remove duplicates.
46453**
46454** The input lists are connected via pRight pointers and are
46455** assumed to each already be in sorted order.
46456*/
46457static struct RowSetEntry *rowSetEntryMerge(
46458  struct RowSetEntry *pA,    /* First sorted list to be merged */
46459  struct RowSetEntry *pB     /* Second sorted list to be merged */
46460){
46461  struct RowSetEntry head;
46462  struct RowSetEntry *pTail;
46463
46464  pTail = &head;
46465  assert( pA!=0 && pB!=0 );
46466  for(;;){
46467    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
46468    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
46469    if( pA->v<=pB->v ){
46470      if( pA->v<pB->v ) pTail = pTail->pRight = pA;
46471      pA = pA->pRight;
46472      if( pA==0 ){
46473        pTail->pRight = pB;
46474        break;
46475      }
46476    }else{
46477      pTail = pTail->pRight = pB;
46478      pB = pB->pRight;
46479      if( pB==0 ){
46480        pTail->pRight = pA;
46481        break;
46482      }
46483    }
46484  }
46485  return head.pRight;
46486}
46487
46488/*
46489** Sort all elements on the list of RowSetEntry objects into order of
46490** increasing v.
46491*/
46492static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
46493  unsigned int i;
46494  struct RowSetEntry *pNext, *aBucket[40];
46495
46496  memset(aBucket, 0, sizeof(aBucket));
46497  while( pIn ){
46498    pNext = pIn->pRight;
46499    pIn->pRight = 0;
46500    for(i=0; aBucket[i]; i++){
46501      pIn = rowSetEntryMerge(aBucket[i], pIn);
46502      aBucket[i] = 0;
46503    }
46504    aBucket[i] = pIn;
46505    pIn = pNext;
46506  }
46507  pIn = aBucket[0];
46508  for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
46509    if( aBucket[i]==0 ) continue;
46510    pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
46511  }
46512  return pIn;
46513}
46514
46515
46516/*
46517** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
46518** Convert this tree into a linked list connected by the pRight pointers
46519** and return pointers to the first and last elements of the new list.
46520*/
46521static void rowSetTreeToList(
46522  struct RowSetEntry *pIn,         /* Root of the input tree */
46523  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
46524  struct RowSetEntry **ppLast      /* Write tail of the output list here */
46525){
46526  assert( pIn!=0 );
46527  if( pIn->pLeft ){
46528    struct RowSetEntry *p;
46529    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
46530    p->pRight = pIn;
46531  }else{
46532    *ppFirst = pIn;
46533  }
46534  if( pIn->pRight ){
46535    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
46536  }else{
46537    *ppLast = pIn;
46538  }
46539  assert( (*ppLast)->pRight==0 );
46540}
46541
46542
46543/*
46544** Convert a sorted list of elements (connected by pRight) into a binary
46545** tree with depth of iDepth.  A depth of 1 means the tree contains a single
46546** node taken from the head of *ppList.  A depth of 2 means a tree with
46547** three nodes.  And so forth.
46548**
46549** Use as many entries from the input list as required and update the
46550** *ppList to point to the unused elements of the list.  If the input
46551** list contains too few elements, then construct an incomplete tree
46552** and leave *ppList set to NULL.
46553**
46554** Return a pointer to the root of the constructed binary tree.
46555*/
46556static struct RowSetEntry *rowSetNDeepTree(
46557  struct RowSetEntry **ppList,
46558  int iDepth
46559){
46560  struct RowSetEntry *p;         /* Root of the new tree */
46561  struct RowSetEntry *pLeft;     /* Left subtree */
46562  if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
46563    /* Prevent unnecessary deep recursion when we run out of entries */
46564    return 0;
46565  }
46566  if( iDepth>1 ){   /*OPTIMIZATION-IF-TRUE*/
46567    /* This branch causes a *balanced* tree to be generated.  A valid tree
46568    ** is still generated without this branch, but the tree is wildly
46569    ** unbalanced and inefficient. */
46570    pLeft = rowSetNDeepTree(ppList, iDepth-1);
46571    p = *ppList;
46572    if( p==0 ){     /*OPTIMIZATION-IF-FALSE*/
46573      /* It is safe to always return here, but the resulting tree
46574      ** would be unbalanced */
46575      return pLeft;
46576    }
46577    p->pLeft = pLeft;
46578    *ppList = p->pRight;
46579    p->pRight = rowSetNDeepTree(ppList, iDepth-1);
46580  }else{
46581    p = *ppList;
46582    *ppList = p->pRight;
46583    p->pLeft = p->pRight = 0;
46584  }
46585  return p;
46586}
46587
46588/*
46589** Convert a sorted list of elements into a binary tree. Make the tree
46590** as deep as it needs to be in order to contain the entire list.
46591*/
46592static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
46593  int iDepth;           /* Depth of the tree so far */
46594  struct RowSetEntry *p;       /* Current tree root */
46595  struct RowSetEntry *pLeft;   /* Left subtree */
46596
46597  assert( pList!=0 );
46598  p = pList;
46599  pList = p->pRight;
46600  p->pLeft = p->pRight = 0;
46601  for(iDepth=1; pList; iDepth++){
46602    pLeft = p;
46603    p = pList;
46604    pList = p->pRight;
46605    p->pLeft = pLeft;
46606    p->pRight = rowSetNDeepTree(&pList, iDepth);
46607  }
46608  return p;
46609}
46610
46611/*
46612** Extract the smallest element from the RowSet.
46613** Write the element into *pRowid.  Return 1 on success.  Return
46614** 0 if the RowSet is already empty.
46615**
46616** After this routine has been called, the sqlite3RowSetInsert()
46617** routine may not be called again.
46618**
46619** This routine may not be called after sqlite3RowSetTest() has
46620** been used.  Older versions of RowSet allowed that, but as the
46621** capability was not used by the code generator, it was removed
46622** for code economy.
46623*/
46624SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
46625  assert( p!=0 );
46626  assert( p->pForest==0 );  /* Cannot be used with sqlite3RowSetText() */
46627
46628  /* Merge the forest into a single sorted list on first call */
46629  if( (p->rsFlags & ROWSET_NEXT)==0 ){  /*OPTIMIZATION-IF-FALSE*/
46630    if( (p->rsFlags & ROWSET_SORTED)==0 ){  /*OPTIMIZATION-IF-FALSE*/
46631      p->pEntry = rowSetEntrySort(p->pEntry);
46632    }
46633    p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
46634  }
46635
46636  /* Return the next entry on the list */
46637  if( p->pEntry ){
46638    *pRowid = p->pEntry->v;
46639    p->pEntry = p->pEntry->pRight;
46640    if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
46641      /* Free memory immediately, rather than waiting on sqlite3_finalize() */
46642      sqlite3RowSetClear(p);
46643    }
46644    return 1;
46645  }else{
46646    return 0;
46647  }
46648}
46649
46650/*
46651** Check to see if element iRowid was inserted into the rowset as
46652** part of any insert batch prior to iBatch.  Return 1 or 0.
46653**
46654** If this is the first test of a new batch and if there exist entries
46655** on pRowSet->pEntry, then sort those entries into the forest at
46656** pRowSet->pForest so that they can be tested.
46657*/
46658SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
46659  struct RowSetEntry *p, *pTree;
46660
46661  /* This routine is never called after sqlite3RowSetNext() */
46662  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
46663
46664  /* Sort entries into the forest on the first test of a new batch.
46665  ** To save unnecessary work, only do this when the batch number changes.
46666  */
46667  if( iBatch!=pRowSet->iBatch ){  /*OPTIMIZATION-IF-FALSE*/
46668    p = pRowSet->pEntry;
46669    if( p ){
46670      struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
46671      if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
46672        /* Only sort the current set of entiries if they need it */
46673        p = rowSetEntrySort(p);
46674      }
46675      for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
46676        ppPrevTree = &pTree->pRight;
46677        if( pTree->pLeft==0 ){
46678          pTree->pLeft = rowSetListToTree(p);
46679          break;
46680        }else{
46681          struct RowSetEntry *pAux, *pTail;
46682          rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
46683          pTree->pLeft = 0;
46684          p = rowSetEntryMerge(pAux, p);
46685        }
46686      }
46687      if( pTree==0 ){
46688        *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
46689        if( pTree ){
46690          pTree->v = 0;
46691          pTree->pRight = 0;
46692          pTree->pLeft = rowSetListToTree(p);
46693        }
46694      }
46695      pRowSet->pEntry = 0;
46696      pRowSet->pLast = 0;
46697      pRowSet->rsFlags |= ROWSET_SORTED;
46698    }
46699    pRowSet->iBatch = iBatch;
46700  }
46701
46702  /* Test to see if the iRowid value appears anywhere in the forest.
46703  ** Return 1 if it does and 0 if not.
46704  */
46705  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
46706    p = pTree->pLeft;
46707    while( p ){
46708      if( p->v<iRowid ){
46709        p = p->pRight;
46710      }else if( p->v>iRowid ){
46711        p = p->pLeft;
46712      }else{
46713        return 1;
46714      }
46715    }
46716  }
46717  return 0;
46718}
46719
46720/************** End of rowset.c **********************************************/
46721/************** Begin file pager.c *******************************************/
46722/*
46723** 2001 September 15
46724**
46725** The author disclaims copyright to this source code.  In place of
46726** a legal notice, here is a blessing:
46727**
46728**    May you do good and not evil.
46729**    May you find forgiveness for yourself and forgive others.
46730**    May you share freely, never taking more than you give.
46731**
46732*************************************************************************
46733** This is the implementation of the page cache subsystem or "pager".
46734**
46735** The pager is used to access a database disk file.  It implements
46736** atomic commit and rollback through the use of a journal file that
46737** is separate from the database file.  The pager also implements file
46738** locking to prevent two processes from writing the same database
46739** file simultaneously, or one process from reading the database while
46740** another is writing.
46741*/
46742#ifndef SQLITE_OMIT_DISKIO
46743/* #include "sqliteInt.h" */
46744/************** Include wal.h in the middle of pager.c ***********************/
46745/************** Begin file wal.h *********************************************/
46746/*
46747** 2010 February 1
46748**
46749** The author disclaims copyright to this source code.  In place of
46750** a legal notice, here is a blessing:
46751**
46752**    May you do good and not evil.
46753**    May you find forgiveness for yourself and forgive others.
46754**    May you share freely, never taking more than you give.
46755**
46756*************************************************************************
46757** This header file defines the interface to the write-ahead logging
46758** system. Refer to the comments below and the header comment attached to
46759** the implementation of each function in log.c for further details.
46760*/
46761
46762#ifndef SQLITE_WAL_H
46763#define SQLITE_WAL_H
46764
46765/* #include "sqliteInt.h" */
46766
46767/* Additional values that can be added to the sync_flags argument of
46768** sqlite3WalFrames():
46769*/
46770#define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
46771#define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
46772
46773#ifdef SQLITE_OMIT_WAL
46774# define sqlite3WalOpen(x,y,z)                   0
46775# define sqlite3WalLimit(x,y)
46776# define sqlite3WalClose(v,w,x,y,z)              0
46777# define sqlite3WalBeginReadTransaction(y,z)     0
46778# define sqlite3WalEndReadTransaction(z)
46779# define sqlite3WalDbsize(y)                     0
46780# define sqlite3WalBeginWriteTransaction(y)      0
46781# define sqlite3WalEndWriteTransaction(x)        0
46782# define sqlite3WalUndo(x,y,z)                   0
46783# define sqlite3WalSavepoint(y,z)
46784# define sqlite3WalSavepointUndo(y,z)            0
46785# define sqlite3WalFrames(u,v,w,x,y,z)           0
46786# define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
46787# define sqlite3WalCallback(z)                   0
46788# define sqlite3WalExclusiveMode(y,z)            0
46789# define sqlite3WalHeapMemory(z)                 0
46790# define sqlite3WalFramesize(z)                  0
46791# define sqlite3WalFindFrame(x,y,z)              0
46792# define sqlite3WalFile(x)                       0
46793#else
46794
46795#define WAL_SAVEPOINT_NDATA 4
46796
46797/* Connection to a write-ahead log (WAL) file.
46798** There is one object of this type for each pager.
46799*/
46800typedef struct Wal Wal;
46801
46802/* Open and close a connection to a write-ahead log. */
46803SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
46804SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
46805
46806/* Set the limiting size of a WAL file. */
46807SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
46808
46809/* Used by readers to open (lock) and close (unlock) a snapshot.  A
46810** snapshot is like a read-transaction.  It is the state of the database
46811** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
46812** preserves the current state even if the other threads or processes
46813** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
46814** transaction and releases the lock.
46815*/
46816SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
46817SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
46818
46819/* Read a page from the write-ahead log, if it is present. */
46820SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
46821SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
46822
46823/* If the WAL is not empty, return the size of the database. */
46824SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
46825
46826/* Obtain or release the WRITER lock. */
46827SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
46828SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
46829
46830/* Undo any frames written (but not committed) to the log */
46831SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
46832
46833/* Return an integer that records the current (uncommitted) write
46834** position in the WAL */
46835SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
46836
46837/* Move the write position of the WAL back to iFrame.  Called in
46838** response to a ROLLBACK TO command. */
46839SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
46840
46841/* Write a frame or frames to the log. */
46842SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
46843
46844/* Copy pages from the log to the database file */
46845SQLITE_PRIVATE int sqlite3WalCheckpoint(
46846  Wal *pWal,                      /* Write-ahead log connection */
46847  sqlite3 *db,                    /* Check this handle's interrupt flag */
46848  int eMode,                      /* One of PASSIVE, FULL and RESTART */
46849  int (*xBusy)(void*),            /* Function to call when busy */
46850  void *pBusyArg,                 /* Context argument for xBusyHandler */
46851  int sync_flags,                 /* Flags to sync db file with (or 0) */
46852  int nBuf,                       /* Size of buffer nBuf */
46853  u8 *zBuf,                       /* Temporary buffer to use */
46854  int *pnLog,                     /* OUT: Number of frames in WAL */
46855  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
46856);
46857
46858/* Return the value to pass to a sqlite3_wal_hook callback, the
46859** number of frames in the WAL at the point of the last commit since
46860** sqlite3WalCallback() was called.  If no commits have occurred since
46861** the last call, then return 0.
46862*/
46863SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
46864
46865/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
46866** by the pager layer on the database file.
46867*/
46868SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
46869
46870/* Return true if the argument is non-NULL and the WAL module is using
46871** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
46872** WAL module is using shared-memory, return false.
46873*/
46874SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
46875
46876#ifdef SQLITE_ENABLE_SNAPSHOT
46877SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
46878SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
46879SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
46880#endif
46881
46882#ifdef SQLITE_ENABLE_ZIPVFS
46883/* If the WAL file is not empty, return the number of bytes of content
46884** stored in each frame (i.e. the db page-size when the WAL was created).
46885*/
46886SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
46887#endif
46888
46889/* Return the sqlite3_file object for the WAL file */
46890SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
46891
46892#endif /* ifndef SQLITE_OMIT_WAL */
46893#endif /* SQLITE_WAL_H */
46894
46895/************** End of wal.h *************************************************/
46896/************** Continuing where we left off in pager.c **********************/
46897
46898
46899/******************* NOTES ON THE DESIGN OF THE PAGER ************************
46900**
46901** This comment block describes invariants that hold when using a rollback
46902** journal.  These invariants do not apply for journal_mode=WAL,
46903** journal_mode=MEMORY, or journal_mode=OFF.
46904**
46905** Within this comment block, a page is deemed to have been synced
46906** automatically as soon as it is written when PRAGMA synchronous=OFF.
46907** Otherwise, the page is not synced until the xSync method of the VFS
46908** is called successfully on the file containing the page.
46909**
46910** Definition:  A page of the database file is said to be "overwriteable" if
46911** one or more of the following are true about the page:
46912**
46913**     (a)  The original content of the page as it was at the beginning of
46914**          the transaction has been written into the rollback journal and
46915**          synced.
46916**
46917**     (b)  The page was a freelist leaf page at the start of the transaction.
46918**
46919**     (c)  The page number is greater than the largest page that existed in
46920**          the database file at the start of the transaction.
46921**
46922** (1) A page of the database file is never overwritten unless one of the
46923**     following are true:
46924**
46925**     (a) The page and all other pages on the same sector are overwriteable.
46926**
46927**     (b) The atomic page write optimization is enabled, and the entire
46928**         transaction other than the update of the transaction sequence
46929**         number consists of a single page change.
46930**
46931** (2) The content of a page written into the rollback journal exactly matches
46932**     both the content in the database when the rollback journal was written
46933**     and the content in the database at the beginning of the current
46934**     transaction.
46935**
46936** (3) Writes to the database file are an integer multiple of the page size
46937**     in length and are aligned on a page boundary.
46938**
46939** (4) Reads from the database file are either aligned on a page boundary and
46940**     an integer multiple of the page size in length or are taken from the
46941**     first 100 bytes of the database file.
46942**
46943** (5) All writes to the database file are synced prior to the rollback journal
46944**     being deleted, truncated, or zeroed.
46945**
46946** (6) If a master journal file is used, then all writes to the database file
46947**     are synced prior to the master journal being deleted.
46948**
46949** Definition: Two databases (or the same database at two points it time)
46950** are said to be "logically equivalent" if they give the same answer to
46951** all queries.  Note in particular the content of freelist leaf
46952** pages can be changed arbitrarily without affecting the logical equivalence
46953** of the database.
46954**
46955** (7) At any time, if any subset, including the empty set and the total set,
46956**     of the unsynced changes to a rollback journal are removed and the
46957**     journal is rolled back, the resulting database file will be logically
46958**     equivalent to the database file at the beginning of the transaction.
46959**
46960** (8) When a transaction is rolled back, the xTruncate method of the VFS
46961**     is called to restore the database file to the same size it was at
46962**     the beginning of the transaction.  (In some VFSes, the xTruncate
46963**     method is a no-op, but that does not change the fact the SQLite will
46964**     invoke it.)
46965**
46966** (9) Whenever the database file is modified, at least one bit in the range
46967**     of bytes from 24 through 39 inclusive will be changed prior to releasing
46968**     the EXCLUSIVE lock, thus signaling other connections on the same
46969**     database to flush their caches.
46970**
46971** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
46972**      than one billion transactions.
46973**
46974** (11) A database file is well-formed at the beginning and at the conclusion
46975**      of every transaction.
46976**
46977** (12) An EXCLUSIVE lock is held on the database file when writing to
46978**      the database file.
46979**
46980** (13) A SHARED lock is held on the database file while reading any
46981**      content out of the database file.
46982**
46983******************************************************************************/
46984
46985/*
46986** Macros for troubleshooting.  Normally turned off
46987*/
46988#if 0
46989int sqlite3PagerTrace=1;  /* True to enable tracing */
46990#define sqlite3DebugPrintf printf
46991#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
46992#else
46993#define PAGERTRACE(X)
46994#endif
46995
46996/*
46997** The following two macros are used within the PAGERTRACE() macros above
46998** to print out file-descriptors.
46999**
47000** PAGERID() takes a pointer to a Pager struct as its argument. The
47001** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
47002** struct as its argument.
47003*/
47004#define PAGERID(p) ((int)(p->fd))
47005#define FILEHANDLEID(fd) ((int)fd)
47006
47007/*
47008** The Pager.eState variable stores the current 'state' of a pager. A
47009** pager may be in any one of the seven states shown in the following
47010** state diagram.
47011**
47012**                            OPEN <------+------+
47013**                              |         |      |
47014**                              V         |      |
47015**               +---------> READER-------+      |
47016**               |              |                |
47017**               |              V                |
47018**               |<-------WRITER_LOCKED------> ERROR
47019**               |              |                ^
47020**               |              V                |
47021**               |<------WRITER_CACHEMOD-------->|
47022**               |              |                |
47023**               |              V                |
47024**               |<-------WRITER_DBMOD---------->|
47025**               |              |                |
47026**               |              V                |
47027**               +<------WRITER_FINISHED-------->+
47028**
47029**
47030** List of state transitions and the C [function] that performs each:
47031**
47032**   OPEN              -> READER              [sqlite3PagerSharedLock]
47033**   READER            -> OPEN                [pager_unlock]
47034**
47035**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
47036**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
47037**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
47038**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
47039**   WRITER_***        -> READER              [pager_end_transaction]
47040**
47041**   WRITER_***        -> ERROR               [pager_error]
47042**   ERROR             -> OPEN                [pager_unlock]
47043**
47044**
47045**  OPEN:
47046**
47047**    The pager starts up in this state. Nothing is guaranteed in this
47048**    state - the file may or may not be locked and the database size is
47049**    unknown. The database may not be read or written.
47050**
47051**    * No read or write transaction is active.
47052**    * Any lock, or no lock at all, may be held on the database file.
47053**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
47054**
47055**  READER:
47056**
47057**    In this state all the requirements for reading the database in
47058**    rollback (non-WAL) mode are met. Unless the pager is (or recently
47059**    was) in exclusive-locking mode, a user-level read transaction is
47060**    open. The database size is known in this state.
47061**
47062**    A connection running with locking_mode=normal enters this state when
47063**    it opens a read-transaction on the database and returns to state
47064**    OPEN after the read-transaction is completed. However a connection
47065**    running in locking_mode=exclusive (including temp databases) remains in
47066**    this state even after the read-transaction is closed. The only way
47067**    a locking_mode=exclusive connection can transition from READER to OPEN
47068**    is via the ERROR state (see below).
47069**
47070**    * A read transaction may be active (but a write-transaction cannot).
47071**    * A SHARED or greater lock is held on the database file.
47072**    * The dbSize variable may be trusted (even if a user-level read
47073**      transaction is not active). The dbOrigSize and dbFileSize variables
47074**      may not be trusted at this point.
47075**    * If the database is a WAL database, then the WAL connection is open.
47076**    * Even if a read-transaction is not open, it is guaranteed that
47077**      there is no hot-journal in the file-system.
47078**
47079**  WRITER_LOCKED:
47080**
47081**    The pager moves to this state from READER when a write-transaction
47082**    is first opened on the database. In WRITER_LOCKED state, all locks
47083**    required to start a write-transaction are held, but no actual
47084**    modifications to the cache or database have taken place.
47085**
47086**    In rollback mode, a RESERVED or (if the transaction was opened with
47087**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
47088**    moving to this state, but the journal file is not written to or opened
47089**    to in this state. If the transaction is committed or rolled back while
47090**    in WRITER_LOCKED state, all that is required is to unlock the database
47091**    file.
47092**
47093**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
47094**    If the connection is running with locking_mode=exclusive, an attempt
47095**    is made to obtain an EXCLUSIVE lock on the database file.
47096**
47097**    * A write transaction is active.
47098**    * If the connection is open in rollback-mode, a RESERVED or greater
47099**      lock is held on the database file.
47100**    * If the connection is open in WAL-mode, a WAL write transaction
47101**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
47102**      called).
47103**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
47104**    * The contents of the pager cache have not been modified.
47105**    * The journal file may or may not be open.
47106**    * Nothing (not even the first header) has been written to the journal.
47107**
47108**  WRITER_CACHEMOD:
47109**
47110**    A pager moves from WRITER_LOCKED state to this state when a page is
47111**    first modified by the upper layer. In rollback mode the journal file
47112**    is opened (if it is not already open) and a header written to the
47113**    start of it. The database file on disk has not been modified.
47114**
47115**    * A write transaction is active.
47116**    * A RESERVED or greater lock is held on the database file.
47117**    * The journal file is open and the first header has been written
47118**      to it, but the header has not been synced to disk.
47119**    * The contents of the page cache have been modified.
47120**
47121**  WRITER_DBMOD:
47122**
47123**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
47124**    when it modifies the contents of the database file. WAL connections
47125**    never enter this state (since they do not modify the database file,
47126**    just the log file).
47127**
47128**    * A write transaction is active.
47129**    * An EXCLUSIVE or greater lock is held on the database file.
47130**    * The journal file is open and the first header has been written
47131**      and synced to disk.
47132**    * The contents of the page cache have been modified (and possibly
47133**      written to disk).
47134**
47135**  WRITER_FINISHED:
47136**
47137**    It is not possible for a WAL connection to enter this state.
47138**
47139**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
47140**    state after the entire transaction has been successfully written into the
47141**    database file. In this state the transaction may be committed simply
47142**    by finalizing the journal file. Once in WRITER_FINISHED state, it is
47143**    not possible to modify the database further. At this point, the upper
47144**    layer must either commit or rollback the transaction.
47145**
47146**    * A write transaction is active.
47147**    * An EXCLUSIVE or greater lock is held on the database file.
47148**    * All writing and syncing of journal and database data has finished.
47149**      If no error occurred, all that remains is to finalize the journal to
47150**      commit the transaction. If an error did occur, the caller will need
47151**      to rollback the transaction.
47152**
47153**  ERROR:
47154**
47155**    The ERROR state is entered when an IO or disk-full error (including
47156**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
47157**    difficult to be sure that the in-memory pager state (cache contents,
47158**    db size etc.) are consistent with the contents of the file-system.
47159**
47160**    Temporary pager files may enter the ERROR state, but in-memory pagers
47161**    cannot.
47162**
47163**    For example, if an IO error occurs while performing a rollback,
47164**    the contents of the page-cache may be left in an inconsistent state.
47165**    At this point it would be dangerous to change back to READER state
47166**    (as usually happens after a rollback). Any subsequent readers might
47167**    report database corruption (due to the inconsistent cache), and if
47168**    they upgrade to writers, they may inadvertently corrupt the database
47169**    file. To avoid this hazard, the pager switches into the ERROR state
47170**    instead of READER following such an error.
47171**
47172**    Once it has entered the ERROR state, any attempt to use the pager
47173**    to read or write data returns an error. Eventually, once all
47174**    outstanding transactions have been abandoned, the pager is able to
47175**    transition back to OPEN state, discarding the contents of the
47176**    page-cache and any other in-memory state at the same time. Everything
47177**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
47178**    when a read-transaction is next opened on the pager (transitioning
47179**    the pager into READER state). At that point the system has recovered
47180**    from the error.
47181**
47182**    Specifically, the pager jumps into the ERROR state if:
47183**
47184**      1. An error occurs while attempting a rollback. This happens in
47185**         function sqlite3PagerRollback().
47186**
47187**      2. An error occurs while attempting to finalize a journal file
47188**         following a commit in function sqlite3PagerCommitPhaseTwo().
47189**
47190**      3. An error occurs while attempting to write to the journal or
47191**         database file in function pagerStress() in order to free up
47192**         memory.
47193**
47194**    In other cases, the error is returned to the b-tree layer. The b-tree
47195**    layer then attempts a rollback operation. If the error condition
47196**    persists, the pager enters the ERROR state via condition (1) above.
47197**
47198**    Condition (3) is necessary because it can be triggered by a read-only
47199**    statement executed within a transaction. In this case, if the error
47200**    code were simply returned to the user, the b-tree layer would not
47201**    automatically attempt a rollback, as it assumes that an error in a
47202**    read-only statement cannot leave the pager in an internally inconsistent
47203**    state.
47204**
47205**    * The Pager.errCode variable is set to something other than SQLITE_OK.
47206**    * There are one or more outstanding references to pages (after the
47207**      last reference is dropped the pager should move back to OPEN state).
47208**    * The pager is not an in-memory pager.
47209**
47210**
47211** Notes:
47212**
47213**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
47214**     connection is open in WAL mode. A WAL connection is always in one
47215**     of the first four states.
47216**
47217**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
47218**     state. There are two exceptions: immediately after exclusive-mode has
47219**     been turned on (and before any read or write transactions are
47220**     executed), and when the pager is leaving the "error state".
47221**
47222**   * See also: assert_pager_state().
47223*/
47224#define PAGER_OPEN                  0
47225#define PAGER_READER                1
47226#define PAGER_WRITER_LOCKED         2
47227#define PAGER_WRITER_CACHEMOD       3
47228#define PAGER_WRITER_DBMOD          4
47229#define PAGER_WRITER_FINISHED       5
47230#define PAGER_ERROR                 6
47231
47232/*
47233** The Pager.eLock variable is almost always set to one of the
47234** following locking-states, according to the lock currently held on
47235** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
47236** This variable is kept up to date as locks are taken and released by
47237** the pagerLockDb() and pagerUnlockDb() wrappers.
47238**
47239** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
47240** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
47241** the operation was successful. In these circumstances pagerLockDb() and
47242** pagerUnlockDb() take a conservative approach - eLock is always updated
47243** when unlocking the file, and only updated when locking the file if the
47244** VFS call is successful. This way, the Pager.eLock variable may be set
47245** to a less exclusive (lower) value than the lock that is actually held
47246** at the system level, but it is never set to a more exclusive value.
47247**
47248** This is usually safe. If an xUnlock fails or appears to fail, there may
47249** be a few redundant xLock() calls or a lock may be held for longer than
47250** required, but nothing really goes wrong.
47251**
47252** The exception is when the database file is unlocked as the pager moves
47253** from ERROR to OPEN state. At this point there may be a hot-journal file
47254** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
47255** transition, by the same pager or any other). If the call to xUnlock()
47256** fails at this point and the pager is left holding an EXCLUSIVE lock, this
47257** can confuse the call to xCheckReservedLock() call made later as part
47258** of hot-journal detection.
47259**
47260** xCheckReservedLock() is defined as returning true "if there is a RESERVED
47261** lock held by this process or any others". So xCheckReservedLock may
47262** return true because the caller itself is holding an EXCLUSIVE lock (but
47263** doesn't know it because of a previous error in xUnlock). If this happens
47264** a hot-journal may be mistaken for a journal being created by an active
47265** transaction in another process, causing SQLite to read from the database
47266** without rolling it back.
47267**
47268** To work around this, if a call to xUnlock() fails when unlocking the
47269** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
47270** is only changed back to a real locking state after a successful call
47271** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
47272** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
47273** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
47274** lock on the database file before attempting to roll it back. See function
47275** PagerSharedLock() for more detail.
47276**
47277** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
47278** PAGER_OPEN state.
47279*/
47280#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
47281
47282/*
47283** A macro used for invoking the codec if there is one
47284*/
47285#ifdef SQLITE_HAS_CODEC
47286# define CODEC1(P,D,N,X,E) \
47287    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
47288# define CODEC2(P,D,N,X,E,O) \
47289    if( P->xCodec==0 ){ O=(char*)D; }else \
47290    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
47291#else
47292# define CODEC1(P,D,N,X,E)   /* NO-OP */
47293# define CODEC2(P,D,N,X,E,O) O=(char*)D
47294#endif
47295
47296/*
47297** The maximum allowed sector size. 64KiB. If the xSectorsize() method
47298** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
47299** This could conceivably cause corruption following a power failure on
47300** such a system. This is currently an undocumented limit.
47301*/
47302#define MAX_SECTOR_SIZE 0x10000
47303
47304
47305/*
47306** An instance of the following structure is allocated for each active
47307** savepoint and statement transaction in the system. All such structures
47308** are stored in the Pager.aSavepoint[] array, which is allocated and
47309** resized using sqlite3Realloc().
47310**
47311** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
47312** set to 0. If a journal-header is written into the main journal while
47313** the savepoint is active, then iHdrOffset is set to the byte offset
47314** immediately following the last journal record written into the main
47315** journal before the journal-header. This is required during savepoint
47316** rollback (see pagerPlaybackSavepoint()).
47317*/
47318typedef struct PagerSavepoint PagerSavepoint;
47319struct PagerSavepoint {
47320  i64 iOffset;                 /* Starting offset in main journal */
47321  i64 iHdrOffset;              /* See above */
47322  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
47323  Pgno nOrig;                  /* Original number of pages in file */
47324  Pgno iSubRec;                /* Index of first record in sub-journal */
47325#ifndef SQLITE_OMIT_WAL
47326  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
47327#endif
47328};
47329
47330/*
47331** Bits of the Pager.doNotSpill flag.  See further description below.
47332*/
47333#define SPILLFLAG_OFF         0x01 /* Never spill cache.  Set via pragma */
47334#define SPILLFLAG_ROLLBACK    0x02 /* Current rolling back, so do not spill */
47335#define SPILLFLAG_NOSYNC      0x04 /* Spill is ok, but do not sync */
47336
47337/*
47338** An open page cache is an instance of struct Pager. A description of
47339** some of the more important member variables follows:
47340**
47341** eState
47342**
47343**   The current 'state' of the pager object. See the comment and state
47344**   diagram above for a description of the pager state.
47345**
47346** eLock
47347**
47348**   For a real on-disk database, the current lock held on the database file -
47349**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
47350**
47351**   For a temporary or in-memory database (neither of which require any
47352**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
47353**   databases always have Pager.exclusiveMode==1, this tricks the pager
47354**   logic into thinking that it already has all the locks it will ever
47355**   need (and no reason to release them).
47356**
47357**   In some (obscure) circumstances, this variable may also be set to
47358**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
47359**   details.
47360**
47361** changeCountDone
47362**
47363**   This boolean variable is used to make sure that the change-counter
47364**   (the 4-byte header field at byte offset 24 of the database file) is
47365**   not updated more often than necessary.
47366**
47367**   It is set to true when the change-counter field is updated, which
47368**   can only happen if an exclusive lock is held on the database file.
47369**   It is cleared (set to false) whenever an exclusive lock is
47370**   relinquished on the database file. Each time a transaction is committed,
47371**   The changeCountDone flag is inspected. If it is true, the work of
47372**   updating the change-counter is omitted for the current transaction.
47373**
47374**   This mechanism means that when running in exclusive mode, a connection
47375**   need only update the change-counter once, for the first transaction
47376**   committed.
47377**
47378** setMaster
47379**
47380**   When PagerCommitPhaseOne() is called to commit a transaction, it may
47381**   (or may not) specify a master-journal name to be written into the
47382**   journal file before it is synced to disk.
47383**
47384**   Whether or not a journal file contains a master-journal pointer affects
47385**   the way in which the journal file is finalized after the transaction is
47386**   committed or rolled back when running in "journal_mode=PERSIST" mode.
47387**   If a journal file does not contain a master-journal pointer, it is
47388**   finalized by overwriting the first journal header with zeroes. If
47389**   it does contain a master-journal pointer the journal file is finalized
47390**   by truncating it to zero bytes, just as if the connection were
47391**   running in "journal_mode=truncate" mode.
47392**
47393**   Journal files that contain master journal pointers cannot be finalized
47394**   simply by overwriting the first journal-header with zeroes, as the
47395**   master journal pointer could interfere with hot-journal rollback of any
47396**   subsequently interrupted transaction that reuses the journal file.
47397**
47398**   The flag is cleared as soon as the journal file is finalized (either
47399**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
47400**   journal file from being successfully finalized, the setMaster flag
47401**   is cleared anyway (and the pager will move to ERROR state).
47402**
47403** doNotSpill
47404**
47405**   This variables control the behavior of cache-spills  (calls made by
47406**   the pcache module to the pagerStress() routine to write cached data
47407**   to the file-system in order to free up memory).
47408**
47409**   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
47410**   writing to the database from pagerStress() is disabled altogether.
47411**   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
47412**   comes up during savepoint rollback that requires the pcache module
47413**   to allocate a new page to prevent the journal file from being written
47414**   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
47415**   case is a user preference.
47416**
47417**   If the SPILLFLAG_NOSYNC bit is set, writing to the database from
47418**   pagerStress() is permitted, but syncing the journal file is not.
47419**   This flag is set by sqlite3PagerWrite() when the file-system sector-size
47420**   is larger than the database page-size in order to prevent a journal sync
47421**   from happening in between the journalling of two pages on the same sector.
47422**
47423** subjInMemory
47424**
47425**   This is a boolean variable. If true, then any required sub-journal
47426**   is opened as an in-memory journal file. If false, then in-memory
47427**   sub-journals are only used for in-memory pager files.
47428**
47429**   This variable is updated by the upper layer each time a new
47430**   write-transaction is opened.
47431**
47432** dbSize, dbOrigSize, dbFileSize
47433**
47434**   Variable dbSize is set to the number of pages in the database file.
47435**   It is valid in PAGER_READER and higher states (all states except for
47436**   OPEN and ERROR).
47437**
47438**   dbSize is set based on the size of the database file, which may be
47439**   larger than the size of the database (the value stored at offset
47440**   28 of the database header by the btree). If the size of the file
47441**   is not an integer multiple of the page-size, the value stored in
47442**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
47443**   Except, any file that is greater than 0 bytes in size is considered
47444**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
47445**   to dbSize==1).
47446**
47447**   During a write-transaction, if pages with page-numbers greater than
47448**   dbSize are modified in the cache, dbSize is updated accordingly.
47449**   Similarly, if the database is truncated using PagerTruncateImage(),
47450**   dbSize is updated.
47451**
47452**   Variables dbOrigSize and dbFileSize are valid in states
47453**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
47454**   variable at the start of the transaction. It is used during rollback,
47455**   and to determine whether or not pages need to be journalled before
47456**   being modified.
47457**
47458**   Throughout a write-transaction, dbFileSize contains the size of
47459**   the file on disk in pages. It is set to a copy of dbSize when the
47460**   write-transaction is first opened, and updated when VFS calls are made
47461**   to write or truncate the database file on disk.
47462**
47463**   The only reason the dbFileSize variable is required is to suppress
47464**   unnecessary calls to xTruncate() after committing a transaction. If,
47465**   when a transaction is committed, the dbFileSize variable indicates
47466**   that the database file is larger than the database image (Pager.dbSize),
47467**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
47468**   to measure the database file on disk, and then truncates it if required.
47469**   dbFileSize is not used when rolling back a transaction. In this case
47470**   pager_truncate() is called unconditionally (which means there may be
47471**   a call to xFilesize() that is not strictly required). In either case,
47472**   pager_truncate() may cause the file to become smaller or larger.
47473**
47474** dbHintSize
47475**
47476**   The dbHintSize variable is used to limit the number of calls made to
47477**   the VFS xFileControl(FCNTL_SIZE_HINT) method.
47478**
47479**   dbHintSize is set to a copy of the dbSize variable when a
47480**   write-transaction is opened (at the same time as dbFileSize and
47481**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
47482**   dbHintSize is increased to the number of pages that correspond to the
47483**   size-hint passed to the method call. See pager_write_pagelist() for
47484**   details.
47485**
47486** errCode
47487**
47488**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
47489**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
47490**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
47491**   sub-codes.
47492*/
47493struct Pager {
47494  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
47495  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
47496  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
47497  u8 useJournal;              /* Use a rollback journal on this file */
47498  u8 noSync;                  /* Do not sync the journal if true */
47499  u8 fullSync;                /* Do extra syncs of the journal for robustness */
47500  u8 extraSync;               /* sync directory after journal delete */
47501  u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
47502  u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
47503  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
47504  u8 tempFile;                /* zFilename is a temporary or immutable file */
47505  u8 noLock;                  /* Do not lock (except in WAL mode) */
47506  u8 readOnly;                /* True for a read-only database */
47507  u8 memDb;                   /* True to inhibit all file I/O */
47508
47509  /**************************************************************************
47510  ** The following block contains those class members that change during
47511  ** routine operation.  Class members not in this block are either fixed
47512  ** when the pager is first created or else only change when there is a
47513  ** significant mode change (such as changing the page_size, locking_mode,
47514  ** or the journal_mode).  From another view, these class members describe
47515  ** the "state" of the pager, while other class members describe the
47516  ** "configuration" of the pager.
47517  */
47518  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
47519  u8 eLock;                   /* Current lock held on database file */
47520  u8 changeCountDone;         /* Set after incrementing the change-counter */
47521  u8 setMaster;               /* True if a m-j name has been written to jrnl */
47522  u8 doNotSpill;              /* Do not spill the cache when non-zero */
47523  u8 subjInMemory;            /* True to use in-memory sub-journals */
47524  u8 bUseFetch;               /* True to use xFetch() */
47525  u8 hasHeldSharedLock;       /* True if a shared lock has ever been held */
47526  Pgno dbSize;                /* Number of pages in the database */
47527  Pgno dbOrigSize;            /* dbSize before the current transaction */
47528  Pgno dbFileSize;            /* Number of pages in the database file */
47529  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
47530  int errCode;                /* One of several kinds of errors */
47531  int nRec;                   /* Pages journalled since last j-header written */
47532  u32 cksumInit;              /* Quasi-random value added to every checksum */
47533  u32 nSubRec;                /* Number of records written to sub-journal */
47534  Bitvec *pInJournal;         /* One bit for each page in the database file */
47535  sqlite3_file *fd;           /* File descriptor for database */
47536  sqlite3_file *jfd;          /* File descriptor for main journal */
47537  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
47538  i64 journalOff;             /* Current write offset in the journal file */
47539  i64 journalHdr;             /* Byte offset to previous journal header */
47540  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
47541  PagerSavepoint *aSavepoint; /* Array of active savepoints */
47542  int nSavepoint;             /* Number of elements in aSavepoint[] */
47543  u32 iDataVersion;           /* Changes whenever database content changes */
47544  char dbFileVers[16];        /* Changes whenever database file changes */
47545
47546  int nMmapOut;               /* Number of mmap pages currently outstanding */
47547  sqlite3_int64 szMmap;       /* Desired maximum mmap size */
47548  PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
47549  /*
47550  ** End of the routinely-changing class members
47551  ***************************************************************************/
47552
47553  u16 nExtra;                 /* Add this many bytes to each in-memory page */
47554  i16 nReserve;               /* Number of unused bytes at end of each page */
47555  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
47556  u32 sectorSize;             /* Assumed sector size during rollback */
47557  int pageSize;               /* Number of bytes in a page */
47558  Pgno mxPgno;                /* Maximum allowed size of the database */
47559  i64 journalSizeLimit;       /* Size limit for persistent journal files */
47560  char *zFilename;            /* Name of the database file */
47561  char *zJournal;             /* Name of the journal file */
47562  int (*xBusyHandler)(void*); /* Function to call when busy */
47563  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
47564  int aStat[3];               /* Total cache hits, misses and writes */
47565#ifdef SQLITE_TEST
47566  int nRead;                  /* Database pages read */
47567#endif
47568  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
47569  int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
47570#ifdef SQLITE_HAS_CODEC
47571  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
47572  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
47573  void (*xCodecFree)(void*);             /* Destructor for the codec */
47574  void *pCodec;               /* First argument to xCodec... methods */
47575#endif
47576  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
47577  PCache *pPCache;            /* Pointer to page cache object */
47578#ifndef SQLITE_OMIT_WAL
47579  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
47580  char *zWal;                 /* File name for write-ahead log */
47581#endif
47582};
47583
47584/*
47585** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
47586** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
47587** or CACHE_WRITE to sqlite3_db_status().
47588*/
47589#define PAGER_STAT_HIT   0
47590#define PAGER_STAT_MISS  1
47591#define PAGER_STAT_WRITE 2
47592
47593/*
47594** The following global variables hold counters used for
47595** testing purposes only.  These variables do not exist in
47596** a non-testing build.  These variables are not thread-safe.
47597*/
47598#ifdef SQLITE_TEST
47599SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
47600SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
47601SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
47602# define PAGER_INCR(v)  v++
47603#else
47604# define PAGER_INCR(v)
47605#endif
47606
47607
47608
47609/*
47610** Journal files begin with the following magic string.  The data
47611** was obtained from /dev/random.  It is used only as a sanity check.
47612**
47613** Since version 2.8.0, the journal format contains additional sanity
47614** checking information.  If the power fails while the journal is being
47615** written, semi-random garbage data might appear in the journal
47616** file after power is restored.  If an attempt is then made
47617** to roll the journal back, the database could be corrupted.  The additional
47618** sanity checking data is an attempt to discover the garbage in the
47619** journal and ignore it.
47620**
47621** The sanity checking information for the new journal format consists
47622** of a 32-bit checksum on each page of data.  The checksum covers both
47623** the page number and the pPager->pageSize bytes of data for the page.
47624** This cksum is initialized to a 32-bit random value that appears in the
47625** journal file right after the header.  The random initializer is important,
47626** because garbage data that appears at the end of a journal is likely
47627** data that was once in other files that have now been deleted.  If the
47628** garbage data came from an obsolete journal file, the checksums might
47629** be correct.  But by initializing the checksum to random value which
47630** is different for every journal, we minimize that risk.
47631*/
47632static const unsigned char aJournalMagic[] = {
47633  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
47634};
47635
47636/*
47637** The size of the of each page record in the journal is given by
47638** the following macro.
47639*/
47640#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
47641
47642/*
47643** The journal header size for this pager. This is usually the same
47644** size as a single disk sector. See also setSectorSize().
47645*/
47646#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
47647
47648/*
47649** The macro MEMDB is true if we are dealing with an in-memory database.
47650** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
47651** the value of MEMDB will be a constant and the compiler will optimize
47652** out code that would never execute.
47653*/
47654#ifdef SQLITE_OMIT_MEMORYDB
47655# define MEMDB 0
47656#else
47657# define MEMDB pPager->memDb
47658#endif
47659
47660/*
47661** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
47662** interfaces to access the database using memory-mapped I/O.
47663*/
47664#if SQLITE_MAX_MMAP_SIZE>0
47665# define USEFETCH(x) ((x)->bUseFetch)
47666#else
47667# define USEFETCH(x) 0
47668#endif
47669
47670/*
47671** The maximum legal page number is (2^31 - 1).
47672*/
47673#define PAGER_MAX_PGNO 2147483647
47674
47675/*
47676** The argument to this macro is a file descriptor (type sqlite3_file*).
47677** Return 0 if it is not open, or non-zero (but not 1) if it is.
47678**
47679** This is so that expressions can be written as:
47680**
47681**   if( isOpen(pPager->jfd) ){ ...
47682**
47683** instead of
47684**
47685**   if( pPager->jfd->pMethods ){ ...
47686*/
47687#define isOpen(pFd) ((pFd)->pMethods!=0)
47688
47689/*
47690** Return true if this pager uses a write-ahead log to read page pgno.
47691** Return false if the pager reads pgno directly from the database.
47692*/
47693#if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_DIRECT_OVERFLOW_READ)
47694SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno pgno){
47695  u32 iRead = 0;
47696  int rc;
47697  if( pPager->pWal==0 ) return 0;
47698  rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
47699  return rc || iRead;
47700}
47701#endif
47702#ifndef SQLITE_OMIT_WAL
47703# define pagerUseWal(x) ((x)->pWal!=0)
47704#else
47705# define pagerUseWal(x) 0
47706# define pagerRollbackWal(x) 0
47707# define pagerWalFrames(v,w,x,y) 0
47708# define pagerOpenWalIfPresent(z) SQLITE_OK
47709# define pagerBeginReadTransaction(z) SQLITE_OK
47710#endif
47711
47712#ifndef NDEBUG
47713/*
47714** Usage:
47715**
47716**   assert( assert_pager_state(pPager) );
47717**
47718** This function runs many asserts to try to find inconsistencies in
47719** the internal state of the Pager object.
47720*/
47721static int assert_pager_state(Pager *p){
47722  Pager *pPager = p;
47723
47724  /* State must be valid. */
47725  assert( p->eState==PAGER_OPEN
47726       || p->eState==PAGER_READER
47727       || p->eState==PAGER_WRITER_LOCKED
47728       || p->eState==PAGER_WRITER_CACHEMOD
47729       || p->eState==PAGER_WRITER_DBMOD
47730       || p->eState==PAGER_WRITER_FINISHED
47731       || p->eState==PAGER_ERROR
47732  );
47733
47734  /* Regardless of the current state, a temp-file connection always behaves
47735  ** as if it has an exclusive lock on the database file. It never updates
47736  ** the change-counter field, so the changeCountDone flag is always set.
47737  */
47738  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
47739  assert( p->tempFile==0 || pPager->changeCountDone );
47740
47741  /* If the useJournal flag is clear, the journal-mode must be "OFF".
47742  ** And if the journal-mode is "OFF", the journal file must not be open.
47743  */
47744  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
47745  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
47746
47747  /* Check that MEMDB implies noSync. And an in-memory journal. Since
47748  ** this means an in-memory pager performs no IO at all, it cannot encounter
47749  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
47750  ** a journal file. (although the in-memory journal implementation may
47751  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
47752  ** is therefore not possible for an in-memory pager to enter the ERROR
47753  ** state.
47754  */
47755  if( MEMDB ){
47756    assert( !isOpen(p->fd) );
47757    assert( p->noSync );
47758    assert( p->journalMode==PAGER_JOURNALMODE_OFF
47759         || p->journalMode==PAGER_JOURNALMODE_MEMORY
47760    );
47761    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
47762    assert( pagerUseWal(p)==0 );
47763  }
47764
47765  /* If changeCountDone is set, a RESERVED lock or greater must be held
47766  ** on the file.
47767  */
47768  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
47769  assert( p->eLock!=PENDING_LOCK );
47770
47771  switch( p->eState ){
47772    case PAGER_OPEN:
47773      assert( !MEMDB );
47774      assert( pPager->errCode==SQLITE_OK );
47775      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
47776      break;
47777
47778    case PAGER_READER:
47779      assert( pPager->errCode==SQLITE_OK );
47780      assert( p->eLock!=UNKNOWN_LOCK );
47781      assert( p->eLock>=SHARED_LOCK );
47782      break;
47783
47784    case PAGER_WRITER_LOCKED:
47785      assert( p->eLock!=UNKNOWN_LOCK );
47786      assert( pPager->errCode==SQLITE_OK );
47787      if( !pagerUseWal(pPager) ){
47788        assert( p->eLock>=RESERVED_LOCK );
47789      }
47790      assert( pPager->dbSize==pPager->dbOrigSize );
47791      assert( pPager->dbOrigSize==pPager->dbFileSize );
47792      assert( pPager->dbOrigSize==pPager->dbHintSize );
47793      assert( pPager->setMaster==0 );
47794      break;
47795
47796    case PAGER_WRITER_CACHEMOD:
47797      assert( p->eLock!=UNKNOWN_LOCK );
47798      assert( pPager->errCode==SQLITE_OK );
47799      if( !pagerUseWal(pPager) ){
47800        /* It is possible that if journal_mode=wal here that neither the
47801        ** journal file nor the WAL file are open. This happens during
47802        ** a rollback transaction that switches from journal_mode=off
47803        ** to journal_mode=wal.
47804        */
47805        assert( p->eLock>=RESERVED_LOCK );
47806        assert( isOpen(p->jfd)
47807             || p->journalMode==PAGER_JOURNALMODE_OFF
47808             || p->journalMode==PAGER_JOURNALMODE_WAL
47809        );
47810      }
47811      assert( pPager->dbOrigSize==pPager->dbFileSize );
47812      assert( pPager->dbOrigSize==pPager->dbHintSize );
47813      break;
47814
47815    case PAGER_WRITER_DBMOD:
47816      assert( p->eLock==EXCLUSIVE_LOCK );
47817      assert( pPager->errCode==SQLITE_OK );
47818      assert( !pagerUseWal(pPager) );
47819      assert( p->eLock>=EXCLUSIVE_LOCK );
47820      assert( isOpen(p->jfd)
47821           || p->journalMode==PAGER_JOURNALMODE_OFF
47822           || p->journalMode==PAGER_JOURNALMODE_WAL
47823      );
47824      assert( pPager->dbOrigSize<=pPager->dbHintSize );
47825      break;
47826
47827    case PAGER_WRITER_FINISHED:
47828      assert( p->eLock==EXCLUSIVE_LOCK );
47829      assert( pPager->errCode==SQLITE_OK );
47830      assert( !pagerUseWal(pPager) );
47831      assert( isOpen(p->jfd)
47832           || p->journalMode==PAGER_JOURNALMODE_OFF
47833           || p->journalMode==PAGER_JOURNALMODE_WAL
47834      );
47835      break;
47836
47837    case PAGER_ERROR:
47838      /* There must be at least one outstanding reference to the pager if
47839      ** in ERROR state. Otherwise the pager should have already dropped
47840      ** back to OPEN state.
47841      */
47842      assert( pPager->errCode!=SQLITE_OK );
47843      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
47844      break;
47845  }
47846
47847  return 1;
47848}
47849#endif /* ifndef NDEBUG */
47850
47851#ifdef SQLITE_DEBUG
47852/*
47853** Return a pointer to a human readable string in a static buffer
47854** containing the state of the Pager object passed as an argument. This
47855** is intended to be used within debuggers. For example, as an alternative
47856** to "print *pPager" in gdb:
47857**
47858** (gdb) printf "%s", print_pager_state(pPager)
47859*/
47860static char *print_pager_state(Pager *p){
47861  static char zRet[1024];
47862
47863  sqlite3_snprintf(1024, zRet,
47864      "Filename:      %s\n"
47865      "State:         %s errCode=%d\n"
47866      "Lock:          %s\n"
47867      "Locking mode:  locking_mode=%s\n"
47868      "Journal mode:  journal_mode=%s\n"
47869      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
47870      "Journal:       journalOff=%lld journalHdr=%lld\n"
47871      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
47872      , p->zFilename
47873      , p->eState==PAGER_OPEN            ? "OPEN" :
47874        p->eState==PAGER_READER          ? "READER" :
47875        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
47876        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
47877        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
47878        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
47879        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
47880      , (int)p->errCode
47881      , p->eLock==NO_LOCK         ? "NO_LOCK" :
47882        p->eLock==RESERVED_LOCK   ? "RESERVED" :
47883        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
47884        p->eLock==SHARED_LOCK     ? "SHARED" :
47885        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
47886      , p->exclusiveMode ? "exclusive" : "normal"
47887      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
47888        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
47889        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
47890        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
47891        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
47892        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
47893      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
47894      , p->journalOff, p->journalHdr
47895      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
47896  );
47897
47898  return zRet;
47899}
47900#endif
47901
47902/* Forward references to the various page getters */
47903static int getPageNormal(Pager*,Pgno,DbPage**,int);
47904static int getPageError(Pager*,Pgno,DbPage**,int);
47905#if SQLITE_MAX_MMAP_SIZE>0
47906static int getPageMMap(Pager*,Pgno,DbPage**,int);
47907#endif
47908
47909/*
47910** Set the Pager.xGet method for the appropriate routine used to fetch
47911** content from the pager.
47912*/
47913static void setGetterMethod(Pager *pPager){
47914  if( pPager->errCode ){
47915    pPager->xGet = getPageError;
47916#if SQLITE_MAX_MMAP_SIZE>0
47917  }else if( USEFETCH(pPager)
47918#ifdef SQLITE_HAS_CODEC
47919   && pPager->xCodec==0
47920#endif
47921  ){
47922    pPager->xGet = getPageMMap;
47923#endif /* SQLITE_MAX_MMAP_SIZE>0 */
47924  }else{
47925    pPager->xGet = getPageNormal;
47926  }
47927}
47928
47929/*
47930** Return true if it is necessary to write page *pPg into the sub-journal.
47931** A page needs to be written into the sub-journal if there exists one
47932** or more open savepoints for which:
47933**
47934**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
47935**   * The bit corresponding to the page-number is not set in
47936**     PagerSavepoint.pInSavepoint.
47937*/
47938static int subjRequiresPage(PgHdr *pPg){
47939  Pager *pPager = pPg->pPager;
47940  PagerSavepoint *p;
47941  Pgno pgno = pPg->pgno;
47942  int i;
47943  for(i=0; i<pPager->nSavepoint; i++){
47944    p = &pPager->aSavepoint[i];
47945    if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
47946      return 1;
47947    }
47948  }
47949  return 0;
47950}
47951
47952#ifdef SQLITE_DEBUG
47953/*
47954** Return true if the page is already in the journal file.
47955*/
47956static int pageInJournal(Pager *pPager, PgHdr *pPg){
47957  return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
47958}
47959#endif
47960
47961/*
47962** Read a 32-bit integer from the given file descriptor.  Store the integer
47963** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
47964** error code is something goes wrong.
47965**
47966** All values are stored on disk as big-endian.
47967*/
47968static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
47969  unsigned char ac[4];
47970  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
47971  if( rc==SQLITE_OK ){
47972    *pRes = sqlite3Get4byte(ac);
47973  }
47974  return rc;
47975}
47976
47977/*
47978** Write a 32-bit integer into a string buffer in big-endian byte order.
47979*/
47980#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
47981
47982
47983/*
47984** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
47985** on success or an error code is something goes wrong.
47986*/
47987static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
47988  char ac[4];
47989  put32bits(ac, val);
47990  return sqlite3OsWrite(fd, ac, 4, offset);
47991}
47992
47993/*
47994** Unlock the database file to level eLock, which must be either NO_LOCK
47995** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
47996** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
47997**
47998** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
47999** called, do not modify it. See the comment above the #define of
48000** UNKNOWN_LOCK for an explanation of this.
48001*/
48002static int pagerUnlockDb(Pager *pPager, int eLock){
48003  int rc = SQLITE_OK;
48004
48005  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
48006  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
48007  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
48008  if( isOpen(pPager->fd) ){
48009    assert( pPager->eLock>=eLock );
48010    rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
48011    if( pPager->eLock!=UNKNOWN_LOCK ){
48012      pPager->eLock = (u8)eLock;
48013    }
48014    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
48015  }
48016  return rc;
48017}
48018
48019/*
48020** Lock the database file to level eLock, which must be either SHARED_LOCK,
48021** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
48022** Pager.eLock variable to the new locking state.
48023**
48024** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
48025** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
48026** See the comment above the #define of UNKNOWN_LOCK for an explanation
48027** of this.
48028*/
48029static int pagerLockDb(Pager *pPager, int eLock){
48030  int rc = SQLITE_OK;
48031
48032  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
48033  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
48034    rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
48035    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
48036      pPager->eLock = (u8)eLock;
48037      IOTRACE(("LOCK %p %d\n", pPager, eLock))
48038    }
48039  }
48040  return rc;
48041}
48042
48043/*
48044** This function determines whether or not the atomic-write optimization
48045** can be used with this pager. The optimization can be used if:
48046**
48047**  (a) the value returned by OsDeviceCharacteristics() indicates that
48048**      a database page may be written atomically, and
48049**  (b) the value returned by OsSectorSize() is less than or equal
48050**      to the page size.
48051**
48052** The optimization is also always enabled for temporary files. It is
48053** an error to call this function if pPager is opened on an in-memory
48054** database.
48055**
48056** If the optimization cannot be used, 0 is returned. If it can be used,
48057** then the value returned is the size of the journal file when it
48058** contains rollback data for exactly one page.
48059*/
48060#ifdef SQLITE_ENABLE_ATOMIC_WRITE
48061static int jrnlBufferSize(Pager *pPager){
48062  assert( !MEMDB );
48063  if( !pPager->tempFile ){
48064    int dc;                           /* Device characteristics */
48065    int nSector;                      /* Sector size */
48066    int szPage;                       /* Page size */
48067
48068    assert( isOpen(pPager->fd) );
48069    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
48070    nSector = pPager->sectorSize;
48071    szPage = pPager->pageSize;
48072
48073    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
48074    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
48075    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
48076      return 0;
48077    }
48078  }
48079
48080  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
48081}
48082#else
48083# define jrnlBufferSize(x) 0
48084#endif
48085
48086/*
48087** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
48088** on the cache using a hash function.  This is used for testing
48089** and debugging only.
48090*/
48091#ifdef SQLITE_CHECK_PAGES
48092/*
48093** Return a 32-bit hash of the page data for pPage.
48094*/
48095static u32 pager_datahash(int nByte, unsigned char *pData){
48096  u32 hash = 0;
48097  int i;
48098  for(i=0; i<nByte; i++){
48099    hash = (hash*1039) + pData[i];
48100  }
48101  return hash;
48102}
48103static u32 pager_pagehash(PgHdr *pPage){
48104  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
48105}
48106static void pager_set_pagehash(PgHdr *pPage){
48107  pPage->pageHash = pager_pagehash(pPage);
48108}
48109
48110/*
48111** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
48112** is defined, and NDEBUG is not defined, an assert() statement checks
48113** that the page is either dirty or still matches the calculated page-hash.
48114*/
48115#define CHECK_PAGE(x) checkPage(x)
48116static void checkPage(PgHdr *pPg){
48117  Pager *pPager = pPg->pPager;
48118  assert( pPager->eState!=PAGER_ERROR );
48119  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
48120}
48121
48122#else
48123#define pager_datahash(X,Y)  0
48124#define pager_pagehash(X)  0
48125#define pager_set_pagehash(X)
48126#define CHECK_PAGE(x)
48127#endif  /* SQLITE_CHECK_PAGES */
48128
48129/*
48130** When this is called the journal file for pager pPager must be open.
48131** This function attempts to read a master journal file name from the
48132** end of the file and, if successful, copies it into memory supplied
48133** by the caller. See comments above writeMasterJournal() for the format
48134** used to store a master journal file name at the end of a journal file.
48135**
48136** zMaster must point to a buffer of at least nMaster bytes allocated by
48137** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
48138** enough space to write the master journal name). If the master journal
48139** name in the journal is longer than nMaster bytes (including a
48140** nul-terminator), then this is handled as if no master journal name
48141** were present in the journal.
48142**
48143** If a master journal file name is present at the end of the journal
48144** file, then it is copied into the buffer pointed to by zMaster. A
48145** nul-terminator byte is appended to the buffer following the master
48146** journal file name.
48147**
48148** If it is determined that no master journal file name is present
48149** zMaster[0] is set to 0 and SQLITE_OK returned.
48150**
48151** If an error occurs while reading from the journal file, an SQLite
48152** error code is returned.
48153*/
48154static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
48155  int rc;                    /* Return code */
48156  u32 len;                   /* Length in bytes of master journal name */
48157  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
48158  u32 cksum;                 /* MJ checksum value read from journal */
48159  u32 u;                     /* Unsigned loop counter */
48160  unsigned char aMagic[8];   /* A buffer to hold the magic header */
48161  zMaster[0] = '\0';
48162
48163  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
48164   || szJ<16
48165   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
48166   || len>=nMaster
48167   || len==0
48168   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
48169   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
48170   || memcmp(aMagic, aJournalMagic, 8)
48171   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
48172  ){
48173    return rc;
48174  }
48175
48176  /* See if the checksum matches the master journal name */
48177  for(u=0; u<len; u++){
48178    cksum -= zMaster[u];
48179  }
48180  if( cksum ){
48181    /* If the checksum doesn't add up, then one or more of the disk sectors
48182    ** containing the master journal filename is corrupted. This means
48183    ** definitely roll back, so just return SQLITE_OK and report a (nul)
48184    ** master-journal filename.
48185    */
48186    len = 0;
48187  }
48188  zMaster[len] = '\0';
48189
48190  return SQLITE_OK;
48191}
48192
48193/*
48194** Return the offset of the sector boundary at or immediately
48195** following the value in pPager->journalOff, assuming a sector
48196** size of pPager->sectorSize bytes.
48197**
48198** i.e for a sector size of 512:
48199**
48200**   Pager.journalOff          Return value
48201**   ---------------------------------------
48202**   0                         0
48203**   512                       512
48204**   100                       512
48205**   2000                      2048
48206**
48207*/
48208static i64 journalHdrOffset(Pager *pPager){
48209  i64 offset = 0;
48210  i64 c = pPager->journalOff;
48211  if( c ){
48212    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
48213  }
48214  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
48215  assert( offset>=c );
48216  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
48217  return offset;
48218}
48219
48220/*
48221** The journal file must be open when this function is called.
48222**
48223** This function is a no-op if the journal file has not been written to
48224** within the current transaction (i.e. if Pager.journalOff==0).
48225**
48226** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
48227** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
48228** zero the 28-byte header at the start of the journal file. In either case,
48229** if the pager is not in no-sync mode, sync the journal file immediately
48230** after writing or truncating it.
48231**
48232** If Pager.journalSizeLimit is set to a positive, non-zero value, and
48233** following the truncation or zeroing described above the size of the
48234** journal file in bytes is larger than this value, then truncate the
48235** journal file to Pager.journalSizeLimit bytes. The journal file does
48236** not need to be synced following this operation.
48237**
48238** If an IO error occurs, abandon processing and return the IO error code.
48239** Otherwise, return SQLITE_OK.
48240*/
48241static int zeroJournalHdr(Pager *pPager, int doTruncate){
48242  int rc = SQLITE_OK;                               /* Return code */
48243  assert( isOpen(pPager->jfd) );
48244  assert( !sqlite3JournalIsInMemory(pPager->jfd) );
48245  if( pPager->journalOff ){
48246    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
48247
48248    IOTRACE(("JZEROHDR %p\n", pPager))
48249    if( doTruncate || iLimit==0 ){
48250      rc = sqlite3OsTruncate(pPager->jfd, 0);
48251    }else{
48252      static const char zeroHdr[28] = {0};
48253      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
48254    }
48255    if( rc==SQLITE_OK && !pPager->noSync ){
48256      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
48257    }
48258
48259    /* At this point the transaction is committed but the write lock
48260    ** is still held on the file. If there is a size limit configured for
48261    ** the persistent journal and the journal file currently consumes more
48262    ** space than that limit allows for, truncate it now. There is no need
48263    ** to sync the file following this operation.
48264    */
48265    if( rc==SQLITE_OK && iLimit>0 ){
48266      i64 sz;
48267      rc = sqlite3OsFileSize(pPager->jfd, &sz);
48268      if( rc==SQLITE_OK && sz>iLimit ){
48269        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
48270      }
48271    }
48272  }
48273  return rc;
48274}
48275
48276/*
48277** The journal file must be open when this routine is called. A journal
48278** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
48279** current location.
48280**
48281** The format for the journal header is as follows:
48282** - 8 bytes: Magic identifying journal format.
48283** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
48284** - 4 bytes: Random number used for page hash.
48285** - 4 bytes: Initial database page count.
48286** - 4 bytes: Sector size used by the process that wrote this journal.
48287** - 4 bytes: Database page size.
48288**
48289** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
48290*/
48291static int writeJournalHdr(Pager *pPager){
48292  int rc = SQLITE_OK;                 /* Return code */
48293  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
48294  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
48295  u32 nWrite;                         /* Bytes of header sector written */
48296  int ii;                             /* Loop counter */
48297
48298  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
48299
48300  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
48301    nHeader = JOURNAL_HDR_SZ(pPager);
48302  }
48303
48304  /* If there are active savepoints and any of them were created
48305  ** since the most recent journal header was written, update the
48306  ** PagerSavepoint.iHdrOffset fields now.
48307  */
48308  for(ii=0; ii<pPager->nSavepoint; ii++){
48309    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
48310      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
48311    }
48312  }
48313
48314  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
48315
48316  /*
48317  ** Write the nRec Field - the number of page records that follow this
48318  ** journal header. Normally, zero is written to this value at this time.
48319  ** After the records are added to the journal (and the journal synced,
48320  ** if in full-sync mode), the zero is overwritten with the true number
48321  ** of records (see syncJournal()).
48322  **
48323  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
48324  ** reading the journal this value tells SQLite to assume that the
48325  ** rest of the journal file contains valid page records. This assumption
48326  ** is dangerous, as if a failure occurred whilst writing to the journal
48327  ** file it may contain some garbage data. There are two scenarios
48328  ** where this risk can be ignored:
48329  **
48330  **   * When the pager is in no-sync mode. Corruption can follow a
48331  **     power failure in this case anyway.
48332  **
48333  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
48334  **     that garbage data is never appended to the journal file.
48335  */
48336  assert( isOpen(pPager->fd) || pPager->noSync );
48337  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
48338   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
48339  ){
48340    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
48341    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
48342  }else{
48343    memset(zHeader, 0, sizeof(aJournalMagic)+4);
48344  }
48345
48346  /* The random check-hash initializer */
48347  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
48348  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
48349  /* The initial database size */
48350  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
48351  /* The assumed sector size for this process */
48352  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
48353
48354  /* The page size */
48355  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
48356
48357  /* Initializing the tail of the buffer is not necessary.  Everything
48358  ** works find if the following memset() is omitted.  But initializing
48359  ** the memory prevents valgrind from complaining, so we are willing to
48360  ** take the performance hit.
48361  */
48362  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
48363         nHeader-(sizeof(aJournalMagic)+20));
48364
48365  /* In theory, it is only necessary to write the 28 bytes that the
48366  ** journal header consumes to the journal file here. Then increment the
48367  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
48368  ** record is written to the following sector (leaving a gap in the file
48369  ** that will be implicitly filled in by the OS).
48370  **
48371  ** However it has been discovered that on some systems this pattern can
48372  ** be significantly slower than contiguously writing data to the file,
48373  ** even if that means explicitly writing data to the block of
48374  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
48375  ** is done.
48376  **
48377  ** The loop is required here in case the sector-size is larger than the
48378  ** database page size. Since the zHeader buffer is only Pager.pageSize
48379  ** bytes in size, more than one call to sqlite3OsWrite() may be required
48380  ** to populate the entire journal header sector.
48381  */
48382  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
48383    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
48384    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
48385    assert( pPager->journalHdr <= pPager->journalOff );
48386    pPager->journalOff += nHeader;
48387  }
48388
48389  return rc;
48390}
48391
48392/*
48393** The journal file must be open when this is called. A journal header file
48394** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
48395** file. The current location in the journal file is given by
48396** pPager->journalOff. See comments above function writeJournalHdr() for
48397** a description of the journal header format.
48398**
48399** If the header is read successfully, *pNRec is set to the number of
48400** page records following this header and *pDbSize is set to the size of the
48401** database before the transaction began, in pages. Also, pPager->cksumInit
48402** is set to the value read from the journal header. SQLITE_OK is returned
48403** in this case.
48404**
48405** If the journal header file appears to be corrupted, SQLITE_DONE is
48406** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
48407** cannot be read from the journal file an error code is returned.
48408*/
48409static int readJournalHdr(
48410  Pager *pPager,               /* Pager object */
48411  int isHot,
48412  i64 journalSize,             /* Size of the open journal file in bytes */
48413  u32 *pNRec,                  /* OUT: Value read from the nRec field */
48414  u32 *pDbSize                 /* OUT: Value of original database size field */
48415){
48416  int rc;                      /* Return code */
48417  unsigned char aMagic[8];     /* A buffer to hold the magic header */
48418  i64 iHdrOff;                 /* Offset of journal header being read */
48419
48420  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
48421
48422  /* Advance Pager.journalOff to the start of the next sector. If the
48423  ** journal file is too small for there to be a header stored at this
48424  ** point, return SQLITE_DONE.
48425  */
48426  pPager->journalOff = journalHdrOffset(pPager);
48427  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
48428    return SQLITE_DONE;
48429  }
48430  iHdrOff = pPager->journalOff;
48431
48432  /* Read in the first 8 bytes of the journal header. If they do not match
48433  ** the  magic string found at the start of each journal header, return
48434  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
48435  ** proceed.
48436  */
48437  if( isHot || iHdrOff!=pPager->journalHdr ){
48438    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
48439    if( rc ){
48440      return rc;
48441    }
48442    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
48443      return SQLITE_DONE;
48444    }
48445  }
48446
48447  /* Read the first three 32-bit fields of the journal header: The nRec
48448  ** field, the checksum-initializer and the database size at the start
48449  ** of the transaction. Return an error code if anything goes wrong.
48450  */
48451  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
48452   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
48453   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
48454  ){
48455    return rc;
48456  }
48457
48458  if( pPager->journalOff==0 ){
48459    u32 iPageSize;               /* Page-size field of journal header */
48460    u32 iSectorSize;             /* Sector-size field of journal header */
48461
48462    /* Read the page-size and sector-size journal header fields. */
48463    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
48464     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
48465    ){
48466      return rc;
48467    }
48468
48469    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
48470    ** journal header to zero. In this case, assume that the Pager.pageSize
48471    ** variable is already set to the correct page size.
48472    */
48473    if( iPageSize==0 ){
48474      iPageSize = pPager->pageSize;
48475    }
48476
48477    /* Check that the values read from the page-size and sector-size fields
48478    ** are within range. To be 'in range', both values need to be a power
48479    ** of two greater than or equal to 512 or 32, and not greater than their
48480    ** respective compile time maximum limits.
48481    */
48482    if( iPageSize<512                  || iSectorSize<32
48483     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
48484     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
48485    ){
48486      /* If the either the page-size or sector-size in the journal-header is
48487      ** invalid, then the process that wrote the journal-header must have
48488      ** crashed before the header was synced. In this case stop reading
48489      ** the journal file here.
48490      */
48491      return SQLITE_DONE;
48492    }
48493
48494    /* Update the page-size to match the value read from the journal.
48495    ** Use a testcase() macro to make sure that malloc failure within
48496    ** PagerSetPagesize() is tested.
48497    */
48498    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
48499    testcase( rc!=SQLITE_OK );
48500
48501    /* Update the assumed sector-size to match the value used by
48502    ** the process that created this journal. If this journal was
48503    ** created by a process other than this one, then this routine
48504    ** is being called from within pager_playback(). The local value
48505    ** of Pager.sectorSize is restored at the end of that routine.
48506    */
48507    pPager->sectorSize = iSectorSize;
48508  }
48509
48510  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
48511  return rc;
48512}
48513
48514
48515/*
48516** Write the supplied master journal name into the journal file for pager
48517** pPager at the current location. The master journal name must be the last
48518** thing written to a journal file. If the pager is in full-sync mode, the
48519** journal file descriptor is advanced to the next sector boundary before
48520** anything is written. The format is:
48521**
48522**   + 4 bytes: PAGER_MJ_PGNO.
48523**   + N bytes: Master journal filename in utf-8.
48524**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
48525**   + 4 bytes: Master journal name checksum.
48526**   + 8 bytes: aJournalMagic[].
48527**
48528** The master journal page checksum is the sum of the bytes in the master
48529** journal name, where each byte is interpreted as a signed 8-bit integer.
48530**
48531** If zMaster is a NULL pointer (occurs for a single database transaction),
48532** this call is a no-op.
48533*/
48534static int writeMasterJournal(Pager *pPager, const char *zMaster){
48535  int rc;                          /* Return code */
48536  int nMaster;                     /* Length of string zMaster */
48537  i64 iHdrOff;                     /* Offset of header in journal file */
48538  i64 jrnlSize;                    /* Size of journal file on disk */
48539  u32 cksum = 0;                   /* Checksum of string zMaster */
48540
48541  assert( pPager->setMaster==0 );
48542  assert( !pagerUseWal(pPager) );
48543
48544  if( !zMaster
48545   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
48546   || !isOpen(pPager->jfd)
48547  ){
48548    return SQLITE_OK;
48549  }
48550  pPager->setMaster = 1;
48551  assert( pPager->journalHdr <= pPager->journalOff );
48552
48553  /* Calculate the length in bytes and the checksum of zMaster */
48554  for(nMaster=0; zMaster[nMaster]; nMaster++){
48555    cksum += zMaster[nMaster];
48556  }
48557
48558  /* If in full-sync mode, advance to the next disk sector before writing
48559  ** the master journal name. This is in case the previous page written to
48560  ** the journal has already been synced.
48561  */
48562  if( pPager->fullSync ){
48563    pPager->journalOff = journalHdrOffset(pPager);
48564  }
48565  iHdrOff = pPager->journalOff;
48566
48567  /* Write the master journal data to the end of the journal file. If
48568  ** an error occurs, return the error code to the caller.
48569  */
48570  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
48571   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
48572   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
48573   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
48574   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
48575                                 iHdrOff+4+nMaster+8)))
48576  ){
48577    return rc;
48578  }
48579  pPager->journalOff += (nMaster+20);
48580
48581  /* If the pager is in peristent-journal mode, then the physical
48582  ** journal-file may extend past the end of the master-journal name
48583  ** and 8 bytes of magic data just written to the file. This is
48584  ** dangerous because the code to rollback a hot-journal file
48585  ** will not be able to find the master-journal name to determine
48586  ** whether or not the journal is hot.
48587  **
48588  ** Easiest thing to do in this scenario is to truncate the journal
48589  ** file to the required size.
48590  */
48591  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
48592   && jrnlSize>pPager->journalOff
48593  ){
48594    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
48595  }
48596  return rc;
48597}
48598
48599/*
48600** Discard the entire contents of the in-memory page-cache.
48601*/
48602static void pager_reset(Pager *pPager){
48603  pPager->iDataVersion++;
48604  sqlite3BackupRestart(pPager->pBackup);
48605  sqlite3PcacheClear(pPager->pPCache);
48606}
48607
48608/*
48609** Return the pPager->iDataVersion value
48610*/
48611SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
48612  assert( pPager->eState>PAGER_OPEN );
48613  return pPager->iDataVersion;
48614}
48615
48616/*
48617** Free all structures in the Pager.aSavepoint[] array and set both
48618** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
48619** if it is open and the pager is not in exclusive mode.
48620*/
48621static void releaseAllSavepoints(Pager *pPager){
48622  int ii;               /* Iterator for looping through Pager.aSavepoint */
48623  for(ii=0; ii<pPager->nSavepoint; ii++){
48624    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
48625  }
48626  if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
48627    sqlite3OsClose(pPager->sjfd);
48628  }
48629  sqlite3_free(pPager->aSavepoint);
48630  pPager->aSavepoint = 0;
48631  pPager->nSavepoint = 0;
48632  pPager->nSubRec = 0;
48633}
48634
48635/*
48636** Set the bit number pgno in the PagerSavepoint.pInSavepoint
48637** bitvecs of all open savepoints. Return SQLITE_OK if successful
48638** or SQLITE_NOMEM if a malloc failure occurs.
48639*/
48640static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
48641  int ii;                   /* Loop counter */
48642  int rc = SQLITE_OK;       /* Result code */
48643
48644  for(ii=0; ii<pPager->nSavepoint; ii++){
48645    PagerSavepoint *p = &pPager->aSavepoint[ii];
48646    if( pgno<=p->nOrig ){
48647      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
48648      testcase( rc==SQLITE_NOMEM );
48649      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
48650    }
48651  }
48652  return rc;
48653}
48654
48655/*
48656** This function is a no-op if the pager is in exclusive mode and not
48657** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
48658** state.
48659**
48660** If the pager is not in exclusive-access mode, the database file is
48661** completely unlocked. If the file is unlocked and the file-system does
48662** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
48663** closed (if it is open).
48664**
48665** If the pager is in ERROR state when this function is called, the
48666** contents of the pager cache are discarded before switching back to
48667** the OPEN state. Regardless of whether the pager is in exclusive-mode
48668** or not, any journal file left in the file-system will be treated
48669** as a hot-journal and rolled back the next time a read-transaction
48670** is opened (by this or by any other connection).
48671*/
48672static void pager_unlock(Pager *pPager){
48673
48674  assert( pPager->eState==PAGER_READER
48675       || pPager->eState==PAGER_OPEN
48676       || pPager->eState==PAGER_ERROR
48677  );
48678
48679  sqlite3BitvecDestroy(pPager->pInJournal);
48680  pPager->pInJournal = 0;
48681  releaseAllSavepoints(pPager);
48682
48683  if( pagerUseWal(pPager) ){
48684    assert( !isOpen(pPager->jfd) );
48685    sqlite3WalEndReadTransaction(pPager->pWal);
48686    pPager->eState = PAGER_OPEN;
48687  }else if( !pPager->exclusiveMode ){
48688    int rc;                       /* Error code returned by pagerUnlockDb() */
48689    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
48690
48691    /* If the operating system support deletion of open files, then
48692    ** close the journal file when dropping the database lock.  Otherwise
48693    ** another connection with journal_mode=delete might delete the file
48694    ** out from under us.
48695    */
48696    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
48697    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
48698    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
48699    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
48700    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
48701    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
48702    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
48703     || 1!=(pPager->journalMode & 5)
48704    ){
48705      sqlite3OsClose(pPager->jfd);
48706    }
48707
48708    /* If the pager is in the ERROR state and the call to unlock the database
48709    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
48710    ** above the #define for UNKNOWN_LOCK for an explanation of why this
48711    ** is necessary.
48712    */
48713    rc = pagerUnlockDb(pPager, NO_LOCK);
48714    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
48715      pPager->eLock = UNKNOWN_LOCK;
48716    }
48717
48718    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
48719    ** without clearing the error code. This is intentional - the error
48720    ** code is cleared and the cache reset in the block below.
48721    */
48722    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
48723    pPager->changeCountDone = 0;
48724    pPager->eState = PAGER_OPEN;
48725  }
48726
48727  /* If Pager.errCode is set, the contents of the pager cache cannot be
48728  ** trusted. Now that there are no outstanding references to the pager,
48729  ** it can safely move back to PAGER_OPEN state. This happens in both
48730  ** normal and exclusive-locking mode.
48731  */
48732  assert( pPager->errCode==SQLITE_OK || !MEMDB );
48733  if( pPager->errCode ){
48734    if( pPager->tempFile==0 ){
48735      pager_reset(pPager);
48736      pPager->changeCountDone = 0;
48737      pPager->eState = PAGER_OPEN;
48738    }else{
48739      pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
48740    }
48741    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
48742    pPager->errCode = SQLITE_OK;
48743    setGetterMethod(pPager);
48744  }
48745
48746  pPager->journalOff = 0;
48747  pPager->journalHdr = 0;
48748  pPager->setMaster = 0;
48749}
48750
48751/*
48752** This function is called whenever an IOERR or FULL error that requires
48753** the pager to transition into the ERROR state may ahve occurred.
48754** The first argument is a pointer to the pager structure, the second
48755** the error-code about to be returned by a pager API function. The
48756** value returned is a copy of the second argument to this function.
48757**
48758** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
48759** IOERR sub-codes, the pager enters the ERROR state and the error code
48760** is stored in Pager.errCode. While the pager remains in the ERROR state,
48761** all major API calls on the Pager will immediately return Pager.errCode.
48762**
48763** The ERROR state indicates that the contents of the pager-cache
48764** cannot be trusted. This state can be cleared by completely discarding
48765** the contents of the pager-cache. If a transaction was active when
48766** the persistent error occurred, then the rollback journal may need
48767** to be replayed to restore the contents of the database file (as if
48768** it were a hot-journal).
48769*/
48770static int pager_error(Pager *pPager, int rc){
48771  int rc2 = rc & 0xff;
48772  assert( rc==SQLITE_OK || !MEMDB );
48773  assert(
48774       pPager->errCode==SQLITE_FULL ||
48775       pPager->errCode==SQLITE_OK ||
48776       (pPager->errCode & 0xff)==SQLITE_IOERR
48777  );
48778  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
48779    pPager->errCode = rc;
48780    pPager->eState = PAGER_ERROR;
48781    setGetterMethod(pPager);
48782  }
48783  return rc;
48784}
48785
48786static int pager_truncate(Pager *pPager, Pgno nPage);
48787
48788/*
48789** The write transaction open on pPager is being committed (bCommit==1)
48790** or rolled back (bCommit==0).
48791**
48792** Return TRUE if and only if all dirty pages should be flushed to disk.
48793**
48794** Rules:
48795**
48796**   *  For non-TEMP databases, always sync to disk.  This is necessary
48797**      for transactions to be durable.
48798**
48799**   *  Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
48800**      file has been created already (via a spill on pagerStress()) and
48801**      when the number of dirty pages in memory exceeds 25% of the total
48802**      cache size.
48803*/
48804static int pagerFlushOnCommit(Pager *pPager, int bCommit){
48805  if( pPager->tempFile==0 ) return 1;
48806  if( !bCommit ) return 0;
48807  if( !isOpen(pPager->fd) ) return 0;
48808  return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
48809}
48810
48811/*
48812** This routine ends a transaction. A transaction is usually ended by
48813** either a COMMIT or a ROLLBACK operation. This routine may be called
48814** after rollback of a hot-journal, or if an error occurs while opening
48815** the journal file or writing the very first journal-header of a
48816** database transaction.
48817**
48818** This routine is never called in PAGER_ERROR state. If it is called
48819** in PAGER_NONE or PAGER_SHARED state and the lock held is less
48820** exclusive than a RESERVED lock, it is a no-op.
48821**
48822** Otherwise, any active savepoints are released.
48823**
48824** If the journal file is open, then it is "finalized". Once a journal
48825** file has been finalized it is not possible to use it to roll back a
48826** transaction. Nor will it be considered to be a hot-journal by this
48827** or any other database connection. Exactly how a journal is finalized
48828** depends on whether or not the pager is running in exclusive mode and
48829** the current journal-mode (Pager.journalMode value), as follows:
48830**
48831**   journalMode==MEMORY
48832**     Journal file descriptor is simply closed. This destroys an
48833**     in-memory journal.
48834**
48835**   journalMode==TRUNCATE
48836**     Journal file is truncated to zero bytes in size.
48837**
48838**   journalMode==PERSIST
48839**     The first 28 bytes of the journal file are zeroed. This invalidates
48840**     the first journal header in the file, and hence the entire journal
48841**     file. An invalid journal file cannot be rolled back.
48842**
48843**   journalMode==DELETE
48844**     The journal file is closed and deleted using sqlite3OsDelete().
48845**
48846**     If the pager is running in exclusive mode, this method of finalizing
48847**     the journal file is never used. Instead, if the journalMode is
48848**     DELETE and the pager is in exclusive mode, the method described under
48849**     journalMode==PERSIST is used instead.
48850**
48851** After the journal is finalized, the pager moves to PAGER_READER state.
48852** If running in non-exclusive rollback mode, the lock on the file is
48853** downgraded to a SHARED_LOCK.
48854**
48855** SQLITE_OK is returned if no error occurs. If an error occurs during
48856** any of the IO operations to finalize the journal file or unlock the
48857** database then the IO error code is returned to the user. If the
48858** operation to finalize the journal file fails, then the code still
48859** tries to unlock the database file if not in exclusive mode. If the
48860** unlock operation fails as well, then the first error code related
48861** to the first error encountered (the journal finalization one) is
48862** returned.
48863*/
48864static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
48865  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
48866  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
48867
48868  /* Do nothing if the pager does not have an open write transaction
48869  ** or at least a RESERVED lock. This function may be called when there
48870  ** is no write-transaction active but a RESERVED or greater lock is
48871  ** held under two circumstances:
48872  **
48873  **   1. After a successful hot-journal rollback, it is called with
48874  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
48875  **
48876  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
48877  **      lock switches back to locking_mode=normal and then executes a
48878  **      read-transaction, this function is called with eState==PAGER_READER
48879  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
48880  */
48881  assert( assert_pager_state(pPager) );
48882  assert( pPager->eState!=PAGER_ERROR );
48883  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
48884    return SQLITE_OK;
48885  }
48886
48887  releaseAllSavepoints(pPager);
48888  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
48889  if( isOpen(pPager->jfd) ){
48890    assert( !pagerUseWal(pPager) );
48891
48892    /* Finalize the journal file. */
48893    if( sqlite3JournalIsInMemory(pPager->jfd) ){
48894      /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
48895      sqlite3OsClose(pPager->jfd);
48896    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
48897      if( pPager->journalOff==0 ){
48898        rc = SQLITE_OK;
48899      }else{
48900        rc = sqlite3OsTruncate(pPager->jfd, 0);
48901        if( rc==SQLITE_OK && pPager->fullSync ){
48902          /* Make sure the new file size is written into the inode right away.
48903          ** Otherwise the journal might resurrect following a power loss and
48904          ** cause the last transaction to roll back.  See
48905          ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
48906          */
48907          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
48908        }
48909      }
48910      pPager->journalOff = 0;
48911    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
48912      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
48913    ){
48914      rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
48915      pPager->journalOff = 0;
48916    }else{
48917      /* This branch may be executed with Pager.journalMode==MEMORY if
48918      ** a hot-journal was just rolled back. In this case the journal
48919      ** file should be closed and deleted. If this connection writes to
48920      ** the database file, it will do so using an in-memory journal.
48921      */
48922      int bDelete = !pPager->tempFile;
48923      assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
48924      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
48925           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
48926           || pPager->journalMode==PAGER_JOURNALMODE_WAL
48927      );
48928      sqlite3OsClose(pPager->jfd);
48929      if( bDelete ){
48930        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
48931      }
48932    }
48933  }
48934
48935#ifdef SQLITE_CHECK_PAGES
48936  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
48937  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
48938    PgHdr *p = sqlite3PagerLookup(pPager, 1);
48939    if( p ){
48940      p->pageHash = 0;
48941      sqlite3PagerUnrefNotNull(p);
48942    }
48943  }
48944#endif
48945
48946  sqlite3BitvecDestroy(pPager->pInJournal);
48947  pPager->pInJournal = 0;
48948  pPager->nRec = 0;
48949  if( rc==SQLITE_OK ){
48950    if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
48951      sqlite3PcacheCleanAll(pPager->pPCache);
48952    }else{
48953      sqlite3PcacheClearWritable(pPager->pPCache);
48954    }
48955    sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
48956  }
48957
48958  if( pagerUseWal(pPager) ){
48959    /* Drop the WAL write-lock, if any. Also, if the connection was in
48960    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
48961    ** lock held on the database file.
48962    */
48963    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
48964    assert( rc2==SQLITE_OK );
48965  }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
48966    /* This branch is taken when committing a transaction in rollback-journal
48967    ** mode if the database file on disk is larger than the database image.
48968    ** At this point the journal has been finalized and the transaction
48969    ** successfully committed, but the EXCLUSIVE lock is still held on the
48970    ** file. So it is safe to truncate the database file to its minimum
48971    ** required size.  */
48972    assert( pPager->eLock==EXCLUSIVE_LOCK );
48973    rc = pager_truncate(pPager, pPager->dbSize);
48974  }
48975
48976  if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
48977    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
48978    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
48979  }
48980
48981  if( !pPager->exclusiveMode
48982   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
48983  ){
48984    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
48985    pPager->changeCountDone = 0;
48986  }
48987  pPager->eState = PAGER_READER;
48988  pPager->setMaster = 0;
48989
48990  return (rc==SQLITE_OK?rc2:rc);
48991}
48992
48993/*
48994** Execute a rollback if a transaction is active and unlock the
48995** database file.
48996**
48997** If the pager has already entered the ERROR state, do not attempt
48998** the rollback at this time. Instead, pager_unlock() is called. The
48999** call to pager_unlock() will discard all in-memory pages, unlock
49000** the database file and move the pager back to OPEN state. If this
49001** means that there is a hot-journal left in the file-system, the next
49002** connection to obtain a shared lock on the pager (which may be this one)
49003** will roll it back.
49004**
49005** If the pager has not already entered the ERROR state, but an IO or
49006** malloc error occurs during a rollback, then this will itself cause
49007** the pager to enter the ERROR state. Which will be cleared by the
49008** call to pager_unlock(), as described above.
49009*/
49010static void pagerUnlockAndRollback(Pager *pPager){
49011  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
49012    assert( assert_pager_state(pPager) );
49013    if( pPager->eState>=PAGER_WRITER_LOCKED ){
49014      sqlite3BeginBenignMalloc();
49015      sqlite3PagerRollback(pPager);
49016      sqlite3EndBenignMalloc();
49017    }else if( !pPager->exclusiveMode ){
49018      assert( pPager->eState==PAGER_READER );
49019      pager_end_transaction(pPager, 0, 0);
49020    }
49021  }
49022  pager_unlock(pPager);
49023}
49024
49025/*
49026** Parameter aData must point to a buffer of pPager->pageSize bytes
49027** of data. Compute and return a checksum based ont the contents of the
49028** page of data and the current value of pPager->cksumInit.
49029**
49030** This is not a real checksum. It is really just the sum of the
49031** random initial value (pPager->cksumInit) and every 200th byte
49032** of the page data, starting with byte offset (pPager->pageSize%200).
49033** Each byte is interpreted as an 8-bit unsigned integer.
49034**
49035** Changing the formula used to compute this checksum results in an
49036** incompatible journal file format.
49037**
49038** If journal corruption occurs due to a power failure, the most likely
49039** scenario is that one end or the other of the record will be changed.
49040** It is much less likely that the two ends of the journal record will be
49041** correct and the middle be corrupt.  Thus, this "checksum" scheme,
49042** though fast and simple, catches the mostly likely kind of corruption.
49043*/
49044static u32 pager_cksum(Pager *pPager, const u8 *aData){
49045  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
49046  int i = pPager->pageSize-200;          /* Loop counter */
49047  while( i>0 ){
49048    cksum += aData[i];
49049    i -= 200;
49050  }
49051  return cksum;
49052}
49053
49054/*
49055** Report the current page size and number of reserved bytes back
49056** to the codec.
49057*/
49058#ifdef SQLITE_HAS_CODEC
49059static void pagerReportSize(Pager *pPager){
49060  if( pPager->xCodecSizeChng ){
49061    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
49062                           (int)pPager->nReserve);
49063  }
49064}
49065#else
49066# define pagerReportSize(X)     /* No-op if we do not support a codec */
49067#endif
49068
49069#ifdef SQLITE_HAS_CODEC
49070/*
49071** Make sure the number of reserved bits is the same in the destination
49072** pager as it is in the source.  This comes up when a VACUUM changes the
49073** number of reserved bits to the "optimal" amount.
49074*/
49075SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
49076  if( pDest->nReserve!=pSrc->nReserve ){
49077    pDest->nReserve = pSrc->nReserve;
49078    pagerReportSize(pDest);
49079  }
49080}
49081#endif
49082
49083/*
49084** Read a single page from either the journal file (if isMainJrnl==1) or
49085** from the sub-journal (if isMainJrnl==0) and playback that page.
49086** The page begins at offset *pOffset into the file. The *pOffset
49087** value is increased to the start of the next page in the journal.
49088**
49089** The main rollback journal uses checksums - the statement journal does
49090** not.
49091**
49092** If the page number of the page record read from the (sub-)journal file
49093** is greater than the current value of Pager.dbSize, then playback is
49094** skipped and SQLITE_OK is returned.
49095**
49096** If pDone is not NULL, then it is a record of pages that have already
49097** been played back.  If the page at *pOffset has already been played back
49098** (if the corresponding pDone bit is set) then skip the playback.
49099** Make sure the pDone bit corresponding to the *pOffset page is set
49100** prior to returning.
49101**
49102** If the page record is successfully read from the (sub-)journal file
49103** and played back, then SQLITE_OK is returned. If an IO error occurs
49104** while reading the record from the (sub-)journal file or while writing
49105** to the database file, then the IO error code is returned. If data
49106** is successfully read from the (sub-)journal file but appears to be
49107** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
49108** two circumstances:
49109**
49110**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
49111**   * If the record is being rolled back from the main journal file
49112**     and the checksum field does not match the record content.
49113**
49114** Neither of these two scenarios are possible during a savepoint rollback.
49115**
49116** If this is a savepoint rollback, then memory may have to be dynamically
49117** allocated by this function. If this is the case and an allocation fails,
49118** SQLITE_NOMEM is returned.
49119*/
49120static int pager_playback_one_page(
49121  Pager *pPager,                /* The pager being played back */
49122  i64 *pOffset,                 /* Offset of record to playback */
49123  Bitvec *pDone,                /* Bitvec of pages already played back */
49124  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
49125  int isSavepnt                 /* True for a savepoint rollback */
49126){
49127  int rc;
49128  PgHdr *pPg;                   /* An existing page in the cache */
49129  Pgno pgno;                    /* The page number of a page in journal */
49130  u32 cksum;                    /* Checksum used for sanity checking */
49131  char *aData;                  /* Temporary storage for the page */
49132  sqlite3_file *jfd;            /* The file descriptor for the journal file */
49133  int isSynced;                 /* True if journal page is synced */
49134
49135  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
49136  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
49137  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
49138  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
49139
49140  aData = pPager->pTmpSpace;
49141  assert( aData );         /* Temp storage must have already been allocated */
49142  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
49143
49144  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
49145  ** or savepoint rollback done at the request of the caller) or this is
49146  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
49147  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
49148  ** only reads from the main journal, not the sub-journal.
49149  */
49150  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
49151       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
49152  );
49153  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
49154
49155  /* Read the page number and page data from the journal or sub-journal
49156  ** file. Return an error code to the caller if an IO error occurs.
49157  */
49158  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
49159  rc = read32bits(jfd, *pOffset, &pgno);
49160  if( rc!=SQLITE_OK ) return rc;
49161  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
49162  if( rc!=SQLITE_OK ) return rc;
49163  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
49164
49165  /* Sanity checking on the page.  This is more important that I originally
49166  ** thought.  If a power failure occurs while the journal is being written,
49167  ** it could cause invalid data to be written into the journal.  We need to
49168  ** detect this invalid data (with high probability) and ignore it.
49169  */
49170  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
49171    assert( !isSavepnt );
49172    return SQLITE_DONE;
49173  }
49174  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
49175    return SQLITE_OK;
49176  }
49177  if( isMainJrnl ){
49178    rc = read32bits(jfd, (*pOffset)-4, &cksum);
49179    if( rc ) return rc;
49180    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
49181      return SQLITE_DONE;
49182    }
49183  }
49184
49185  /* If this page has already been played back before during the current
49186  ** rollback, then don't bother to play it back again.
49187  */
49188  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
49189    return rc;
49190  }
49191
49192  /* When playing back page 1, restore the nReserve setting
49193  */
49194  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
49195    pPager->nReserve = ((u8*)aData)[20];
49196    pagerReportSize(pPager);
49197  }
49198
49199  /* If the pager is in CACHEMOD state, then there must be a copy of this
49200  ** page in the pager cache. In this case just update the pager cache,
49201  ** not the database file. The page is left marked dirty in this case.
49202  **
49203  ** An exception to the above rule: If the database is in no-sync mode
49204  ** and a page is moved during an incremental vacuum then the page may
49205  ** not be in the pager cache. Later: if a malloc() or IO error occurs
49206  ** during a Movepage() call, then the page may not be in the cache
49207  ** either. So the condition described in the above paragraph is not
49208  ** assert()able.
49209  **
49210  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
49211  ** pager cache if it exists and the main file. The page is then marked
49212  ** not dirty. Since this code is only executed in PAGER_OPEN state for
49213  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
49214  ** if the pager is in OPEN state.
49215  **
49216  ** Ticket #1171:  The statement journal might contain page content that is
49217  ** different from the page content at the start of the transaction.
49218  ** This occurs when a page is changed prior to the start of a statement
49219  ** then changed again within the statement.  When rolling back such a
49220  ** statement we must not write to the original database unless we know
49221  ** for certain that original page contents are synced into the main rollback
49222  ** journal.  Otherwise, a power loss might leave modified data in the
49223  ** database file without an entry in the rollback journal that can
49224  ** restore the database to its original form.  Two conditions must be
49225  ** met before writing to the database files. (1) the database must be
49226  ** locked.  (2) we know that the original page content is fully synced
49227  ** in the main journal either because the page is not in cache or else
49228  ** the page is marked as needSync==0.
49229  **
49230  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
49231  ** is possible to fail a statement on a database that does not yet exist.
49232  ** Do not attempt to write if database file has never been opened.
49233  */
49234  if( pagerUseWal(pPager) ){
49235    pPg = 0;
49236  }else{
49237    pPg = sqlite3PagerLookup(pPager, pgno);
49238  }
49239  assert( pPg || !MEMDB );
49240  assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
49241  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
49242           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
49243           (isMainJrnl?"main-journal":"sub-journal")
49244  ));
49245  if( isMainJrnl ){
49246    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
49247  }else{
49248    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
49249  }
49250  if( isOpen(pPager->fd)
49251   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
49252   && isSynced
49253  ){
49254    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
49255    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
49256    assert( !pagerUseWal(pPager) );
49257    rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
49258    if( pgno>pPager->dbFileSize ){
49259      pPager->dbFileSize = pgno;
49260    }
49261    if( pPager->pBackup ){
49262      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
49263      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
49264      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
49265    }
49266  }else if( !isMainJrnl && pPg==0 ){
49267    /* If this is a rollback of a savepoint and data was not written to
49268    ** the database and the page is not in-memory, there is a potential
49269    ** problem. When the page is next fetched by the b-tree layer, it
49270    ** will be read from the database file, which may or may not be
49271    ** current.
49272    **
49273    ** There are a couple of different ways this can happen. All are quite
49274    ** obscure. When running in synchronous mode, this can only happen
49275    ** if the page is on the free-list at the start of the transaction, then
49276    ** populated, then moved using sqlite3PagerMovepage().
49277    **
49278    ** The solution is to add an in-memory page to the cache containing
49279    ** the data just read from the sub-journal. Mark the page as dirty
49280    ** and if the pager requires a journal-sync, then mark the page as
49281    ** requiring a journal-sync before it is written.
49282    */
49283    assert( isSavepnt );
49284    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
49285    pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
49286    rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
49287    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
49288    pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
49289    if( rc!=SQLITE_OK ) return rc;
49290    sqlite3PcacheMakeDirty(pPg);
49291  }
49292  if( pPg ){
49293    /* No page should ever be explicitly rolled back that is in use, except
49294    ** for page 1 which is held in use in order to keep the lock on the
49295    ** database active. However such a page may be rolled back as a result
49296    ** of an internal error resulting in an automatic call to
49297    ** sqlite3PagerRollback().
49298    */
49299    void *pData;
49300    pData = pPg->pData;
49301    memcpy(pData, (u8*)aData, pPager->pageSize);
49302    pPager->xReiniter(pPg);
49303    /* It used to be that sqlite3PcacheMakeClean(pPg) was called here.  But
49304    ** that call was dangerous and had no detectable benefit since the cache
49305    ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
49306    ** has been removed. */
49307    pager_set_pagehash(pPg);
49308
49309    /* If this was page 1, then restore the value of Pager.dbFileVers.
49310    ** Do this before any decoding. */
49311    if( pgno==1 ){
49312      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
49313    }
49314
49315    /* Decode the page just read from disk */
49316    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT);
49317    sqlite3PcacheRelease(pPg);
49318  }
49319  return rc;
49320}
49321
49322/*
49323** Parameter zMaster is the name of a master journal file. A single journal
49324** file that referred to the master journal file has just been rolled back.
49325** This routine checks if it is possible to delete the master journal file,
49326** and does so if it is.
49327**
49328** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
49329** available for use within this function.
49330**
49331** When a master journal file is created, it is populated with the names
49332** of all of its child journals, one after another, formatted as utf-8
49333** encoded text. The end of each child journal file is marked with a
49334** nul-terminator byte (0x00). i.e. the entire contents of a master journal
49335** file for a transaction involving two databases might be:
49336**
49337**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
49338**
49339** A master journal file may only be deleted once all of its child
49340** journals have been rolled back.
49341**
49342** This function reads the contents of the master-journal file into
49343** memory and loops through each of the child journal names. For
49344** each child journal, it checks if:
49345**
49346**   * if the child journal exists, and if so
49347**   * if the child journal contains a reference to master journal
49348**     file zMaster
49349**
49350** If a child journal can be found that matches both of the criteria
49351** above, this function returns without doing anything. Otherwise, if
49352** no such child journal can be found, file zMaster is deleted from
49353** the file-system using sqlite3OsDelete().
49354**
49355** If an IO error within this function, an error code is returned. This
49356** function allocates memory by calling sqlite3Malloc(). If an allocation
49357** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
49358** occur, SQLITE_OK is returned.
49359**
49360** TODO: This function allocates a single block of memory to load
49361** the entire contents of the master journal file. This could be
49362** a couple of kilobytes or so - potentially larger than the page
49363** size.
49364*/
49365static int pager_delmaster(Pager *pPager, const char *zMaster){
49366  sqlite3_vfs *pVfs = pPager->pVfs;
49367  int rc;                   /* Return code */
49368  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
49369  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
49370  char *zMasterJournal = 0; /* Contents of master journal file */
49371  i64 nMasterJournal;       /* Size of master journal file */
49372  char *zJournal;           /* Pointer to one journal within MJ file */
49373  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
49374  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
49375
49376  /* Allocate space for both the pJournal and pMaster file descriptors.
49377  ** If successful, open the master journal file for reading.
49378  */
49379  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
49380  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
49381  if( !pMaster ){
49382    rc = SQLITE_NOMEM_BKPT;
49383  }else{
49384    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
49385    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
49386  }
49387  if( rc!=SQLITE_OK ) goto delmaster_out;
49388
49389  /* Load the entire master journal file into space obtained from
49390  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
49391  ** sufficient space (in zMasterPtr) to hold the names of master
49392  ** journal files extracted from regular rollback-journals.
49393  */
49394  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
49395  if( rc!=SQLITE_OK ) goto delmaster_out;
49396  nMasterPtr = pVfs->mxPathname+1;
49397  zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
49398  if( !zMasterJournal ){
49399    rc = SQLITE_NOMEM_BKPT;
49400    goto delmaster_out;
49401  }
49402  zMasterPtr = &zMasterJournal[nMasterJournal+1];
49403  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
49404  if( rc!=SQLITE_OK ) goto delmaster_out;
49405  zMasterJournal[nMasterJournal] = 0;
49406
49407  zJournal = zMasterJournal;
49408  while( (zJournal-zMasterJournal)<nMasterJournal ){
49409    int exists;
49410    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
49411    if( rc!=SQLITE_OK ){
49412      goto delmaster_out;
49413    }
49414    if( exists ){
49415      /* One of the journals pointed to by the master journal exists.
49416      ** Open it and check if it points at the master journal. If
49417      ** so, return without deleting the master journal file.
49418      */
49419      int c;
49420      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
49421      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
49422      if( rc!=SQLITE_OK ){
49423        goto delmaster_out;
49424      }
49425
49426      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
49427      sqlite3OsClose(pJournal);
49428      if( rc!=SQLITE_OK ){
49429        goto delmaster_out;
49430      }
49431
49432      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
49433      if( c ){
49434        /* We have a match. Do not delete the master journal file. */
49435        goto delmaster_out;
49436      }
49437    }
49438    zJournal += (sqlite3Strlen30(zJournal)+1);
49439  }
49440
49441  sqlite3OsClose(pMaster);
49442  rc = sqlite3OsDelete(pVfs, zMaster, 0);
49443
49444delmaster_out:
49445  sqlite3_free(zMasterJournal);
49446  if( pMaster ){
49447    sqlite3OsClose(pMaster);
49448    assert( !isOpen(pJournal) );
49449    sqlite3_free(pMaster);
49450  }
49451  return rc;
49452}
49453
49454
49455/*
49456** This function is used to change the actual size of the database
49457** file in the file-system. This only happens when committing a transaction,
49458** or rolling back a transaction (including rolling back a hot-journal).
49459**
49460** If the main database file is not open, or the pager is not in either
49461** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
49462** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
49463** If the file on disk is currently larger than nPage pages, then use the VFS
49464** xTruncate() method to truncate it.
49465**
49466** Or, it might be the case that the file on disk is smaller than
49467** nPage pages. Some operating system implementations can get confused if
49468** you try to truncate a file to some size that is larger than it
49469** currently is, so detect this case and write a single zero byte to
49470** the end of the new file instead.
49471**
49472** If successful, return SQLITE_OK. If an IO error occurs while modifying
49473** the database file, return the error code to the caller.
49474*/
49475static int pager_truncate(Pager *pPager, Pgno nPage){
49476  int rc = SQLITE_OK;
49477  assert( pPager->eState!=PAGER_ERROR );
49478  assert( pPager->eState!=PAGER_READER );
49479
49480  if( isOpen(pPager->fd)
49481   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
49482  ){
49483    i64 currentSize, newSize;
49484    int szPage = pPager->pageSize;
49485    assert( pPager->eLock==EXCLUSIVE_LOCK );
49486    /* TODO: Is it safe to use Pager.dbFileSize here? */
49487    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
49488    newSize = szPage*(i64)nPage;
49489    if( rc==SQLITE_OK && currentSize!=newSize ){
49490      if( currentSize>newSize ){
49491        rc = sqlite3OsTruncate(pPager->fd, newSize);
49492      }else if( (currentSize+szPage)<=newSize ){
49493        char *pTmp = pPager->pTmpSpace;
49494        memset(pTmp, 0, szPage);
49495        testcase( (newSize-szPage) == currentSize );
49496        testcase( (newSize-szPage) >  currentSize );
49497        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
49498      }
49499      if( rc==SQLITE_OK ){
49500        pPager->dbFileSize = nPage;
49501      }
49502    }
49503  }
49504  return rc;
49505}
49506
49507/*
49508** Return a sanitized version of the sector-size of OS file pFile. The
49509** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
49510*/
49511SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
49512  int iRet = sqlite3OsSectorSize(pFile);
49513  if( iRet<32 ){
49514    iRet = 512;
49515  }else if( iRet>MAX_SECTOR_SIZE ){
49516    assert( MAX_SECTOR_SIZE>=512 );
49517    iRet = MAX_SECTOR_SIZE;
49518  }
49519  return iRet;
49520}
49521
49522/*
49523** Set the value of the Pager.sectorSize variable for the given
49524** pager based on the value returned by the xSectorSize method
49525** of the open database file. The sector size will be used
49526** to determine the size and alignment of journal header and
49527** master journal pointers within created journal files.
49528**
49529** For temporary files the effective sector size is always 512 bytes.
49530**
49531** Otherwise, for non-temporary files, the effective sector size is
49532** the value returned by the xSectorSize() method rounded up to 32 if
49533** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
49534** is greater than MAX_SECTOR_SIZE.
49535**
49536** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
49537** the effective sector size to its minimum value (512).  The purpose of
49538** pPager->sectorSize is to define the "blast radius" of bytes that
49539** might change if a crash occurs while writing to a single byte in
49540** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
49541** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
49542** size.  For backwards compatibility of the rollback journal file format,
49543** we cannot reduce the effective sector size below 512.
49544*/
49545static void setSectorSize(Pager *pPager){
49546  assert( isOpen(pPager->fd) || pPager->tempFile );
49547
49548  if( pPager->tempFile
49549   || (sqlite3OsDeviceCharacteristics(pPager->fd) &
49550              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
49551  ){
49552    /* Sector size doesn't matter for temporary files. Also, the file
49553    ** may not have been opened yet, in which case the OsSectorSize()
49554    ** call will segfault. */
49555    pPager->sectorSize = 512;
49556  }else{
49557    pPager->sectorSize = sqlite3SectorSize(pPager->fd);
49558  }
49559}
49560
49561/*
49562** Playback the journal and thus restore the database file to
49563** the state it was in before we started making changes.
49564**
49565** The journal file format is as follows:
49566**
49567**  (1)  8 byte prefix.  A copy of aJournalMagic[].
49568**  (2)  4 byte big-endian integer which is the number of valid page records
49569**       in the journal.  If this value is 0xffffffff, then compute the
49570**       number of page records from the journal size.
49571**  (3)  4 byte big-endian integer which is the initial value for the
49572**       sanity checksum.
49573**  (4)  4 byte integer which is the number of pages to truncate the
49574**       database to during a rollback.
49575**  (5)  4 byte big-endian integer which is the sector size.  The header
49576**       is this many bytes in size.
49577**  (6)  4 byte big-endian integer which is the page size.
49578**  (7)  zero padding out to the next sector size.
49579**  (8)  Zero or more pages instances, each as follows:
49580**        +  4 byte page number.
49581**        +  pPager->pageSize bytes of data.
49582**        +  4 byte checksum
49583**
49584** When we speak of the journal header, we mean the first 7 items above.
49585** Each entry in the journal is an instance of the 8th item.
49586**
49587** Call the value from the second bullet "nRec".  nRec is the number of
49588** valid page entries in the journal.  In most cases, you can compute the
49589** value of nRec from the size of the journal file.  But if a power
49590** failure occurred while the journal was being written, it could be the
49591** case that the size of the journal file had already been increased but
49592** the extra entries had not yet made it safely to disk.  In such a case,
49593** the value of nRec computed from the file size would be too large.  For
49594** that reason, we always use the nRec value in the header.
49595**
49596** If the nRec value is 0xffffffff it means that nRec should be computed
49597** from the file size.  This value is used when the user selects the
49598** no-sync option for the journal.  A power failure could lead to corruption
49599** in this case.  But for things like temporary table (which will be
49600** deleted when the power is restored) we don't care.
49601**
49602** If the file opened as the journal file is not a well-formed
49603** journal file then all pages up to the first corrupted page are rolled
49604** back (or no pages if the journal header is corrupted). The journal file
49605** is then deleted and SQLITE_OK returned, just as if no corruption had
49606** been encountered.
49607**
49608** If an I/O or malloc() error occurs, the journal-file is not deleted
49609** and an error code is returned.
49610**
49611** The isHot parameter indicates that we are trying to rollback a journal
49612** that might be a hot journal.  Or, it could be that the journal is
49613** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
49614** If the journal really is hot, reset the pager cache prior rolling
49615** back any content.  If the journal is merely persistent, no reset is
49616** needed.
49617*/
49618static int pager_playback(Pager *pPager, int isHot){
49619  sqlite3_vfs *pVfs = pPager->pVfs;
49620  i64 szJ;                 /* Size of the journal file in bytes */
49621  u32 nRec;                /* Number of Records in the journal */
49622  u32 u;                   /* Unsigned loop counter */
49623  Pgno mxPg = 0;           /* Size of the original file in pages */
49624  int rc;                  /* Result code of a subroutine */
49625  int res = 1;             /* Value returned by sqlite3OsAccess() */
49626  char *zMaster = 0;       /* Name of master journal file if any */
49627  int needPagerReset;      /* True to reset page prior to first page rollback */
49628  int nPlayback = 0;       /* Total number of pages restored from journal */
49629
49630  /* Figure out how many records are in the journal.  Abort early if
49631  ** the journal is empty.
49632  */
49633  assert( isOpen(pPager->jfd) );
49634  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
49635  if( rc!=SQLITE_OK ){
49636    goto end_playback;
49637  }
49638
49639  /* Read the master journal name from the journal, if it is present.
49640  ** If a master journal file name is specified, but the file is not
49641  ** present on disk, then the journal is not hot and does not need to be
49642  ** played back.
49643  **
49644  ** TODO: Technically the following is an error because it assumes that
49645  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
49646  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
49647  ** mxPathname is 512, which is the same as the minimum allowable value
49648  ** for pageSize.
49649  */
49650  zMaster = pPager->pTmpSpace;
49651  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
49652  if( rc==SQLITE_OK && zMaster[0] ){
49653    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
49654  }
49655  zMaster = 0;
49656  if( rc!=SQLITE_OK || !res ){
49657    goto end_playback;
49658  }
49659  pPager->journalOff = 0;
49660  needPagerReset = isHot;
49661
49662  /* This loop terminates either when a readJournalHdr() or
49663  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
49664  ** occurs.
49665  */
49666  while( 1 ){
49667    /* Read the next journal header from the journal file.  If there are
49668    ** not enough bytes left in the journal file for a complete header, or
49669    ** it is corrupted, then a process must have failed while writing it.
49670    ** This indicates nothing more needs to be rolled back.
49671    */
49672    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
49673    if( rc!=SQLITE_OK ){
49674      if( rc==SQLITE_DONE ){
49675        rc = SQLITE_OK;
49676      }
49677      goto end_playback;
49678    }
49679
49680    /* If nRec is 0xffffffff, then this journal was created by a process
49681    ** working in no-sync mode. This means that the rest of the journal
49682    ** file consists of pages, there are no more journal headers. Compute
49683    ** the value of nRec based on this assumption.
49684    */
49685    if( nRec==0xffffffff ){
49686      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
49687      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
49688    }
49689
49690    /* If nRec is 0 and this rollback is of a transaction created by this
49691    ** process and if this is the final header in the journal, then it means
49692    ** that this part of the journal was being filled but has not yet been
49693    ** synced to disk.  Compute the number of pages based on the remaining
49694    ** size of the file.
49695    **
49696    ** The third term of the test was added to fix ticket #2565.
49697    ** When rolling back a hot journal, nRec==0 always means that the next
49698    ** chunk of the journal contains zero pages to be rolled back.  But
49699    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
49700    ** the journal, it means that the journal might contain additional
49701    ** pages that need to be rolled back and that the number of pages
49702    ** should be computed based on the journal file size.
49703    */
49704    if( nRec==0 && !isHot &&
49705        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
49706      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
49707    }
49708
49709    /* If this is the first header read from the journal, truncate the
49710    ** database file back to its original size.
49711    */
49712    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
49713      rc = pager_truncate(pPager, mxPg);
49714      if( rc!=SQLITE_OK ){
49715        goto end_playback;
49716      }
49717      pPager->dbSize = mxPg;
49718    }
49719
49720    /* Copy original pages out of the journal and back into the
49721    ** database file and/or page cache.
49722    */
49723    for(u=0; u<nRec; u++){
49724      if( needPagerReset ){
49725        pager_reset(pPager);
49726        needPagerReset = 0;
49727      }
49728      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
49729      if( rc==SQLITE_OK ){
49730        nPlayback++;
49731      }else{
49732        if( rc==SQLITE_DONE ){
49733          pPager->journalOff = szJ;
49734          break;
49735        }else if( rc==SQLITE_IOERR_SHORT_READ ){
49736          /* If the journal has been truncated, simply stop reading and
49737          ** processing the journal. This might happen if the journal was
49738          ** not completely written and synced prior to a crash.  In that
49739          ** case, the database should have never been written in the
49740          ** first place so it is OK to simply abandon the rollback. */
49741          rc = SQLITE_OK;
49742          goto end_playback;
49743        }else{
49744          /* If we are unable to rollback, quit and return the error
49745          ** code.  This will cause the pager to enter the error state
49746          ** so that no further harm will be done.  Perhaps the next
49747          ** process to come along will be able to rollback the database.
49748          */
49749          goto end_playback;
49750        }
49751      }
49752    }
49753  }
49754  /*NOTREACHED*/
49755  assert( 0 );
49756
49757end_playback:
49758  /* Following a rollback, the database file should be back in its original
49759  ** state prior to the start of the transaction, so invoke the
49760  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
49761  ** assertion that the transaction counter was modified.
49762  */
49763#ifdef SQLITE_DEBUG
49764  if( pPager->fd->pMethods ){
49765    sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
49766  }
49767#endif
49768
49769  /* If this playback is happening automatically as a result of an IO or
49770  ** malloc error that occurred after the change-counter was updated but
49771  ** before the transaction was committed, then the change-counter
49772  ** modification may just have been reverted. If this happens in exclusive
49773  ** mode, then subsequent transactions performed by the connection will not
49774  ** update the change-counter at all. This may lead to cache inconsistency
49775  ** problems for other processes at some point in the future. So, just
49776  ** in case this has happened, clear the changeCountDone flag now.
49777  */
49778  pPager->changeCountDone = pPager->tempFile;
49779
49780  if( rc==SQLITE_OK ){
49781    zMaster = pPager->pTmpSpace;
49782    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
49783    testcase( rc!=SQLITE_OK );
49784  }
49785  if( rc==SQLITE_OK
49786   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
49787  ){
49788    rc = sqlite3PagerSync(pPager, 0);
49789  }
49790  if( rc==SQLITE_OK ){
49791    rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
49792    testcase( rc!=SQLITE_OK );
49793  }
49794  if( rc==SQLITE_OK && zMaster[0] && res ){
49795    /* If there was a master journal and this routine will return success,
49796    ** see if it is possible to delete the master journal.
49797    */
49798    rc = pager_delmaster(pPager, zMaster);
49799    testcase( rc!=SQLITE_OK );
49800  }
49801  if( isHot && nPlayback ){
49802    sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
49803                nPlayback, pPager->zJournal);
49804  }
49805
49806  /* The Pager.sectorSize variable may have been updated while rolling
49807  ** back a journal created by a process with a different sector size
49808  ** value. Reset it to the correct value for this process.
49809  */
49810  setSectorSize(pPager);
49811  return rc;
49812}
49813
49814
49815/*
49816** Read the content for page pPg out of the database file and into
49817** pPg->pData. A shared lock or greater must be held on the database
49818** file before this function is called.
49819**
49820** If page 1 is read, then the value of Pager.dbFileVers[] is set to
49821** the value read from the database file.
49822**
49823** If an IO error occurs, then the IO error is returned to the caller.
49824** Otherwise, SQLITE_OK is returned.
49825*/
49826static int readDbPage(PgHdr *pPg, u32 iFrame){
49827  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
49828  Pgno pgno = pPg->pgno;       /* Page number to read */
49829  int rc = SQLITE_OK;          /* Return code */
49830  int pgsz = pPager->pageSize; /* Number of bytes to read */
49831
49832  assert( pPager->eState>=PAGER_READER && !MEMDB );
49833  assert( isOpen(pPager->fd) );
49834
49835#ifndef SQLITE_OMIT_WAL
49836  if( iFrame ){
49837    /* Try to pull the page from the write-ahead log. */
49838    rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
49839  }else
49840#endif
49841  {
49842    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
49843    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
49844    if( rc==SQLITE_IOERR_SHORT_READ ){
49845      rc = SQLITE_OK;
49846    }
49847  }
49848
49849  if( pgno==1 ){
49850    if( rc ){
49851      /* If the read is unsuccessful, set the dbFileVers[] to something
49852      ** that will never be a valid file version.  dbFileVers[] is a copy
49853      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
49854      ** zero or the size of the database in page. Bytes 32..35 and 35..39
49855      ** should be page numbers which are never 0xffffffff.  So filling
49856      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
49857      **
49858      ** For an encrypted database, the situation is more complex:  bytes
49859      ** 24..39 of the database are white noise.  But the probability of
49860      ** white noise equaling 16 bytes of 0xff is vanishingly small so
49861      ** we should still be ok.
49862      */
49863      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
49864    }else{
49865      u8 *dbFileVers = &((u8*)pPg->pData)[24];
49866      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
49867    }
49868  }
49869  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT);
49870
49871  PAGER_INCR(sqlite3_pager_readdb_count);
49872  PAGER_INCR(pPager->nRead);
49873  IOTRACE(("PGIN %p %d\n", pPager, pgno));
49874  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
49875               PAGERID(pPager), pgno, pager_pagehash(pPg)));
49876
49877  return rc;
49878}
49879
49880/*
49881** Update the value of the change-counter at offsets 24 and 92 in
49882** the header and the sqlite version number at offset 96.
49883**
49884** This is an unconditional update.  See also the pager_incr_changecounter()
49885** routine which only updates the change-counter if the update is actually
49886** needed, as determined by the pPager->changeCountDone state variable.
49887*/
49888static void pager_write_changecounter(PgHdr *pPg){
49889  u32 change_counter;
49890
49891  /* Increment the value just read and write it back to byte 24. */
49892  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
49893  put32bits(((char*)pPg->pData)+24, change_counter);
49894
49895  /* Also store the SQLite version number in bytes 96..99 and in
49896  ** bytes 92..95 store the change counter for which the version number
49897  ** is valid. */
49898  put32bits(((char*)pPg->pData)+92, change_counter);
49899  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
49900}
49901
49902#ifndef SQLITE_OMIT_WAL
49903/*
49904** This function is invoked once for each page that has already been
49905** written into the log file when a WAL transaction is rolled back.
49906** Parameter iPg is the page number of said page. The pCtx argument
49907** is actually a pointer to the Pager structure.
49908**
49909** If page iPg is present in the cache, and has no outstanding references,
49910** it is discarded. Otherwise, if there are one or more outstanding
49911** references, the page content is reloaded from the database. If the
49912** attempt to reload content from the database is required and fails,
49913** return an SQLite error code. Otherwise, SQLITE_OK.
49914*/
49915static int pagerUndoCallback(void *pCtx, Pgno iPg){
49916  int rc = SQLITE_OK;
49917  Pager *pPager = (Pager *)pCtx;
49918  PgHdr *pPg;
49919
49920  assert( pagerUseWal(pPager) );
49921  pPg = sqlite3PagerLookup(pPager, iPg);
49922  if( pPg ){
49923    if( sqlite3PcachePageRefcount(pPg)==1 ){
49924      sqlite3PcacheDrop(pPg);
49925    }else{
49926      u32 iFrame = 0;
49927      rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
49928      if( rc==SQLITE_OK ){
49929        rc = readDbPage(pPg, iFrame);
49930      }
49931      if( rc==SQLITE_OK ){
49932        pPager->xReiniter(pPg);
49933      }
49934      sqlite3PagerUnrefNotNull(pPg);
49935    }
49936  }
49937
49938  /* Normally, if a transaction is rolled back, any backup processes are
49939  ** updated as data is copied out of the rollback journal and into the
49940  ** database. This is not generally possible with a WAL database, as
49941  ** rollback involves simply truncating the log file. Therefore, if one
49942  ** or more frames have already been written to the log (and therefore
49943  ** also copied into the backup databases) as part of this transaction,
49944  ** the backups must be restarted.
49945  */
49946  sqlite3BackupRestart(pPager->pBackup);
49947
49948  return rc;
49949}
49950
49951/*
49952** This function is called to rollback a transaction on a WAL database.
49953*/
49954static int pagerRollbackWal(Pager *pPager){
49955  int rc;                         /* Return Code */
49956  PgHdr *pList;                   /* List of dirty pages to revert */
49957
49958  /* For all pages in the cache that are currently dirty or have already
49959  ** been written (but not committed) to the log file, do one of the
49960  ** following:
49961  **
49962  **   + Discard the cached page (if refcount==0), or
49963  **   + Reload page content from the database (if refcount>0).
49964  */
49965  pPager->dbSize = pPager->dbOrigSize;
49966  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
49967  pList = sqlite3PcacheDirtyList(pPager->pPCache);
49968  while( pList && rc==SQLITE_OK ){
49969    PgHdr *pNext = pList->pDirty;
49970    rc = pagerUndoCallback((void *)pPager, pList->pgno);
49971    pList = pNext;
49972  }
49973
49974  return rc;
49975}
49976
49977/*
49978** This function is a wrapper around sqlite3WalFrames(). As well as logging
49979** the contents of the list of pages headed by pList (connected by pDirty),
49980** this function notifies any active backup processes that the pages have
49981** changed.
49982**
49983** The list of pages passed into this routine is always sorted by page number.
49984** Hence, if page 1 appears anywhere on the list, it will be the first page.
49985*/
49986static int pagerWalFrames(
49987  Pager *pPager,                  /* Pager object */
49988  PgHdr *pList,                   /* List of frames to log */
49989  Pgno nTruncate,                 /* Database size after this commit */
49990  int isCommit                    /* True if this is a commit */
49991){
49992  int rc;                         /* Return code */
49993  int nList;                      /* Number of pages in pList */
49994  PgHdr *p;                       /* For looping over pages */
49995
49996  assert( pPager->pWal );
49997  assert( pList );
49998#ifdef SQLITE_DEBUG
49999  /* Verify that the page list is in accending order */
50000  for(p=pList; p && p->pDirty; p=p->pDirty){
50001    assert( p->pgno < p->pDirty->pgno );
50002  }
50003#endif
50004
50005  assert( pList->pDirty==0 || isCommit );
50006  if( isCommit ){
50007    /* If a WAL transaction is being committed, there is no point in writing
50008    ** any pages with page numbers greater than nTruncate into the WAL file.
50009    ** They will never be read by any client. So remove them from the pDirty
50010    ** list here. */
50011    PgHdr **ppNext = &pList;
50012    nList = 0;
50013    for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
50014      if( p->pgno<=nTruncate ){
50015        ppNext = &p->pDirty;
50016        nList++;
50017      }
50018    }
50019    assert( pList );
50020  }else{
50021    nList = 1;
50022  }
50023  pPager->aStat[PAGER_STAT_WRITE] += nList;
50024
50025  if( pList->pgno==1 ) pager_write_changecounter(pList);
50026  rc = sqlite3WalFrames(pPager->pWal,
50027      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
50028  );
50029  if( rc==SQLITE_OK && pPager->pBackup ){
50030    for(p=pList; p; p=p->pDirty){
50031      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
50032    }
50033  }
50034
50035#ifdef SQLITE_CHECK_PAGES
50036  pList = sqlite3PcacheDirtyList(pPager->pPCache);
50037  for(p=pList; p; p=p->pDirty){
50038    pager_set_pagehash(p);
50039  }
50040#endif
50041
50042  return rc;
50043}
50044
50045/*
50046** Begin a read transaction on the WAL.
50047**
50048** This routine used to be called "pagerOpenSnapshot()" because it essentially
50049** makes a snapshot of the database at the current point in time and preserves
50050** that snapshot for use by the reader in spite of concurrently changes by
50051** other writers or checkpointers.
50052*/
50053static int pagerBeginReadTransaction(Pager *pPager){
50054  int rc;                         /* Return code */
50055  int changed = 0;                /* True if cache must be reset */
50056
50057  assert( pagerUseWal(pPager) );
50058  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
50059
50060  /* sqlite3WalEndReadTransaction() was not called for the previous
50061  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
50062  ** are in locking_mode=NORMAL and EndRead() was previously called,
50063  ** the duplicate call is harmless.
50064  */
50065  sqlite3WalEndReadTransaction(pPager->pWal);
50066
50067  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
50068  if( rc!=SQLITE_OK || changed ){
50069    pager_reset(pPager);
50070    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
50071  }
50072
50073  return rc;
50074}
50075#endif
50076
50077/*
50078** This function is called as part of the transition from PAGER_OPEN
50079** to PAGER_READER state to determine the size of the database file
50080** in pages (assuming the page size currently stored in Pager.pageSize).
50081**
50082** If no error occurs, SQLITE_OK is returned and the size of the database
50083** in pages is stored in *pnPage. Otherwise, an error code (perhaps
50084** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
50085*/
50086static int pagerPagecount(Pager *pPager, Pgno *pnPage){
50087  Pgno nPage;                     /* Value to return via *pnPage */
50088
50089  /* Query the WAL sub-system for the database size. The WalDbsize()
50090  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
50091  ** if the database size is not available. The database size is not
50092  ** available from the WAL sub-system if the log file is empty or
50093  ** contains no valid committed transactions.
50094  */
50095  assert( pPager->eState==PAGER_OPEN );
50096  assert( pPager->eLock>=SHARED_LOCK );
50097  assert( isOpen(pPager->fd) );
50098  assert( pPager->tempFile==0 );
50099  nPage = sqlite3WalDbsize(pPager->pWal);
50100
50101  /* If the number of pages in the database is not available from the
50102  ** WAL sub-system, determine the page counte based on the size of
50103  ** the database file.  If the size of the database file is not an
50104  ** integer multiple of the page-size, round up the result.
50105  */
50106  if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
50107    i64 n = 0;                    /* Size of db file in bytes */
50108    int rc = sqlite3OsFileSize(pPager->fd, &n);
50109    if( rc!=SQLITE_OK ){
50110      return rc;
50111    }
50112    nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
50113  }
50114
50115  /* If the current number of pages in the file is greater than the
50116  ** configured maximum pager number, increase the allowed limit so
50117  ** that the file can be read.
50118  */
50119  if( nPage>pPager->mxPgno ){
50120    pPager->mxPgno = (Pgno)nPage;
50121  }
50122
50123  *pnPage = nPage;
50124  return SQLITE_OK;
50125}
50126
50127#ifndef SQLITE_OMIT_WAL
50128/*
50129** Check if the *-wal file that corresponds to the database opened by pPager
50130** exists if the database is not empy, or verify that the *-wal file does
50131** not exist (by deleting it) if the database file is empty.
50132**
50133** If the database is not empty and the *-wal file exists, open the pager
50134** in WAL mode.  If the database is empty or if no *-wal file exists and
50135** if no error occurs, make sure Pager.journalMode is not set to
50136** PAGER_JOURNALMODE_WAL.
50137**
50138** Return SQLITE_OK or an error code.
50139**
50140** The caller must hold a SHARED lock on the database file to call this
50141** function. Because an EXCLUSIVE lock on the db file is required to delete
50142** a WAL on a none-empty database, this ensures there is no race condition
50143** between the xAccess() below and an xDelete() being executed by some
50144** other connection.
50145*/
50146static int pagerOpenWalIfPresent(Pager *pPager){
50147  int rc = SQLITE_OK;
50148  assert( pPager->eState==PAGER_OPEN );
50149  assert( pPager->eLock>=SHARED_LOCK );
50150
50151  if( !pPager->tempFile ){
50152    int isWal;                    /* True if WAL file exists */
50153    Pgno nPage;                   /* Size of the database file */
50154
50155    rc = pagerPagecount(pPager, &nPage);
50156    if( rc ) return rc;
50157    if( nPage==0 ){
50158      rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
50159      if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
50160      isWal = 0;
50161    }else{
50162      rc = sqlite3OsAccess(
50163          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
50164      );
50165    }
50166    if( rc==SQLITE_OK ){
50167      if( isWal ){
50168        testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
50169        rc = sqlite3PagerOpenWal(pPager, 0);
50170      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
50171        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
50172      }
50173    }
50174  }
50175  return rc;
50176}
50177#endif
50178
50179/*
50180** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
50181** the entire master journal file. The case pSavepoint==NULL occurs when
50182** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
50183** savepoint.
50184**
50185** When pSavepoint is not NULL (meaning a non-transaction savepoint is
50186** being rolled back), then the rollback consists of up to three stages,
50187** performed in the order specified:
50188**
50189**   * Pages are played back from the main journal starting at byte
50190**     offset PagerSavepoint.iOffset and continuing to
50191**     PagerSavepoint.iHdrOffset, or to the end of the main journal
50192**     file if PagerSavepoint.iHdrOffset is zero.
50193**
50194**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
50195**     back starting from the journal header immediately following
50196**     PagerSavepoint.iHdrOffset to the end of the main journal file.
50197**
50198**   * Pages are then played back from the sub-journal file, starting
50199**     with the PagerSavepoint.iSubRec and continuing to the end of
50200**     the journal file.
50201**
50202** Throughout the rollback process, each time a page is rolled back, the
50203** corresponding bit is set in a bitvec structure (variable pDone in the
50204** implementation below). This is used to ensure that a page is only
50205** rolled back the first time it is encountered in either journal.
50206**
50207** If pSavepoint is NULL, then pages are only played back from the main
50208** journal file. There is no need for a bitvec in this case.
50209**
50210** In either case, before playback commences the Pager.dbSize variable
50211** is reset to the value that it held at the start of the savepoint
50212** (or transaction). No page with a page-number greater than this value
50213** is played back. If one is encountered it is simply skipped.
50214*/
50215static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
50216  i64 szJ;                 /* Effective size of the main journal */
50217  i64 iHdrOff;             /* End of first segment of main-journal records */
50218  int rc = SQLITE_OK;      /* Return code */
50219  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
50220
50221  assert( pPager->eState!=PAGER_ERROR );
50222  assert( pPager->eState>=PAGER_WRITER_LOCKED );
50223
50224  /* Allocate a bitvec to use to store the set of pages rolled back */
50225  if( pSavepoint ){
50226    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
50227    if( !pDone ){
50228      return SQLITE_NOMEM_BKPT;
50229    }
50230  }
50231
50232  /* Set the database size back to the value it was before the savepoint
50233  ** being reverted was opened.
50234  */
50235  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
50236  pPager->changeCountDone = pPager->tempFile;
50237
50238  if( !pSavepoint && pagerUseWal(pPager) ){
50239    return pagerRollbackWal(pPager);
50240  }
50241
50242  /* Use pPager->journalOff as the effective size of the main rollback
50243  ** journal.  The actual file might be larger than this in
50244  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
50245  ** past pPager->journalOff is off-limits to us.
50246  */
50247  szJ = pPager->journalOff;
50248  assert( pagerUseWal(pPager)==0 || szJ==0 );
50249
50250  /* Begin by rolling back records from the main journal starting at
50251  ** PagerSavepoint.iOffset and continuing to the next journal header.
50252  ** There might be records in the main journal that have a page number
50253  ** greater than the current database size (pPager->dbSize) but those
50254  ** will be skipped automatically.  Pages are added to pDone as they
50255  ** are played back.
50256  */
50257  if( pSavepoint && !pagerUseWal(pPager) ){
50258    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
50259    pPager->journalOff = pSavepoint->iOffset;
50260    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
50261      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
50262    }
50263    assert( rc!=SQLITE_DONE );
50264  }else{
50265    pPager->journalOff = 0;
50266  }
50267
50268  /* Continue rolling back records out of the main journal starting at
50269  ** the first journal header seen and continuing until the effective end
50270  ** of the main journal file.  Continue to skip out-of-range pages and
50271  ** continue adding pages rolled back to pDone.
50272  */
50273  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
50274    u32 ii;            /* Loop counter */
50275    u32 nJRec = 0;     /* Number of Journal Records */
50276    u32 dummy;
50277    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
50278    assert( rc!=SQLITE_DONE );
50279
50280    /*
50281    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
50282    ** test is related to ticket #2565.  See the discussion in the
50283    ** pager_playback() function for additional information.
50284    */
50285    if( nJRec==0
50286     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
50287    ){
50288      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
50289    }
50290    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
50291      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
50292    }
50293    assert( rc!=SQLITE_DONE );
50294  }
50295  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
50296
50297  /* Finally,  rollback pages from the sub-journal.  Page that were
50298  ** previously rolled back out of the main journal (and are hence in pDone)
50299  ** will be skipped.  Out-of-range pages are also skipped.
50300  */
50301  if( pSavepoint ){
50302    u32 ii;            /* Loop counter */
50303    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
50304
50305    if( pagerUseWal(pPager) ){
50306      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
50307    }
50308    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
50309      assert( offset==(i64)ii*(4+pPager->pageSize) );
50310      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
50311    }
50312    assert( rc!=SQLITE_DONE );
50313  }
50314
50315  sqlite3BitvecDestroy(pDone);
50316  if( rc==SQLITE_OK ){
50317    pPager->journalOff = szJ;
50318  }
50319
50320  return rc;
50321}
50322
50323/*
50324** Change the maximum number of in-memory pages that are allowed
50325** before attempting to recycle clean and unused pages.
50326*/
50327SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
50328  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
50329}
50330
50331/*
50332** Change the maximum number of in-memory pages that are allowed
50333** before attempting to spill pages to journal.
50334*/
50335SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
50336  return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
50337}
50338
50339/*
50340** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
50341*/
50342static void pagerFixMaplimit(Pager *pPager){
50343#if SQLITE_MAX_MMAP_SIZE>0
50344  sqlite3_file *fd = pPager->fd;
50345  if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
50346    sqlite3_int64 sz;
50347    sz = pPager->szMmap;
50348    pPager->bUseFetch = (sz>0);
50349    setGetterMethod(pPager);
50350    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
50351  }
50352#endif
50353}
50354
50355/*
50356** Change the maximum size of any memory mapping made of the database file.
50357*/
50358SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
50359  pPager->szMmap = szMmap;
50360  pagerFixMaplimit(pPager);
50361}
50362
50363/*
50364** Free as much memory as possible from the pager.
50365*/
50366SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
50367  sqlite3PcacheShrink(pPager->pPCache);
50368}
50369
50370/*
50371** Adjust settings of the pager to those specified in the pgFlags parameter.
50372**
50373** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
50374** of the database to damage due to OS crashes or power failures by
50375** changing the number of syncs()s when writing the journals.
50376** There are four levels:
50377**
50378**    OFF       sqlite3OsSync() is never called.  This is the default
50379**              for temporary and transient files.
50380**
50381**    NORMAL    The journal is synced once before writes begin on the
50382**              database.  This is normally adequate protection, but
50383**              it is theoretically possible, though very unlikely,
50384**              that an inopertune power failure could leave the journal
50385**              in a state which would cause damage to the database
50386**              when it is rolled back.
50387**
50388**    FULL      The journal is synced twice before writes begin on the
50389**              database (with some additional information - the nRec field
50390**              of the journal header - being written in between the two
50391**              syncs).  If we assume that writing a
50392**              single disk sector is atomic, then this mode provides
50393**              assurance that the journal will not be corrupted to the
50394**              point of causing damage to the database during rollback.
50395**
50396**    EXTRA     This is like FULL except that is also syncs the directory
50397**              that contains the rollback journal after the rollback
50398**              journal is unlinked.
50399**
50400** The above is for a rollback-journal mode.  For WAL mode, OFF continues
50401** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
50402** prior to the start of checkpoint and that the database file is synced
50403** at the conclusion of the checkpoint if the entire content of the WAL
50404** was written back into the database.  But no sync operations occur for
50405** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
50406** file is synced following each commit operation, in addition to the
50407** syncs associated with NORMAL.  There is no difference between FULL
50408** and EXTRA for WAL mode.
50409**
50410** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
50411** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
50412** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
50413** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
50414** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
50415** synchronous=FULL versus synchronous=NORMAL setting determines when
50416** the xSync primitive is called and is relevant to all platforms.
50417**
50418** Numeric values associated with these states are OFF==1, NORMAL=2,
50419** and FULL=3.
50420*/
50421#ifndef SQLITE_OMIT_PAGER_PRAGMAS
50422SQLITE_PRIVATE void sqlite3PagerSetFlags(
50423  Pager *pPager,        /* The pager to set safety level for */
50424  unsigned pgFlags      /* Various flags */
50425){
50426  unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
50427  if( pPager->tempFile ){
50428    pPager->noSync = 1;
50429    pPager->fullSync = 0;
50430    pPager->extraSync = 0;
50431  }else{
50432    pPager->noSync =  level==PAGER_SYNCHRONOUS_OFF ?1:0;
50433    pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
50434    pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
50435  }
50436  if( pPager->noSync ){
50437    pPager->syncFlags = 0;
50438    pPager->ckptSyncFlags = 0;
50439  }else if( pgFlags & PAGER_FULLFSYNC ){
50440    pPager->syncFlags = SQLITE_SYNC_FULL;
50441    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
50442  }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
50443    pPager->syncFlags = SQLITE_SYNC_NORMAL;
50444    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
50445  }else{
50446    pPager->syncFlags = SQLITE_SYNC_NORMAL;
50447    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
50448  }
50449  pPager->walSyncFlags = pPager->syncFlags;
50450  if( pPager->fullSync ){
50451    pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
50452  }
50453  if( pgFlags & PAGER_CACHESPILL ){
50454    pPager->doNotSpill &= ~SPILLFLAG_OFF;
50455  }else{
50456    pPager->doNotSpill |= SPILLFLAG_OFF;
50457  }
50458}
50459#endif
50460
50461/*
50462** The following global variable is incremented whenever the library
50463** attempts to open a temporary file.  This information is used for
50464** testing and analysis only.
50465*/
50466#ifdef SQLITE_TEST
50467SQLITE_API int sqlite3_opentemp_count = 0;
50468#endif
50469
50470/*
50471** Open a temporary file.
50472**
50473** Write the file descriptor into *pFile. Return SQLITE_OK on success
50474** or some other error code if we fail. The OS will automatically
50475** delete the temporary file when it is closed.
50476**
50477** The flags passed to the VFS layer xOpen() call are those specified
50478** by parameter vfsFlags ORed with the following:
50479**
50480**     SQLITE_OPEN_READWRITE
50481**     SQLITE_OPEN_CREATE
50482**     SQLITE_OPEN_EXCLUSIVE
50483**     SQLITE_OPEN_DELETEONCLOSE
50484*/
50485static int pagerOpentemp(
50486  Pager *pPager,        /* The pager object */
50487  sqlite3_file *pFile,  /* Write the file descriptor here */
50488  int vfsFlags          /* Flags passed through to the VFS */
50489){
50490  int rc;               /* Return code */
50491
50492#ifdef SQLITE_TEST
50493  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
50494#endif
50495
50496  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
50497            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
50498  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
50499  assert( rc!=SQLITE_OK || isOpen(pFile) );
50500  return rc;
50501}
50502
50503/*
50504** Set the busy handler function.
50505**
50506** The pager invokes the busy-handler if sqlite3OsLock() returns
50507** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
50508** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
50509** lock. It does *not* invoke the busy handler when upgrading from
50510** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
50511** (which occurs during hot-journal rollback). Summary:
50512**
50513**   Transition                        | Invokes xBusyHandler
50514**   --------------------------------------------------------
50515**   NO_LOCK       -> SHARED_LOCK      | Yes
50516**   SHARED_LOCK   -> RESERVED_LOCK    | No
50517**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
50518**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
50519**
50520** If the busy-handler callback returns non-zero, the lock is
50521** retried. If it returns zero, then the SQLITE_BUSY error is
50522** returned to the caller of the pager API function.
50523*/
50524SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
50525  Pager *pPager,                       /* Pager object */
50526  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
50527  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
50528){
50529  pPager->xBusyHandler = xBusyHandler;
50530  pPager->pBusyHandlerArg = pBusyHandlerArg;
50531
50532  if( isOpen(pPager->fd) ){
50533    void **ap = (void **)&pPager->xBusyHandler;
50534    assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
50535    assert( ap[1]==pBusyHandlerArg );
50536    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
50537  }
50538}
50539
50540/*
50541** Change the page size used by the Pager object. The new page size
50542** is passed in *pPageSize.
50543**
50544** If the pager is in the error state when this function is called, it
50545** is a no-op. The value returned is the error state error code (i.e.
50546** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
50547**
50548** Otherwise, if all of the following are true:
50549**
50550**   * the new page size (value of *pPageSize) is valid (a power
50551**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
50552**
50553**   * there are no outstanding page references, and
50554**
50555**   * the database is either not an in-memory database or it is
50556**     an in-memory database that currently consists of zero pages.
50557**
50558** then the pager object page size is set to *pPageSize.
50559**
50560** If the page size is changed, then this function uses sqlite3PagerMalloc()
50561** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
50562** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
50563** In all other cases, SQLITE_OK is returned.
50564**
50565** If the page size is not changed, either because one of the enumerated
50566** conditions above is not true, the pager was in error state when this
50567** function was called, or because the memory allocation attempt failed,
50568** then *pPageSize is set to the old, retained page size before returning.
50569*/
50570SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
50571  int rc = SQLITE_OK;
50572
50573  /* It is not possible to do a full assert_pager_state() here, as this
50574  ** function may be called from within PagerOpen(), before the state
50575  ** of the Pager object is internally consistent.
50576  **
50577  ** At one point this function returned an error if the pager was in
50578  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
50579  ** there is at least one outstanding page reference, this function
50580  ** is a no-op for that case anyhow.
50581  */
50582
50583  u32 pageSize = *pPageSize;
50584  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
50585  if( (pPager->memDb==0 || pPager->dbSize==0)
50586   && sqlite3PcacheRefCount(pPager->pPCache)==0
50587   && pageSize && pageSize!=(u32)pPager->pageSize
50588  ){
50589    char *pNew = NULL;             /* New temp space */
50590    i64 nByte = 0;
50591
50592    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
50593      rc = sqlite3OsFileSize(pPager->fd, &nByte);
50594    }
50595    if( rc==SQLITE_OK ){
50596      pNew = (char *)sqlite3PageMalloc(pageSize);
50597      if( !pNew ) rc = SQLITE_NOMEM_BKPT;
50598    }
50599
50600    if( rc==SQLITE_OK ){
50601      pager_reset(pPager);
50602      rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
50603    }
50604    if( rc==SQLITE_OK ){
50605      sqlite3PageFree(pPager->pTmpSpace);
50606      pPager->pTmpSpace = pNew;
50607      pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
50608      pPager->pageSize = pageSize;
50609    }else{
50610      sqlite3PageFree(pNew);
50611    }
50612  }
50613
50614  *pPageSize = pPager->pageSize;
50615  if( rc==SQLITE_OK ){
50616    if( nReserve<0 ) nReserve = pPager->nReserve;
50617    assert( nReserve>=0 && nReserve<1000 );
50618    pPager->nReserve = (i16)nReserve;
50619    pagerReportSize(pPager);
50620    pagerFixMaplimit(pPager);
50621  }
50622  return rc;
50623}
50624
50625/*
50626** Return a pointer to the "temporary page" buffer held internally
50627** by the pager.  This is a buffer that is big enough to hold the
50628** entire content of a database page.  This buffer is used internally
50629** during rollback and will be overwritten whenever a rollback
50630** occurs.  But other modules are free to use it too, as long as
50631** no rollbacks are happening.
50632*/
50633SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
50634  return pPager->pTmpSpace;
50635}
50636
50637/*
50638** Attempt to set the maximum database page count if mxPage is positive.
50639** Make no changes if mxPage is zero or negative.  And never reduce the
50640** maximum page count below the current size of the database.
50641**
50642** Regardless of mxPage, return the current maximum page count.
50643*/
50644SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
50645  if( mxPage>0 ){
50646    pPager->mxPgno = mxPage;
50647  }
50648  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
50649  assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
50650  return pPager->mxPgno;
50651}
50652
50653/*
50654** The following set of routines are used to disable the simulated
50655** I/O error mechanism.  These routines are used to avoid simulated
50656** errors in places where we do not care about errors.
50657**
50658** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
50659** and generate no code.
50660*/
50661#ifdef SQLITE_TEST
50662SQLITE_API extern int sqlite3_io_error_pending;
50663SQLITE_API extern int sqlite3_io_error_hit;
50664static int saved_cnt;
50665void disable_simulated_io_errors(void){
50666  saved_cnt = sqlite3_io_error_pending;
50667  sqlite3_io_error_pending = -1;
50668}
50669void enable_simulated_io_errors(void){
50670  sqlite3_io_error_pending = saved_cnt;
50671}
50672#else
50673# define disable_simulated_io_errors()
50674# define enable_simulated_io_errors()
50675#endif
50676
50677/*
50678** Read the first N bytes from the beginning of the file into memory
50679** that pDest points to.
50680**
50681** If the pager was opened on a transient file (zFilename==""), or
50682** opened on a file less than N bytes in size, the output buffer is
50683** zeroed and SQLITE_OK returned. The rationale for this is that this
50684** function is used to read database headers, and a new transient or
50685** zero sized database has a header than consists entirely of zeroes.
50686**
50687** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
50688** the error code is returned to the caller and the contents of the
50689** output buffer undefined.
50690*/
50691SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
50692  int rc = SQLITE_OK;
50693  memset(pDest, 0, N);
50694  assert( isOpen(pPager->fd) || pPager->tempFile );
50695
50696  /* This routine is only called by btree immediately after creating
50697  ** the Pager object.  There has not been an opportunity to transition
50698  ** to WAL mode yet.
50699  */
50700  assert( !pagerUseWal(pPager) );
50701
50702  if( isOpen(pPager->fd) ){
50703    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
50704    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
50705    if( rc==SQLITE_IOERR_SHORT_READ ){
50706      rc = SQLITE_OK;
50707    }
50708  }
50709  return rc;
50710}
50711
50712/*
50713** This function may only be called when a read-transaction is open on
50714** the pager. It returns the total number of pages in the database.
50715**
50716** However, if the file is between 1 and <page-size> bytes in size, then
50717** this is considered a 1 page file.
50718*/
50719SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
50720  assert( pPager->eState>=PAGER_READER );
50721  assert( pPager->eState!=PAGER_WRITER_FINISHED );
50722  *pnPage = (int)pPager->dbSize;
50723}
50724
50725
50726/*
50727** Try to obtain a lock of type locktype on the database file. If
50728** a similar or greater lock is already held, this function is a no-op
50729** (returning SQLITE_OK immediately).
50730**
50731** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
50732** the busy callback if the lock is currently not available. Repeat
50733** until the busy callback returns false or until the attempt to
50734** obtain the lock succeeds.
50735**
50736** Return SQLITE_OK on success and an error code if we cannot obtain
50737** the lock. If the lock is obtained successfully, set the Pager.state
50738** variable to locktype before returning.
50739*/
50740static int pager_wait_on_lock(Pager *pPager, int locktype){
50741  int rc;                              /* Return code */
50742
50743  /* Check that this is either a no-op (because the requested lock is
50744  ** already held), or one of the transitions that the busy-handler
50745  ** may be invoked during, according to the comment above
50746  ** sqlite3PagerSetBusyhandler().
50747  */
50748  assert( (pPager->eLock>=locktype)
50749       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
50750       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
50751  );
50752
50753  do {
50754    rc = pagerLockDb(pPager, locktype);
50755  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
50756  return rc;
50757}
50758
50759/*
50760** Function assertTruncateConstraint(pPager) checks that one of the
50761** following is true for all dirty pages currently in the page-cache:
50762**
50763**   a) The page number is less than or equal to the size of the
50764**      current database image, in pages, OR
50765**
50766**   b) if the page content were written at this time, it would not
50767**      be necessary to write the current content out to the sub-journal
50768**      (as determined by function subjRequiresPage()).
50769**
50770** If the condition asserted by this function were not true, and the
50771** dirty page were to be discarded from the cache via the pagerStress()
50772** routine, pagerStress() would not write the current page content to
50773** the database file. If a savepoint transaction were rolled back after
50774** this happened, the correct behavior would be to restore the current
50775** content of the page. However, since this content is not present in either
50776** the database file or the portion of the rollback journal and
50777** sub-journal rolled back the content could not be restored and the
50778** database image would become corrupt. It is therefore fortunate that
50779** this circumstance cannot arise.
50780*/
50781#if defined(SQLITE_DEBUG)
50782static void assertTruncateConstraintCb(PgHdr *pPg){
50783  assert( pPg->flags&PGHDR_DIRTY );
50784  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
50785}
50786static void assertTruncateConstraint(Pager *pPager){
50787  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
50788}
50789#else
50790# define assertTruncateConstraint(pPager)
50791#endif
50792
50793/*
50794** Truncate the in-memory database file image to nPage pages. This
50795** function does not actually modify the database file on disk. It
50796** just sets the internal state of the pager object so that the
50797** truncation will be done when the current transaction is committed.
50798**
50799** This function is only called right before committing a transaction.
50800** Once this function has been called, the transaction must either be
50801** rolled back or committed. It is not safe to call this function and
50802** then continue writing to the database.
50803*/
50804SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
50805  assert( pPager->dbSize>=nPage );
50806  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
50807  pPager->dbSize = nPage;
50808
50809  /* At one point the code here called assertTruncateConstraint() to
50810  ** ensure that all pages being truncated away by this operation are,
50811  ** if one or more savepoints are open, present in the savepoint
50812  ** journal so that they can be restored if the savepoint is rolled
50813  ** back. This is no longer necessary as this function is now only
50814  ** called right before committing a transaction. So although the
50815  ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
50816  ** they cannot be rolled back. So the assertTruncateConstraint() call
50817  ** is no longer correct. */
50818}
50819
50820
50821/*
50822** This function is called before attempting a hot-journal rollback. It
50823** syncs the journal file to disk, then sets pPager->journalHdr to the
50824** size of the journal file so that the pager_playback() routine knows
50825** that the entire journal file has been synced.
50826**
50827** Syncing a hot-journal to disk before attempting to roll it back ensures
50828** that if a power-failure occurs during the rollback, the process that
50829** attempts rollback following system recovery sees the same journal
50830** content as this process.
50831**
50832** If everything goes as planned, SQLITE_OK is returned. Otherwise,
50833** an SQLite error code.
50834*/
50835static int pagerSyncHotJournal(Pager *pPager){
50836  int rc = SQLITE_OK;
50837  if( !pPager->noSync ){
50838    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
50839  }
50840  if( rc==SQLITE_OK ){
50841    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
50842  }
50843  return rc;
50844}
50845
50846#if SQLITE_MAX_MMAP_SIZE>0
50847/*
50848** Obtain a reference to a memory mapped page object for page number pgno.
50849** The new object will use the pointer pData, obtained from xFetch().
50850** If successful, set *ppPage to point to the new page reference
50851** and return SQLITE_OK. Otherwise, return an SQLite error code and set
50852** *ppPage to zero.
50853**
50854** Page references obtained by calling this function should be released
50855** by calling pagerReleaseMapPage().
50856*/
50857static int pagerAcquireMapPage(
50858  Pager *pPager,                  /* Pager object */
50859  Pgno pgno,                      /* Page number */
50860  void *pData,                    /* xFetch()'d data for this page */
50861  PgHdr **ppPage                  /* OUT: Acquired page object */
50862){
50863  PgHdr *p;                       /* Memory mapped page to return */
50864
50865  if( pPager->pMmapFreelist ){
50866    *ppPage = p = pPager->pMmapFreelist;
50867    pPager->pMmapFreelist = p->pDirty;
50868    p->pDirty = 0;
50869    assert( pPager->nExtra>=8 );
50870    memset(p->pExtra, 0, 8);
50871  }else{
50872    *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
50873    if( p==0 ){
50874      sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
50875      return SQLITE_NOMEM_BKPT;
50876    }
50877    p->pExtra = (void *)&p[1];
50878    p->flags = PGHDR_MMAP;
50879    p->nRef = 1;
50880    p->pPager = pPager;
50881  }
50882
50883  assert( p->pExtra==(void *)&p[1] );
50884  assert( p->pPage==0 );
50885  assert( p->flags==PGHDR_MMAP );
50886  assert( p->pPager==pPager );
50887  assert( p->nRef==1 );
50888
50889  p->pgno = pgno;
50890  p->pData = pData;
50891  pPager->nMmapOut++;
50892
50893  return SQLITE_OK;
50894}
50895#endif
50896
50897/*
50898** Release a reference to page pPg. pPg must have been returned by an
50899** earlier call to pagerAcquireMapPage().
50900*/
50901static void pagerReleaseMapPage(PgHdr *pPg){
50902  Pager *pPager = pPg->pPager;
50903  pPager->nMmapOut--;
50904  pPg->pDirty = pPager->pMmapFreelist;
50905  pPager->pMmapFreelist = pPg;
50906
50907  assert( pPager->fd->pMethods->iVersion>=3 );
50908  sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
50909}
50910
50911/*
50912** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
50913*/
50914static void pagerFreeMapHdrs(Pager *pPager){
50915  PgHdr *p;
50916  PgHdr *pNext;
50917  for(p=pPager->pMmapFreelist; p; p=pNext){
50918    pNext = p->pDirty;
50919    sqlite3_free(p);
50920  }
50921}
50922
50923
50924/*
50925** Shutdown the page cache.  Free all memory and close all files.
50926**
50927** If a transaction was in progress when this routine is called, that
50928** transaction is rolled back.  All outstanding pages are invalidated
50929** and their memory is freed.  Any attempt to use a page associated
50930** with this page cache after this function returns will likely
50931** result in a coredump.
50932**
50933** This function always succeeds. If a transaction is active an attempt
50934** is made to roll it back. If an error occurs during the rollback
50935** a hot journal may be left in the filesystem but no error is returned
50936** to the caller.
50937*/
50938SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
50939  u8 *pTmp = (u8 *)pPager->pTmpSpace;
50940
50941  assert( db || pagerUseWal(pPager)==0 );
50942  assert( assert_pager_state(pPager) );
50943  disable_simulated_io_errors();
50944  sqlite3BeginBenignMalloc();
50945  pagerFreeMapHdrs(pPager);
50946  /* pPager->errCode = 0; */
50947  pPager->exclusiveMode = 0;
50948#ifndef SQLITE_OMIT_WAL
50949  assert( db || pPager->pWal==0 );
50950  sqlite3WalClose(pPager->pWal, db, pPager->ckptSyncFlags, pPager->pageSize,
50951      (db && (db->flags & SQLITE_NoCkptOnClose) ? 0 : pTmp)
50952  );
50953  pPager->pWal = 0;
50954#endif
50955  pager_reset(pPager);
50956  if( MEMDB ){
50957    pager_unlock(pPager);
50958  }else{
50959    /* If it is open, sync the journal file before calling UnlockAndRollback.
50960    ** If this is not done, then an unsynced portion of the open journal
50961    ** file may be played back into the database. If a power failure occurs
50962    ** while this is happening, the database could become corrupt.
50963    **
50964    ** If an error occurs while trying to sync the journal, shift the pager
50965    ** into the ERROR state. This causes UnlockAndRollback to unlock the
50966    ** database and close the journal file without attempting to roll it
50967    ** back or finalize it. The next database user will have to do hot-journal
50968    ** rollback before accessing the database file.
50969    */
50970    if( isOpen(pPager->jfd) ){
50971      pager_error(pPager, pagerSyncHotJournal(pPager));
50972    }
50973    pagerUnlockAndRollback(pPager);
50974  }
50975  sqlite3EndBenignMalloc();
50976  enable_simulated_io_errors();
50977  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
50978  IOTRACE(("CLOSE %p\n", pPager))
50979  sqlite3OsClose(pPager->jfd);
50980  sqlite3OsClose(pPager->fd);
50981  sqlite3PageFree(pTmp);
50982  sqlite3PcacheClose(pPager->pPCache);
50983
50984#ifdef SQLITE_HAS_CODEC
50985  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
50986#endif
50987
50988  assert( !pPager->aSavepoint && !pPager->pInJournal );
50989  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
50990
50991  sqlite3_free(pPager);
50992  return SQLITE_OK;
50993}
50994
50995#if !defined(NDEBUG) || defined(SQLITE_TEST)
50996/*
50997** Return the page number for page pPg.
50998*/
50999SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
51000  return pPg->pgno;
51001}
51002#endif
51003
51004/*
51005** Increment the reference count for page pPg.
51006*/
51007SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
51008  sqlite3PcacheRef(pPg);
51009}
51010
51011/*
51012** Sync the journal. In other words, make sure all the pages that have
51013** been written to the journal have actually reached the surface of the
51014** disk and can be restored in the event of a hot-journal rollback.
51015**
51016** If the Pager.noSync flag is set, then this function is a no-op.
51017** Otherwise, the actions required depend on the journal-mode and the
51018** device characteristics of the file-system, as follows:
51019**
51020**   * If the journal file is an in-memory journal file, no action need
51021**     be taken.
51022**
51023**   * Otherwise, if the device does not support the SAFE_APPEND property,
51024**     then the nRec field of the most recently written journal header
51025**     is updated to contain the number of journal records that have
51026**     been written following it. If the pager is operating in full-sync
51027**     mode, then the journal file is synced before this field is updated.
51028**
51029**   * If the device does not support the SEQUENTIAL property, then
51030**     journal file is synced.
51031**
51032** Or, in pseudo-code:
51033**
51034**   if( NOT <in-memory journal> ){
51035**     if( NOT SAFE_APPEND ){
51036**       if( <full-sync mode> ) xSync(<journal file>);
51037**       <update nRec field>
51038**     }
51039**     if( NOT SEQUENTIAL ) xSync(<journal file>);
51040**   }
51041**
51042** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
51043** page currently held in memory before returning SQLITE_OK. If an IO
51044** error is encountered, then the IO error code is returned to the caller.
51045*/
51046static int syncJournal(Pager *pPager, int newHdr){
51047  int rc;                         /* Return code */
51048
51049  assert( pPager->eState==PAGER_WRITER_CACHEMOD
51050       || pPager->eState==PAGER_WRITER_DBMOD
51051  );
51052  assert( assert_pager_state(pPager) );
51053  assert( !pagerUseWal(pPager) );
51054
51055  rc = sqlite3PagerExclusiveLock(pPager);
51056  if( rc!=SQLITE_OK ) return rc;
51057
51058  if( !pPager->noSync ){
51059    assert( !pPager->tempFile );
51060    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
51061      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
51062      assert( isOpen(pPager->jfd) );
51063
51064      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
51065        /* This block deals with an obscure problem. If the last connection
51066        ** that wrote to this database was operating in persistent-journal
51067        ** mode, then the journal file may at this point actually be larger
51068        ** than Pager.journalOff bytes. If the next thing in the journal
51069        ** file happens to be a journal-header (written as part of the
51070        ** previous connection's transaction), and a crash or power-failure
51071        ** occurs after nRec is updated but before this connection writes
51072        ** anything else to the journal file (or commits/rolls back its
51073        ** transaction), then SQLite may become confused when doing the
51074        ** hot-journal rollback following recovery. It may roll back all
51075        ** of this connections data, then proceed to rolling back the old,
51076        ** out-of-date data that follows it. Database corruption.
51077        **
51078        ** To work around this, if the journal file does appear to contain
51079        ** a valid header following Pager.journalOff, then write a 0x00
51080        ** byte to the start of it to prevent it from being recognized.
51081        **
51082        ** Variable iNextHdrOffset is set to the offset at which this
51083        ** problematic header will occur, if it exists. aMagic is used
51084        ** as a temporary buffer to inspect the first couple of bytes of
51085        ** the potential journal header.
51086        */
51087        i64 iNextHdrOffset;
51088        u8 aMagic[8];
51089        u8 zHeader[sizeof(aJournalMagic)+4];
51090
51091        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
51092        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
51093
51094        iNextHdrOffset = journalHdrOffset(pPager);
51095        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
51096        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
51097          static const u8 zerobyte = 0;
51098          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
51099        }
51100        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
51101          return rc;
51102        }
51103
51104        /* Write the nRec value into the journal file header. If in
51105        ** full-synchronous mode, sync the journal first. This ensures that
51106        ** all data has really hit the disk before nRec is updated to mark
51107        ** it as a candidate for rollback.
51108        **
51109        ** This is not required if the persistent media supports the
51110        ** SAFE_APPEND property. Because in this case it is not possible
51111        ** for garbage data to be appended to the file, the nRec field
51112        ** is populated with 0xFFFFFFFF when the journal header is written
51113        ** and never needs to be updated.
51114        */
51115        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
51116          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
51117          IOTRACE(("JSYNC %p\n", pPager))
51118          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
51119          if( rc!=SQLITE_OK ) return rc;
51120        }
51121        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
51122        rc = sqlite3OsWrite(
51123            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
51124        );
51125        if( rc!=SQLITE_OK ) return rc;
51126      }
51127      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
51128        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
51129        IOTRACE(("JSYNC %p\n", pPager))
51130        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
51131          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
51132        );
51133        if( rc!=SQLITE_OK ) return rc;
51134      }
51135
51136      pPager->journalHdr = pPager->journalOff;
51137      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
51138        pPager->nRec = 0;
51139        rc = writeJournalHdr(pPager);
51140        if( rc!=SQLITE_OK ) return rc;
51141      }
51142    }else{
51143      pPager->journalHdr = pPager->journalOff;
51144    }
51145  }
51146
51147  /* Unless the pager is in noSync mode, the journal file was just
51148  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
51149  ** all pages.
51150  */
51151  sqlite3PcacheClearSyncFlags(pPager->pPCache);
51152  pPager->eState = PAGER_WRITER_DBMOD;
51153  assert( assert_pager_state(pPager) );
51154  return SQLITE_OK;
51155}
51156
51157/*
51158** The argument is the first in a linked list of dirty pages connected
51159** by the PgHdr.pDirty pointer. This function writes each one of the
51160** in-memory pages in the list to the database file. The argument may
51161** be NULL, representing an empty list. In this case this function is
51162** a no-op.
51163**
51164** The pager must hold at least a RESERVED lock when this function
51165** is called. Before writing anything to the database file, this lock
51166** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
51167** SQLITE_BUSY is returned and no data is written to the database file.
51168**
51169** If the pager is a temp-file pager and the actual file-system file
51170** is not yet open, it is created and opened before any data is
51171** written out.
51172**
51173** Once the lock has been upgraded and, if necessary, the file opened,
51174** the pages are written out to the database file in list order. Writing
51175** a page is skipped if it meets either of the following criteria:
51176**
51177**   * The page number is greater than Pager.dbSize, or
51178**   * The PGHDR_DONT_WRITE flag is set on the page.
51179**
51180** If writing out a page causes the database file to grow, Pager.dbFileSize
51181** is updated accordingly. If page 1 is written out, then the value cached
51182** in Pager.dbFileVers[] is updated to match the new value stored in
51183** the database file.
51184**
51185** If everything is successful, SQLITE_OK is returned. If an IO error
51186** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
51187** be obtained, SQLITE_BUSY is returned.
51188*/
51189static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
51190  int rc = SQLITE_OK;                  /* Return code */
51191
51192  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
51193  assert( !pagerUseWal(pPager) );
51194  assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
51195  assert( pPager->eLock==EXCLUSIVE_LOCK );
51196  assert( isOpen(pPager->fd) || pList->pDirty==0 );
51197
51198  /* If the file is a temp-file has not yet been opened, open it now. It
51199  ** is not possible for rc to be other than SQLITE_OK if this branch
51200  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
51201  */
51202  if( !isOpen(pPager->fd) ){
51203    assert( pPager->tempFile && rc==SQLITE_OK );
51204    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
51205  }
51206
51207  /* Before the first write, give the VFS a hint of what the final
51208  ** file size will be.
51209  */
51210  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
51211  if( rc==SQLITE_OK
51212   && pPager->dbHintSize<pPager->dbSize
51213   && (pList->pDirty || pList->pgno>pPager->dbHintSize)
51214  ){
51215    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
51216    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
51217    pPager->dbHintSize = pPager->dbSize;
51218  }
51219
51220  while( rc==SQLITE_OK && pList ){
51221    Pgno pgno = pList->pgno;
51222
51223    /* If there are dirty pages in the page cache with page numbers greater
51224    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
51225    ** make the file smaller (presumably by auto-vacuum code). Do not write
51226    ** any such pages to the file.
51227    **
51228    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
51229    ** set (set by sqlite3PagerDontWrite()).
51230    */
51231    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
51232      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
51233      char *pData;                                   /* Data to write */
51234
51235      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
51236      if( pList->pgno==1 ) pager_write_changecounter(pList);
51237
51238      /* Encode the database */
51239      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
51240
51241      /* Write out the page data. */
51242      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
51243
51244      /* If page 1 was just written, update Pager.dbFileVers to match
51245      ** the value now stored in the database file. If writing this
51246      ** page caused the database file to grow, update dbFileSize.
51247      */
51248      if( pgno==1 ){
51249        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
51250      }
51251      if( pgno>pPager->dbFileSize ){
51252        pPager->dbFileSize = pgno;
51253      }
51254      pPager->aStat[PAGER_STAT_WRITE]++;
51255
51256      /* Update any backup objects copying the contents of this pager. */
51257      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
51258
51259      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
51260                   PAGERID(pPager), pgno, pager_pagehash(pList)));
51261      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
51262      PAGER_INCR(sqlite3_pager_writedb_count);
51263    }else{
51264      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
51265    }
51266    pager_set_pagehash(pList);
51267    pList = pList->pDirty;
51268  }
51269
51270  return rc;
51271}
51272
51273/*
51274** Ensure that the sub-journal file is open. If it is already open, this
51275** function is a no-op.
51276**
51277** SQLITE_OK is returned if everything goes according to plan. An
51278** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
51279** fails.
51280*/
51281static int openSubJournal(Pager *pPager){
51282  int rc = SQLITE_OK;
51283  if( !isOpen(pPager->sjfd) ){
51284    const int flags =  SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
51285      | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
51286      | SQLITE_OPEN_DELETEONCLOSE;
51287    int nStmtSpill = sqlite3Config.nStmtSpill;
51288    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
51289      nStmtSpill = -1;
51290    }
51291    rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
51292  }
51293  return rc;
51294}
51295
51296/*
51297** Append a record of the current state of page pPg to the sub-journal.
51298**
51299** If successful, set the bit corresponding to pPg->pgno in the bitvecs
51300** for all open savepoints before returning.
51301**
51302** This function returns SQLITE_OK if everything is successful, an IO
51303** error code if the attempt to write to the sub-journal fails, or
51304** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
51305** bitvec.
51306*/
51307static int subjournalPage(PgHdr *pPg){
51308  int rc = SQLITE_OK;
51309  Pager *pPager = pPg->pPager;
51310  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
51311
51312    /* Open the sub-journal, if it has not already been opened */
51313    assert( pPager->useJournal );
51314    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
51315    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
51316    assert( pagerUseWal(pPager)
51317         || pageInJournal(pPager, pPg)
51318         || pPg->pgno>pPager->dbOrigSize
51319    );
51320    rc = openSubJournal(pPager);
51321
51322    /* If the sub-journal was opened successfully (or was already open),
51323    ** write the journal record into the file.  */
51324    if( rc==SQLITE_OK ){
51325      void *pData = pPg->pData;
51326      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
51327      char *pData2;
51328
51329      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
51330      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
51331      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
51332      if( rc==SQLITE_OK ){
51333        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
51334      }
51335    }
51336  }
51337  if( rc==SQLITE_OK ){
51338    pPager->nSubRec++;
51339    assert( pPager->nSavepoint>0 );
51340    rc = addToSavepointBitvecs(pPager, pPg->pgno);
51341  }
51342  return rc;
51343}
51344static int subjournalPageIfRequired(PgHdr *pPg){
51345  if( subjRequiresPage(pPg) ){
51346    return subjournalPage(pPg);
51347  }else{
51348    return SQLITE_OK;
51349  }
51350}
51351
51352/*
51353** This function is called by the pcache layer when it has reached some
51354** soft memory limit. The first argument is a pointer to a Pager object
51355** (cast as a void*). The pager is always 'purgeable' (not an in-memory
51356** database). The second argument is a reference to a page that is
51357** currently dirty but has no outstanding references. The page
51358** is always associated with the Pager object passed as the first
51359** argument.
51360**
51361** The job of this function is to make pPg clean by writing its contents
51362** out to the database file, if possible. This may involve syncing the
51363** journal file.
51364**
51365** If successful, sqlite3PcacheMakeClean() is called on the page and
51366** SQLITE_OK returned. If an IO error occurs while trying to make the
51367** page clean, the IO error code is returned. If the page cannot be
51368** made clean for some other reason, but no error occurs, then SQLITE_OK
51369** is returned by sqlite3PcacheMakeClean() is not called.
51370*/
51371static int pagerStress(void *p, PgHdr *pPg){
51372  Pager *pPager = (Pager *)p;
51373  int rc = SQLITE_OK;
51374
51375  assert( pPg->pPager==pPager );
51376  assert( pPg->flags&PGHDR_DIRTY );
51377
51378  /* The doNotSpill NOSYNC bit is set during times when doing a sync of
51379  ** journal (and adding a new header) is not allowed.  This occurs
51380  ** during calls to sqlite3PagerWrite() while trying to journal multiple
51381  ** pages belonging to the same sector.
51382  **
51383  ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
51384  ** regardless of whether or not a sync is required.  This is set during
51385  ** a rollback or by user request, respectively.
51386  **
51387  ** Spilling is also prohibited when in an error state since that could
51388  ** lead to database corruption.   In the current implementation it
51389  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
51390  ** while in the error state, hence it is impossible for this routine to
51391  ** be called in the error state.  Nevertheless, we include a NEVER()
51392  ** test for the error state as a safeguard against future changes.
51393  */
51394  if( NEVER(pPager->errCode) ) return SQLITE_OK;
51395  testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
51396  testcase( pPager->doNotSpill & SPILLFLAG_OFF );
51397  testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
51398  if( pPager->doNotSpill
51399   && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
51400      || (pPg->flags & PGHDR_NEED_SYNC)!=0)
51401  ){
51402    return SQLITE_OK;
51403  }
51404
51405  pPg->pDirty = 0;
51406  if( pagerUseWal(pPager) ){
51407    /* Write a single frame for this page to the log. */
51408    rc = subjournalPageIfRequired(pPg);
51409    if( rc==SQLITE_OK ){
51410      rc = pagerWalFrames(pPager, pPg, 0, 0);
51411    }
51412  }else{
51413
51414    /* Sync the journal file if required. */
51415    if( pPg->flags&PGHDR_NEED_SYNC
51416     || pPager->eState==PAGER_WRITER_CACHEMOD
51417    ){
51418      rc = syncJournal(pPager, 1);
51419    }
51420
51421    /* Write the contents of the page out to the database file. */
51422    if( rc==SQLITE_OK ){
51423      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
51424      rc = pager_write_pagelist(pPager, pPg);
51425    }
51426  }
51427
51428  /* Mark the page as clean. */
51429  if( rc==SQLITE_OK ){
51430    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
51431    sqlite3PcacheMakeClean(pPg);
51432  }
51433
51434  return pager_error(pPager, rc);
51435}
51436
51437/*
51438** Flush all unreferenced dirty pages to disk.
51439*/
51440SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
51441  int rc = pPager->errCode;
51442  if( !MEMDB ){
51443    PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
51444    assert( assert_pager_state(pPager) );
51445    while( rc==SQLITE_OK && pList ){
51446      PgHdr *pNext = pList->pDirty;
51447      if( pList->nRef==0 ){
51448        rc = pagerStress((void*)pPager, pList);
51449      }
51450      pList = pNext;
51451    }
51452  }
51453
51454  return rc;
51455}
51456
51457/*
51458** Allocate and initialize a new Pager object and put a pointer to it
51459** in *ppPager. The pager should eventually be freed by passing it
51460** to sqlite3PagerClose().
51461**
51462** The zFilename argument is the path to the database file to open.
51463** If zFilename is NULL then a randomly-named temporary file is created
51464** and used as the file to be cached. Temporary files are be deleted
51465** automatically when they are closed. If zFilename is ":memory:" then
51466** all information is held in cache. It is never written to disk.
51467** This can be used to implement an in-memory database.
51468**
51469** The nExtra parameter specifies the number of bytes of space allocated
51470** along with each page reference. This space is available to the user
51471** via the sqlite3PagerGetExtra() API.  When a new page is allocated, the
51472** first 8 bytes of this space are zeroed but the remainder is uninitialized.
51473** (The extra space is used by btree as the MemPage object.)
51474**
51475** The flags argument is used to specify properties that affect the
51476** operation of the pager. It should be passed some bitwise combination
51477** of the PAGER_* flags.
51478**
51479** The vfsFlags parameter is a bitmask to pass to the flags parameter
51480** of the xOpen() method of the supplied VFS when opening files.
51481**
51482** If the pager object is allocated and the specified file opened
51483** successfully, SQLITE_OK is returned and *ppPager set to point to
51484** the new pager object. If an error occurs, *ppPager is set to NULL
51485** and error code returned. This function may return SQLITE_NOMEM
51486** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
51487** various SQLITE_IO_XXX errors.
51488*/
51489SQLITE_PRIVATE int sqlite3PagerOpen(
51490  sqlite3_vfs *pVfs,       /* The virtual file system to use */
51491  Pager **ppPager,         /* OUT: Return the Pager structure here */
51492  const char *zFilename,   /* Name of the database file to open */
51493  int nExtra,              /* Extra bytes append to each in-memory page */
51494  int flags,               /* flags controlling this file */
51495  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
51496  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
51497){
51498  u8 *pPtr;
51499  Pager *pPager = 0;       /* Pager object to allocate and return */
51500  int rc = SQLITE_OK;      /* Return code */
51501  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
51502  int memDb = 0;           /* True if this is an in-memory file */
51503  int readOnly = 0;        /* True if this is a read-only file */
51504  int journalFileSize;     /* Bytes to allocate for each journal fd */
51505  char *zPathname = 0;     /* Full path to database file */
51506  int nPathname = 0;       /* Number of bytes in zPathname */
51507  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
51508  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
51509  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
51510  const char *zUri = 0;    /* URI args to copy */
51511  int nUri = 0;            /* Number of bytes of URI args at *zUri */
51512
51513  /* Figure out how much space is required for each journal file-handle
51514  ** (there are two of them, the main journal and the sub-journal).  */
51515  journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
51516
51517  /* Set the output variable to NULL in case an error occurs. */
51518  *ppPager = 0;
51519
51520#ifndef SQLITE_OMIT_MEMORYDB
51521  if( flags & PAGER_MEMORY ){
51522    memDb = 1;
51523    if( zFilename && zFilename[0] ){
51524      zPathname = sqlite3DbStrDup(0, zFilename);
51525      if( zPathname==0  ) return SQLITE_NOMEM_BKPT;
51526      nPathname = sqlite3Strlen30(zPathname);
51527      zFilename = 0;
51528    }
51529  }
51530#endif
51531
51532  /* Compute and store the full pathname in an allocated buffer pointed
51533  ** to by zPathname, length nPathname. Or, if this is a temporary file,
51534  ** leave both nPathname and zPathname set to 0.
51535  */
51536  if( zFilename && zFilename[0] ){
51537    const char *z;
51538    nPathname = pVfs->mxPathname+1;
51539    zPathname = sqlite3DbMallocRaw(0, nPathname*2);
51540    if( zPathname==0 ){
51541      return SQLITE_NOMEM_BKPT;
51542    }
51543    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
51544    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
51545    nPathname = sqlite3Strlen30(zPathname);
51546    z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
51547    while( *z ){
51548      z += sqlite3Strlen30(z)+1;
51549      z += sqlite3Strlen30(z)+1;
51550    }
51551    nUri = (int)(&z[1] - zUri);
51552    assert( nUri>=0 );
51553    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
51554      /* This branch is taken when the journal path required by
51555      ** the database being opened will be more than pVfs->mxPathname
51556      ** bytes in length. This means the database cannot be opened,
51557      ** as it will not be possible to open the journal file or even
51558      ** check for a hot-journal before reading.
51559      */
51560      rc = SQLITE_CANTOPEN_BKPT;
51561    }
51562    if( rc!=SQLITE_OK ){
51563      sqlite3DbFree(0, zPathname);
51564      return rc;
51565    }
51566  }
51567
51568  /* Allocate memory for the Pager structure, PCache object, the
51569  ** three file descriptors, the database file name and the journal
51570  ** file name. The layout in memory is as follows:
51571  **
51572  **     Pager object                    (sizeof(Pager) bytes)
51573  **     PCache object                   (sqlite3PcacheSize() bytes)
51574  **     Database file handle            (pVfs->szOsFile bytes)
51575  **     Sub-journal file handle         (journalFileSize bytes)
51576  **     Main journal file handle        (journalFileSize bytes)
51577  **     Database file name              (nPathname+1 bytes)
51578  **     Journal file name               (nPathname+8+1 bytes)
51579  */
51580  pPtr = (u8 *)sqlite3MallocZero(
51581    ROUND8(sizeof(*pPager)) +      /* Pager structure */
51582    ROUND8(pcacheSize) +           /* PCache object */
51583    ROUND8(pVfs->szOsFile) +       /* The main db file */
51584    journalFileSize * 2 +          /* The two journal files */
51585    nPathname + 1 + nUri +         /* zFilename */
51586    nPathname + 8 + 2              /* zJournal */
51587#ifndef SQLITE_OMIT_WAL
51588    + nPathname + 4 + 2            /* zWal */
51589#endif
51590  );
51591  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
51592  if( !pPtr ){
51593    sqlite3DbFree(0, zPathname);
51594    return SQLITE_NOMEM_BKPT;
51595  }
51596  pPager =              (Pager*)(pPtr);
51597  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
51598  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
51599  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
51600  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
51601  pPager->zFilename =    (char*)(pPtr += journalFileSize);
51602  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
51603
51604  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
51605  if( zPathname ){
51606    assert( nPathname>0 );
51607    pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
51608    memcpy(pPager->zFilename, zPathname, nPathname);
51609    if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
51610    memcpy(pPager->zJournal, zPathname, nPathname);
51611    memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
51612    sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
51613#ifndef SQLITE_OMIT_WAL
51614    pPager->zWal = &pPager->zJournal[nPathname+8+1];
51615    memcpy(pPager->zWal, zPathname, nPathname);
51616    memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
51617    sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
51618#endif
51619    sqlite3DbFree(0, zPathname);
51620  }
51621  pPager->pVfs = pVfs;
51622  pPager->vfsFlags = vfsFlags;
51623
51624  /* Open the pager file.
51625  */
51626  if( zFilename && zFilename[0] ){
51627    int fout = 0;                    /* VFS flags returned by xOpen() */
51628    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
51629    assert( !memDb );
51630    readOnly = (fout&SQLITE_OPEN_READONLY);
51631
51632    /* If the file was successfully opened for read/write access,
51633    ** choose a default page size in case we have to create the
51634    ** database file. The default page size is the maximum of:
51635    **
51636    **    + SQLITE_DEFAULT_PAGE_SIZE,
51637    **    + The value returned by sqlite3OsSectorSize()
51638    **    + The largest page size that can be written atomically.
51639    */
51640    if( rc==SQLITE_OK ){
51641      int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
51642      if( !readOnly ){
51643        setSectorSize(pPager);
51644        assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
51645        if( szPageDflt<pPager->sectorSize ){
51646          if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
51647            szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
51648          }else{
51649            szPageDflt = (u32)pPager->sectorSize;
51650          }
51651        }
51652#ifdef SQLITE_ENABLE_ATOMIC_WRITE
51653        {
51654          int ii;
51655          assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
51656          assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
51657          assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
51658          for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
51659            if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
51660              szPageDflt = ii;
51661            }
51662          }
51663        }
51664#endif
51665      }
51666      pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
51667      if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
51668       || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
51669          vfsFlags |= SQLITE_OPEN_READONLY;
51670          goto act_like_temp_file;
51671      }
51672    }
51673  }else{
51674    /* If a temporary file is requested, it is not opened immediately.
51675    ** In this case we accept the default page size and delay actually
51676    ** opening the file until the first call to OsWrite().
51677    **
51678    ** This branch is also run for an in-memory database. An in-memory
51679    ** database is the same as a temp-file that is never written out to
51680    ** disk and uses an in-memory rollback journal.
51681    **
51682    ** This branch also runs for files marked as immutable.
51683    */
51684act_like_temp_file:
51685    tempFile = 1;
51686    pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
51687    pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE mode */
51688    pPager->noLock = 1;                /* Do no locking */
51689    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
51690  }
51691
51692  /* The following call to PagerSetPagesize() serves to set the value of
51693  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
51694  */
51695  if( rc==SQLITE_OK ){
51696    assert( pPager->memDb==0 );
51697    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
51698    testcase( rc!=SQLITE_OK );
51699  }
51700
51701  /* Initialize the PCache object. */
51702  if( rc==SQLITE_OK ){
51703    nExtra = ROUND8(nExtra);
51704    assert( nExtra>=8 && nExtra<1000 );
51705    rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
51706                       !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
51707  }
51708
51709  /* If an error occurred above, free the  Pager structure and close the file.
51710  */
51711  if( rc!=SQLITE_OK ){
51712    sqlite3OsClose(pPager->fd);
51713    sqlite3PageFree(pPager->pTmpSpace);
51714    sqlite3_free(pPager);
51715    return rc;
51716  }
51717
51718  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
51719  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
51720
51721  pPager->useJournal = (u8)useJournal;
51722  /* pPager->stmtOpen = 0; */
51723  /* pPager->stmtInUse = 0; */
51724  /* pPager->nRef = 0; */
51725  /* pPager->stmtSize = 0; */
51726  /* pPager->stmtJSize = 0; */
51727  /* pPager->nPage = 0; */
51728  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
51729  /* pPager->state = PAGER_UNLOCK; */
51730  /* pPager->errMask = 0; */
51731  pPager->tempFile = (u8)tempFile;
51732  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
51733          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
51734  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
51735  pPager->exclusiveMode = (u8)tempFile;
51736  pPager->changeCountDone = pPager->tempFile;
51737  pPager->memDb = (u8)memDb;
51738  pPager->readOnly = (u8)readOnly;
51739  assert( useJournal || pPager->tempFile );
51740  pPager->noSync = pPager->tempFile;
51741  if( pPager->noSync ){
51742    assert( pPager->fullSync==0 );
51743    assert( pPager->extraSync==0 );
51744    assert( pPager->syncFlags==0 );
51745    assert( pPager->walSyncFlags==0 );
51746    assert( pPager->ckptSyncFlags==0 );
51747  }else{
51748    pPager->fullSync = 1;
51749    pPager->extraSync = 0;
51750    pPager->syncFlags = SQLITE_SYNC_NORMAL;
51751    pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
51752    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
51753  }
51754  /* pPager->pFirst = 0; */
51755  /* pPager->pFirstSynced = 0; */
51756  /* pPager->pLast = 0; */
51757  pPager->nExtra = (u16)nExtra;
51758  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
51759  assert( isOpen(pPager->fd) || tempFile );
51760  setSectorSize(pPager);
51761  if( !useJournal ){
51762    pPager->journalMode = PAGER_JOURNALMODE_OFF;
51763  }else if( memDb ){
51764    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
51765  }
51766  /* pPager->xBusyHandler = 0; */
51767  /* pPager->pBusyHandlerArg = 0; */
51768  pPager->xReiniter = xReinit;
51769  setGetterMethod(pPager);
51770  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
51771  /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
51772
51773  *ppPager = pPager;
51774  return SQLITE_OK;
51775}
51776
51777
51778/* Verify that the database file has not be deleted or renamed out from
51779** under the pager.  Return SQLITE_OK if the database is still were it ought
51780** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
51781** code from sqlite3OsAccess()) if the database has gone missing.
51782*/
51783static int databaseIsUnmoved(Pager *pPager){
51784  int bHasMoved = 0;
51785  int rc;
51786
51787  if( pPager->tempFile ) return SQLITE_OK;
51788  if( pPager->dbSize==0 ) return SQLITE_OK;
51789  assert( pPager->zFilename && pPager->zFilename[0] );
51790  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
51791  if( rc==SQLITE_NOTFOUND ){
51792    /* If the HAS_MOVED file-control is unimplemented, assume that the file
51793    ** has not been moved.  That is the historical behavior of SQLite: prior to
51794    ** version 3.8.3, it never checked */
51795    rc = SQLITE_OK;
51796  }else if( rc==SQLITE_OK && bHasMoved ){
51797    rc = SQLITE_READONLY_DBMOVED;
51798  }
51799  return rc;
51800}
51801
51802
51803/*
51804** This function is called after transitioning from PAGER_UNLOCK to
51805** PAGER_SHARED state. It tests if there is a hot journal present in
51806** the file-system for the given pager. A hot journal is one that
51807** needs to be played back. According to this function, a hot-journal
51808** file exists if the following criteria are met:
51809**
51810**   * The journal file exists in the file system, and
51811**   * No process holds a RESERVED or greater lock on the database file, and
51812**   * The database file itself is greater than 0 bytes in size, and
51813**   * The first byte of the journal file exists and is not 0x00.
51814**
51815** If the current size of the database file is 0 but a journal file
51816** exists, that is probably an old journal left over from a prior
51817** database with the same name. In this case the journal file is
51818** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
51819** is returned.
51820**
51821** This routine does not check if there is a master journal filename
51822** at the end of the file. If there is, and that master journal file
51823** does not exist, then the journal file is not really hot. In this
51824** case this routine will return a false-positive. The pager_playback()
51825** routine will discover that the journal file is not really hot and
51826** will not roll it back.
51827**
51828** If a hot-journal file is found to exist, *pExists is set to 1 and
51829** SQLITE_OK returned. If no hot-journal file is present, *pExists is
51830** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
51831** to determine whether or not a hot-journal file exists, the IO error
51832** code is returned and the value of *pExists is undefined.
51833*/
51834static int hasHotJournal(Pager *pPager, int *pExists){
51835  sqlite3_vfs * const pVfs = pPager->pVfs;
51836  int rc = SQLITE_OK;           /* Return code */
51837  int exists = 1;               /* True if a journal file is present */
51838  int jrnlOpen = !!isOpen(pPager->jfd);
51839
51840  assert( pPager->useJournal );
51841  assert( isOpen(pPager->fd) );
51842  assert( pPager->eState==PAGER_OPEN );
51843
51844  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
51845    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
51846  ));
51847
51848  *pExists = 0;
51849  if( !jrnlOpen ){
51850    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
51851  }
51852  if( rc==SQLITE_OK && exists ){
51853    int locked = 0;             /* True if some process holds a RESERVED lock */
51854
51855    /* Race condition here:  Another process might have been holding the
51856    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
51857    ** call above, but then delete the journal and drop the lock before
51858    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
51859    ** is the case, this routine might think there is a hot journal when
51860    ** in fact there is none.  This results in a false-positive which will
51861    ** be dealt with by the playback routine.  Ticket #3883.
51862    */
51863    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
51864    if( rc==SQLITE_OK && !locked ){
51865      Pgno nPage;                 /* Number of pages in database file */
51866
51867      assert( pPager->tempFile==0 );
51868      rc = pagerPagecount(pPager, &nPage);
51869      if( rc==SQLITE_OK ){
51870        /* If the database is zero pages in size, that means that either (1) the
51871        ** journal is a remnant from a prior database with the same name where
51872        ** the database file but not the journal was deleted, or (2) the initial
51873        ** transaction that populates a new database is being rolled back.
51874        ** In either case, the journal file can be deleted.  However, take care
51875        ** not to delete the journal file if it is already open due to
51876        ** journal_mode=PERSIST.
51877        */
51878        if( nPage==0 && !jrnlOpen ){
51879          sqlite3BeginBenignMalloc();
51880          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
51881            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
51882            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
51883          }
51884          sqlite3EndBenignMalloc();
51885        }else{
51886          /* The journal file exists and no other connection has a reserved
51887          ** or greater lock on the database file. Now check that there is
51888          ** at least one non-zero bytes at the start of the journal file.
51889          ** If there is, then we consider this journal to be hot. If not,
51890          ** it can be ignored.
51891          */
51892          if( !jrnlOpen ){
51893            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
51894            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
51895          }
51896          if( rc==SQLITE_OK ){
51897            u8 first = 0;
51898            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
51899            if( rc==SQLITE_IOERR_SHORT_READ ){
51900              rc = SQLITE_OK;
51901            }
51902            if( !jrnlOpen ){
51903              sqlite3OsClose(pPager->jfd);
51904            }
51905            *pExists = (first!=0);
51906          }else if( rc==SQLITE_CANTOPEN ){
51907            /* If we cannot open the rollback journal file in order to see if
51908            ** it has a zero header, that might be due to an I/O error, or
51909            ** it might be due to the race condition described above and in
51910            ** ticket #3883.  Either way, assume that the journal is hot.
51911            ** This might be a false positive.  But if it is, then the
51912            ** automatic journal playback and recovery mechanism will deal
51913            ** with it under an EXCLUSIVE lock where we do not need to
51914            ** worry so much with race conditions.
51915            */
51916            *pExists = 1;
51917            rc = SQLITE_OK;
51918          }
51919        }
51920      }
51921    }
51922  }
51923
51924  return rc;
51925}
51926
51927/*
51928** This function is called to obtain a shared lock on the database file.
51929** It is illegal to call sqlite3PagerGet() until after this function
51930** has been successfully called. If a shared-lock is already held when
51931** this function is called, it is a no-op.
51932**
51933** The following operations are also performed by this function.
51934**
51935**   1) If the pager is currently in PAGER_OPEN state (no lock held
51936**      on the database file), then an attempt is made to obtain a
51937**      SHARED lock on the database file. Immediately after obtaining
51938**      the SHARED lock, the file-system is checked for a hot-journal,
51939**      which is played back if present. Following any hot-journal
51940**      rollback, the contents of the cache are validated by checking
51941**      the 'change-counter' field of the database file header and
51942**      discarded if they are found to be invalid.
51943**
51944**   2) If the pager is running in exclusive-mode, and there are currently
51945**      no outstanding references to any pages, and is in the error state,
51946**      then an attempt is made to clear the error state by discarding
51947**      the contents of the page cache and rolling back any open journal
51948**      file.
51949**
51950** If everything is successful, SQLITE_OK is returned. If an IO error
51951** occurs while locking the database, checking for a hot-journal file or
51952** rolling back a journal file, the IO error code is returned.
51953*/
51954SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
51955  int rc = SQLITE_OK;                /* Return code */
51956
51957  /* This routine is only called from b-tree and only when there are no
51958  ** outstanding pages. This implies that the pager state should either
51959  ** be OPEN or READER. READER is only possible if the pager is or was in
51960  ** exclusive access mode.  */
51961  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
51962  assert( assert_pager_state(pPager) );
51963  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
51964  assert( pPager->errCode==SQLITE_OK );
51965
51966  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
51967    int bHotJournal = 1;          /* True if there exists a hot journal-file */
51968
51969    assert( !MEMDB );
51970    assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
51971
51972    rc = pager_wait_on_lock(pPager, SHARED_LOCK);
51973    if( rc!=SQLITE_OK ){
51974      assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
51975      goto failed;
51976    }
51977
51978    /* If a journal file exists, and there is no RESERVED lock on the
51979    ** database file, then it either needs to be played back or deleted.
51980    */
51981    if( pPager->eLock<=SHARED_LOCK ){
51982      rc = hasHotJournal(pPager, &bHotJournal);
51983    }
51984    if( rc!=SQLITE_OK ){
51985      goto failed;
51986    }
51987    if( bHotJournal ){
51988      if( pPager->readOnly ){
51989        rc = SQLITE_READONLY_ROLLBACK;
51990        goto failed;
51991      }
51992
51993      /* Get an EXCLUSIVE lock on the database file. At this point it is
51994      ** important that a RESERVED lock is not obtained on the way to the
51995      ** EXCLUSIVE lock. If it were, another process might open the
51996      ** database file, detect the RESERVED lock, and conclude that the
51997      ** database is safe to read while this process is still rolling the
51998      ** hot-journal back.
51999      **
52000      ** Because the intermediate RESERVED lock is not requested, any
52001      ** other process attempting to access the database file will get to
52002      ** this point in the code and fail to obtain its own EXCLUSIVE lock
52003      ** on the database file.
52004      **
52005      ** Unless the pager is in locking_mode=exclusive mode, the lock is
52006      ** downgraded to SHARED_LOCK before this function returns.
52007      */
52008      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
52009      if( rc!=SQLITE_OK ){
52010        goto failed;
52011      }
52012
52013      /* If it is not already open and the file exists on disk, open the
52014      ** journal for read/write access. Write access is required because
52015      ** in exclusive-access mode the file descriptor will be kept open
52016      ** and possibly used for a transaction later on. Also, write-access
52017      ** is usually required to finalize the journal in journal_mode=persist
52018      ** mode (and also for journal_mode=truncate on some systems).
52019      **
52020      ** If the journal does not exist, it usually means that some
52021      ** other connection managed to get in and roll it back before
52022      ** this connection obtained the exclusive lock above. Or, it
52023      ** may mean that the pager was in the error-state when this
52024      ** function was called and the journal file does not exist.
52025      */
52026      if( !isOpen(pPager->jfd) ){
52027        sqlite3_vfs * const pVfs = pPager->pVfs;
52028        int bExists;              /* True if journal file exists */
52029        rc = sqlite3OsAccess(
52030            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
52031        if( rc==SQLITE_OK && bExists ){
52032          int fout = 0;
52033          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
52034          assert( !pPager->tempFile );
52035          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
52036          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
52037          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
52038            rc = SQLITE_CANTOPEN_BKPT;
52039            sqlite3OsClose(pPager->jfd);
52040          }
52041        }
52042      }
52043
52044      /* Playback and delete the journal.  Drop the database write
52045      ** lock and reacquire the read lock. Purge the cache before
52046      ** playing back the hot-journal so that we don't end up with
52047      ** an inconsistent cache.  Sync the hot journal before playing
52048      ** it back since the process that crashed and left the hot journal
52049      ** probably did not sync it and we are required to always sync
52050      ** the journal before playing it back.
52051      */
52052      if( isOpen(pPager->jfd) ){
52053        assert( rc==SQLITE_OK );
52054        rc = pagerSyncHotJournal(pPager);
52055        if( rc==SQLITE_OK ){
52056          rc = pager_playback(pPager, !pPager->tempFile);
52057          pPager->eState = PAGER_OPEN;
52058        }
52059      }else if( !pPager->exclusiveMode ){
52060        pagerUnlockDb(pPager, SHARED_LOCK);
52061      }
52062
52063      if( rc!=SQLITE_OK ){
52064        /* This branch is taken if an error occurs while trying to open
52065        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
52066        ** pager_unlock() routine will be called before returning to unlock
52067        ** the file. If the unlock attempt fails, then Pager.eLock must be
52068        ** set to UNKNOWN_LOCK (see the comment above the #define for
52069        ** UNKNOWN_LOCK above for an explanation).
52070        **
52071        ** In order to get pager_unlock() to do this, set Pager.eState to
52072        ** PAGER_ERROR now. This is not actually counted as a transition
52073        ** to ERROR state in the state diagram at the top of this file,
52074        ** since we know that the same call to pager_unlock() will very
52075        ** shortly transition the pager object to the OPEN state. Calling
52076        ** assert_pager_state() would fail now, as it should not be possible
52077        ** to be in ERROR state when there are zero outstanding page
52078        ** references.
52079        */
52080        pager_error(pPager, rc);
52081        goto failed;
52082      }
52083
52084      assert( pPager->eState==PAGER_OPEN );
52085      assert( (pPager->eLock==SHARED_LOCK)
52086           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
52087      );
52088    }
52089
52090    if( !pPager->tempFile && pPager->hasHeldSharedLock ){
52091      /* The shared-lock has just been acquired then check to
52092      ** see if the database has been modified.  If the database has changed,
52093      ** flush the cache.  The hasHeldSharedLock flag prevents this from
52094      ** occurring on the very first access to a file, in order to save a
52095      ** single unnecessary sqlite3OsRead() call at the start-up.
52096      **
52097      ** Database changes are detected by looking at 15 bytes beginning
52098      ** at offset 24 into the file.  The first 4 of these 16 bytes are
52099      ** a 32-bit counter that is incremented with each change.  The
52100      ** other bytes change randomly with each file change when
52101      ** a codec is in use.
52102      **
52103      ** There is a vanishingly small chance that a change will not be
52104      ** detected.  The chance of an undetected change is so small that
52105      ** it can be neglected.
52106      */
52107      Pgno nPage = 0;
52108      char dbFileVers[sizeof(pPager->dbFileVers)];
52109
52110      rc = pagerPagecount(pPager, &nPage);
52111      if( rc ) goto failed;
52112
52113      if( nPage>0 ){
52114        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
52115        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
52116        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
52117          goto failed;
52118        }
52119      }else{
52120        memset(dbFileVers, 0, sizeof(dbFileVers));
52121      }
52122
52123      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
52124        pager_reset(pPager);
52125
52126        /* Unmap the database file. It is possible that external processes
52127        ** may have truncated the database file and then extended it back
52128        ** to its original size while this process was not holding a lock.
52129        ** In this case there may exist a Pager.pMap mapping that appears
52130        ** to be the right size but is not actually valid. Avoid this
52131        ** possibility by unmapping the db here. */
52132        if( USEFETCH(pPager) ){
52133          sqlite3OsUnfetch(pPager->fd, 0, 0);
52134        }
52135      }
52136    }
52137
52138    /* If there is a WAL file in the file-system, open this database in WAL
52139    ** mode. Otherwise, the following function call is a no-op.
52140    */
52141    rc = pagerOpenWalIfPresent(pPager);
52142#ifndef SQLITE_OMIT_WAL
52143    assert( pPager->pWal==0 || rc==SQLITE_OK );
52144#endif
52145  }
52146
52147  if( pagerUseWal(pPager) ){
52148    assert( rc==SQLITE_OK );
52149    rc = pagerBeginReadTransaction(pPager);
52150  }
52151
52152  if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
52153    rc = pagerPagecount(pPager, &pPager->dbSize);
52154  }
52155
52156 failed:
52157  if( rc!=SQLITE_OK ){
52158    assert( !MEMDB );
52159    pager_unlock(pPager);
52160    assert( pPager->eState==PAGER_OPEN );
52161  }else{
52162    pPager->eState = PAGER_READER;
52163    pPager->hasHeldSharedLock = 1;
52164  }
52165  return rc;
52166}
52167
52168/*
52169** If the reference count has reached zero, rollback any active
52170** transaction and unlock the pager.
52171**
52172** Except, in locking_mode=EXCLUSIVE when there is nothing to in
52173** the rollback journal, the unlock is not performed and there is
52174** nothing to rollback, so this routine is a no-op.
52175*/
52176static void pagerUnlockIfUnused(Pager *pPager){
52177  if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
52178    pagerUnlockAndRollback(pPager);
52179  }
52180}
52181
52182/*
52183** The page getter methods each try to acquire a reference to a
52184** page with page number pgno. If the requested reference is
52185** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
52186**
52187** There are different implementations of the getter method depending
52188** on the current state of the pager.
52189**
52190**     getPageNormal()         --  The normal getter
52191**     getPageError()          --  Used if the pager is in an error state
52192**     getPageMmap()           --  Used if memory-mapped I/O is enabled
52193**
52194** If the requested page is already in the cache, it is returned.
52195** Otherwise, a new page object is allocated and populated with data
52196** read from the database file. In some cases, the pcache module may
52197** choose not to allocate a new page object and may reuse an existing
52198** object with no outstanding references.
52199**
52200** The extra data appended to a page is always initialized to zeros the
52201** first time a page is loaded into memory. If the page requested is
52202** already in the cache when this function is called, then the extra
52203** data is left as it was when the page object was last used.
52204**
52205** If the database image is smaller than the requested page or if
52206** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
52207** requested page is not already stored in the cache, then no
52208** actual disk read occurs. In this case the memory image of the
52209** page is initialized to all zeros.
52210**
52211** If PAGER_GET_NOCONTENT is true, it means that we do not care about
52212** the contents of the page. This occurs in two scenarios:
52213**
52214**   a) When reading a free-list leaf page from the database, and
52215**
52216**   b) When a savepoint is being rolled back and we need to load
52217**      a new page into the cache to be filled with the data read
52218**      from the savepoint journal.
52219**
52220** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
52221** of being read from the database. Additionally, the bits corresponding
52222** to pgno in Pager.pInJournal (bitvec of pages already written to the
52223** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
52224** savepoints are set. This means if the page is made writable at any
52225** point in the future, using a call to sqlite3PagerWrite(), its contents
52226** will not be journaled. This saves IO.
52227**
52228** The acquisition might fail for several reasons.  In all cases,
52229** an appropriate error code is returned and *ppPage is set to NULL.
52230**
52231** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
52232** to find a page in the in-memory cache first.  If the page is not already
52233** in memory, this routine goes to disk to read it in whereas Lookup()
52234** just returns 0.  This routine acquires a read-lock the first time it
52235** has to go to disk, and could also playback an old journal if necessary.
52236** Since Lookup() never goes to disk, it never has to deal with locks
52237** or journal files.
52238*/
52239static int getPageNormal(
52240  Pager *pPager,      /* The pager open on the database file */
52241  Pgno pgno,          /* Page number to fetch */
52242  DbPage **ppPage,    /* Write a pointer to the page here */
52243  int flags           /* PAGER_GET_XXX flags */
52244){
52245  int rc = SQLITE_OK;
52246  PgHdr *pPg;
52247  u8 noContent;                   /* True if PAGER_GET_NOCONTENT is set */
52248  sqlite3_pcache_page *pBase;
52249
52250  assert( pPager->errCode==SQLITE_OK );
52251  assert( pPager->eState>=PAGER_READER );
52252  assert( assert_pager_state(pPager) );
52253  assert( pPager->hasHeldSharedLock==1 );
52254
52255  if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
52256  pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
52257  if( pBase==0 ){
52258    pPg = 0;
52259    rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
52260    if( rc!=SQLITE_OK ) goto pager_acquire_err;
52261    if( pBase==0 ){
52262      rc = SQLITE_NOMEM_BKPT;
52263      goto pager_acquire_err;
52264    }
52265  }
52266  pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
52267  assert( pPg==(*ppPage) );
52268  assert( pPg->pgno==pgno );
52269  assert( pPg->pPager==pPager || pPg->pPager==0 );
52270
52271  noContent = (flags & PAGER_GET_NOCONTENT)!=0;
52272  if( pPg->pPager && !noContent ){
52273    /* In this case the pcache already contains an initialized copy of
52274    ** the page. Return without further ado.  */
52275    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
52276    pPager->aStat[PAGER_STAT_HIT]++;
52277    return SQLITE_OK;
52278
52279  }else{
52280    /* The pager cache has created a new page. Its content needs to
52281    ** be initialized. But first some error checks:
52282    **
52283    ** (1) The maximum page number is 2^31
52284    ** (2) Never try to fetch the locking page
52285    */
52286    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
52287      rc = SQLITE_CORRUPT_BKPT;
52288      goto pager_acquire_err;
52289    }
52290
52291    pPg->pPager = pPager;
52292
52293    assert( !isOpen(pPager->fd) || !MEMDB );
52294    if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
52295      if( pgno>pPager->mxPgno ){
52296        rc = SQLITE_FULL;
52297        goto pager_acquire_err;
52298      }
52299      if( noContent ){
52300        /* Failure to set the bits in the InJournal bit-vectors is benign.
52301        ** It merely means that we might do some extra work to journal a
52302        ** page that does not need to be journaled.  Nevertheless, be sure
52303        ** to test the case where a malloc error occurs while trying to set
52304        ** a bit in a bit vector.
52305        */
52306        sqlite3BeginBenignMalloc();
52307        if( pgno<=pPager->dbOrigSize ){
52308          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
52309          testcase( rc==SQLITE_NOMEM );
52310        }
52311        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
52312        testcase( rc==SQLITE_NOMEM );
52313        sqlite3EndBenignMalloc();
52314      }
52315      memset(pPg->pData, 0, pPager->pageSize);
52316      IOTRACE(("ZERO %p %d\n", pPager, pgno));
52317    }else{
52318      u32 iFrame = 0;                 /* Frame to read from WAL file */
52319      if( pagerUseWal(pPager) ){
52320        rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
52321        if( rc!=SQLITE_OK ) goto pager_acquire_err;
52322      }
52323      assert( pPg->pPager==pPager );
52324      pPager->aStat[PAGER_STAT_MISS]++;
52325      rc = readDbPage(pPg, iFrame);
52326      if( rc!=SQLITE_OK ){
52327        goto pager_acquire_err;
52328      }
52329    }
52330    pager_set_pagehash(pPg);
52331  }
52332  return SQLITE_OK;
52333
52334pager_acquire_err:
52335  assert( rc!=SQLITE_OK );
52336  if( pPg ){
52337    sqlite3PcacheDrop(pPg);
52338  }
52339  pagerUnlockIfUnused(pPager);
52340  *ppPage = 0;
52341  return rc;
52342}
52343
52344#if SQLITE_MAX_MMAP_SIZE>0
52345/* The page getter for when memory-mapped I/O is enabled */
52346static int getPageMMap(
52347  Pager *pPager,      /* The pager open on the database file */
52348  Pgno pgno,          /* Page number to fetch */
52349  DbPage **ppPage,    /* Write a pointer to the page here */
52350  int flags           /* PAGER_GET_XXX flags */
52351){
52352  int rc = SQLITE_OK;
52353  PgHdr *pPg = 0;
52354  u32 iFrame = 0;                 /* Frame to read from WAL file */
52355
52356  /* It is acceptable to use a read-only (mmap) page for any page except
52357  ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
52358  ** flag was specified by the caller. And so long as the db is not a
52359  ** temporary or in-memory database.  */
52360  const int bMmapOk = (pgno>1
52361   && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
52362  );
52363
52364  assert( USEFETCH(pPager) );
52365#ifdef SQLITE_HAS_CODEC
52366  assert( pPager->xCodec==0 );
52367#endif
52368
52369  /* Optimization note:  Adding the "pgno<=1" term before "pgno==0" here
52370  ** allows the compiler optimizer to reuse the results of the "pgno>1"
52371  ** test in the previous statement, and avoid testing pgno==0 in the
52372  ** common case where pgno is large. */
52373  if( pgno<=1 && pgno==0 ){
52374    return SQLITE_CORRUPT_BKPT;
52375  }
52376  assert( pPager->eState>=PAGER_READER );
52377  assert( assert_pager_state(pPager) );
52378  assert( pPager->hasHeldSharedLock==1 );
52379  assert( pPager->errCode==SQLITE_OK );
52380
52381  if( bMmapOk && pagerUseWal(pPager) ){
52382    rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
52383    if( rc!=SQLITE_OK ){
52384      *ppPage = 0;
52385      return rc;
52386    }
52387  }
52388  if( bMmapOk && iFrame==0 ){
52389    void *pData = 0;
52390    rc = sqlite3OsFetch(pPager->fd,
52391        (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
52392    );
52393    if( rc==SQLITE_OK && pData ){
52394      if( pPager->eState>PAGER_READER || pPager->tempFile ){
52395        pPg = sqlite3PagerLookup(pPager, pgno);
52396      }
52397      if( pPg==0 ){
52398        rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
52399     }else{
52400        sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
52401      }
52402      if( pPg ){
52403        assert( rc==SQLITE_OK );
52404        *ppPage = pPg;
52405        return SQLITE_OK;
52406      }
52407    }
52408    if( rc!=SQLITE_OK ){
52409      *ppPage = 0;
52410      return rc;
52411    }
52412  }
52413  return getPageNormal(pPager, pgno, ppPage, flags);
52414}
52415#endif /* SQLITE_MAX_MMAP_SIZE>0 */
52416
52417/* The page getter method for when the pager is an error state */
52418static int getPageError(
52419  Pager *pPager,      /* The pager open on the database file */
52420  Pgno pgno,          /* Page number to fetch */
52421  DbPage **ppPage,    /* Write a pointer to the page here */
52422  int flags           /* PAGER_GET_XXX flags */
52423){
52424  UNUSED_PARAMETER(pgno);
52425  UNUSED_PARAMETER(flags);
52426  assert( pPager->errCode!=SQLITE_OK );
52427  *ppPage = 0;
52428  return pPager->errCode;
52429}
52430
52431
52432/* Dispatch all page fetch requests to the appropriate getter method.
52433*/
52434SQLITE_PRIVATE int sqlite3PagerGet(
52435  Pager *pPager,      /* The pager open on the database file */
52436  Pgno pgno,          /* Page number to fetch */
52437  DbPage **ppPage,    /* Write a pointer to the page here */
52438  int flags           /* PAGER_GET_XXX flags */
52439){
52440  return pPager->xGet(pPager, pgno, ppPage, flags);
52441}
52442
52443/*
52444** Acquire a page if it is already in the in-memory cache.  Do
52445** not read the page from disk.  Return a pointer to the page,
52446** or 0 if the page is not in cache.
52447**
52448** See also sqlite3PagerGet().  The difference between this routine
52449** and sqlite3PagerGet() is that _get() will go to the disk and read
52450** in the page if the page is not already in cache.  This routine
52451** returns NULL if the page is not in cache or if a disk I/O error
52452** has ever happened.
52453*/
52454SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
52455  sqlite3_pcache_page *pPage;
52456  assert( pPager!=0 );
52457  assert( pgno!=0 );
52458  assert( pPager->pPCache!=0 );
52459  pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
52460  assert( pPage==0 || pPager->hasHeldSharedLock );
52461  if( pPage==0 ) return 0;
52462  return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
52463}
52464
52465/*
52466** Release a page reference.
52467**
52468** If the number of references to the page drop to zero, then the
52469** page is added to the LRU list.  When all references to all pages
52470** are released, a rollback occurs and the lock on the database is
52471** removed.
52472*/
52473SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
52474  Pager *pPager;
52475  assert( pPg!=0 );
52476  pPager = pPg->pPager;
52477  if( pPg->flags & PGHDR_MMAP ){
52478    pagerReleaseMapPage(pPg);
52479  }else{
52480    sqlite3PcacheRelease(pPg);
52481  }
52482  pagerUnlockIfUnused(pPager);
52483}
52484SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
52485  if( pPg ) sqlite3PagerUnrefNotNull(pPg);
52486}
52487
52488/*
52489** This function is called at the start of every write transaction.
52490** There must already be a RESERVED or EXCLUSIVE lock on the database
52491** file when this routine is called.
52492**
52493** Open the journal file for pager pPager and write a journal header
52494** to the start of it. If there are active savepoints, open the sub-journal
52495** as well. This function is only used when the journal file is being
52496** opened to write a rollback log for a transaction. It is not used
52497** when opening a hot journal file to roll it back.
52498**
52499** If the journal file is already open (as it may be in exclusive mode),
52500** then this function just writes a journal header to the start of the
52501** already open file.
52502**
52503** Whether or not the journal file is opened by this function, the
52504** Pager.pInJournal bitvec structure is allocated.
52505**
52506** Return SQLITE_OK if everything is successful. Otherwise, return
52507** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
52508** an IO error code if opening or writing the journal file fails.
52509*/
52510static int pager_open_journal(Pager *pPager){
52511  int rc = SQLITE_OK;                        /* Return code */
52512  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
52513
52514  assert( pPager->eState==PAGER_WRITER_LOCKED );
52515  assert( assert_pager_state(pPager) );
52516  assert( pPager->pInJournal==0 );
52517
52518  /* If already in the error state, this function is a no-op.  But on
52519  ** the other hand, this routine is never called if we are already in
52520  ** an error state. */
52521  if( NEVER(pPager->errCode) ) return pPager->errCode;
52522
52523  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
52524    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
52525    if( pPager->pInJournal==0 ){
52526      return SQLITE_NOMEM_BKPT;
52527    }
52528
52529    /* Open the journal file if it is not already open. */
52530    if( !isOpen(pPager->jfd) ){
52531      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
52532        sqlite3MemJournalOpen(pPager->jfd);
52533      }else{
52534        int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
52535        int nSpill;
52536
52537        if( pPager->tempFile ){
52538          flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
52539          nSpill = sqlite3Config.nStmtSpill;
52540        }else{
52541          flags |= SQLITE_OPEN_MAIN_JOURNAL;
52542          nSpill = jrnlBufferSize(pPager);
52543        }
52544
52545        /* Verify that the database still has the same name as it did when
52546        ** it was originally opened. */
52547        rc = databaseIsUnmoved(pPager);
52548        if( rc==SQLITE_OK ){
52549          rc = sqlite3JournalOpen (
52550              pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
52551          );
52552        }
52553      }
52554      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
52555    }
52556
52557
52558    /* Write the first journal header to the journal file and open
52559    ** the sub-journal if necessary.
52560    */
52561    if( rc==SQLITE_OK ){
52562      /* TODO: Check if all of these are really required. */
52563      pPager->nRec = 0;
52564      pPager->journalOff = 0;
52565      pPager->setMaster = 0;
52566      pPager->journalHdr = 0;
52567      rc = writeJournalHdr(pPager);
52568    }
52569  }
52570
52571  if( rc!=SQLITE_OK ){
52572    sqlite3BitvecDestroy(pPager->pInJournal);
52573    pPager->pInJournal = 0;
52574  }else{
52575    assert( pPager->eState==PAGER_WRITER_LOCKED );
52576    pPager->eState = PAGER_WRITER_CACHEMOD;
52577  }
52578
52579  return rc;
52580}
52581
52582/*
52583** Begin a write-transaction on the specified pager object. If a
52584** write-transaction has already been opened, this function is a no-op.
52585**
52586** If the exFlag argument is false, then acquire at least a RESERVED
52587** lock on the database file. If exFlag is true, then acquire at least
52588** an EXCLUSIVE lock. If such a lock is already held, no locking
52589** functions need be called.
52590**
52591** If the subjInMemory argument is non-zero, then any sub-journal opened
52592** within this transaction will be opened as an in-memory file. This
52593** has no effect if the sub-journal is already opened (as it may be when
52594** running in exclusive mode) or if the transaction does not require a
52595** sub-journal. If the subjInMemory argument is zero, then any required
52596** sub-journal is implemented in-memory if pPager is an in-memory database,
52597** or using a temporary file otherwise.
52598*/
52599SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
52600  int rc = SQLITE_OK;
52601
52602  if( pPager->errCode ) return pPager->errCode;
52603  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
52604  pPager->subjInMemory = (u8)subjInMemory;
52605
52606  if( ALWAYS(pPager->eState==PAGER_READER) ){
52607    assert( pPager->pInJournal==0 );
52608
52609    if( pagerUseWal(pPager) ){
52610      /* If the pager is configured to use locking_mode=exclusive, and an
52611      ** exclusive lock on the database is not already held, obtain it now.
52612      */
52613      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
52614        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
52615        if( rc!=SQLITE_OK ){
52616          return rc;
52617        }
52618        (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
52619      }
52620
52621      /* Grab the write lock on the log file. If successful, upgrade to
52622      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
52623      ** The busy-handler is not invoked if another connection already
52624      ** holds the write-lock. If possible, the upper layer will call it.
52625      */
52626      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
52627    }else{
52628      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
52629      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
52630      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
52631      ** lock, but not when obtaining the RESERVED lock.
52632      */
52633      rc = pagerLockDb(pPager, RESERVED_LOCK);
52634      if( rc==SQLITE_OK && exFlag ){
52635        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
52636      }
52637    }
52638
52639    if( rc==SQLITE_OK ){
52640      /* Change to WRITER_LOCKED state.
52641      **
52642      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
52643      ** when it has an open transaction, but never to DBMOD or FINISHED.
52644      ** This is because in those states the code to roll back savepoint
52645      ** transactions may copy data from the sub-journal into the database
52646      ** file as well as into the page cache. Which would be incorrect in
52647      ** WAL mode.
52648      */
52649      pPager->eState = PAGER_WRITER_LOCKED;
52650      pPager->dbHintSize = pPager->dbSize;
52651      pPager->dbFileSize = pPager->dbSize;
52652      pPager->dbOrigSize = pPager->dbSize;
52653      pPager->journalOff = 0;
52654    }
52655
52656    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
52657    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
52658    assert( assert_pager_state(pPager) );
52659  }
52660
52661  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
52662  return rc;
52663}
52664
52665/*
52666** Write page pPg onto the end of the rollback journal.
52667*/
52668static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
52669  Pager *pPager = pPg->pPager;
52670  int rc;
52671  u32 cksum;
52672  char *pData2;
52673  i64 iOff = pPager->journalOff;
52674
52675  /* We should never write to the journal file the page that
52676  ** contains the database locks.  The following assert verifies
52677  ** that we do not. */
52678  assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
52679
52680  assert( pPager->journalHdr<=pPager->journalOff );
52681  CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
52682  cksum = pager_cksum(pPager, (u8*)pData2);
52683
52684  /* Even if an IO or diskfull error occurs while journalling the
52685  ** page in the block above, set the need-sync flag for the page.
52686  ** Otherwise, when the transaction is rolled back, the logic in
52687  ** playback_one_page() will think that the page needs to be restored
52688  ** in the database file. And if an IO error occurs while doing so,
52689  ** then corruption may follow.
52690  */
52691  pPg->flags |= PGHDR_NEED_SYNC;
52692
52693  rc = write32bits(pPager->jfd, iOff, pPg->pgno);
52694  if( rc!=SQLITE_OK ) return rc;
52695  rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
52696  if( rc!=SQLITE_OK ) return rc;
52697  rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
52698  if( rc!=SQLITE_OK ) return rc;
52699
52700  IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
52701           pPager->journalOff, pPager->pageSize));
52702  PAGER_INCR(sqlite3_pager_writej_count);
52703  PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
52704       PAGERID(pPager), pPg->pgno,
52705       ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
52706
52707  pPager->journalOff += 8 + pPager->pageSize;
52708  pPager->nRec++;
52709  assert( pPager->pInJournal!=0 );
52710  rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
52711  testcase( rc==SQLITE_NOMEM );
52712  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
52713  rc |= addToSavepointBitvecs(pPager, pPg->pgno);
52714  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
52715  return rc;
52716}
52717
52718/*
52719** Mark a single data page as writeable. The page is written into the
52720** main journal or sub-journal as required. If the page is written into
52721** one of the journals, the corresponding bit is set in the
52722** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
52723** of any open savepoints as appropriate.
52724*/
52725static int pager_write(PgHdr *pPg){
52726  Pager *pPager = pPg->pPager;
52727  int rc = SQLITE_OK;
52728
52729  /* This routine is not called unless a write-transaction has already
52730  ** been started. The journal file may or may not be open at this point.
52731  ** It is never called in the ERROR state.
52732  */
52733  assert( pPager->eState==PAGER_WRITER_LOCKED
52734       || pPager->eState==PAGER_WRITER_CACHEMOD
52735       || pPager->eState==PAGER_WRITER_DBMOD
52736  );
52737  assert( assert_pager_state(pPager) );
52738  assert( pPager->errCode==0 );
52739  assert( pPager->readOnly==0 );
52740  CHECK_PAGE(pPg);
52741
52742  /* The journal file needs to be opened. Higher level routines have already
52743  ** obtained the necessary locks to begin the write-transaction, but the
52744  ** rollback journal might not yet be open. Open it now if this is the case.
52745  **
52746  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
52747  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
52748  ** an error might occur and the pager would end up in WRITER_LOCKED state
52749  ** with pages marked as dirty in the cache.
52750  */
52751  if( pPager->eState==PAGER_WRITER_LOCKED ){
52752    rc = pager_open_journal(pPager);
52753    if( rc!=SQLITE_OK ) return rc;
52754  }
52755  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
52756  assert( assert_pager_state(pPager) );
52757
52758  /* Mark the page that is about to be modified as dirty. */
52759  sqlite3PcacheMakeDirty(pPg);
52760
52761  /* If a rollback journal is in use, them make sure the page that is about
52762  ** to change is in the rollback journal, or if the page is a new page off
52763  ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
52764  */
52765  assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
52766  if( pPager->pInJournal!=0
52767   && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
52768  ){
52769    assert( pagerUseWal(pPager)==0 );
52770    if( pPg->pgno<=pPager->dbOrigSize ){
52771      rc = pagerAddPageToRollbackJournal(pPg);
52772      if( rc!=SQLITE_OK ){
52773        return rc;
52774      }
52775    }else{
52776      if( pPager->eState!=PAGER_WRITER_DBMOD ){
52777        pPg->flags |= PGHDR_NEED_SYNC;
52778      }
52779      PAGERTRACE(("APPEND %d page %d needSync=%d\n",
52780              PAGERID(pPager), pPg->pgno,
52781             ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
52782    }
52783  }
52784
52785  /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
52786  ** and before writing the page into the rollback journal.  Wait until now,
52787  ** after the page has been successfully journalled, before setting the
52788  ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
52789  */
52790  pPg->flags |= PGHDR_WRITEABLE;
52791
52792  /* If the statement journal is open and the page is not in it,
52793  ** then write the page into the statement journal.
52794  */
52795  if( pPager->nSavepoint>0 ){
52796    rc = subjournalPageIfRequired(pPg);
52797  }
52798
52799  /* Update the database size and return. */
52800  if( pPager->dbSize<pPg->pgno ){
52801    pPager->dbSize = pPg->pgno;
52802  }
52803  return rc;
52804}
52805
52806/*
52807** This is a variant of sqlite3PagerWrite() that runs when the sector size
52808** is larger than the page size.  SQLite makes the (reasonable) assumption that
52809** all bytes of a sector are written together by hardware.  Hence, all bytes of
52810** a sector need to be journalled in case of a power loss in the middle of
52811** a write.
52812**
52813** Usually, the sector size is less than or equal to the page size, in which
52814** case pages can be individually written.  This routine only runs in the
52815** exceptional case where the page size is smaller than the sector size.
52816*/
52817static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
52818  int rc = SQLITE_OK;          /* Return code */
52819  Pgno nPageCount;             /* Total number of pages in database file */
52820  Pgno pg1;                    /* First page of the sector pPg is located on. */
52821  int nPage = 0;               /* Number of pages starting at pg1 to journal */
52822  int ii;                      /* Loop counter */
52823  int needSync = 0;            /* True if any page has PGHDR_NEED_SYNC */
52824  Pager *pPager = pPg->pPager; /* The pager that owns pPg */
52825  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
52826
52827  /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
52828  ** a journal header to be written between the pages journaled by
52829  ** this function.
52830  */
52831  assert( !MEMDB );
52832  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
52833  pPager->doNotSpill |= SPILLFLAG_NOSYNC;
52834
52835  /* This trick assumes that both the page-size and sector-size are
52836  ** an integer power of 2. It sets variable pg1 to the identifier
52837  ** of the first page of the sector pPg is located on.
52838  */
52839  pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
52840
52841  nPageCount = pPager->dbSize;
52842  if( pPg->pgno>nPageCount ){
52843    nPage = (pPg->pgno - pg1)+1;
52844  }else if( (pg1+nPagePerSector-1)>nPageCount ){
52845    nPage = nPageCount+1-pg1;
52846  }else{
52847    nPage = nPagePerSector;
52848  }
52849  assert(nPage>0);
52850  assert(pg1<=pPg->pgno);
52851  assert((pg1+nPage)>pPg->pgno);
52852
52853  for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
52854    Pgno pg = pg1+ii;
52855    PgHdr *pPage;
52856    if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
52857      if( pg!=PAGER_MJ_PGNO(pPager) ){
52858        rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
52859        if( rc==SQLITE_OK ){
52860          rc = pager_write(pPage);
52861          if( pPage->flags&PGHDR_NEED_SYNC ){
52862            needSync = 1;
52863          }
52864          sqlite3PagerUnrefNotNull(pPage);
52865        }
52866      }
52867    }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
52868      if( pPage->flags&PGHDR_NEED_SYNC ){
52869        needSync = 1;
52870      }
52871      sqlite3PagerUnrefNotNull(pPage);
52872    }
52873  }
52874
52875  /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
52876  ** starting at pg1, then it needs to be set for all of them. Because
52877  ** writing to any of these nPage pages may damage the others, the
52878  ** journal file must contain sync()ed copies of all of them
52879  ** before any of them can be written out to the database file.
52880  */
52881  if( rc==SQLITE_OK && needSync ){
52882    assert( !MEMDB );
52883    for(ii=0; ii<nPage; ii++){
52884      PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
52885      if( pPage ){
52886        pPage->flags |= PGHDR_NEED_SYNC;
52887        sqlite3PagerUnrefNotNull(pPage);
52888      }
52889    }
52890  }
52891
52892  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
52893  pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
52894  return rc;
52895}
52896
52897/*
52898** Mark a data page as writeable. This routine must be called before
52899** making changes to a page. The caller must check the return value
52900** of this function and be careful not to change any page data unless
52901** this routine returns SQLITE_OK.
52902**
52903** The difference between this function and pager_write() is that this
52904** function also deals with the special case where 2 or more pages
52905** fit on a single disk sector. In this case all co-resident pages
52906** must have been written to the journal file before returning.
52907**
52908** If an error occurs, SQLITE_NOMEM or an IO error code is returned
52909** as appropriate. Otherwise, SQLITE_OK.
52910*/
52911SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
52912  Pager *pPager = pPg->pPager;
52913  assert( (pPg->flags & PGHDR_MMAP)==0 );
52914  assert( pPager->eState>=PAGER_WRITER_LOCKED );
52915  assert( assert_pager_state(pPager) );
52916  if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
52917    if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
52918    return SQLITE_OK;
52919  }else if( pPager->errCode ){
52920    return pPager->errCode;
52921  }else if( pPager->sectorSize > (u32)pPager->pageSize ){
52922    assert( pPager->tempFile==0 );
52923    return pagerWriteLargeSector(pPg);
52924  }else{
52925    return pager_write(pPg);
52926  }
52927}
52928
52929/*
52930** Return TRUE if the page given in the argument was previously passed
52931** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
52932** to change the content of the page.
52933*/
52934#ifndef NDEBUG
52935SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
52936  return pPg->flags & PGHDR_WRITEABLE;
52937}
52938#endif
52939
52940/*
52941** A call to this routine tells the pager that it is not necessary to
52942** write the information on page pPg back to the disk, even though
52943** that page might be marked as dirty.  This happens, for example, when
52944** the page has been added as a leaf of the freelist and so its
52945** content no longer matters.
52946**
52947** The overlying software layer calls this routine when all of the data
52948** on the given page is unused. The pager marks the page as clean so
52949** that it does not get written to disk.
52950**
52951** Tests show that this optimization can quadruple the speed of large
52952** DELETE operations.
52953**
52954** This optimization cannot be used with a temp-file, as the page may
52955** have been dirty at the start of the transaction. In that case, if
52956** memory pressure forces page pPg out of the cache, the data does need
52957** to be written out to disk so that it may be read back in if the
52958** current transaction is rolled back.
52959*/
52960SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
52961  Pager *pPager = pPg->pPager;
52962  if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
52963    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
52964    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
52965    pPg->flags |= PGHDR_DONT_WRITE;
52966    pPg->flags &= ~PGHDR_WRITEABLE;
52967    testcase( pPg->flags & PGHDR_NEED_SYNC );
52968    pager_set_pagehash(pPg);
52969  }
52970}
52971
52972/*
52973** This routine is called to increment the value of the database file
52974** change-counter, stored as a 4-byte big-endian integer starting at
52975** byte offset 24 of the pager file.  The secondary change counter at
52976** 92 is also updated, as is the SQLite version number at offset 96.
52977**
52978** But this only happens if the pPager->changeCountDone flag is false.
52979** To avoid excess churning of page 1, the update only happens once.
52980** See also the pager_write_changecounter() routine that does an
52981** unconditional update of the change counters.
52982**
52983** If the isDirectMode flag is zero, then this is done by calling
52984** sqlite3PagerWrite() on page 1, then modifying the contents of the
52985** page data. In this case the file will be updated when the current
52986** transaction is committed.
52987**
52988** The isDirectMode flag may only be non-zero if the library was compiled
52989** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
52990** if isDirect is non-zero, then the database file is updated directly
52991** by writing an updated version of page 1 using a call to the
52992** sqlite3OsWrite() function.
52993*/
52994static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
52995  int rc = SQLITE_OK;
52996
52997  assert( pPager->eState==PAGER_WRITER_CACHEMOD
52998       || pPager->eState==PAGER_WRITER_DBMOD
52999  );
53000  assert( assert_pager_state(pPager) );
53001
53002  /* Declare and initialize constant integer 'isDirect'. If the
53003  ** atomic-write optimization is enabled in this build, then isDirect
53004  ** is initialized to the value passed as the isDirectMode parameter
53005  ** to this function. Otherwise, it is always set to zero.
53006  **
53007  ** The idea is that if the atomic-write optimization is not
53008  ** enabled at compile time, the compiler can omit the tests of
53009  ** 'isDirect' below, as well as the block enclosed in the
53010  ** "if( isDirect )" condition.
53011  */
53012#ifndef SQLITE_ENABLE_ATOMIC_WRITE
53013# define DIRECT_MODE 0
53014  assert( isDirectMode==0 );
53015  UNUSED_PARAMETER(isDirectMode);
53016#else
53017# define DIRECT_MODE isDirectMode
53018#endif
53019
53020  if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
53021    PgHdr *pPgHdr;                /* Reference to page 1 */
53022
53023    assert( !pPager->tempFile && isOpen(pPager->fd) );
53024
53025    /* Open page 1 of the file for writing. */
53026    rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
53027    assert( pPgHdr==0 || rc==SQLITE_OK );
53028
53029    /* If page one was fetched successfully, and this function is not
53030    ** operating in direct-mode, make page 1 writable.  When not in
53031    ** direct mode, page 1 is always held in cache and hence the PagerGet()
53032    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
53033    */
53034    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
53035      rc = sqlite3PagerWrite(pPgHdr);
53036    }
53037
53038    if( rc==SQLITE_OK ){
53039      /* Actually do the update of the change counter */
53040      pager_write_changecounter(pPgHdr);
53041
53042      /* If running in direct mode, write the contents of page 1 to the file. */
53043      if( DIRECT_MODE ){
53044        const void *zBuf;
53045        assert( pPager->dbFileSize>0 );
53046        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
53047        if( rc==SQLITE_OK ){
53048          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
53049          pPager->aStat[PAGER_STAT_WRITE]++;
53050        }
53051        if( rc==SQLITE_OK ){
53052          /* Update the pager's copy of the change-counter. Otherwise, the
53053          ** next time a read transaction is opened the cache will be
53054          ** flushed (as the change-counter values will not match).  */
53055          const void *pCopy = (const void *)&((const char *)zBuf)[24];
53056          memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
53057          pPager->changeCountDone = 1;
53058        }
53059      }else{
53060        pPager->changeCountDone = 1;
53061      }
53062    }
53063
53064    /* Release the page reference. */
53065    sqlite3PagerUnref(pPgHdr);
53066  }
53067  return rc;
53068}
53069
53070/*
53071** Sync the database file to disk. This is a no-op for in-memory databases
53072** or pages with the Pager.noSync flag set.
53073**
53074** If successful, or if called on a pager for which it is a no-op, this
53075** function returns SQLITE_OK. Otherwise, an IO error code is returned.
53076*/
53077SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
53078  int rc = SQLITE_OK;
53079
53080  if( isOpen(pPager->fd) ){
53081    void *pArg = (void*)zMaster;
53082    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
53083    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
53084  }
53085  if( rc==SQLITE_OK && !pPager->noSync ){
53086    assert( !MEMDB );
53087    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
53088  }
53089  return rc;
53090}
53091
53092/*
53093** This function may only be called while a write-transaction is active in
53094** rollback. If the connection is in WAL mode, this call is a no-op.
53095** Otherwise, if the connection does not already have an EXCLUSIVE lock on
53096** the database file, an attempt is made to obtain one.
53097**
53098** If the EXCLUSIVE lock is already held or the attempt to obtain it is
53099** successful, or the connection is in WAL mode, SQLITE_OK is returned.
53100** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
53101** returned.
53102*/
53103SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
53104  int rc = pPager->errCode;
53105  assert( assert_pager_state(pPager) );
53106  if( rc==SQLITE_OK ){
53107    assert( pPager->eState==PAGER_WRITER_CACHEMOD
53108         || pPager->eState==PAGER_WRITER_DBMOD
53109         || pPager->eState==PAGER_WRITER_LOCKED
53110    );
53111    assert( assert_pager_state(pPager) );
53112    if( 0==pagerUseWal(pPager) ){
53113      rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
53114    }
53115  }
53116  return rc;
53117}
53118
53119/*
53120** Sync the database file for the pager pPager. zMaster points to the name
53121** of a master journal file that should be written into the individual
53122** journal file. zMaster may be NULL, which is interpreted as no master
53123** journal (a single database transaction).
53124**
53125** This routine ensures that:
53126**
53127**   * The database file change-counter is updated,
53128**   * the journal is synced (unless the atomic-write optimization is used),
53129**   * all dirty pages are written to the database file,
53130**   * the database file is truncated (if required), and
53131**   * the database file synced.
53132**
53133** The only thing that remains to commit the transaction is to finalize
53134** (delete, truncate or zero the first part of) the journal file (or
53135** delete the master journal file if specified).
53136**
53137** Note that if zMaster==NULL, this does not overwrite a previous value
53138** passed to an sqlite3PagerCommitPhaseOne() call.
53139**
53140** If the final parameter - noSync - is true, then the database file itself
53141** is not synced. The caller must call sqlite3PagerSync() directly to
53142** sync the database file before calling CommitPhaseTwo() to delete the
53143** journal file in this case.
53144*/
53145SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
53146  Pager *pPager,                  /* Pager object */
53147  const char *zMaster,            /* If not NULL, the master journal name */
53148  int noSync                      /* True to omit the xSync on the db file */
53149){
53150  int rc = SQLITE_OK;             /* Return code */
53151
53152  assert( pPager->eState==PAGER_WRITER_LOCKED
53153       || pPager->eState==PAGER_WRITER_CACHEMOD
53154       || pPager->eState==PAGER_WRITER_DBMOD
53155       || pPager->eState==PAGER_ERROR
53156  );
53157  assert( assert_pager_state(pPager) );
53158
53159  /* If a prior error occurred, report that error again. */
53160  if( NEVER(pPager->errCode) ) return pPager->errCode;
53161
53162  /* Provide the ability to easily simulate an I/O error during testing */
53163  if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
53164
53165  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
53166      pPager->zFilename, zMaster, pPager->dbSize));
53167
53168  /* If no database changes have been made, return early. */
53169  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
53170
53171  assert( MEMDB==0 || pPager->tempFile );
53172  assert( isOpen(pPager->fd) || pPager->tempFile );
53173  if( 0==pagerFlushOnCommit(pPager, 1) ){
53174    /* If this is an in-memory db, or no pages have been written to, or this
53175    ** function has already been called, it is mostly a no-op.  However, any
53176    ** backup in progress needs to be restarted.  */
53177    sqlite3BackupRestart(pPager->pBackup);
53178  }else{
53179    if( pagerUseWal(pPager) ){
53180      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
53181      PgHdr *pPageOne = 0;
53182      if( pList==0 ){
53183        /* Must have at least one page for the WAL commit flag.
53184        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
53185        rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
53186        pList = pPageOne;
53187        pList->pDirty = 0;
53188      }
53189      assert( rc==SQLITE_OK );
53190      if( ALWAYS(pList) ){
53191        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
53192      }
53193      sqlite3PagerUnref(pPageOne);
53194      if( rc==SQLITE_OK ){
53195        sqlite3PcacheCleanAll(pPager->pPCache);
53196      }
53197    }else{
53198      /* The following block updates the change-counter. Exactly how it
53199      ** does this depends on whether or not the atomic-update optimization
53200      ** was enabled at compile time, and if this transaction meets the
53201      ** runtime criteria to use the operation:
53202      **
53203      **    * The file-system supports the atomic-write property for
53204      **      blocks of size page-size, and
53205      **    * This commit is not part of a multi-file transaction, and
53206      **    * Exactly one page has been modified and store in the journal file.
53207      **
53208      ** If the optimization was not enabled at compile time, then the
53209      ** pager_incr_changecounter() function is called to update the change
53210      ** counter in 'indirect-mode'. If the optimization is compiled in but
53211      ** is not applicable to this transaction, call sqlite3JournalCreate()
53212      ** to make sure the journal file has actually been created, then call
53213      ** pager_incr_changecounter() to update the change-counter in indirect
53214      ** mode.
53215      **
53216      ** Otherwise, if the optimization is both enabled and applicable,
53217      ** then call pager_incr_changecounter() to update the change-counter
53218      ** in 'direct' mode. In this case the journal file will never be
53219      ** created for this transaction.
53220      */
53221  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
53222      PgHdr *pPg;
53223      assert( isOpen(pPager->jfd)
53224           || pPager->journalMode==PAGER_JOURNALMODE_OFF
53225           || pPager->journalMode==PAGER_JOURNALMODE_WAL
53226      );
53227      if( !zMaster && isOpen(pPager->jfd)
53228       && pPager->journalOff==jrnlBufferSize(pPager)
53229       && pPager->dbSize>=pPager->dbOrigSize
53230       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
53231      ){
53232        /* Update the db file change counter via the direct-write method. The
53233        ** following call will modify the in-memory representation of page 1
53234        ** to include the updated change counter and then write page 1
53235        ** directly to the database file. Because of the atomic-write
53236        ** property of the host file-system, this is safe.
53237        */
53238        rc = pager_incr_changecounter(pPager, 1);
53239      }else{
53240        rc = sqlite3JournalCreate(pPager->jfd);
53241        if( rc==SQLITE_OK ){
53242          rc = pager_incr_changecounter(pPager, 0);
53243        }
53244      }
53245  #else
53246      rc = pager_incr_changecounter(pPager, 0);
53247  #endif
53248      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
53249
53250      /* Write the master journal name into the journal file. If a master
53251      ** journal file name has already been written to the journal file,
53252      ** or if zMaster is NULL (no master journal), then this call is a no-op.
53253      */
53254      rc = writeMasterJournal(pPager, zMaster);
53255      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
53256
53257      /* Sync the journal file and write all dirty pages to the database.
53258      ** If the atomic-update optimization is being used, this sync will not
53259      ** create the journal file or perform any real IO.
53260      **
53261      ** Because the change-counter page was just modified, unless the
53262      ** atomic-update optimization is used it is almost certain that the
53263      ** journal requires a sync here. However, in locking_mode=exclusive
53264      ** on a system under memory pressure it is just possible that this is
53265      ** not the case. In this case it is likely enough that the redundant
53266      ** xSync() call will be changed to a no-op by the OS anyhow.
53267      */
53268      rc = syncJournal(pPager, 0);
53269      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
53270
53271      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
53272      if( rc!=SQLITE_OK ){
53273        assert( rc!=SQLITE_IOERR_BLOCKED );
53274        goto commit_phase_one_exit;
53275      }
53276      sqlite3PcacheCleanAll(pPager->pPCache);
53277
53278      /* If the file on disk is smaller than the database image, use
53279      ** pager_truncate to grow the file here. This can happen if the database
53280      ** image was extended as part of the current transaction and then the
53281      ** last page in the db image moved to the free-list. In this case the
53282      ** last page is never written out to disk, leaving the database file
53283      ** undersized. Fix this now if it is the case.  */
53284      if( pPager->dbSize>pPager->dbFileSize ){
53285        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
53286        assert( pPager->eState==PAGER_WRITER_DBMOD );
53287        rc = pager_truncate(pPager, nNew);
53288        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
53289      }
53290
53291      /* Finally, sync the database file. */
53292      if( !noSync ){
53293        rc = sqlite3PagerSync(pPager, zMaster);
53294      }
53295      IOTRACE(("DBSYNC %p\n", pPager))
53296    }
53297  }
53298
53299commit_phase_one_exit:
53300  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
53301    pPager->eState = PAGER_WRITER_FINISHED;
53302  }
53303  return rc;
53304}
53305
53306
53307/*
53308** When this function is called, the database file has been completely
53309** updated to reflect the changes made by the current transaction and
53310** synced to disk. The journal file still exists in the file-system
53311** though, and if a failure occurs at this point it will eventually
53312** be used as a hot-journal and the current transaction rolled back.
53313**
53314** This function finalizes the journal file, either by deleting,
53315** truncating or partially zeroing it, so that it cannot be used
53316** for hot-journal rollback. Once this is done the transaction is
53317** irrevocably committed.
53318**
53319** If an error occurs, an IO error code is returned and the pager
53320** moves into the error state. Otherwise, SQLITE_OK is returned.
53321*/
53322SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
53323  int rc = SQLITE_OK;                  /* Return code */
53324
53325  /* This routine should not be called if a prior error has occurred.
53326  ** But if (due to a coding error elsewhere in the system) it does get
53327  ** called, just return the same error code without doing anything. */
53328  if( NEVER(pPager->errCode) ) return pPager->errCode;
53329
53330  assert( pPager->eState==PAGER_WRITER_LOCKED
53331       || pPager->eState==PAGER_WRITER_FINISHED
53332       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
53333  );
53334  assert( assert_pager_state(pPager) );
53335
53336  /* An optimization. If the database was not actually modified during
53337  ** this transaction, the pager is running in exclusive-mode and is
53338  ** using persistent journals, then this function is a no-op.
53339  **
53340  ** The start of the journal file currently contains a single journal
53341  ** header with the nRec field set to 0. If such a journal is used as
53342  ** a hot-journal during hot-journal rollback, 0 changes will be made
53343  ** to the database file. So there is no need to zero the journal
53344  ** header. Since the pager is in exclusive mode, there is no need
53345  ** to drop any locks either.
53346  */
53347  if( pPager->eState==PAGER_WRITER_LOCKED
53348   && pPager->exclusiveMode
53349   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
53350  ){
53351    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
53352    pPager->eState = PAGER_READER;
53353    return SQLITE_OK;
53354  }
53355
53356  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
53357  pPager->iDataVersion++;
53358  rc = pager_end_transaction(pPager, pPager->setMaster, 1);
53359  return pager_error(pPager, rc);
53360}
53361
53362/*
53363** If a write transaction is open, then all changes made within the
53364** transaction are reverted and the current write-transaction is closed.
53365** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
53366** state if an error occurs.
53367**
53368** If the pager is already in PAGER_ERROR state when this function is called,
53369** it returns Pager.errCode immediately. No work is performed in this case.
53370**
53371** Otherwise, in rollback mode, this function performs two functions:
53372**
53373**   1) It rolls back the journal file, restoring all database file and
53374**      in-memory cache pages to the state they were in when the transaction
53375**      was opened, and
53376**
53377**   2) It finalizes the journal file, so that it is not used for hot
53378**      rollback at any point in the future.
53379**
53380** Finalization of the journal file (task 2) is only performed if the
53381** rollback is successful.
53382**
53383** In WAL mode, all cache-entries containing data modified within the
53384** current transaction are either expelled from the cache or reverted to
53385** their pre-transaction state by re-reading data from the database or
53386** WAL files. The WAL transaction is then closed.
53387*/
53388SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
53389  int rc = SQLITE_OK;                  /* Return code */
53390  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
53391
53392  /* PagerRollback() is a no-op if called in READER or OPEN state. If
53393  ** the pager is already in the ERROR state, the rollback is not
53394  ** attempted here. Instead, the error code is returned to the caller.
53395  */
53396  assert( assert_pager_state(pPager) );
53397  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
53398  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
53399
53400  if( pagerUseWal(pPager) ){
53401    int rc2;
53402    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
53403    rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
53404    if( rc==SQLITE_OK ) rc = rc2;
53405  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
53406    int eState = pPager->eState;
53407    rc = pager_end_transaction(pPager, 0, 0);
53408    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
53409      /* This can happen using journal_mode=off. Move the pager to the error
53410      ** state to indicate that the contents of the cache may not be trusted.
53411      ** Any active readers will get SQLITE_ABORT.
53412      */
53413      pPager->errCode = SQLITE_ABORT;
53414      pPager->eState = PAGER_ERROR;
53415      setGetterMethod(pPager);
53416      return rc;
53417    }
53418  }else{
53419    rc = pager_playback(pPager, 0);
53420  }
53421
53422  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
53423  assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
53424          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
53425          || rc==SQLITE_CANTOPEN
53426  );
53427
53428  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
53429  ** cache. So call pager_error() on the way out to make any error persistent.
53430  */
53431  return pager_error(pPager, rc);
53432}
53433
53434/*
53435** Return TRUE if the database file is opened read-only.  Return FALSE
53436** if the database is (in theory) writable.
53437*/
53438SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
53439  return pPager->readOnly;
53440}
53441
53442#ifdef SQLITE_DEBUG
53443/*
53444** Return the sum of the reference counts for all pages held by pPager.
53445*/
53446SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
53447  return sqlite3PcacheRefCount(pPager->pPCache);
53448}
53449#endif
53450
53451/*
53452** Return the approximate number of bytes of memory currently
53453** used by the pager and its associated cache.
53454*/
53455SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
53456  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
53457                                     + 5*sizeof(void*);
53458  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
53459           + sqlite3MallocSize(pPager)
53460           + pPager->pageSize;
53461}
53462
53463/*
53464** Return the number of references to the specified page.
53465*/
53466SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
53467  return sqlite3PcachePageRefcount(pPage);
53468}
53469
53470#ifdef SQLITE_TEST
53471/*
53472** This routine is used for testing and analysis only.
53473*/
53474SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
53475  static int a[11];
53476  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
53477  a[1] = sqlite3PcachePagecount(pPager->pPCache);
53478  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
53479  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
53480  a[4] = pPager->eState;
53481  a[5] = pPager->errCode;
53482  a[6] = pPager->aStat[PAGER_STAT_HIT];
53483  a[7] = pPager->aStat[PAGER_STAT_MISS];
53484  a[8] = 0;  /* Used to be pPager->nOvfl */
53485  a[9] = pPager->nRead;
53486  a[10] = pPager->aStat[PAGER_STAT_WRITE];
53487  return a;
53488}
53489#endif
53490
53491/*
53492** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
53493** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
53494** current cache hit or miss count, according to the value of eStat. If the
53495** reset parameter is non-zero, the cache hit or miss count is zeroed before
53496** returning.
53497*/
53498SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
53499
53500  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
53501       || eStat==SQLITE_DBSTATUS_CACHE_MISS
53502       || eStat==SQLITE_DBSTATUS_CACHE_WRITE
53503  );
53504
53505  assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
53506  assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
53507  assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
53508
53509  *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
53510  if( reset ){
53511    pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
53512  }
53513}
53514
53515/*
53516** Return true if this is an in-memory or temp-file backed pager.
53517*/
53518SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
53519  return pPager->tempFile;
53520}
53521
53522/*
53523** Check that there are at least nSavepoint savepoints open. If there are
53524** currently less than nSavepoints open, then open one or more savepoints
53525** to make up the difference. If the number of savepoints is already
53526** equal to nSavepoint, then this function is a no-op.
53527**
53528** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
53529** occurs while opening the sub-journal file, then an IO error code is
53530** returned. Otherwise, SQLITE_OK.
53531*/
53532static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
53533  int rc = SQLITE_OK;                       /* Return code */
53534  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
53535  int ii;                                   /* Iterator variable */
53536  PagerSavepoint *aNew;                     /* New Pager.aSavepoint array */
53537
53538  assert( pPager->eState>=PAGER_WRITER_LOCKED );
53539  assert( assert_pager_state(pPager) );
53540  assert( nSavepoint>nCurrent && pPager->useJournal );
53541
53542  /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
53543  ** if the allocation fails. Otherwise, zero the new portion in case a
53544  ** malloc failure occurs while populating it in the for(...) loop below.
53545  */
53546  aNew = (PagerSavepoint *)sqlite3Realloc(
53547      pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
53548  );
53549  if( !aNew ){
53550    return SQLITE_NOMEM_BKPT;
53551  }
53552  memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
53553  pPager->aSavepoint = aNew;
53554
53555  /* Populate the PagerSavepoint structures just allocated. */
53556  for(ii=nCurrent; ii<nSavepoint; ii++){
53557    aNew[ii].nOrig = pPager->dbSize;
53558    if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
53559      aNew[ii].iOffset = pPager->journalOff;
53560    }else{
53561      aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
53562    }
53563    aNew[ii].iSubRec = pPager->nSubRec;
53564    aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
53565    if( !aNew[ii].pInSavepoint ){
53566      return SQLITE_NOMEM_BKPT;
53567    }
53568    if( pagerUseWal(pPager) ){
53569      sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
53570    }
53571    pPager->nSavepoint = ii+1;
53572  }
53573  assert( pPager->nSavepoint==nSavepoint );
53574  assertTruncateConstraint(pPager);
53575  return rc;
53576}
53577SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
53578  assert( pPager->eState>=PAGER_WRITER_LOCKED );
53579  assert( assert_pager_state(pPager) );
53580
53581  if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
53582    return pagerOpenSavepoint(pPager, nSavepoint);
53583  }else{
53584    return SQLITE_OK;
53585  }
53586}
53587
53588
53589/*
53590** This function is called to rollback or release (commit) a savepoint.
53591** The savepoint to release or rollback need not be the most recently
53592** created savepoint.
53593**
53594** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
53595** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
53596** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
53597** that have occurred since the specified savepoint was created.
53598**
53599** The savepoint to rollback or release is identified by parameter
53600** iSavepoint. A value of 0 means to operate on the outermost savepoint
53601** (the first created). A value of (Pager.nSavepoint-1) means operate
53602** on the most recently created savepoint. If iSavepoint is greater than
53603** (Pager.nSavepoint-1), then this function is a no-op.
53604**
53605** If a negative value is passed to this function, then the current
53606** transaction is rolled back. This is different to calling
53607** sqlite3PagerRollback() because this function does not terminate
53608** the transaction or unlock the database, it just restores the
53609** contents of the database to its original state.
53610**
53611** In any case, all savepoints with an index greater than iSavepoint
53612** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
53613** then savepoint iSavepoint is also destroyed.
53614**
53615** This function may return SQLITE_NOMEM if a memory allocation fails,
53616** or an IO error code if an IO error occurs while rolling back a
53617** savepoint. If no errors occur, SQLITE_OK is returned.
53618*/
53619SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
53620  int rc = pPager->errCode;
53621
53622#ifdef SQLITE_ENABLE_ZIPVFS
53623  if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
53624#endif
53625
53626  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
53627  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
53628
53629  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
53630    int ii;            /* Iterator variable */
53631    int nNew;          /* Number of remaining savepoints after this op. */
53632
53633    /* Figure out how many savepoints will still be active after this
53634    ** operation. Store this value in nNew. Then free resources associated
53635    ** with any savepoints that are destroyed by this operation.
53636    */
53637    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
53638    for(ii=nNew; ii<pPager->nSavepoint; ii++){
53639      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
53640    }
53641    pPager->nSavepoint = nNew;
53642
53643    /* If this is a release of the outermost savepoint, truncate
53644    ** the sub-journal to zero bytes in size. */
53645    if( op==SAVEPOINT_RELEASE ){
53646      if( nNew==0 && isOpen(pPager->sjfd) ){
53647        /* Only truncate if it is an in-memory sub-journal. */
53648        if( sqlite3JournalIsInMemory(pPager->sjfd) ){
53649          rc = sqlite3OsTruncate(pPager->sjfd, 0);
53650          assert( rc==SQLITE_OK );
53651        }
53652        pPager->nSubRec = 0;
53653      }
53654    }
53655    /* Else this is a rollback operation, playback the specified savepoint.
53656    ** If this is a temp-file, it is possible that the journal file has
53657    ** not yet been opened. In this case there have been no changes to
53658    ** the database file, so the playback operation can be skipped.
53659    */
53660    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
53661      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
53662      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
53663      assert(rc!=SQLITE_DONE);
53664    }
53665
53666#ifdef SQLITE_ENABLE_ZIPVFS
53667    /* If the cache has been modified but the savepoint cannot be rolled
53668    ** back journal_mode=off, put the pager in the error state. This way,
53669    ** if the VFS used by this pager includes ZipVFS, the entire transaction
53670    ** can be rolled back at the ZipVFS level.  */
53671    else if(
53672        pPager->journalMode==PAGER_JOURNALMODE_OFF
53673     && pPager->eState>=PAGER_WRITER_CACHEMOD
53674    ){
53675      pPager->errCode = SQLITE_ABORT;
53676      pPager->eState = PAGER_ERROR;
53677      setGetterMethod(pPager);
53678    }
53679#endif
53680  }
53681
53682  return rc;
53683}
53684
53685/*
53686** Return the full pathname of the database file.
53687**
53688** Except, if the pager is in-memory only, then return an empty string if
53689** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
53690** used to report the filename to the user, for compatibility with legacy
53691** behavior.  But when the Btree needs to know the filename for matching to
53692** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
53693** participate in shared-cache.
53694*/
53695SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
53696  return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
53697}
53698
53699/*
53700** Return the VFS structure for the pager.
53701*/
53702SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
53703  return pPager->pVfs;
53704}
53705
53706/*
53707** Return the file handle for the database file associated
53708** with the pager.  This might return NULL if the file has
53709** not yet been opened.
53710*/
53711SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
53712  return pPager->fd;
53713}
53714
53715/*
53716** Return the file handle for the journal file (if it exists).
53717** This will be either the rollback journal or the WAL file.
53718*/
53719SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
53720#if SQLITE_OMIT_WAL
53721  return pPager->jfd;
53722#else
53723  return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
53724#endif
53725}
53726
53727/*
53728** Return the full pathname of the journal file.
53729*/
53730SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
53731  return pPager->zJournal;
53732}
53733
53734#ifdef SQLITE_HAS_CODEC
53735/*
53736** Set or retrieve the codec for this pager
53737*/
53738SQLITE_PRIVATE void sqlite3PagerSetCodec(
53739  Pager *pPager,
53740  void *(*xCodec)(void*,void*,Pgno,int),
53741  void (*xCodecSizeChng)(void*,int,int),
53742  void (*xCodecFree)(void*),
53743  void *pCodec
53744){
53745  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
53746  pPager->xCodec = pPager->memDb ? 0 : xCodec;
53747  pPager->xCodecSizeChng = xCodecSizeChng;
53748  pPager->xCodecFree = xCodecFree;
53749  pPager->pCodec = pCodec;
53750  setGetterMethod(pPager);
53751  pagerReportSize(pPager);
53752}
53753SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
53754  return pPager->pCodec;
53755}
53756
53757/*
53758** This function is called by the wal module when writing page content
53759** into the log file.
53760**
53761** This function returns a pointer to a buffer containing the encrypted
53762** page content. If a malloc fails, this function may return NULL.
53763*/
53764SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
53765  void *aData = 0;
53766  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
53767  return aData;
53768}
53769
53770/*
53771** Return the current pager state
53772*/
53773SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
53774  return pPager->eState;
53775}
53776#endif /* SQLITE_HAS_CODEC */
53777
53778#ifndef SQLITE_OMIT_AUTOVACUUM
53779/*
53780** Move the page pPg to location pgno in the file.
53781**
53782** There must be no references to the page previously located at
53783** pgno (which we call pPgOld) though that page is allowed to be
53784** in cache.  If the page previously located at pgno is not already
53785** in the rollback journal, it is not put there by by this routine.
53786**
53787** References to the page pPg remain valid. Updating any
53788** meta-data associated with pPg (i.e. data stored in the nExtra bytes
53789** allocated along with the page) is the responsibility of the caller.
53790**
53791** A transaction must be active when this routine is called. It used to be
53792** required that a statement transaction was not active, but this restriction
53793** has been removed (CREATE INDEX needs to move a page when a statement
53794** transaction is active).
53795**
53796** If the fourth argument, isCommit, is non-zero, then this page is being
53797** moved as part of a database reorganization just before the transaction
53798** is being committed. In this case, it is guaranteed that the database page
53799** pPg refers to will not be written to again within this transaction.
53800**
53801** This function may return SQLITE_NOMEM or an IO error code if an error
53802** occurs. Otherwise, it returns SQLITE_OK.
53803*/
53804SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
53805  PgHdr *pPgOld;               /* The page being overwritten. */
53806  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
53807  int rc;                      /* Return code */
53808  Pgno origPgno;               /* The original page number */
53809
53810  assert( pPg->nRef>0 );
53811  assert( pPager->eState==PAGER_WRITER_CACHEMOD
53812       || pPager->eState==PAGER_WRITER_DBMOD
53813  );
53814  assert( assert_pager_state(pPager) );
53815
53816  /* In order to be able to rollback, an in-memory database must journal
53817  ** the page we are moving from.
53818  */
53819  assert( pPager->tempFile || !MEMDB );
53820  if( pPager->tempFile ){
53821    rc = sqlite3PagerWrite(pPg);
53822    if( rc ) return rc;
53823  }
53824
53825  /* If the page being moved is dirty and has not been saved by the latest
53826  ** savepoint, then save the current contents of the page into the
53827  ** sub-journal now. This is required to handle the following scenario:
53828  **
53829  **   BEGIN;
53830  **     <journal page X, then modify it in memory>
53831  **     SAVEPOINT one;
53832  **       <Move page X to location Y>
53833  **     ROLLBACK TO one;
53834  **
53835  ** If page X were not written to the sub-journal here, it would not
53836  ** be possible to restore its contents when the "ROLLBACK TO one"
53837  ** statement were is processed.
53838  **
53839  ** subjournalPage() may need to allocate space to store pPg->pgno into
53840  ** one or more savepoint bitvecs. This is the reason this function
53841  ** may return SQLITE_NOMEM.
53842  */
53843  if( (pPg->flags & PGHDR_DIRTY)!=0
53844   && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
53845  ){
53846    return rc;
53847  }
53848
53849  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
53850      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
53851  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
53852
53853  /* If the journal needs to be sync()ed before page pPg->pgno can
53854  ** be written to, store pPg->pgno in local variable needSyncPgno.
53855  **
53856  ** If the isCommit flag is set, there is no need to remember that
53857  ** the journal needs to be sync()ed before database page pPg->pgno
53858  ** can be written to. The caller has already promised not to write to it.
53859  */
53860  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
53861    needSyncPgno = pPg->pgno;
53862    assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
53863            pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
53864    assert( pPg->flags&PGHDR_DIRTY );
53865  }
53866
53867  /* If the cache contains a page with page-number pgno, remove it
53868  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
53869  ** page pgno before the 'move' operation, it needs to be retained
53870  ** for the page moved there.
53871  */
53872  pPg->flags &= ~PGHDR_NEED_SYNC;
53873  pPgOld = sqlite3PagerLookup(pPager, pgno);
53874  assert( !pPgOld || pPgOld->nRef==1 );
53875  if( pPgOld ){
53876    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
53877    if( pPager->tempFile ){
53878      /* Do not discard pages from an in-memory database since we might
53879      ** need to rollback later.  Just move the page out of the way. */
53880      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
53881    }else{
53882      sqlite3PcacheDrop(pPgOld);
53883    }
53884  }
53885
53886  origPgno = pPg->pgno;
53887  sqlite3PcacheMove(pPg, pgno);
53888  sqlite3PcacheMakeDirty(pPg);
53889
53890  /* For an in-memory database, make sure the original page continues
53891  ** to exist, in case the transaction needs to roll back.  Use pPgOld
53892  ** as the original page since it has already been allocated.
53893  */
53894  if( pPager->tempFile && pPgOld ){
53895    sqlite3PcacheMove(pPgOld, origPgno);
53896    sqlite3PagerUnrefNotNull(pPgOld);
53897  }
53898
53899  if( needSyncPgno ){
53900    /* If needSyncPgno is non-zero, then the journal file needs to be
53901    ** sync()ed before any data is written to database file page needSyncPgno.
53902    ** Currently, no such page exists in the page-cache and the
53903    ** "is journaled" bitvec flag has been set. This needs to be remedied by
53904    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
53905    ** flag.
53906    **
53907    ** If the attempt to load the page into the page-cache fails, (due
53908    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
53909    ** array. Otherwise, if the page is loaded and written again in
53910    ** this transaction, it may be written to the database file before
53911    ** it is synced into the journal file. This way, it may end up in
53912    ** the journal file twice, but that is not a problem.
53913    */
53914    PgHdr *pPgHdr;
53915    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
53916    if( rc!=SQLITE_OK ){
53917      if( needSyncPgno<=pPager->dbOrigSize ){
53918        assert( pPager->pTmpSpace!=0 );
53919        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
53920      }
53921      return rc;
53922    }
53923    pPgHdr->flags |= PGHDR_NEED_SYNC;
53924    sqlite3PcacheMakeDirty(pPgHdr);
53925    sqlite3PagerUnrefNotNull(pPgHdr);
53926  }
53927
53928  return SQLITE_OK;
53929}
53930#endif
53931
53932/*
53933** The page handle passed as the first argument refers to a dirty page
53934** with a page number other than iNew. This function changes the page's
53935** page number to iNew and sets the value of the PgHdr.flags field to
53936** the value passed as the third parameter.
53937*/
53938SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
53939  assert( pPg->pgno!=iNew );
53940  pPg->flags = flags;
53941  sqlite3PcacheMove(pPg, iNew);
53942}
53943
53944/*
53945** Return a pointer to the data for the specified page.
53946*/
53947SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
53948  assert( pPg->nRef>0 || pPg->pPager->memDb );
53949  return pPg->pData;
53950}
53951
53952/*
53953** Return a pointer to the Pager.nExtra bytes of "extra" space
53954** allocated along with the specified page.
53955*/
53956SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
53957  return pPg->pExtra;
53958}
53959
53960/*
53961** Get/set the locking-mode for this pager. Parameter eMode must be one
53962** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
53963** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
53964** the locking-mode is set to the value specified.
53965**
53966** The returned value is either PAGER_LOCKINGMODE_NORMAL or
53967** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
53968** locking-mode.
53969*/
53970SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
53971  assert( eMode==PAGER_LOCKINGMODE_QUERY
53972            || eMode==PAGER_LOCKINGMODE_NORMAL
53973            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
53974  assert( PAGER_LOCKINGMODE_QUERY<0 );
53975  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
53976  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
53977  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
53978    pPager->exclusiveMode = (u8)eMode;
53979  }
53980  return (int)pPager->exclusiveMode;
53981}
53982
53983/*
53984** Set the journal-mode for this pager. Parameter eMode must be one of:
53985**
53986**    PAGER_JOURNALMODE_DELETE
53987**    PAGER_JOURNALMODE_TRUNCATE
53988**    PAGER_JOURNALMODE_PERSIST
53989**    PAGER_JOURNALMODE_OFF
53990**    PAGER_JOURNALMODE_MEMORY
53991**    PAGER_JOURNALMODE_WAL
53992**
53993** The journalmode is set to the value specified if the change is allowed.
53994** The change may be disallowed for the following reasons:
53995**
53996**   *  An in-memory database can only have its journal_mode set to _OFF
53997**      or _MEMORY.
53998**
53999**   *  Temporary databases cannot have _WAL journalmode.
54000**
54001** The returned indicate the current (possibly updated) journal-mode.
54002*/
54003SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
54004  u8 eOld = pPager->journalMode;    /* Prior journalmode */
54005
54006#ifdef SQLITE_DEBUG
54007  /* The print_pager_state() routine is intended to be used by the debugger
54008  ** only.  We invoke it once here to suppress a compiler warning. */
54009  print_pager_state(pPager);
54010#endif
54011
54012
54013  /* The eMode parameter is always valid */
54014  assert(      eMode==PAGER_JOURNALMODE_DELETE
54015            || eMode==PAGER_JOURNALMODE_TRUNCATE
54016            || eMode==PAGER_JOURNALMODE_PERSIST
54017            || eMode==PAGER_JOURNALMODE_OFF
54018            || eMode==PAGER_JOURNALMODE_WAL
54019            || eMode==PAGER_JOURNALMODE_MEMORY );
54020
54021  /* This routine is only called from the OP_JournalMode opcode, and
54022  ** the logic there will never allow a temporary file to be changed
54023  ** to WAL mode.
54024  */
54025  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
54026
54027  /* Do allow the journalmode of an in-memory database to be set to
54028  ** anything other than MEMORY or OFF
54029  */
54030  if( MEMDB ){
54031    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
54032    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
54033      eMode = eOld;
54034    }
54035  }
54036
54037  if( eMode!=eOld ){
54038
54039    /* Change the journal mode. */
54040    assert( pPager->eState!=PAGER_ERROR );
54041    pPager->journalMode = (u8)eMode;
54042
54043    /* When transistioning from TRUNCATE or PERSIST to any other journal
54044    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
54045    ** delete the journal file.
54046    */
54047    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
54048    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
54049    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
54050    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
54051    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
54052    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
54053
54054    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
54055    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
54056
54057      /* In this case we would like to delete the journal file. If it is
54058      ** not possible, then that is not a problem. Deleting the journal file
54059      ** here is an optimization only.
54060      **
54061      ** Before deleting the journal file, obtain a RESERVED lock on the
54062      ** database file. This ensures that the journal file is not deleted
54063      ** while it is in use by some other client.
54064      */
54065      sqlite3OsClose(pPager->jfd);
54066      if( pPager->eLock>=RESERVED_LOCK ){
54067        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
54068      }else{
54069        int rc = SQLITE_OK;
54070        int state = pPager->eState;
54071        assert( state==PAGER_OPEN || state==PAGER_READER );
54072        if( state==PAGER_OPEN ){
54073          rc = sqlite3PagerSharedLock(pPager);
54074        }
54075        if( pPager->eState==PAGER_READER ){
54076          assert( rc==SQLITE_OK );
54077          rc = pagerLockDb(pPager, RESERVED_LOCK);
54078        }
54079        if( rc==SQLITE_OK ){
54080          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
54081        }
54082        if( rc==SQLITE_OK && state==PAGER_READER ){
54083          pagerUnlockDb(pPager, SHARED_LOCK);
54084        }else if( state==PAGER_OPEN ){
54085          pager_unlock(pPager);
54086        }
54087        assert( state==pPager->eState );
54088      }
54089    }else if( eMode==PAGER_JOURNALMODE_OFF ){
54090      sqlite3OsClose(pPager->jfd);
54091    }
54092  }
54093
54094  /* Return the new journal mode */
54095  return (int)pPager->journalMode;
54096}
54097
54098/*
54099** Return the current journal mode.
54100*/
54101SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
54102  return (int)pPager->journalMode;
54103}
54104
54105/*
54106** Return TRUE if the pager is in a state where it is OK to change the
54107** journalmode.  Journalmode changes can only happen when the database
54108** is unmodified.
54109*/
54110SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
54111  assert( assert_pager_state(pPager) );
54112  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
54113  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
54114  return 1;
54115}
54116
54117/*
54118** Get/set the size-limit used for persistent journal files.
54119**
54120** Setting the size limit to -1 means no limit is enforced.
54121** An attempt to set a limit smaller than -1 is a no-op.
54122*/
54123SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
54124  if( iLimit>=-1 ){
54125    pPager->journalSizeLimit = iLimit;
54126    sqlite3WalLimit(pPager->pWal, iLimit);
54127  }
54128  return pPager->journalSizeLimit;
54129}
54130
54131/*
54132** Return a pointer to the pPager->pBackup variable. The backup module
54133** in backup.c maintains the content of this variable. This module
54134** uses it opaquely as an argument to sqlite3BackupRestart() and
54135** sqlite3BackupUpdate() only.
54136*/
54137SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
54138  return &pPager->pBackup;
54139}
54140
54141#ifndef SQLITE_OMIT_VACUUM
54142/*
54143** Unless this is an in-memory or temporary database, clear the pager cache.
54144*/
54145SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
54146  assert( MEMDB==0 || pPager->tempFile );
54147  if( pPager->tempFile==0 ) pager_reset(pPager);
54148}
54149#endif
54150
54151
54152#ifndef SQLITE_OMIT_WAL
54153/*
54154** This function is called when the user invokes "PRAGMA wal_checkpoint",
54155** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
54156** or wal_blocking_checkpoint() API functions.
54157**
54158** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
54159*/
54160SQLITE_PRIVATE int sqlite3PagerCheckpoint(
54161  Pager *pPager,                  /* Checkpoint on this pager */
54162  sqlite3 *db,                    /* Db handle used to check for interrupts */
54163  int eMode,                      /* Type of checkpoint */
54164  int *pnLog,                     /* OUT: Final number of frames in log */
54165  int *pnCkpt                     /* OUT: Final number of checkpointed frames */
54166){
54167  int rc = SQLITE_OK;
54168  if( pPager->pWal ){
54169    rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
54170        (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
54171        pPager->pBusyHandlerArg,
54172        pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
54173        pnLog, pnCkpt
54174    );
54175  }
54176  return rc;
54177}
54178
54179SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
54180  return sqlite3WalCallback(pPager->pWal);
54181}
54182
54183/*
54184** Return true if the underlying VFS for the given pager supports the
54185** primitives necessary for write-ahead logging.
54186*/
54187SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
54188  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
54189  if( pPager->noLock ) return 0;
54190  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
54191}
54192
54193/*
54194** Attempt to take an exclusive lock on the database file. If a PENDING lock
54195** is obtained instead, immediately release it.
54196*/
54197static int pagerExclusiveLock(Pager *pPager){
54198  int rc;                         /* Return code */
54199
54200  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
54201  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
54202  if( rc!=SQLITE_OK ){
54203    /* If the attempt to grab the exclusive lock failed, release the
54204    ** pending lock that may have been obtained instead.  */
54205    pagerUnlockDb(pPager, SHARED_LOCK);
54206  }
54207
54208  return rc;
54209}
54210
54211/*
54212** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
54213** exclusive-locking mode when this function is called, take an EXCLUSIVE
54214** lock on the database file and use heap-memory to store the wal-index
54215** in. Otherwise, use the normal shared-memory.
54216*/
54217static int pagerOpenWal(Pager *pPager){
54218  int rc = SQLITE_OK;
54219
54220  assert( pPager->pWal==0 && pPager->tempFile==0 );
54221  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
54222
54223  /* If the pager is already in exclusive-mode, the WAL module will use
54224  ** heap-memory for the wal-index instead of the VFS shared-memory
54225  ** implementation. Take the exclusive lock now, before opening the WAL
54226  ** file, to make sure this is safe.
54227  */
54228  if( pPager->exclusiveMode ){
54229    rc = pagerExclusiveLock(pPager);
54230  }
54231
54232  /* Open the connection to the log file. If this operation fails,
54233  ** (e.g. due to malloc() failure), return an error code.
54234  */
54235  if( rc==SQLITE_OK ){
54236    rc = sqlite3WalOpen(pPager->pVfs,
54237        pPager->fd, pPager->zWal, pPager->exclusiveMode,
54238        pPager->journalSizeLimit, &pPager->pWal
54239    );
54240  }
54241  pagerFixMaplimit(pPager);
54242
54243  return rc;
54244}
54245
54246
54247/*
54248** The caller must be holding a SHARED lock on the database file to call
54249** this function.
54250**
54251** If the pager passed as the first argument is open on a real database
54252** file (not a temp file or an in-memory database), and the WAL file
54253** is not already open, make an attempt to open it now. If successful,
54254** return SQLITE_OK. If an error occurs or the VFS used by the pager does
54255** not support the xShmXXX() methods, return an error code. *pbOpen is
54256** not modified in either case.
54257**
54258** If the pager is open on a temp-file (or in-memory database), or if
54259** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
54260** without doing anything.
54261*/
54262SQLITE_PRIVATE int sqlite3PagerOpenWal(
54263  Pager *pPager,                  /* Pager object */
54264  int *pbOpen                     /* OUT: Set to true if call is a no-op */
54265){
54266  int rc = SQLITE_OK;             /* Return code */
54267
54268  assert( assert_pager_state(pPager) );
54269  assert( pPager->eState==PAGER_OPEN   || pbOpen );
54270  assert( pPager->eState==PAGER_READER || !pbOpen );
54271  assert( pbOpen==0 || *pbOpen==0 );
54272  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
54273
54274  if( !pPager->tempFile && !pPager->pWal ){
54275    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
54276
54277    /* Close any rollback journal previously open */
54278    sqlite3OsClose(pPager->jfd);
54279
54280    rc = pagerOpenWal(pPager);
54281    if( rc==SQLITE_OK ){
54282      pPager->journalMode = PAGER_JOURNALMODE_WAL;
54283      pPager->eState = PAGER_OPEN;
54284    }
54285  }else{
54286    *pbOpen = 1;
54287  }
54288
54289  return rc;
54290}
54291
54292/*
54293** This function is called to close the connection to the log file prior
54294** to switching from WAL to rollback mode.
54295**
54296** Before closing the log file, this function attempts to take an
54297** EXCLUSIVE lock on the database file. If this cannot be obtained, an
54298** error (SQLITE_BUSY) is returned and the log connection is not closed.
54299** If successful, the EXCLUSIVE lock is not released before returning.
54300*/
54301SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
54302  int rc = SQLITE_OK;
54303
54304  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
54305
54306  /* If the log file is not already open, but does exist in the file-system,
54307  ** it may need to be checkpointed before the connection can switch to
54308  ** rollback mode. Open it now so this can happen.
54309  */
54310  if( !pPager->pWal ){
54311    int logexists = 0;
54312    rc = pagerLockDb(pPager, SHARED_LOCK);
54313    if( rc==SQLITE_OK ){
54314      rc = sqlite3OsAccess(
54315          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
54316      );
54317    }
54318    if( rc==SQLITE_OK && logexists ){
54319      rc = pagerOpenWal(pPager);
54320    }
54321  }
54322
54323  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
54324  ** the database file, the log and log-summary files will be deleted.
54325  */
54326  if( rc==SQLITE_OK && pPager->pWal ){
54327    rc = pagerExclusiveLock(pPager);
54328    if( rc==SQLITE_OK ){
54329      rc = sqlite3WalClose(pPager->pWal, db, pPager->ckptSyncFlags,
54330                           pPager->pageSize, (u8*)pPager->pTmpSpace);
54331      pPager->pWal = 0;
54332      pagerFixMaplimit(pPager);
54333      if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
54334    }
54335  }
54336  return rc;
54337}
54338
54339#ifdef SQLITE_ENABLE_SNAPSHOT
54340/*
54341** If this is a WAL database, obtain a snapshot handle for the snapshot
54342** currently open. Otherwise, return an error.
54343*/
54344SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
54345  int rc = SQLITE_ERROR;
54346  if( pPager->pWal ){
54347    rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
54348  }
54349  return rc;
54350}
54351
54352/*
54353** If this is a WAL database, store a pointer to pSnapshot. Next time a
54354** read transaction is opened, attempt to read from the snapshot it
54355** identifies. If this is not a WAL database, return an error.
54356*/
54357SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
54358  int rc = SQLITE_OK;
54359  if( pPager->pWal ){
54360    sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
54361  }else{
54362    rc = SQLITE_ERROR;
54363  }
54364  return rc;
54365}
54366
54367/*
54368** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
54369** is not a WAL database, return an error.
54370*/
54371SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
54372  int rc;
54373  if( pPager->pWal ){
54374    rc = sqlite3WalSnapshotRecover(pPager->pWal);
54375  }else{
54376    rc = SQLITE_ERROR;
54377  }
54378  return rc;
54379}
54380#endif /* SQLITE_ENABLE_SNAPSHOT */
54381#endif /* !SQLITE_OMIT_WAL */
54382
54383#ifdef SQLITE_ENABLE_ZIPVFS
54384/*
54385** A read-lock must be held on the pager when this function is called. If
54386** the pager is in WAL mode and the WAL file currently contains one or more
54387** frames, return the size in bytes of the page images stored within the
54388** WAL frames. Otherwise, if this is not a WAL database or the WAL file
54389** is empty, return 0.
54390*/
54391SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
54392  assert( pPager->eState>=PAGER_READER );
54393  return sqlite3WalFramesize(pPager->pWal);
54394}
54395#endif
54396
54397#endif /* SQLITE_OMIT_DISKIO */
54398
54399/************** End of pager.c ***********************************************/
54400/************** Begin file wal.c *********************************************/
54401/*
54402** 2010 February 1
54403**
54404** The author disclaims copyright to this source code.  In place of
54405** a legal notice, here is a blessing:
54406**
54407**    May you do good and not evil.
54408**    May you find forgiveness for yourself and forgive others.
54409**    May you share freely, never taking more than you give.
54410**
54411*************************************************************************
54412**
54413** This file contains the implementation of a write-ahead log (WAL) used in
54414** "journal_mode=WAL" mode.
54415**
54416** WRITE-AHEAD LOG (WAL) FILE FORMAT
54417**
54418** A WAL file consists of a header followed by zero or more "frames".
54419** Each frame records the revised content of a single page from the
54420** database file.  All changes to the database are recorded by writing
54421** frames into the WAL.  Transactions commit when a frame is written that
54422** contains a commit marker.  A single WAL can and usually does record
54423** multiple transactions.  Periodically, the content of the WAL is
54424** transferred back into the database file in an operation called a
54425** "checkpoint".
54426**
54427** A single WAL file can be used multiple times.  In other words, the
54428** WAL can fill up with frames and then be checkpointed and then new
54429** frames can overwrite the old ones.  A WAL always grows from beginning
54430** toward the end.  Checksums and counters attached to each frame are
54431** used to determine which frames within the WAL are valid and which
54432** are leftovers from prior checkpoints.
54433**
54434** The WAL header is 32 bytes in size and consists of the following eight
54435** big-endian 32-bit unsigned integer values:
54436**
54437**     0: Magic number.  0x377f0682 or 0x377f0683
54438**     4: File format version.  Currently 3007000
54439**     8: Database page size.  Example: 1024
54440**    12: Checkpoint sequence number
54441**    16: Salt-1, random integer incremented with each checkpoint
54442**    20: Salt-2, a different random integer changing with each ckpt
54443**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
54444**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
54445**
54446** Immediately following the wal-header are zero or more frames. Each
54447** frame consists of a 24-byte frame-header followed by a <page-size> bytes
54448** of page data. The frame-header is six big-endian 32-bit unsigned
54449** integer values, as follows:
54450**
54451**     0: Page number.
54452**     4: For commit records, the size of the database image in pages
54453**        after the commit. For all other records, zero.
54454**     8: Salt-1 (copied from the header)
54455**    12: Salt-2 (copied from the header)
54456**    16: Checksum-1.
54457**    20: Checksum-2.
54458**
54459** A frame is considered valid if and only if the following conditions are
54460** true:
54461**
54462**    (1) The salt-1 and salt-2 values in the frame-header match
54463**        salt values in the wal-header
54464**
54465**    (2) The checksum values in the final 8 bytes of the frame-header
54466**        exactly match the checksum computed consecutively on the
54467**        WAL header and the first 8 bytes and the content of all frames
54468**        up to and including the current frame.
54469**
54470** The checksum is computed using 32-bit big-endian integers if the
54471** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
54472** is computed using little-endian if the magic number is 0x377f0682.
54473** The checksum values are always stored in the frame header in a
54474** big-endian format regardless of which byte order is used to compute
54475** the checksum.  The checksum is computed by interpreting the input as
54476** an even number of unsigned 32-bit integers: x[0] through x[N].  The
54477** algorithm used for the checksum is as follows:
54478**
54479**   for i from 0 to n-1 step 2:
54480**     s0 += x[i] + s1;
54481**     s1 += x[i+1] + s0;
54482**   endfor
54483**
54484** Note that s0 and s1 are both weighted checksums using fibonacci weights
54485** in reverse order (the largest fibonacci weight occurs on the first element
54486** of the sequence being summed.)  The s1 value spans all 32-bit
54487** terms of the sequence whereas s0 omits the final term.
54488**
54489** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
54490** WAL is transferred into the database, then the database is VFS.xSync-ed.
54491** The VFS.xSync operations serve as write barriers - all writes launched
54492** before the xSync must complete before any write that launches after the
54493** xSync begins.
54494**
54495** After each checkpoint, the salt-1 value is incremented and the salt-2
54496** value is randomized.  This prevents old and new frames in the WAL from
54497** being considered valid at the same time and being checkpointing together
54498** following a crash.
54499**
54500** READER ALGORITHM
54501**
54502** To read a page from the database (call it page number P), a reader
54503** first checks the WAL to see if it contains page P.  If so, then the
54504** last valid instance of page P that is a followed by a commit frame
54505** or is a commit frame itself becomes the value read.  If the WAL
54506** contains no copies of page P that are valid and which are a commit
54507** frame or are followed by a commit frame, then page P is read from
54508** the database file.
54509**
54510** To start a read transaction, the reader records the index of the last
54511** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
54512** for all subsequent read operations.  New transactions can be appended
54513** to the WAL, but as long as the reader uses its original mxFrame value
54514** and ignores the newly appended content, it will see a consistent snapshot
54515** of the database from a single point in time.  This technique allows
54516** multiple concurrent readers to view different versions of the database
54517** content simultaneously.
54518**
54519** The reader algorithm in the previous paragraphs works correctly, but
54520** because frames for page P can appear anywhere within the WAL, the
54521** reader has to scan the entire WAL looking for page P frames.  If the
54522** WAL is large (multiple megabytes is typical) that scan can be slow,
54523** and read performance suffers.  To overcome this problem, a separate
54524** data structure called the wal-index is maintained to expedite the
54525** search for frames of a particular page.
54526**
54527** WAL-INDEX FORMAT
54528**
54529** Conceptually, the wal-index is shared memory, though VFS implementations
54530** might choose to implement the wal-index using a mmapped file.  Because
54531** the wal-index is shared memory, SQLite does not support journal_mode=WAL
54532** on a network filesystem.  All users of the database must be able to
54533** share memory.
54534**
54535** The wal-index is transient.  After a crash, the wal-index can (and should
54536** be) reconstructed from the original WAL file.  In fact, the VFS is required
54537** to either truncate or zero the header of the wal-index when the last
54538** connection to it closes.  Because the wal-index is transient, it can
54539** use an architecture-specific format; it does not have to be cross-platform.
54540** Hence, unlike the database and WAL file formats which store all values
54541** as big endian, the wal-index can store multi-byte values in the native
54542** byte order of the host computer.
54543**
54544** The purpose of the wal-index is to answer this question quickly:  Given
54545** a page number P and a maximum frame index M, return the index of the
54546** last frame in the wal before frame M for page P in the WAL, or return
54547** NULL if there are no frames for page P in the WAL prior to M.
54548**
54549** The wal-index consists of a header region, followed by an one or
54550** more index blocks.
54551**
54552** The wal-index header contains the total number of frames within the WAL
54553** in the mxFrame field.
54554**
54555** Each index block except for the first contains information on
54556** HASHTABLE_NPAGE frames. The first index block contains information on
54557** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
54558** HASHTABLE_NPAGE are selected so that together the wal-index header and
54559** first index block are the same size as all other index blocks in the
54560** wal-index.
54561**
54562** Each index block contains two sections, a page-mapping that contains the
54563** database page number associated with each wal frame, and a hash-table
54564** that allows readers to query an index block for a specific page number.
54565** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
54566** for the first index block) 32-bit page numbers. The first entry in the
54567** first index-block contains the database page number corresponding to the
54568** first frame in the WAL file. The first entry in the second index block
54569** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
54570** the log, and so on.
54571**
54572** The last index block in a wal-index usually contains less than the full
54573** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
54574** depending on the contents of the WAL file. This does not change the
54575** allocated size of the page-mapping array - the page-mapping array merely
54576** contains unused entries.
54577**
54578** Even without using the hash table, the last frame for page P
54579** can be found by scanning the page-mapping sections of each index block
54580** starting with the last index block and moving toward the first, and
54581** within each index block, starting at the end and moving toward the
54582** beginning.  The first entry that equals P corresponds to the frame
54583** holding the content for that page.
54584**
54585** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
54586** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
54587** hash table for each page number in the mapping section, so the hash
54588** table is never more than half full.  The expected number of collisions
54589** prior to finding a match is 1.  Each entry of the hash table is an
54590** 1-based index of an entry in the mapping section of the same
54591** index block.   Let K be the 1-based index of the largest entry in
54592** the mapping section.  (For index blocks other than the last, K will
54593** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
54594** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
54595** contain a value of 0.
54596**
54597** To look for page P in the hash table, first compute a hash iKey on
54598** P as follows:
54599**
54600**      iKey = (P * 383) % HASHTABLE_NSLOT
54601**
54602** Then start scanning entries of the hash table, starting with iKey
54603** (wrapping around to the beginning when the end of the hash table is
54604** reached) until an unused hash slot is found. Let the first unused slot
54605** be at index iUnused.  (iUnused might be less than iKey if there was
54606** wrap-around.) Because the hash table is never more than half full,
54607** the search is guaranteed to eventually hit an unused entry.  Let
54608** iMax be the value between iKey and iUnused, closest to iUnused,
54609** where aHash[iMax]==P.  If there is no iMax entry (if there exists
54610** no hash slot such that aHash[i]==p) then page P is not in the
54611** current index block.  Otherwise the iMax-th mapping entry of the
54612** current index block corresponds to the last entry that references
54613** page P.
54614**
54615** A hash search begins with the last index block and moves toward the
54616** first index block, looking for entries corresponding to page P.  On
54617** average, only two or three slots in each index block need to be
54618** examined in order to either find the last entry for page P, or to
54619** establish that no such entry exists in the block.  Each index block
54620** holds over 4000 entries.  So two or three index blocks are sufficient
54621** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
54622** comparisons (on average) suffice to either locate a frame in the
54623** WAL or to establish that the frame does not exist in the WAL.  This
54624** is much faster than scanning the entire 10MB WAL.
54625**
54626** Note that entries are added in order of increasing K.  Hence, one
54627** reader might be using some value K0 and a second reader that started
54628** at a later time (after additional transactions were added to the WAL
54629** and to the wal-index) might be using a different value K1, where K1>K0.
54630** Both readers can use the same hash table and mapping section to get
54631** the correct result.  There may be entries in the hash table with
54632** K>K0 but to the first reader, those entries will appear to be unused
54633** slots in the hash table and so the first reader will get an answer as
54634** if no values greater than K0 had ever been inserted into the hash table
54635** in the first place - which is what reader one wants.  Meanwhile, the
54636** second reader using K1 will see additional values that were inserted
54637** later, which is exactly what reader two wants.
54638**
54639** When a rollback occurs, the value of K is decreased. Hash table entries
54640** that correspond to frames greater than the new K value are removed
54641** from the hash table at this point.
54642*/
54643#ifndef SQLITE_OMIT_WAL
54644
54645/* #include "wal.h" */
54646
54647/*
54648** Trace output macros
54649*/
54650#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
54651SQLITE_PRIVATE int sqlite3WalTrace = 0;
54652# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
54653#else
54654# define WALTRACE(X)
54655#endif
54656
54657/*
54658** The maximum (and only) versions of the wal and wal-index formats
54659** that may be interpreted by this version of SQLite.
54660**
54661** If a client begins recovering a WAL file and finds that (a) the checksum
54662** values in the wal-header are correct and (b) the version field is not
54663** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
54664**
54665** Similarly, if a client successfully reads a wal-index header (i.e. the
54666** checksum test is successful) and finds that the version field is not
54667** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
54668** returns SQLITE_CANTOPEN.
54669*/
54670#define WAL_MAX_VERSION      3007000
54671#define WALINDEX_MAX_VERSION 3007000
54672
54673/*
54674** Indices of various locking bytes.   WAL_NREADER is the number
54675** of available reader locks and should be at least 3.  The default
54676** is SQLITE_SHM_NLOCK==8 and  WAL_NREADER==5.
54677*/
54678#define WAL_WRITE_LOCK         0
54679#define WAL_ALL_BUT_WRITE      1
54680#define WAL_CKPT_LOCK          1
54681#define WAL_RECOVER_LOCK       2
54682#define WAL_READ_LOCK(I)       (3+(I))
54683#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
54684
54685
54686/* Object declarations */
54687typedef struct WalIndexHdr WalIndexHdr;
54688typedef struct WalIterator WalIterator;
54689typedef struct WalCkptInfo WalCkptInfo;
54690
54691
54692/*
54693** The following object holds a copy of the wal-index header content.
54694**
54695** The actual header in the wal-index consists of two copies of this
54696** object followed by one instance of the WalCkptInfo object.
54697** For all versions of SQLite through 3.10.0 and probably beyond,
54698** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
54699** the total header size is 136 bytes.
54700**
54701** The szPage value can be any power of 2 between 512 and 32768, inclusive.
54702** Or it can be 1 to represent a 65536-byte page.  The latter case was
54703** added in 3.7.1 when support for 64K pages was added.
54704*/
54705struct WalIndexHdr {
54706  u32 iVersion;                   /* Wal-index version */
54707  u32 unused;                     /* Unused (padding) field */
54708  u32 iChange;                    /* Counter incremented each transaction */
54709  u8 isInit;                      /* 1 when initialized */
54710  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
54711  u16 szPage;                     /* Database page size in bytes. 1==64K */
54712  u32 mxFrame;                    /* Index of last valid frame in the WAL */
54713  u32 nPage;                      /* Size of database in pages */
54714  u32 aFrameCksum[2];             /* Checksum of last frame in log */
54715  u32 aSalt[2];                   /* Two salt values copied from WAL header */
54716  u32 aCksum[2];                  /* Checksum over all prior fields */
54717};
54718
54719/*
54720** A copy of the following object occurs in the wal-index immediately
54721** following the second copy of the WalIndexHdr.  This object stores
54722** information used by checkpoint.
54723**
54724** nBackfill is the number of frames in the WAL that have been written
54725** back into the database. (We call the act of moving content from WAL to
54726** database "backfilling".)  The nBackfill number is never greater than
54727** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
54728** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
54729** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
54730** mxFrame back to zero when the WAL is reset.
54731**
54732** nBackfillAttempted is the largest value of nBackfill that a checkpoint
54733** has attempted to achieve.  Normally nBackfill==nBackfillAtempted, however
54734** the nBackfillAttempted is set before any backfilling is done and the
54735** nBackfill is only set after all backfilling completes.  So if a checkpoint
54736** crashes, nBackfillAttempted might be larger than nBackfill.  The
54737** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
54738**
54739** The aLock[] field is a set of bytes used for locking.  These bytes should
54740** never be read or written.
54741**
54742** There is one entry in aReadMark[] for each reader lock.  If a reader
54743** holds read-lock K, then the value in aReadMark[K] is no greater than
54744** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
54745** for any aReadMark[] means that entry is unused.  aReadMark[0] is
54746** a special case; its value is never used and it exists as a place-holder
54747** to avoid having to offset aReadMark[] indexs by one.  Readers holding
54748** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
54749** directly from the database.
54750**
54751** The value of aReadMark[K] may only be changed by a thread that
54752** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
54753** aReadMark[K] cannot changed while there is a reader is using that mark
54754** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
54755**
54756** The checkpointer may only transfer frames from WAL to database where
54757** the frame numbers are less than or equal to every aReadMark[] that is
54758** in use (that is, every aReadMark[j] for which there is a corresponding
54759** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
54760** largest value and will increase an unused aReadMark[] to mxFrame if there
54761** is not already an aReadMark[] equal to mxFrame.  The exception to the
54762** previous sentence is when nBackfill equals mxFrame (meaning that everything
54763** in the WAL has been backfilled into the database) then new readers
54764** will choose aReadMark[0] which has value 0 and hence such reader will
54765** get all their all content directly from the database file and ignore
54766** the WAL.
54767**
54768** Writers normally append new frames to the end of the WAL.  However,
54769** if nBackfill equals mxFrame (meaning that all WAL content has been
54770** written back into the database) and if no readers are using the WAL
54771** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
54772** the writer will first "reset" the WAL back to the beginning and start
54773** writing new content beginning at frame 1.
54774**
54775** We assume that 32-bit loads are atomic and so no locks are needed in
54776** order to read from any aReadMark[] entries.
54777*/
54778struct WalCkptInfo {
54779  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
54780  u32 aReadMark[WAL_NREADER];     /* Reader marks */
54781  u8 aLock[SQLITE_SHM_NLOCK];     /* Reserved space for locks */
54782  u32 nBackfillAttempted;         /* WAL frames perhaps written, or maybe not */
54783  u32 notUsed0;                   /* Available for future enhancements */
54784};
54785#define READMARK_NOT_USED  0xffffffff
54786
54787
54788/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
54789** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
54790** only support mandatory file-locks, we do not read or write data
54791** from the region of the file on which locks are applied.
54792*/
54793#define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
54794#define WALINDEX_HDR_SIZE    (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
54795
54796/* Size of header before each frame in wal */
54797#define WAL_FRAME_HDRSIZE 24
54798
54799/* Size of write ahead log header, including checksum. */
54800/* #define WAL_HDRSIZE 24 */
54801#define WAL_HDRSIZE 32
54802
54803/* WAL magic value. Either this value, or the same value with the least
54804** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
54805** big-endian format in the first 4 bytes of a WAL file.
54806**
54807** If the LSB is set, then the checksums for each frame within the WAL
54808** file are calculated by treating all data as an array of 32-bit
54809** big-endian words. Otherwise, they are calculated by interpreting
54810** all data as 32-bit little-endian words.
54811*/
54812#define WAL_MAGIC 0x377f0682
54813
54814/*
54815** Return the offset of frame iFrame in the write-ahead log file,
54816** assuming a database page size of szPage bytes. The offset returned
54817** is to the start of the write-ahead log frame-header.
54818*/
54819#define walFrameOffset(iFrame, szPage) (                               \
54820  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
54821)
54822
54823/*
54824** An open write-ahead log file is represented by an instance of the
54825** following object.
54826*/
54827struct Wal {
54828  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
54829  sqlite3_file *pDbFd;       /* File handle for the database file */
54830  sqlite3_file *pWalFd;      /* File handle for WAL file */
54831  u32 iCallback;             /* Value to pass to log callback (or 0) */
54832  i64 mxWalSize;             /* Truncate WAL to this size upon reset */
54833  int nWiData;               /* Size of array apWiData */
54834  int szFirstBlock;          /* Size of first block written to WAL file */
54835  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
54836  u32 szPage;                /* Database page size */
54837  i16 readLock;              /* Which read lock is being held.  -1 for none */
54838  u8 syncFlags;              /* Flags to use to sync header writes */
54839  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
54840  u8 writeLock;              /* True if in a write transaction */
54841  u8 ckptLock;               /* True if holding a checkpoint lock */
54842  u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
54843  u8 truncateOnCommit;       /* True to truncate WAL file on commit */
54844  u8 syncHeader;             /* Fsync the WAL header if true */
54845  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
54846  WalIndexHdr hdr;           /* Wal-index header for current transaction */
54847  u32 minFrame;              /* Ignore wal frames before this one */
54848  u32 iReCksum;              /* On commit, recalculate checksums from here */
54849  const char *zWalName;      /* Name of WAL file */
54850  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
54851#ifdef SQLITE_DEBUG
54852  u8 lockError;              /* True if a locking error has occurred */
54853#endif
54854#ifdef SQLITE_ENABLE_SNAPSHOT
54855  WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */
54856#endif
54857};
54858
54859/*
54860** Candidate values for Wal.exclusiveMode.
54861*/
54862#define WAL_NORMAL_MODE     0
54863#define WAL_EXCLUSIVE_MODE  1
54864#define WAL_HEAPMEMORY_MODE 2
54865
54866/*
54867** Possible values for WAL.readOnly
54868*/
54869#define WAL_RDWR        0    /* Normal read/write connection */
54870#define WAL_RDONLY      1    /* The WAL file is readonly */
54871#define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
54872
54873/*
54874** Each page of the wal-index mapping contains a hash-table made up of
54875** an array of HASHTABLE_NSLOT elements of the following type.
54876*/
54877typedef u16 ht_slot;
54878
54879/*
54880** This structure is used to implement an iterator that loops through
54881** all frames in the WAL in database page order. Where two or more frames
54882** correspond to the same database page, the iterator visits only the
54883** frame most recently written to the WAL (in other words, the frame with
54884** the largest index).
54885**
54886** The internals of this structure are only accessed by:
54887**
54888**   walIteratorInit() - Create a new iterator,
54889**   walIteratorNext() - Step an iterator,
54890**   walIteratorFree() - Free an iterator.
54891**
54892** This functionality is used by the checkpoint code (see walCheckpoint()).
54893*/
54894struct WalIterator {
54895  int iPrior;                     /* Last result returned from the iterator */
54896  int nSegment;                   /* Number of entries in aSegment[] */
54897  struct WalSegment {
54898    int iNext;                    /* Next slot in aIndex[] not yet returned */
54899    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
54900    u32 *aPgno;                   /* Array of page numbers. */
54901    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
54902    int iZero;                    /* Frame number associated with aPgno[0] */
54903  } aSegment[1];                  /* One for every 32KB page in the wal-index */
54904};
54905
54906/*
54907** Define the parameters of the hash tables in the wal-index file. There
54908** is a hash-table following every HASHTABLE_NPAGE page numbers in the
54909** wal-index.
54910**
54911** Changing any of these constants will alter the wal-index format and
54912** create incompatibilities.
54913*/
54914#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
54915#define HASHTABLE_HASH_1     383                  /* Should be prime */
54916#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
54917
54918/*
54919** The block of page numbers associated with the first hash-table in a
54920** wal-index is smaller than usual. This is so that there is a complete
54921** hash-table on each aligned 32KB page of the wal-index.
54922*/
54923#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
54924
54925/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
54926#define WALINDEX_PGSZ   (                                         \
54927    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
54928)
54929
54930/*
54931** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
54932** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
54933** numbered from zero.
54934**
54935** If this call is successful, *ppPage is set to point to the wal-index
54936** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
54937** then an SQLite error code is returned and *ppPage is set to 0.
54938*/
54939static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
54940  int rc = SQLITE_OK;
54941
54942  /* Enlarge the pWal->apWiData[] array if required */
54943  if( pWal->nWiData<=iPage ){
54944    int nByte = sizeof(u32*)*(iPage+1);
54945    volatile u32 **apNew;
54946    apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
54947    if( !apNew ){
54948      *ppPage = 0;
54949      return SQLITE_NOMEM_BKPT;
54950    }
54951    memset((void*)&apNew[pWal->nWiData], 0,
54952           sizeof(u32*)*(iPage+1-pWal->nWiData));
54953    pWal->apWiData = apNew;
54954    pWal->nWiData = iPage+1;
54955  }
54956
54957  /* Request a pointer to the required page from the VFS */
54958  if( pWal->apWiData[iPage]==0 ){
54959    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
54960      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
54961      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
54962    }else{
54963      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
54964          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
54965      );
54966      if( rc==SQLITE_READONLY ){
54967        pWal->readOnly |= WAL_SHM_RDONLY;
54968        rc = SQLITE_OK;
54969      }
54970    }
54971  }
54972
54973  *ppPage = pWal->apWiData[iPage];
54974  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
54975  return rc;
54976}
54977
54978/*
54979** Return a pointer to the WalCkptInfo structure in the wal-index.
54980*/
54981static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
54982  assert( pWal->nWiData>0 && pWal->apWiData[0] );
54983  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
54984}
54985
54986/*
54987** Return a pointer to the WalIndexHdr structure in the wal-index.
54988*/
54989static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
54990  assert( pWal->nWiData>0 && pWal->apWiData[0] );
54991  return (volatile WalIndexHdr*)pWal->apWiData[0];
54992}
54993
54994/*
54995** The argument to this macro must be of type u32. On a little-endian
54996** architecture, it returns the u32 value that results from interpreting
54997** the 4 bytes as a big-endian value. On a big-endian architecture, it
54998** returns the value that would be produced by interpreting the 4 bytes
54999** of the input value as a little-endian integer.
55000*/
55001#define BYTESWAP32(x) ( \
55002    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
55003  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
55004)
55005
55006/*
55007** Generate or extend an 8 byte checksum based on the data in
55008** array aByte[] and the initial values of aIn[0] and aIn[1] (or
55009** initial values of 0 and 0 if aIn==NULL).
55010**
55011** The checksum is written back into aOut[] before returning.
55012**
55013** nByte must be a positive multiple of 8.
55014*/
55015static void walChecksumBytes(
55016  int nativeCksum, /* True for native byte-order, false for non-native */
55017  u8 *a,           /* Content to be checksummed */
55018  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
55019  const u32 *aIn,  /* Initial checksum value input */
55020  u32 *aOut        /* OUT: Final checksum value output */
55021){
55022  u32 s1, s2;
55023  u32 *aData = (u32 *)a;
55024  u32 *aEnd = (u32 *)&a[nByte];
55025
55026  if( aIn ){
55027    s1 = aIn[0];
55028    s2 = aIn[1];
55029  }else{
55030    s1 = s2 = 0;
55031  }
55032
55033  assert( nByte>=8 );
55034  assert( (nByte&0x00000007)==0 );
55035
55036  if( nativeCksum ){
55037    do {
55038      s1 += *aData++ + s2;
55039      s2 += *aData++ + s1;
55040    }while( aData<aEnd );
55041  }else{
55042    do {
55043      s1 += BYTESWAP32(aData[0]) + s2;
55044      s2 += BYTESWAP32(aData[1]) + s1;
55045      aData += 2;
55046    }while( aData<aEnd );
55047  }
55048
55049  aOut[0] = s1;
55050  aOut[1] = s2;
55051}
55052
55053static void walShmBarrier(Wal *pWal){
55054  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
55055    sqlite3OsShmBarrier(pWal->pDbFd);
55056  }
55057}
55058
55059/*
55060** Write the header information in pWal->hdr into the wal-index.
55061**
55062** The checksum on pWal->hdr is updated before it is written.
55063*/
55064static void walIndexWriteHdr(Wal *pWal){
55065  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
55066  const int nCksum = offsetof(WalIndexHdr, aCksum);
55067
55068  assert( pWal->writeLock );
55069  pWal->hdr.isInit = 1;
55070  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
55071  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
55072  memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
55073  walShmBarrier(pWal);
55074  memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
55075}
55076
55077/*
55078** This function encodes a single frame header and writes it to a buffer
55079** supplied by the caller. A frame-header is made up of a series of
55080** 4-byte big-endian integers, as follows:
55081**
55082**     0: Page number.
55083**     4: For commit records, the size of the database image in pages
55084**        after the commit. For all other records, zero.
55085**     8: Salt-1 (copied from the wal-header)
55086**    12: Salt-2 (copied from the wal-header)
55087**    16: Checksum-1.
55088**    20: Checksum-2.
55089*/
55090static void walEncodeFrame(
55091  Wal *pWal,                      /* The write-ahead log */
55092  u32 iPage,                      /* Database page number for frame */
55093  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
55094  u8 *aData,                      /* Pointer to page data */
55095  u8 *aFrame                      /* OUT: Write encoded frame here */
55096){
55097  int nativeCksum;                /* True for native byte-order checksums */
55098  u32 *aCksum = pWal->hdr.aFrameCksum;
55099  assert( WAL_FRAME_HDRSIZE==24 );
55100  sqlite3Put4byte(&aFrame[0], iPage);
55101  sqlite3Put4byte(&aFrame[4], nTruncate);
55102  if( pWal->iReCksum==0 ){
55103    memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
55104
55105    nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
55106    walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
55107    walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
55108
55109    sqlite3Put4byte(&aFrame[16], aCksum[0]);
55110    sqlite3Put4byte(&aFrame[20], aCksum[1]);
55111  }else{
55112    memset(&aFrame[8], 0, 16);
55113  }
55114}
55115
55116/*
55117** Check to see if the frame with header in aFrame[] and content
55118** in aData[] is valid.  If it is a valid frame, fill *piPage and
55119** *pnTruncate and return true.  Return if the frame is not valid.
55120*/
55121static int walDecodeFrame(
55122  Wal *pWal,                      /* The write-ahead log */
55123  u32 *piPage,                    /* OUT: Database page number for frame */
55124  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
55125  u8 *aData,                      /* Pointer to page data (for checksum) */
55126  u8 *aFrame                      /* Frame data */
55127){
55128  int nativeCksum;                /* True for native byte-order checksums */
55129  u32 *aCksum = pWal->hdr.aFrameCksum;
55130  u32 pgno;                       /* Page number of the frame */
55131  assert( WAL_FRAME_HDRSIZE==24 );
55132
55133  /* A frame is only valid if the salt values in the frame-header
55134  ** match the salt values in the wal-header.
55135  */
55136  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
55137    return 0;
55138  }
55139
55140  /* A frame is only valid if the page number is creater than zero.
55141  */
55142  pgno = sqlite3Get4byte(&aFrame[0]);
55143  if( pgno==0 ){
55144    return 0;
55145  }
55146
55147  /* A frame is only valid if a checksum of the WAL header,
55148  ** all prior frams, the first 16 bytes of this frame-header,
55149  ** and the frame-data matches the checksum in the last 8
55150  ** bytes of this frame-header.
55151  */
55152  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
55153  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
55154  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
55155  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
55156   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
55157  ){
55158    /* Checksum failed. */
55159    return 0;
55160  }
55161
55162  /* If we reach this point, the frame is valid.  Return the page number
55163  ** and the new database size.
55164  */
55165  *piPage = pgno;
55166  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
55167  return 1;
55168}
55169
55170
55171#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
55172/*
55173** Names of locks.  This routine is used to provide debugging output and is not
55174** a part of an ordinary build.
55175*/
55176static const char *walLockName(int lockIdx){
55177  if( lockIdx==WAL_WRITE_LOCK ){
55178    return "WRITE-LOCK";
55179  }else if( lockIdx==WAL_CKPT_LOCK ){
55180    return "CKPT-LOCK";
55181  }else if( lockIdx==WAL_RECOVER_LOCK ){
55182    return "RECOVER-LOCK";
55183  }else{
55184    static char zName[15];
55185    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
55186                     lockIdx-WAL_READ_LOCK(0));
55187    return zName;
55188  }
55189}
55190#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
55191
55192
55193/*
55194** Set or release locks on the WAL.  Locks are either shared or exclusive.
55195** A lock cannot be moved directly between shared and exclusive - it must go
55196** through the unlocked state first.
55197**
55198** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
55199*/
55200static int walLockShared(Wal *pWal, int lockIdx){
55201  int rc;
55202  if( pWal->exclusiveMode ) return SQLITE_OK;
55203  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
55204                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
55205  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
55206            walLockName(lockIdx), rc ? "failed" : "ok"));
55207  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
55208  return rc;
55209}
55210static void walUnlockShared(Wal *pWal, int lockIdx){
55211  if( pWal->exclusiveMode ) return;
55212  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
55213                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
55214  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
55215}
55216static int walLockExclusive(Wal *pWal, int lockIdx, int n){
55217  int rc;
55218  if( pWal->exclusiveMode ) return SQLITE_OK;
55219  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
55220                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
55221  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
55222            walLockName(lockIdx), n, rc ? "failed" : "ok"));
55223  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
55224  return rc;
55225}
55226static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
55227  if( pWal->exclusiveMode ) return;
55228  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
55229                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
55230  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
55231             walLockName(lockIdx), n));
55232}
55233
55234/*
55235** Compute a hash on a page number.  The resulting hash value must land
55236** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
55237** the hash to the next value in the event of a collision.
55238*/
55239static int walHash(u32 iPage){
55240  assert( iPage>0 );
55241  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
55242  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
55243}
55244static int walNextHash(int iPriorHash){
55245  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
55246}
55247
55248/*
55249** Return pointers to the hash table and page number array stored on
55250** page iHash of the wal-index. The wal-index is broken into 32KB pages
55251** numbered starting from 0.
55252**
55253** Set output variable *paHash to point to the start of the hash table
55254** in the wal-index file. Set *piZero to one less than the frame
55255** number of the first frame indexed by this hash table. If a
55256** slot in the hash table is set to N, it refers to frame number
55257** (*piZero+N) in the log.
55258**
55259** Finally, set *paPgno so that *paPgno[1] is the page number of the
55260** first frame indexed by the hash table, frame (*piZero+1).
55261*/
55262static int walHashGet(
55263  Wal *pWal,                      /* WAL handle */
55264  int iHash,                      /* Find the iHash'th table */
55265  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
55266  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
55267  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
55268){
55269  int rc;                         /* Return code */
55270  volatile u32 *aPgno;
55271
55272  rc = walIndexPage(pWal, iHash, &aPgno);
55273  assert( rc==SQLITE_OK || iHash>0 );
55274
55275  if( rc==SQLITE_OK ){
55276    u32 iZero;
55277    volatile ht_slot *aHash;
55278
55279    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
55280    if( iHash==0 ){
55281      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
55282      iZero = 0;
55283    }else{
55284      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
55285    }
55286
55287    *paPgno = &aPgno[-1];
55288    *paHash = aHash;
55289    *piZero = iZero;
55290  }
55291  return rc;
55292}
55293
55294/*
55295** Return the number of the wal-index page that contains the hash-table
55296** and page-number array that contain entries corresponding to WAL frame
55297** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
55298** are numbered starting from 0.
55299*/
55300static int walFramePage(u32 iFrame){
55301  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
55302  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
55303       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
55304       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
55305       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
55306       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
55307  );
55308  return iHash;
55309}
55310
55311/*
55312** Return the page number associated with frame iFrame in this WAL.
55313*/
55314static u32 walFramePgno(Wal *pWal, u32 iFrame){
55315  int iHash = walFramePage(iFrame);
55316  if( iHash==0 ){
55317    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
55318  }
55319  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
55320}
55321
55322/*
55323** Remove entries from the hash table that point to WAL slots greater
55324** than pWal->hdr.mxFrame.
55325**
55326** This function is called whenever pWal->hdr.mxFrame is decreased due
55327** to a rollback or savepoint.
55328**
55329** At most only the hash table containing pWal->hdr.mxFrame needs to be
55330** updated.  Any later hash tables will be automatically cleared when
55331** pWal->hdr.mxFrame advances to the point where those hash tables are
55332** actually needed.
55333*/
55334static void walCleanupHash(Wal *pWal){
55335  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
55336  volatile u32 *aPgno = 0;        /* Page number array for hash table */
55337  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
55338  int iLimit = 0;                 /* Zero values greater than this */
55339  int nByte;                      /* Number of bytes to zero in aPgno[] */
55340  int i;                          /* Used to iterate through aHash[] */
55341
55342  assert( pWal->writeLock );
55343  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
55344  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
55345  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
55346
55347  if( pWal->hdr.mxFrame==0 ) return;
55348
55349  /* Obtain pointers to the hash-table and page-number array containing
55350  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
55351  ** that the page said hash-table and array reside on is already mapped.
55352  */
55353  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
55354  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
55355  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
55356
55357  /* Zero all hash-table entries that correspond to frame numbers greater
55358  ** than pWal->hdr.mxFrame.
55359  */
55360  iLimit = pWal->hdr.mxFrame - iZero;
55361  assert( iLimit>0 );
55362  for(i=0; i<HASHTABLE_NSLOT; i++){
55363    if( aHash[i]>iLimit ){
55364      aHash[i] = 0;
55365    }
55366  }
55367
55368  /* Zero the entries in the aPgno array that correspond to frames with
55369  ** frame numbers greater than pWal->hdr.mxFrame.
55370  */
55371  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
55372  memset((void *)&aPgno[iLimit+1], 0, nByte);
55373
55374#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
55375  /* Verify that the every entry in the mapping region is still reachable
55376  ** via the hash table even after the cleanup.
55377  */
55378  if( iLimit ){
55379    int j;           /* Loop counter */
55380    int iKey;        /* Hash key */
55381    for(j=1; j<=iLimit; j++){
55382      for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
55383        if( aHash[iKey]==j ) break;
55384      }
55385      assert( aHash[iKey]==j );
55386    }
55387  }
55388#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
55389}
55390
55391
55392/*
55393** Set an entry in the wal-index that will map database page number
55394** pPage into WAL frame iFrame.
55395*/
55396static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
55397  int rc;                         /* Return code */
55398  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
55399  volatile u32 *aPgno = 0;        /* Page number array */
55400  volatile ht_slot *aHash = 0;    /* Hash table */
55401
55402  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
55403
55404  /* Assuming the wal-index file was successfully mapped, populate the
55405  ** page number array and hash table entry.
55406  */
55407  if( rc==SQLITE_OK ){
55408    int iKey;                     /* Hash table key */
55409    int idx;                      /* Value to write to hash-table slot */
55410    int nCollide;                 /* Number of hash collisions */
55411
55412    idx = iFrame - iZero;
55413    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
55414
55415    /* If this is the first entry to be added to this hash-table, zero the
55416    ** entire hash table and aPgno[] array before proceeding.
55417    */
55418    if( idx==1 ){
55419      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
55420      memset((void*)&aPgno[1], 0, nByte);
55421    }
55422
55423    /* If the entry in aPgno[] is already set, then the previous writer
55424    ** must have exited unexpectedly in the middle of a transaction (after
55425    ** writing one or more dirty pages to the WAL to free up memory).
55426    ** Remove the remnants of that writers uncommitted transaction from
55427    ** the hash-table before writing any new entries.
55428    */
55429    if( aPgno[idx] ){
55430      walCleanupHash(pWal);
55431      assert( !aPgno[idx] );
55432    }
55433
55434    /* Write the aPgno[] array entry and the hash-table slot. */
55435    nCollide = idx;
55436    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
55437      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
55438    }
55439    aPgno[idx] = iPage;
55440    aHash[iKey] = (ht_slot)idx;
55441
55442#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
55443    /* Verify that the number of entries in the hash table exactly equals
55444    ** the number of entries in the mapping region.
55445    */
55446    {
55447      int i;           /* Loop counter */
55448      int nEntry = 0;  /* Number of entries in the hash table */
55449      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
55450      assert( nEntry==idx );
55451    }
55452
55453    /* Verify that the every entry in the mapping region is reachable
55454    ** via the hash table.  This turns out to be a really, really expensive
55455    ** thing to check, so only do this occasionally - not on every
55456    ** iteration.
55457    */
55458    if( (idx&0x3ff)==0 ){
55459      int i;           /* Loop counter */
55460      for(i=1; i<=idx; i++){
55461        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
55462          if( aHash[iKey]==i ) break;
55463        }
55464        assert( aHash[iKey]==i );
55465      }
55466    }
55467#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
55468  }
55469
55470
55471  return rc;
55472}
55473
55474
55475/*
55476** Recover the wal-index by reading the write-ahead log file.
55477**
55478** This routine first tries to establish an exclusive lock on the
55479** wal-index to prevent other threads/processes from doing anything
55480** with the WAL or wal-index while recovery is running.  The
55481** WAL_RECOVER_LOCK is also held so that other threads will know
55482** that this thread is running recovery.  If unable to establish
55483** the necessary locks, this routine returns SQLITE_BUSY.
55484*/
55485static int walIndexRecover(Wal *pWal){
55486  int rc;                         /* Return Code */
55487  i64 nSize;                      /* Size of log file */
55488  u32 aFrameCksum[2] = {0, 0};
55489  int iLock;                      /* Lock offset to lock for checkpoint */
55490  int nLock;                      /* Number of locks to hold */
55491
55492  /* Obtain an exclusive lock on all byte in the locking range not already
55493  ** locked by the caller. The caller is guaranteed to have locked the
55494  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
55495  ** If successful, the same bytes that are locked here are unlocked before
55496  ** this function returns.
55497  */
55498  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
55499  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
55500  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
55501  assert( pWal->writeLock );
55502  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
55503  nLock = SQLITE_SHM_NLOCK - iLock;
55504  rc = walLockExclusive(pWal, iLock, nLock);
55505  if( rc ){
55506    return rc;
55507  }
55508  WALTRACE(("WAL%p: recovery begin...\n", pWal));
55509
55510  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
55511
55512  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
55513  if( rc!=SQLITE_OK ){
55514    goto recovery_error;
55515  }
55516
55517  if( nSize>WAL_HDRSIZE ){
55518    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
55519    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
55520    int szFrame;                  /* Number of bytes in buffer aFrame[] */
55521    u8 *aData;                    /* Pointer to data part of aFrame buffer */
55522    int iFrame;                   /* Index of last frame read */
55523    i64 iOffset;                  /* Next offset to read from log file */
55524    int szPage;                   /* Page size according to the log */
55525    u32 magic;                    /* Magic value read from WAL header */
55526    u32 version;                  /* Magic value read from WAL header */
55527    int isValid;                  /* True if this frame is valid */
55528
55529    /* Read in the WAL header. */
55530    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
55531    if( rc!=SQLITE_OK ){
55532      goto recovery_error;
55533    }
55534
55535    /* If the database page size is not a power of two, or is greater than
55536    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
55537    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
55538    ** WAL file.
55539    */
55540    magic = sqlite3Get4byte(&aBuf[0]);
55541    szPage = sqlite3Get4byte(&aBuf[8]);
55542    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
55543     || szPage&(szPage-1)
55544     || szPage>SQLITE_MAX_PAGE_SIZE
55545     || szPage<512
55546    ){
55547      goto finished;
55548    }
55549    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
55550    pWal->szPage = szPage;
55551    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
55552    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
55553
55554    /* Verify that the WAL header checksum is correct */
55555    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
55556        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
55557    );
55558    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
55559     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
55560    ){
55561      goto finished;
55562    }
55563
55564    /* Verify that the version number on the WAL format is one that
55565    ** are able to understand */
55566    version = sqlite3Get4byte(&aBuf[4]);
55567    if( version!=WAL_MAX_VERSION ){
55568      rc = SQLITE_CANTOPEN_BKPT;
55569      goto finished;
55570    }
55571
55572    /* Malloc a buffer to read frames into. */
55573    szFrame = szPage + WAL_FRAME_HDRSIZE;
55574    aFrame = (u8 *)sqlite3_malloc64(szFrame);
55575    if( !aFrame ){
55576      rc = SQLITE_NOMEM_BKPT;
55577      goto recovery_error;
55578    }
55579    aData = &aFrame[WAL_FRAME_HDRSIZE];
55580
55581    /* Read all frames from the log file. */
55582    iFrame = 0;
55583    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
55584      u32 pgno;                   /* Database page number for frame */
55585      u32 nTruncate;              /* dbsize field from frame header */
55586
55587      /* Read and decode the next log frame. */
55588      iFrame++;
55589      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
55590      if( rc!=SQLITE_OK ) break;
55591      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
55592      if( !isValid ) break;
55593      rc = walIndexAppend(pWal, iFrame, pgno);
55594      if( rc!=SQLITE_OK ) break;
55595
55596      /* If nTruncate is non-zero, this is a commit record. */
55597      if( nTruncate ){
55598        pWal->hdr.mxFrame = iFrame;
55599        pWal->hdr.nPage = nTruncate;
55600        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
55601        testcase( szPage<=32768 );
55602        testcase( szPage>=65536 );
55603        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
55604        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
55605      }
55606    }
55607
55608    sqlite3_free(aFrame);
55609  }
55610
55611finished:
55612  if( rc==SQLITE_OK ){
55613    volatile WalCkptInfo *pInfo;
55614    int i;
55615    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
55616    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
55617    walIndexWriteHdr(pWal);
55618
55619    /* Reset the checkpoint-header. This is safe because this thread is
55620    ** currently holding locks that exclude all other readers, writers and
55621    ** checkpointers.
55622    */
55623    pInfo = walCkptInfo(pWal);
55624    pInfo->nBackfill = 0;
55625    pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
55626    pInfo->aReadMark[0] = 0;
55627    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
55628    if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
55629
55630    /* If more than one frame was recovered from the log file, report an
55631    ** event via sqlite3_log(). This is to help with identifying performance
55632    ** problems caused by applications routinely shutting down without
55633    ** checkpointing the log file.
55634    */
55635    if( pWal->hdr.nPage ){
55636      sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
55637          "recovered %d frames from WAL file %s",
55638          pWal->hdr.mxFrame, pWal->zWalName
55639      );
55640    }
55641  }
55642
55643recovery_error:
55644  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
55645  walUnlockExclusive(pWal, iLock, nLock);
55646  return rc;
55647}
55648
55649/*
55650** Close an open wal-index.
55651*/
55652static void walIndexClose(Wal *pWal, int isDelete){
55653  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
55654    int i;
55655    for(i=0; i<pWal->nWiData; i++){
55656      sqlite3_free((void *)pWal->apWiData[i]);
55657      pWal->apWiData[i] = 0;
55658    }
55659  }else{
55660    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
55661  }
55662}
55663
55664/*
55665** Open a connection to the WAL file zWalName. The database file must
55666** already be opened on connection pDbFd. The buffer that zWalName points
55667** to must remain valid for the lifetime of the returned Wal* handle.
55668**
55669** A SHARED lock should be held on the database file when this function
55670** is called. The purpose of this SHARED lock is to prevent any other
55671** client from unlinking the WAL or wal-index file. If another process
55672** were to do this just after this client opened one of these files, the
55673** system would be badly broken.
55674**
55675** If the log file is successfully opened, SQLITE_OK is returned and
55676** *ppWal is set to point to a new WAL handle. If an error occurs,
55677** an SQLite error code is returned and *ppWal is left unmodified.
55678*/
55679SQLITE_PRIVATE int sqlite3WalOpen(
55680  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
55681  sqlite3_file *pDbFd,            /* The open database file */
55682  const char *zWalName,           /* Name of the WAL file */
55683  int bNoShm,                     /* True to run in heap-memory mode */
55684  i64 mxWalSize,                  /* Truncate WAL to this size on reset */
55685  Wal **ppWal                     /* OUT: Allocated Wal handle */
55686){
55687  int rc;                         /* Return Code */
55688  Wal *pRet;                      /* Object to allocate and return */
55689  int flags;                      /* Flags passed to OsOpen() */
55690
55691  assert( zWalName && zWalName[0] );
55692  assert( pDbFd );
55693
55694  /* In the amalgamation, the os_unix.c and os_win.c source files come before
55695  ** this source file.  Verify that the #defines of the locking byte offsets
55696  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
55697  ** For that matter, if the lock offset ever changes from its initial design
55698  ** value of 120, we need to know that so there is an assert() to check it.
55699  */
55700  assert( 120==WALINDEX_LOCK_OFFSET );
55701  assert( 136==WALINDEX_HDR_SIZE );
55702#ifdef WIN_SHM_BASE
55703  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
55704#endif
55705#ifdef UNIX_SHM_BASE
55706  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
55707#endif
55708
55709
55710  /* Allocate an instance of struct Wal to return. */
55711  *ppWal = 0;
55712  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
55713  if( !pRet ){
55714    return SQLITE_NOMEM_BKPT;
55715  }
55716
55717  pRet->pVfs = pVfs;
55718  pRet->pWalFd = (sqlite3_file *)&pRet[1];
55719  pRet->pDbFd = pDbFd;
55720  pRet->readLock = -1;
55721  pRet->mxWalSize = mxWalSize;
55722  pRet->zWalName = zWalName;
55723  pRet->syncHeader = 1;
55724  pRet->padToSectorBoundary = 1;
55725  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
55726
55727  /* Open file handle on the write-ahead log file. */
55728  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
55729  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
55730  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
55731    pRet->readOnly = WAL_RDONLY;
55732  }
55733
55734  if( rc!=SQLITE_OK ){
55735    walIndexClose(pRet, 0);
55736    sqlite3OsClose(pRet->pWalFd);
55737    sqlite3_free(pRet);
55738  }else{
55739    int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
55740    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
55741    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
55742      pRet->padToSectorBoundary = 0;
55743    }
55744    *ppWal = pRet;
55745    WALTRACE(("WAL%d: opened\n", pRet));
55746  }
55747  return rc;
55748}
55749
55750/*
55751** Change the size to which the WAL file is trucated on each reset.
55752*/
55753SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
55754  if( pWal ) pWal->mxWalSize = iLimit;
55755}
55756
55757/*
55758** Find the smallest page number out of all pages held in the WAL that
55759** has not been returned by any prior invocation of this method on the
55760** same WalIterator object.   Write into *piFrame the frame index where
55761** that page was last written into the WAL.  Write into *piPage the page
55762** number.
55763**
55764** Return 0 on success.  If there are no pages in the WAL with a page
55765** number larger than *piPage, then return 1.
55766*/
55767static int walIteratorNext(
55768  WalIterator *p,               /* Iterator */
55769  u32 *piPage,                  /* OUT: The page number of the next page */
55770  u32 *piFrame                  /* OUT: Wal frame index of next page */
55771){
55772  u32 iMin;                     /* Result pgno must be greater than iMin */
55773  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
55774  int i;                        /* For looping through segments */
55775
55776  iMin = p->iPrior;
55777  assert( iMin<0xffffffff );
55778  for(i=p->nSegment-1; i>=0; i--){
55779    struct WalSegment *pSegment = &p->aSegment[i];
55780    while( pSegment->iNext<pSegment->nEntry ){
55781      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
55782      if( iPg>iMin ){
55783        if( iPg<iRet ){
55784          iRet = iPg;
55785          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
55786        }
55787        break;
55788      }
55789      pSegment->iNext++;
55790    }
55791  }
55792
55793  *piPage = p->iPrior = iRet;
55794  return (iRet==0xFFFFFFFF);
55795}
55796
55797/*
55798** This function merges two sorted lists into a single sorted list.
55799**
55800** aLeft[] and aRight[] are arrays of indices.  The sort key is
55801** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
55802** is guaranteed for all J<K:
55803**
55804**        aContent[aLeft[J]] < aContent[aLeft[K]]
55805**        aContent[aRight[J]] < aContent[aRight[K]]
55806**
55807** This routine overwrites aRight[] with a new (probably longer) sequence
55808** of indices such that the aRight[] contains every index that appears in
55809** either aLeft[] or the old aRight[] and such that the second condition
55810** above is still met.
55811**
55812** The aContent[aLeft[X]] values will be unique for all X.  And the
55813** aContent[aRight[X]] values will be unique too.  But there might be
55814** one or more combinations of X and Y such that
55815**
55816**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
55817**
55818** When that happens, omit the aLeft[X] and use the aRight[Y] index.
55819*/
55820static void walMerge(
55821  const u32 *aContent,            /* Pages in wal - keys for the sort */
55822  ht_slot *aLeft,                 /* IN: Left hand input list */
55823  int nLeft,                      /* IN: Elements in array *paLeft */
55824  ht_slot **paRight,              /* IN/OUT: Right hand input list */
55825  int *pnRight,                   /* IN/OUT: Elements in *paRight */
55826  ht_slot *aTmp                   /* Temporary buffer */
55827){
55828  int iLeft = 0;                  /* Current index in aLeft */
55829  int iRight = 0;                 /* Current index in aRight */
55830  int iOut = 0;                   /* Current index in output buffer */
55831  int nRight = *pnRight;
55832  ht_slot *aRight = *paRight;
55833
55834  assert( nLeft>0 && nRight>0 );
55835  while( iRight<nRight || iLeft<nLeft ){
55836    ht_slot logpage;
55837    Pgno dbpage;
55838
55839    if( (iLeft<nLeft)
55840     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
55841    ){
55842      logpage = aLeft[iLeft++];
55843    }else{
55844      logpage = aRight[iRight++];
55845    }
55846    dbpage = aContent[logpage];
55847
55848    aTmp[iOut++] = logpage;
55849    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
55850
55851    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
55852    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
55853  }
55854
55855  *paRight = aLeft;
55856  *pnRight = iOut;
55857  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
55858}
55859
55860/*
55861** Sort the elements in list aList using aContent[] as the sort key.
55862** Remove elements with duplicate keys, preferring to keep the
55863** larger aList[] values.
55864**
55865** The aList[] entries are indices into aContent[].  The values in
55866** aList[] are to be sorted so that for all J<K:
55867**
55868**      aContent[aList[J]] < aContent[aList[K]]
55869**
55870** For any X and Y such that
55871**
55872**      aContent[aList[X]] == aContent[aList[Y]]
55873**
55874** Keep the larger of the two values aList[X] and aList[Y] and discard
55875** the smaller.
55876*/
55877static void walMergesort(
55878  const u32 *aContent,            /* Pages in wal */
55879  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
55880  ht_slot *aList,                 /* IN/OUT: List to sort */
55881  int *pnList                     /* IN/OUT: Number of elements in aList[] */
55882){
55883  struct Sublist {
55884    int nList;                    /* Number of elements in aList */
55885    ht_slot *aList;               /* Pointer to sub-list content */
55886  };
55887
55888  const int nList = *pnList;      /* Size of input list */
55889  int nMerge = 0;                 /* Number of elements in list aMerge */
55890  ht_slot *aMerge = 0;            /* List to be merged */
55891  int iList;                      /* Index into input list */
55892  u32 iSub = 0;                   /* Index into aSub array */
55893  struct Sublist aSub[13];        /* Array of sub-lists */
55894
55895  memset(aSub, 0, sizeof(aSub));
55896  assert( nList<=HASHTABLE_NPAGE && nList>0 );
55897  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
55898
55899  for(iList=0; iList<nList; iList++){
55900    nMerge = 1;
55901    aMerge = &aList[iList];
55902    for(iSub=0; iList & (1<<iSub); iSub++){
55903      struct Sublist *p;
55904      assert( iSub<ArraySize(aSub) );
55905      p = &aSub[iSub];
55906      assert( p->aList && p->nList<=(1<<iSub) );
55907      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
55908      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
55909    }
55910    aSub[iSub].aList = aMerge;
55911    aSub[iSub].nList = nMerge;
55912  }
55913
55914  for(iSub++; iSub<ArraySize(aSub); iSub++){
55915    if( nList & (1<<iSub) ){
55916      struct Sublist *p;
55917      assert( iSub<ArraySize(aSub) );
55918      p = &aSub[iSub];
55919      assert( p->nList<=(1<<iSub) );
55920      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
55921      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
55922    }
55923  }
55924  assert( aMerge==aList );
55925  *pnList = nMerge;
55926
55927#ifdef SQLITE_DEBUG
55928  {
55929    int i;
55930    for(i=1; i<*pnList; i++){
55931      assert( aContent[aList[i]] > aContent[aList[i-1]] );
55932    }
55933  }
55934#endif
55935}
55936
55937/*
55938** Free an iterator allocated by walIteratorInit().
55939*/
55940static void walIteratorFree(WalIterator *p){
55941  sqlite3_free(p);
55942}
55943
55944/*
55945** Construct a WalInterator object that can be used to loop over all
55946** pages in the WAL in ascending order. The caller must hold the checkpoint
55947** lock.
55948**
55949** On success, make *pp point to the newly allocated WalInterator object
55950** return SQLITE_OK. Otherwise, return an error code. If this routine
55951** returns an error, the value of *pp is undefined.
55952**
55953** The calling routine should invoke walIteratorFree() to destroy the
55954** WalIterator object when it has finished with it.
55955*/
55956static int walIteratorInit(Wal *pWal, WalIterator **pp){
55957  WalIterator *p;                 /* Return value */
55958  int nSegment;                   /* Number of segments to merge */
55959  u32 iLast;                      /* Last frame in log */
55960  int nByte;                      /* Number of bytes to allocate */
55961  int i;                          /* Iterator variable */
55962  ht_slot *aTmp;                  /* Temp space used by merge-sort */
55963  int rc = SQLITE_OK;             /* Return Code */
55964
55965  /* This routine only runs while holding the checkpoint lock. And
55966  ** it only runs if there is actually content in the log (mxFrame>0).
55967  */
55968  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
55969  iLast = pWal->hdr.mxFrame;
55970
55971  /* Allocate space for the WalIterator object. */
55972  nSegment = walFramePage(iLast) + 1;
55973  nByte = sizeof(WalIterator)
55974        + (nSegment-1)*sizeof(struct WalSegment)
55975        + iLast*sizeof(ht_slot);
55976  p = (WalIterator *)sqlite3_malloc64(nByte);
55977  if( !p ){
55978    return SQLITE_NOMEM_BKPT;
55979  }
55980  memset(p, 0, nByte);
55981  p->nSegment = nSegment;
55982
55983  /* Allocate temporary space used by the merge-sort routine. This block
55984  ** of memory will be freed before this function returns.
55985  */
55986  aTmp = (ht_slot *)sqlite3_malloc64(
55987      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
55988  );
55989  if( !aTmp ){
55990    rc = SQLITE_NOMEM_BKPT;
55991  }
55992
55993  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
55994    volatile ht_slot *aHash;
55995    u32 iZero;
55996    volatile u32 *aPgno;
55997
55998    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
55999    if( rc==SQLITE_OK ){
56000      int j;                      /* Counter variable */
56001      int nEntry;                 /* Number of entries in this segment */
56002      ht_slot *aIndex;            /* Sorted index for this segment */
56003
56004      aPgno++;
56005      if( (i+1)==nSegment ){
56006        nEntry = (int)(iLast - iZero);
56007      }else{
56008        nEntry = (int)((u32*)aHash - (u32*)aPgno);
56009      }
56010      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
56011      iZero++;
56012
56013      for(j=0; j<nEntry; j++){
56014        aIndex[j] = (ht_slot)j;
56015      }
56016      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
56017      p->aSegment[i].iZero = iZero;
56018      p->aSegment[i].nEntry = nEntry;
56019      p->aSegment[i].aIndex = aIndex;
56020      p->aSegment[i].aPgno = (u32 *)aPgno;
56021    }
56022  }
56023  sqlite3_free(aTmp);
56024
56025  if( rc!=SQLITE_OK ){
56026    walIteratorFree(p);
56027  }
56028  *pp = p;
56029  return rc;
56030}
56031
56032/*
56033** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
56034** n. If the attempt fails and parameter xBusy is not NULL, then it is a
56035** busy-handler function. Invoke it and retry the lock until either the
56036** lock is successfully obtained or the busy-handler returns 0.
56037*/
56038static int walBusyLock(
56039  Wal *pWal,                      /* WAL connection */
56040  int (*xBusy)(void*),            /* Function to call when busy */
56041  void *pBusyArg,                 /* Context argument for xBusyHandler */
56042  int lockIdx,                    /* Offset of first byte to lock */
56043  int n                           /* Number of bytes to lock */
56044){
56045  int rc;
56046  do {
56047    rc = walLockExclusive(pWal, lockIdx, n);
56048  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
56049  return rc;
56050}
56051
56052/*
56053** The cache of the wal-index header must be valid to call this function.
56054** Return the page-size in bytes used by the database.
56055*/
56056static int walPagesize(Wal *pWal){
56057  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
56058}
56059
56060/*
56061** The following is guaranteed when this function is called:
56062**
56063**   a) the WRITER lock is held,
56064**   b) the entire log file has been checkpointed, and
56065**   c) any existing readers are reading exclusively from the database
56066**      file - there are no readers that may attempt to read a frame from
56067**      the log file.
56068**
56069** This function updates the shared-memory structures so that the next
56070** client to write to the database (which may be this one) does so by
56071** writing frames into the start of the log file.
56072**
56073** The value of parameter salt1 is used as the aSalt[1] value in the
56074** new wal-index header. It should be passed a pseudo-random value (i.e.
56075** one obtained from sqlite3_randomness()).
56076*/
56077static void walRestartHdr(Wal *pWal, u32 salt1){
56078  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56079  int i;                          /* Loop counter */
56080  u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
56081  pWal->nCkpt++;
56082  pWal->hdr.mxFrame = 0;
56083  sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
56084  memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
56085  walIndexWriteHdr(pWal);
56086  pInfo->nBackfill = 0;
56087  pInfo->nBackfillAttempted = 0;
56088  pInfo->aReadMark[1] = 0;
56089  for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
56090  assert( pInfo->aReadMark[0]==0 );
56091}
56092
56093/*
56094** Copy as much content as we can from the WAL back into the database file
56095** in response to an sqlite3_wal_checkpoint() request or the equivalent.
56096**
56097** The amount of information copies from WAL to database might be limited
56098** by active readers.  This routine will never overwrite a database page
56099** that a concurrent reader might be using.
56100**
56101** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
56102** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
56103** checkpoints are always run by a background thread or background
56104** process, foreground threads will never block on a lengthy fsync call.
56105**
56106** Fsync is called on the WAL before writing content out of the WAL and
56107** into the database.  This ensures that if the new content is persistent
56108** in the WAL and can be recovered following a power-loss or hard reset.
56109**
56110** Fsync is also called on the database file if (and only if) the entire
56111** WAL content is copied into the database file.  This second fsync makes
56112** it safe to delete the WAL since the new content will persist in the
56113** database file.
56114**
56115** This routine uses and updates the nBackfill field of the wal-index header.
56116** This is the only routine that will increase the value of nBackfill.
56117** (A WAL reset or recovery will revert nBackfill to zero, but not increase
56118** its value.)
56119**
56120** The caller must be holding sufficient locks to ensure that no other
56121** checkpoint is running (in any other thread or process) at the same
56122** time.
56123*/
56124static int walCheckpoint(
56125  Wal *pWal,                      /* Wal connection */
56126  sqlite3 *db,                    /* Check for interrupts on this handle */
56127  int eMode,                      /* One of PASSIVE, FULL or RESTART */
56128  int (*xBusy)(void*),            /* Function to call when busy */
56129  void *pBusyArg,                 /* Context argument for xBusyHandler */
56130  int sync_flags,                 /* Flags for OsSync() (or 0) */
56131  u8 *zBuf                        /* Temporary buffer to use */
56132){
56133  int rc = SQLITE_OK;             /* Return code */
56134  int szPage;                     /* Database page-size */
56135  WalIterator *pIter = 0;         /* Wal iterator context */
56136  u32 iDbpage = 0;                /* Next database page to write */
56137  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
56138  u32 mxSafeFrame;                /* Max frame that can be backfilled */
56139  u32 mxPage;                     /* Max database page to write */
56140  int i;                          /* Loop counter */
56141  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
56142
56143  szPage = walPagesize(pWal);
56144  testcase( szPage<=32768 );
56145  testcase( szPage>=65536 );
56146  pInfo = walCkptInfo(pWal);
56147  if( pInfo->nBackfill<pWal->hdr.mxFrame ){
56148
56149    /* Allocate the iterator */
56150    rc = walIteratorInit(pWal, &pIter);
56151    if( rc!=SQLITE_OK ){
56152      return rc;
56153    }
56154    assert( pIter );
56155
56156    /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
56157    ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
56158    assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
56159
56160    /* Compute in mxSafeFrame the index of the last frame of the WAL that is
56161    ** safe to write into the database.  Frames beyond mxSafeFrame might
56162    ** overwrite database pages that are in use by active readers and thus
56163    ** cannot be backfilled from the WAL.
56164    */
56165    mxSafeFrame = pWal->hdr.mxFrame;
56166    mxPage = pWal->hdr.nPage;
56167    for(i=1; i<WAL_NREADER; i++){
56168      /* Thread-sanitizer reports that the following is an unsafe read,
56169      ** as some other thread may be in the process of updating the value
56170      ** of the aReadMark[] slot. The assumption here is that if that is
56171      ** happening, the other client may only be increasing the value,
56172      ** not decreasing it. So assuming either that either the "old" or
56173      ** "new" version of the value is read, and not some arbitrary value
56174      ** that would never be written by a real client, things are still
56175      ** safe.  */
56176      u32 y = pInfo->aReadMark[i];
56177      if( mxSafeFrame>y ){
56178        assert( y<=pWal->hdr.mxFrame );
56179        rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
56180        if( rc==SQLITE_OK ){
56181          pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
56182          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
56183        }else if( rc==SQLITE_BUSY ){
56184          mxSafeFrame = y;
56185          xBusy = 0;
56186        }else{
56187          goto walcheckpoint_out;
56188        }
56189      }
56190    }
56191
56192    if( pInfo->nBackfill<mxSafeFrame
56193     && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
56194    ){
56195      i64 nSize;                    /* Current size of database file */
56196      u32 nBackfill = pInfo->nBackfill;
56197
56198      pInfo->nBackfillAttempted = mxSafeFrame;
56199
56200      /* Sync the WAL to disk */
56201      if( sync_flags ){
56202        rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
56203      }
56204
56205      /* If the database may grow as a result of this checkpoint, hint
56206      ** about the eventual size of the db file to the VFS layer.
56207      */
56208      if( rc==SQLITE_OK ){
56209        i64 nReq = ((i64)mxPage * szPage);
56210        rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
56211        if( rc==SQLITE_OK && nSize<nReq ){
56212          sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
56213        }
56214      }
56215
56216
56217      /* Iterate through the contents of the WAL, copying data to the db file */
56218      while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
56219        i64 iOffset;
56220        assert( walFramePgno(pWal, iFrame)==iDbpage );
56221        if( db->u1.isInterrupted ){
56222          rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
56223          break;
56224        }
56225        if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
56226          continue;
56227        }
56228        iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
56229        /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
56230        rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
56231        if( rc!=SQLITE_OK ) break;
56232        iOffset = (iDbpage-1)*(i64)szPage;
56233        testcase( IS_BIG_INT(iOffset) );
56234        rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
56235        if( rc!=SQLITE_OK ) break;
56236      }
56237
56238      /* If work was actually accomplished... */
56239      if( rc==SQLITE_OK ){
56240        if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
56241          i64 szDb = pWal->hdr.nPage*(i64)szPage;
56242          testcase( IS_BIG_INT(szDb) );
56243          rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
56244          if( rc==SQLITE_OK && sync_flags ){
56245            rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
56246          }
56247        }
56248        if( rc==SQLITE_OK ){
56249          pInfo->nBackfill = mxSafeFrame;
56250        }
56251      }
56252
56253      /* Release the reader lock held while backfilling */
56254      walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
56255    }
56256
56257    if( rc==SQLITE_BUSY ){
56258      /* Reset the return code so as not to report a checkpoint failure
56259      ** just because there are active readers.  */
56260      rc = SQLITE_OK;
56261    }
56262  }
56263
56264  /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
56265  ** entire wal file has been copied into the database file, then block
56266  ** until all readers have finished using the wal file. This ensures that
56267  ** the next process to write to the database restarts the wal file.
56268  */
56269  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
56270    assert( pWal->writeLock );
56271    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
56272      rc = SQLITE_BUSY;
56273    }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
56274      u32 salt1;
56275      sqlite3_randomness(4, &salt1);
56276      assert( pInfo->nBackfill==pWal->hdr.mxFrame );
56277      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
56278      if( rc==SQLITE_OK ){
56279        if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
56280          /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
56281          ** SQLITE_CHECKPOINT_RESTART with the addition that it also
56282          ** truncates the log file to zero bytes just prior to a
56283          ** successful return.
56284          **
56285          ** In theory, it might be safe to do this without updating the
56286          ** wal-index header in shared memory, as all subsequent reader or
56287          ** writer clients should see that the entire log file has been
56288          ** checkpointed and behave accordingly. This seems unsafe though,
56289          ** as it would leave the system in a state where the contents of
56290          ** the wal-index header do not match the contents of the
56291          ** file-system. To avoid this, update the wal-index header to
56292          ** indicate that the log file contains zero valid frames.  */
56293          walRestartHdr(pWal, salt1);
56294          rc = sqlite3OsTruncate(pWal->pWalFd, 0);
56295        }
56296        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
56297      }
56298    }
56299  }
56300
56301 walcheckpoint_out:
56302  walIteratorFree(pIter);
56303  return rc;
56304}
56305
56306/*
56307** If the WAL file is currently larger than nMax bytes in size, truncate
56308** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
56309*/
56310static void walLimitSize(Wal *pWal, i64 nMax){
56311  i64 sz;
56312  int rx;
56313  sqlite3BeginBenignMalloc();
56314  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
56315  if( rx==SQLITE_OK && (sz > nMax ) ){
56316    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
56317  }
56318  sqlite3EndBenignMalloc();
56319  if( rx ){
56320    sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
56321  }
56322}
56323
56324/*
56325** Close a connection to a log file.
56326*/
56327SQLITE_PRIVATE int sqlite3WalClose(
56328  Wal *pWal,                      /* Wal to close */
56329  sqlite3 *db,                    /* For interrupt flag */
56330  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
56331  int nBuf,
56332  u8 *zBuf                        /* Buffer of at least nBuf bytes */
56333){
56334  int rc = SQLITE_OK;
56335  if( pWal ){
56336    int isDelete = 0;             /* True to unlink wal and wal-index files */
56337
56338    /* If an EXCLUSIVE lock can be obtained on the database file (using the
56339    ** ordinary, rollback-mode locking methods, this guarantees that the
56340    ** connection associated with this log file is the only connection to
56341    ** the database. In this case checkpoint the database and unlink both
56342    ** the wal and wal-index files.
56343    **
56344    ** The EXCLUSIVE lock is not released before returning.
56345    */
56346    if( zBuf!=0
56347     && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
56348    ){
56349      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
56350        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
56351      }
56352      rc = sqlite3WalCheckpoint(pWal, db,
56353          SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
56354      );
56355      if( rc==SQLITE_OK ){
56356        int bPersist = -1;
56357        sqlite3OsFileControlHint(
56358            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
56359        );
56360        if( bPersist!=1 ){
56361          /* Try to delete the WAL file if the checkpoint completed and
56362          ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
56363          ** mode (!bPersist) */
56364          isDelete = 1;
56365        }else if( pWal->mxWalSize>=0 ){
56366          /* Try to truncate the WAL file to zero bytes if the checkpoint
56367          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
56368          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
56369          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
56370          ** to zero bytes as truncating to the journal_size_limit might
56371          ** leave a corrupt WAL file on disk. */
56372          walLimitSize(pWal, 0);
56373        }
56374      }
56375    }
56376
56377    walIndexClose(pWal, isDelete);
56378    sqlite3OsClose(pWal->pWalFd);
56379    if( isDelete ){
56380      sqlite3BeginBenignMalloc();
56381      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
56382      sqlite3EndBenignMalloc();
56383    }
56384    WALTRACE(("WAL%p: closed\n", pWal));
56385    sqlite3_free((void *)pWal->apWiData);
56386    sqlite3_free(pWal);
56387  }
56388  return rc;
56389}
56390
56391/*
56392** Try to read the wal-index header.  Return 0 on success and 1 if
56393** there is a problem.
56394**
56395** The wal-index is in shared memory.  Another thread or process might
56396** be writing the header at the same time this procedure is trying to
56397** read it, which might result in inconsistency.  A dirty read is detected
56398** by verifying that both copies of the header are the same and also by
56399** a checksum on the header.
56400**
56401** If and only if the read is consistent and the header is different from
56402** pWal->hdr, then pWal->hdr is updated to the content of the new header
56403** and *pChanged is set to 1.
56404**
56405** If the checksum cannot be verified return non-zero. If the header
56406** is read successfully and the checksum verified, return zero.
56407*/
56408static int walIndexTryHdr(Wal *pWal, int *pChanged){
56409  u32 aCksum[2];                  /* Checksum on the header content */
56410  WalIndexHdr h1, h2;             /* Two copies of the header content */
56411  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
56412
56413  /* The first page of the wal-index must be mapped at this point. */
56414  assert( pWal->nWiData>0 && pWal->apWiData[0] );
56415
56416  /* Read the header. This might happen concurrently with a write to the
56417  ** same area of shared memory on a different CPU in a SMP,
56418  ** meaning it is possible that an inconsistent snapshot is read
56419  ** from the file. If this happens, return non-zero.
56420  **
56421  ** There are two copies of the header at the beginning of the wal-index.
56422  ** When reading, read [0] first then [1].  Writes are in the reverse order.
56423  ** Memory barriers are used to prevent the compiler or the hardware from
56424  ** reordering the reads and writes.
56425  */
56426  aHdr = walIndexHdr(pWal);
56427  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
56428  walShmBarrier(pWal);
56429  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
56430
56431  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
56432    return 1;   /* Dirty read */
56433  }
56434  if( h1.isInit==0 ){
56435    return 1;   /* Malformed header - probably all zeros */
56436  }
56437  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
56438  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
56439    return 1;   /* Checksum does not match */
56440  }
56441
56442  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
56443    *pChanged = 1;
56444    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
56445    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
56446    testcase( pWal->szPage<=32768 );
56447    testcase( pWal->szPage>=65536 );
56448  }
56449
56450  /* The header was successfully read. Return zero. */
56451  return 0;
56452}
56453
56454/*
56455** Read the wal-index header from the wal-index and into pWal->hdr.
56456** If the wal-header appears to be corrupt, try to reconstruct the
56457** wal-index from the WAL before returning.
56458**
56459** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
56460** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
56461** to 0.
56462**
56463** If the wal-index header is successfully read, return SQLITE_OK.
56464** Otherwise an SQLite error code.
56465*/
56466static int walIndexReadHdr(Wal *pWal, int *pChanged){
56467  int rc;                         /* Return code */
56468  int badHdr;                     /* True if a header read failed */
56469  volatile u32 *page0;            /* Chunk of wal-index containing header */
56470
56471  /* Ensure that page 0 of the wal-index (the page that contains the
56472  ** wal-index header) is mapped. Return early if an error occurs here.
56473  */
56474  assert( pChanged );
56475  rc = walIndexPage(pWal, 0, &page0);
56476  if( rc!=SQLITE_OK ){
56477    return rc;
56478  };
56479  assert( page0 || pWal->writeLock==0 );
56480
56481  /* If the first page of the wal-index has been mapped, try to read the
56482  ** wal-index header immediately, without holding any lock. This usually
56483  ** works, but may fail if the wal-index header is corrupt or currently
56484  ** being modified by another thread or process.
56485  */
56486  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
56487
56488  /* If the first attempt failed, it might have been due to a race
56489  ** with a writer.  So get a WRITE lock and try again.
56490  */
56491  assert( badHdr==0 || pWal->writeLock==0 );
56492  if( badHdr ){
56493    if( pWal->readOnly & WAL_SHM_RDONLY ){
56494      if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
56495        walUnlockShared(pWal, WAL_WRITE_LOCK);
56496        rc = SQLITE_READONLY_RECOVERY;
56497      }
56498    }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
56499      pWal->writeLock = 1;
56500      if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
56501        badHdr = walIndexTryHdr(pWal, pChanged);
56502        if( badHdr ){
56503          /* If the wal-index header is still malformed even while holding
56504          ** a WRITE lock, it can only mean that the header is corrupted and
56505          ** needs to be reconstructed.  So run recovery to do exactly that.
56506          */
56507          rc = walIndexRecover(pWal);
56508          *pChanged = 1;
56509        }
56510      }
56511      pWal->writeLock = 0;
56512      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
56513    }
56514  }
56515
56516  /* If the header is read successfully, check the version number to make
56517  ** sure the wal-index was not constructed with some future format that
56518  ** this version of SQLite cannot understand.
56519  */
56520  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
56521    rc = SQLITE_CANTOPEN_BKPT;
56522  }
56523
56524  return rc;
56525}
56526
56527/*
56528** This is the value that walTryBeginRead returns when it needs to
56529** be retried.
56530*/
56531#define WAL_RETRY  (-1)
56532
56533/*
56534** Attempt to start a read transaction.  This might fail due to a race or
56535** other transient condition.  When that happens, it returns WAL_RETRY to
56536** indicate to the caller that it is safe to retry immediately.
56537**
56538** On success return SQLITE_OK.  On a permanent failure (such an
56539** I/O error or an SQLITE_BUSY because another process is running
56540** recovery) return a positive error code.
56541**
56542** The useWal parameter is true to force the use of the WAL and disable
56543** the case where the WAL is bypassed because it has been completely
56544** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
56545** to make a copy of the wal-index header into pWal->hdr.  If the
56546** wal-index header has changed, *pChanged is set to 1 (as an indication
56547** to the caller that the local paget cache is obsolete and needs to be
56548** flushed.)  When useWal==1, the wal-index header is assumed to already
56549** be loaded and the pChanged parameter is unused.
56550**
56551** The caller must set the cnt parameter to the number of prior calls to
56552** this routine during the current read attempt that returned WAL_RETRY.
56553** This routine will start taking more aggressive measures to clear the
56554** race conditions after multiple WAL_RETRY returns, and after an excessive
56555** number of errors will ultimately return SQLITE_PROTOCOL.  The
56556** SQLITE_PROTOCOL return indicates that some other process has gone rogue
56557** and is not honoring the locking protocol.  There is a vanishingly small
56558** chance that SQLITE_PROTOCOL could be returned because of a run of really
56559** bad luck when there is lots of contention for the wal-index, but that
56560** possibility is so small that it can be safely neglected, we believe.
56561**
56562** On success, this routine obtains a read lock on
56563** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
56564** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
56565** that means the Wal does not hold any read lock.  The reader must not
56566** access any database page that is modified by a WAL frame up to and
56567** including frame number aReadMark[pWal->readLock].  The reader will
56568** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
56569** Or if pWal->readLock==0, then the reader will ignore the WAL
56570** completely and get all content directly from the database file.
56571** If the useWal parameter is 1 then the WAL will never be ignored and
56572** this routine will always set pWal->readLock>0 on success.
56573** When the read transaction is completed, the caller must release the
56574** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
56575**
56576** This routine uses the nBackfill and aReadMark[] fields of the header
56577** to select a particular WAL_READ_LOCK() that strives to let the
56578** checkpoint process do as much work as possible.  This routine might
56579** update values of the aReadMark[] array in the header, but if it does
56580** so it takes care to hold an exclusive lock on the corresponding
56581** WAL_READ_LOCK() while changing values.
56582*/
56583static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
56584  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
56585  u32 mxReadMark;                 /* Largest aReadMark[] value */
56586  int mxI;                        /* Index of largest aReadMark[] value */
56587  int i;                          /* Loop counter */
56588  int rc = SQLITE_OK;             /* Return code  */
56589  u32 mxFrame;                    /* Wal frame to lock to */
56590
56591  assert( pWal->readLock<0 );     /* Not currently locked */
56592
56593  /* Take steps to avoid spinning forever if there is a protocol error.
56594  **
56595  ** Circumstances that cause a RETRY should only last for the briefest
56596  ** instances of time.  No I/O or other system calls are done while the
56597  ** locks are held, so the locks should not be held for very long. But
56598  ** if we are unlucky, another process that is holding a lock might get
56599  ** paged out or take a page-fault that is time-consuming to resolve,
56600  ** during the few nanoseconds that it is holding the lock.  In that case,
56601  ** it might take longer than normal for the lock to free.
56602  **
56603  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
56604  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
56605  ** is more of a scheduler yield than an actual delay.  But on the 10th
56606  ** an subsequent retries, the delays start becoming longer and longer,
56607  ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
56608  ** The total delay time before giving up is less than 10 seconds.
56609  */
56610  if( cnt>5 ){
56611    int nDelay = 1;                      /* Pause time in microseconds */
56612    if( cnt>100 ){
56613      VVA_ONLY( pWal->lockError = 1; )
56614      return SQLITE_PROTOCOL;
56615    }
56616    if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
56617    sqlite3OsSleep(pWal->pVfs, nDelay);
56618  }
56619
56620  if( !useWal ){
56621    rc = walIndexReadHdr(pWal, pChanged);
56622    if( rc==SQLITE_BUSY ){
56623      /* If there is not a recovery running in another thread or process
56624      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
56625      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
56626      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
56627      ** would be technically correct.  But the race is benign since with
56628      ** WAL_RETRY this routine will be called again and will probably be
56629      ** right on the second iteration.
56630      */
56631      if( pWal->apWiData[0]==0 ){
56632        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
56633        ** We assume this is a transient condition, so return WAL_RETRY. The
56634        ** xShmMap() implementation used by the default unix and win32 VFS
56635        ** modules may return SQLITE_BUSY due to a race condition in the
56636        ** code that determines whether or not the shared-memory region
56637        ** must be zeroed before the requested page is returned.
56638        */
56639        rc = WAL_RETRY;
56640      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
56641        walUnlockShared(pWal, WAL_RECOVER_LOCK);
56642        rc = WAL_RETRY;
56643      }else if( rc==SQLITE_BUSY ){
56644        rc = SQLITE_BUSY_RECOVERY;
56645      }
56646    }
56647    if( rc!=SQLITE_OK ){
56648      return rc;
56649    }
56650  }
56651
56652  pInfo = walCkptInfo(pWal);
56653  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
56654#ifdef SQLITE_ENABLE_SNAPSHOT
56655   && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
56656     || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
56657#endif
56658  ){
56659    /* The WAL has been completely backfilled (or it is empty).
56660    ** and can be safely ignored.
56661    */
56662    rc = walLockShared(pWal, WAL_READ_LOCK(0));
56663    walShmBarrier(pWal);
56664    if( rc==SQLITE_OK ){
56665      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
56666        /* It is not safe to allow the reader to continue here if frames
56667        ** may have been appended to the log before READ_LOCK(0) was obtained.
56668        ** When holding READ_LOCK(0), the reader ignores the entire log file,
56669        ** which implies that the database file contains a trustworthy
56670        ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
56671        ** happening, this is usually correct.
56672        **
56673        ** However, if frames have been appended to the log (or if the log
56674        ** is wrapped and written for that matter) before the READ_LOCK(0)
56675        ** is obtained, that is not necessarily true. A checkpointer may
56676        ** have started to backfill the appended frames but crashed before
56677        ** it finished. Leaving a corrupt image in the database file.
56678        */
56679        walUnlockShared(pWal, WAL_READ_LOCK(0));
56680        return WAL_RETRY;
56681      }
56682      pWal->readLock = 0;
56683      return SQLITE_OK;
56684    }else if( rc!=SQLITE_BUSY ){
56685      return rc;
56686    }
56687  }
56688
56689  /* If we get this far, it means that the reader will want to use
56690  ** the WAL to get at content from recent commits.  The job now is
56691  ** to select one of the aReadMark[] entries that is closest to
56692  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
56693  */
56694  mxReadMark = 0;
56695  mxI = 0;
56696  mxFrame = pWal->hdr.mxFrame;
56697#ifdef SQLITE_ENABLE_SNAPSHOT
56698  if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
56699    mxFrame = pWal->pSnapshot->mxFrame;
56700  }
56701#endif
56702  for(i=1; i<WAL_NREADER; i++){
56703    u32 thisMark = pInfo->aReadMark[i];
56704    if( mxReadMark<=thisMark && thisMark<=mxFrame ){
56705      assert( thisMark!=READMARK_NOT_USED );
56706      mxReadMark = thisMark;
56707      mxI = i;
56708    }
56709  }
56710  if( (pWal->readOnly & WAL_SHM_RDONLY)==0
56711   && (mxReadMark<mxFrame || mxI==0)
56712  ){
56713    for(i=1; i<WAL_NREADER; i++){
56714      rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
56715      if( rc==SQLITE_OK ){
56716        mxReadMark = pInfo->aReadMark[i] = mxFrame;
56717        mxI = i;
56718        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
56719        break;
56720      }else if( rc!=SQLITE_BUSY ){
56721        return rc;
56722      }
56723    }
56724  }
56725  if( mxI==0 ){
56726    assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
56727    return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
56728  }
56729
56730  rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
56731  if( rc ){
56732    return rc==SQLITE_BUSY ? WAL_RETRY : rc;
56733  }
56734  /* Now that the read-lock has been obtained, check that neither the
56735  ** value in the aReadMark[] array or the contents of the wal-index
56736  ** header have changed.
56737  **
56738  ** It is necessary to check that the wal-index header did not change
56739  ** between the time it was read and when the shared-lock was obtained
56740  ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
56741  ** that the log file may have been wrapped by a writer, or that frames
56742  ** that occur later in the log than pWal->hdr.mxFrame may have been
56743  ** copied into the database by a checkpointer. If either of these things
56744  ** happened, then reading the database with the current value of
56745  ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
56746  ** instead.
56747  **
56748  ** Before checking that the live wal-index header has not changed
56749  ** since it was read, set Wal.minFrame to the first frame in the wal
56750  ** file that has not yet been checkpointed. This client will not need
56751  ** to read any frames earlier than minFrame from the wal file - they
56752  ** can be safely read directly from the database file.
56753  **
56754  ** Because a ShmBarrier() call is made between taking the copy of
56755  ** nBackfill and checking that the wal-header in shared-memory still
56756  ** matches the one cached in pWal->hdr, it is guaranteed that the
56757  ** checkpointer that set nBackfill was not working with a wal-index
56758  ** header newer than that cached in pWal->hdr. If it were, that could
56759  ** cause a problem. The checkpointer could omit to checkpoint
56760  ** a version of page X that lies before pWal->minFrame (call that version
56761  ** A) on the basis that there is a newer version (version B) of the same
56762  ** page later in the wal file. But if version B happens to like past
56763  ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
56764  ** that it can read version A from the database file. However, since
56765  ** we can guarantee that the checkpointer that set nBackfill could not
56766  ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
56767  */
56768  pWal->minFrame = pInfo->nBackfill+1;
56769  walShmBarrier(pWal);
56770  if( pInfo->aReadMark[mxI]!=mxReadMark
56771   || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
56772  ){
56773    walUnlockShared(pWal, WAL_READ_LOCK(mxI));
56774    return WAL_RETRY;
56775  }else{
56776    assert( mxReadMark<=pWal->hdr.mxFrame );
56777    pWal->readLock = (i16)mxI;
56778  }
56779  return rc;
56780}
56781
56782#ifdef SQLITE_ENABLE_SNAPSHOT
56783/*
56784** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
56785** variable so that older snapshots can be accessed. To do this, loop
56786** through all wal frames from nBackfillAttempted to (nBackfill+1),
56787** comparing their content to the corresponding page with the database
56788** file, if any. Set nBackfillAttempted to the frame number of the
56789** first frame for which the wal file content matches the db file.
56790**
56791** This is only really safe if the file-system is such that any page
56792** writes made by earlier checkpointers were atomic operations, which
56793** is not always true. It is also possible that nBackfillAttempted
56794** may be left set to a value larger than expected, if a wal frame
56795** contains content that duplicate of an earlier version of the same
56796** page.
56797**
56798** SQLITE_OK is returned if successful, or an SQLite error code if an
56799** error occurs. It is not an error if nBackfillAttempted cannot be
56800** decreased at all.
56801*/
56802SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
56803  int rc;
56804
56805  assert( pWal->readLock>=0 );
56806  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
56807  if( rc==SQLITE_OK ){
56808    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56809    int szPage = (int)pWal->szPage;
56810    i64 szDb;                   /* Size of db file in bytes */
56811
56812    rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
56813    if( rc==SQLITE_OK ){
56814      void *pBuf1 = sqlite3_malloc(szPage);
56815      void *pBuf2 = sqlite3_malloc(szPage);
56816      if( pBuf1==0 || pBuf2==0 ){
56817        rc = SQLITE_NOMEM;
56818      }else{
56819        u32 i = pInfo->nBackfillAttempted;
56820        for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
56821          volatile ht_slot *dummy;
56822          volatile u32 *aPgno;      /* Array of page numbers */
56823          u32 iZero;                /* Frame corresponding to aPgno[0] */
56824          u32 pgno;                 /* Page number in db file */
56825          i64 iDbOff;               /* Offset of db file entry */
56826          i64 iWalOff;              /* Offset of wal file entry */
56827
56828          rc = walHashGet(pWal, walFramePage(i), &dummy, &aPgno, &iZero);
56829          if( rc!=SQLITE_OK ) break;
56830          pgno = aPgno[i-iZero];
56831          iDbOff = (i64)(pgno-1) * szPage;
56832
56833          if( iDbOff+szPage<=szDb ){
56834            iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
56835            rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
56836
56837            if( rc==SQLITE_OK ){
56838              rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
56839            }
56840
56841            if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
56842              break;
56843            }
56844          }
56845
56846          pInfo->nBackfillAttempted = i-1;
56847        }
56848      }
56849
56850      sqlite3_free(pBuf1);
56851      sqlite3_free(pBuf2);
56852    }
56853    walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
56854  }
56855
56856  return rc;
56857}
56858#endif /* SQLITE_ENABLE_SNAPSHOT */
56859
56860/*
56861** Begin a read transaction on the database.
56862**
56863** This routine used to be called sqlite3OpenSnapshot() and with good reason:
56864** it takes a snapshot of the state of the WAL and wal-index for the current
56865** instant in time.  The current thread will continue to use this snapshot.
56866** Other threads might append new content to the WAL and wal-index but
56867** that extra content is ignored by the current thread.
56868**
56869** If the database contents have changes since the previous read
56870** transaction, then *pChanged is set to 1 before returning.  The
56871** Pager layer will use this to know that is cache is stale and
56872** needs to be flushed.
56873*/
56874SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
56875  int rc;                         /* Return code */
56876  int cnt = 0;                    /* Number of TryBeginRead attempts */
56877
56878#ifdef SQLITE_ENABLE_SNAPSHOT
56879  int bChanged = 0;
56880  WalIndexHdr *pSnapshot = pWal->pSnapshot;
56881  if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
56882    bChanged = 1;
56883  }
56884#endif
56885
56886  do{
56887    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
56888  }while( rc==WAL_RETRY );
56889  testcase( (rc&0xff)==SQLITE_BUSY );
56890  testcase( (rc&0xff)==SQLITE_IOERR );
56891  testcase( rc==SQLITE_PROTOCOL );
56892  testcase( rc==SQLITE_OK );
56893
56894#ifdef SQLITE_ENABLE_SNAPSHOT
56895  if( rc==SQLITE_OK ){
56896    if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
56897      /* At this point the client has a lock on an aReadMark[] slot holding
56898      ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
56899      ** is populated with the wal-index header corresponding to the head
56900      ** of the wal file. Verify that pSnapshot is still valid before
56901      ** continuing.  Reasons why pSnapshot might no longer be valid:
56902      **
56903      **    (1)  The WAL file has been reset since the snapshot was taken.
56904      **         In this case, the salt will have changed.
56905      **
56906      **    (2)  A checkpoint as been attempted that wrote frames past
56907      **         pSnapshot->mxFrame into the database file.  Note that the
56908      **         checkpoint need not have completed for this to cause problems.
56909      */
56910      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56911
56912      assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
56913      assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
56914
56915      /* It is possible that there is a checkpointer thread running
56916      ** concurrent with this code. If this is the case, it may be that the
56917      ** checkpointer has already determined that it will checkpoint
56918      ** snapshot X, where X is later in the wal file than pSnapshot, but
56919      ** has not yet set the pInfo->nBackfillAttempted variable to indicate
56920      ** its intent. To avoid the race condition this leads to, ensure that
56921      ** there is no checkpointer process by taking a shared CKPT lock
56922      ** before checking pInfo->nBackfillAttempted.
56923      **
56924      ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
56925      **       this already?
56926      */
56927      rc = walLockShared(pWal, WAL_CKPT_LOCK);
56928
56929      if( rc==SQLITE_OK ){
56930        /* Check that the wal file has not been wrapped. Assuming that it has
56931        ** not, also check that no checkpointer has attempted to checkpoint any
56932        ** frames beyond pSnapshot->mxFrame. If either of these conditions are
56933        ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
56934        ** with *pSnapshot and set *pChanged as appropriate for opening the
56935        ** snapshot.  */
56936        if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
56937         && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
56938        ){
56939          assert( pWal->readLock>0 );
56940          memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
56941          *pChanged = bChanged;
56942        }else{
56943          rc = SQLITE_BUSY_SNAPSHOT;
56944        }
56945
56946        /* Release the shared CKPT lock obtained above. */
56947        walUnlockShared(pWal, WAL_CKPT_LOCK);
56948      }
56949
56950
56951      if( rc!=SQLITE_OK ){
56952        sqlite3WalEndReadTransaction(pWal);
56953      }
56954    }
56955  }
56956#endif
56957  return rc;
56958}
56959
56960/*
56961** Finish with a read transaction.  All this does is release the
56962** read-lock.
56963*/
56964SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
56965  sqlite3WalEndWriteTransaction(pWal);
56966  if( pWal->readLock>=0 ){
56967    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
56968    pWal->readLock = -1;
56969  }
56970}
56971
56972/*
56973** Search the wal file for page pgno. If found, set *piRead to the frame that
56974** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
56975** to zero.
56976**
56977** Return SQLITE_OK if successful, or an error code if an error occurs. If an
56978** error does occur, the final value of *piRead is undefined.
56979*/
56980SQLITE_PRIVATE int sqlite3WalFindFrame(
56981  Wal *pWal,                      /* WAL handle */
56982  Pgno pgno,                      /* Database page number to read data for */
56983  u32 *piRead                     /* OUT: Frame number (or zero) */
56984){
56985  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
56986  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
56987  int iHash;                      /* Used to loop through N hash tables */
56988  int iMinHash;
56989
56990  /* This routine is only be called from within a read transaction. */
56991  assert( pWal->readLock>=0 || pWal->lockError );
56992
56993  /* If the "last page" field of the wal-index header snapshot is 0, then
56994  ** no data will be read from the wal under any circumstances. Return early
56995  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
56996  ** then the WAL is ignored by the reader so return early, as if the
56997  ** WAL were empty.
56998  */
56999  if( iLast==0 || pWal->readLock==0 ){
57000    *piRead = 0;
57001    return SQLITE_OK;
57002  }
57003
57004  /* Search the hash table or tables for an entry matching page number
57005  ** pgno. Each iteration of the following for() loop searches one
57006  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
57007  **
57008  ** This code might run concurrently to the code in walIndexAppend()
57009  ** that adds entries to the wal-index (and possibly to this hash
57010  ** table). This means the value just read from the hash
57011  ** slot (aHash[iKey]) may have been added before or after the
57012  ** current read transaction was opened. Values added after the
57013  ** read transaction was opened may have been written incorrectly -
57014  ** i.e. these slots may contain garbage data. However, we assume
57015  ** that any slots written before the current read transaction was
57016  ** opened remain unmodified.
57017  **
57018  ** For the reasons above, the if(...) condition featured in the inner
57019  ** loop of the following block is more stringent that would be required
57020  ** if we had exclusive access to the hash-table:
57021  **
57022  **   (aPgno[iFrame]==pgno):
57023  **     This condition filters out normal hash-table collisions.
57024  **
57025  **   (iFrame<=iLast):
57026  **     This condition filters out entries that were added to the hash
57027  **     table after the current read-transaction had started.
57028  */
57029  iMinHash = walFramePage(pWal->minFrame);
57030  for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
57031    volatile ht_slot *aHash;      /* Pointer to hash table */
57032    volatile u32 *aPgno;          /* Pointer to array of page numbers */
57033    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
57034    int iKey;                     /* Hash slot index */
57035    int nCollide;                 /* Number of hash collisions remaining */
57036    int rc;                       /* Error code */
57037
57038    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
57039    if( rc!=SQLITE_OK ){
57040      return rc;
57041    }
57042    nCollide = HASHTABLE_NSLOT;
57043    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
57044      u32 iFrame = aHash[iKey] + iZero;
57045      if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
57046        assert( iFrame>iRead || CORRUPT_DB );
57047        iRead = iFrame;
57048      }
57049      if( (nCollide--)==0 ){
57050        return SQLITE_CORRUPT_BKPT;
57051      }
57052    }
57053  }
57054
57055#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
57056  /* If expensive assert() statements are available, do a linear search
57057  ** of the wal-index file content. Make sure the results agree with the
57058  ** result obtained using the hash indexes above.  */
57059  {
57060    u32 iRead2 = 0;
57061    u32 iTest;
57062    assert( pWal->minFrame>0 );
57063    for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
57064      if( walFramePgno(pWal, iTest)==pgno ){
57065        iRead2 = iTest;
57066        break;
57067      }
57068    }
57069    assert( iRead==iRead2 );
57070  }
57071#endif
57072
57073  *piRead = iRead;
57074  return SQLITE_OK;
57075}
57076
57077/*
57078** Read the contents of frame iRead from the wal file into buffer pOut
57079** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
57080** error code otherwise.
57081*/
57082SQLITE_PRIVATE int sqlite3WalReadFrame(
57083  Wal *pWal,                      /* WAL handle */
57084  u32 iRead,                      /* Frame to read */
57085  int nOut,                       /* Size of buffer pOut in bytes */
57086  u8 *pOut                        /* Buffer to write page data to */
57087){
57088  int sz;
57089  i64 iOffset;
57090  sz = pWal->hdr.szPage;
57091  sz = (sz&0xfe00) + ((sz&0x0001)<<16);
57092  testcase( sz<=32768 );
57093  testcase( sz>=65536 );
57094  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
57095  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
57096  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
57097}
57098
57099/*
57100** Return the size of the database in pages (or zero, if unknown).
57101*/
57102SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
57103  if( pWal && ALWAYS(pWal->readLock>=0) ){
57104    return pWal->hdr.nPage;
57105  }
57106  return 0;
57107}
57108
57109
57110/*
57111** This function starts a write transaction on the WAL.
57112**
57113** A read transaction must have already been started by a prior call
57114** to sqlite3WalBeginReadTransaction().
57115**
57116** If another thread or process has written into the database since
57117** the read transaction was started, then it is not possible for this
57118** thread to write as doing so would cause a fork.  So this routine
57119** returns SQLITE_BUSY in that case and no write transaction is started.
57120**
57121** There can only be a single writer active at a time.
57122*/
57123SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
57124  int rc;
57125
57126  /* Cannot start a write transaction without first holding a read
57127  ** transaction. */
57128  assert( pWal->readLock>=0 );
57129  assert( pWal->writeLock==0 && pWal->iReCksum==0 );
57130
57131  if( pWal->readOnly ){
57132    return SQLITE_READONLY;
57133  }
57134
57135  /* Only one writer allowed at a time.  Get the write lock.  Return
57136  ** SQLITE_BUSY if unable.
57137  */
57138  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
57139  if( rc ){
57140    return rc;
57141  }
57142  pWal->writeLock = 1;
57143
57144  /* If another connection has written to the database file since the
57145  ** time the read transaction on this connection was started, then
57146  ** the write is disallowed.
57147  */
57148  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
57149    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
57150    pWal->writeLock = 0;
57151    rc = SQLITE_BUSY_SNAPSHOT;
57152  }
57153
57154  return rc;
57155}
57156
57157/*
57158** End a write transaction.  The commit has already been done.  This
57159** routine merely releases the lock.
57160*/
57161SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
57162  if( pWal->writeLock ){
57163    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
57164    pWal->writeLock = 0;
57165    pWal->iReCksum = 0;
57166    pWal->truncateOnCommit = 0;
57167  }
57168  return SQLITE_OK;
57169}
57170
57171/*
57172** If any data has been written (but not committed) to the log file, this
57173** function moves the write-pointer back to the start of the transaction.
57174**
57175** Additionally, the callback function is invoked for each frame written
57176** to the WAL since the start of the transaction. If the callback returns
57177** other than SQLITE_OK, it is not invoked again and the error code is
57178** returned to the caller.
57179**
57180** Otherwise, if the callback function does not return an error, this
57181** function returns SQLITE_OK.
57182*/
57183SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
57184  int rc = SQLITE_OK;
57185  if( ALWAYS(pWal->writeLock) ){
57186    Pgno iMax = pWal->hdr.mxFrame;
57187    Pgno iFrame;
57188
57189    /* Restore the clients cache of the wal-index header to the state it
57190    ** was in before the client began writing to the database.
57191    */
57192    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
57193
57194    for(iFrame=pWal->hdr.mxFrame+1;
57195        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
57196        iFrame++
57197    ){
57198      /* This call cannot fail. Unless the page for which the page number
57199      ** is passed as the second argument is (a) in the cache and
57200      ** (b) has an outstanding reference, then xUndo is either a no-op
57201      ** (if (a) is false) or simply expels the page from the cache (if (b)
57202      ** is false).
57203      **
57204      ** If the upper layer is doing a rollback, it is guaranteed that there
57205      ** are no outstanding references to any page other than page 1. And
57206      ** page 1 is never written to the log until the transaction is
57207      ** committed. As a result, the call to xUndo may not fail.
57208      */
57209      assert( walFramePgno(pWal, iFrame)!=1 );
57210      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
57211    }
57212    if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
57213  }
57214  return rc;
57215}
57216
57217/*
57218** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
57219** values. This function populates the array with values required to
57220** "rollback" the write position of the WAL handle back to the current
57221** point in the event of a savepoint rollback (via WalSavepointUndo()).
57222*/
57223SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
57224  assert( pWal->writeLock );
57225  aWalData[0] = pWal->hdr.mxFrame;
57226  aWalData[1] = pWal->hdr.aFrameCksum[0];
57227  aWalData[2] = pWal->hdr.aFrameCksum[1];
57228  aWalData[3] = pWal->nCkpt;
57229}
57230
57231/*
57232** Move the write position of the WAL back to the point identified by
57233** the values in the aWalData[] array. aWalData must point to an array
57234** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
57235** by a call to WalSavepoint().
57236*/
57237SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
57238  int rc = SQLITE_OK;
57239
57240  assert( pWal->writeLock );
57241  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
57242
57243  if( aWalData[3]!=pWal->nCkpt ){
57244    /* This savepoint was opened immediately after the write-transaction
57245    ** was started. Right after that, the writer decided to wrap around
57246    ** to the start of the log. Update the savepoint values to match.
57247    */
57248    aWalData[0] = 0;
57249    aWalData[3] = pWal->nCkpt;
57250  }
57251
57252  if( aWalData[0]<pWal->hdr.mxFrame ){
57253    pWal->hdr.mxFrame = aWalData[0];
57254    pWal->hdr.aFrameCksum[0] = aWalData[1];
57255    pWal->hdr.aFrameCksum[1] = aWalData[2];
57256    walCleanupHash(pWal);
57257  }
57258
57259  return rc;
57260}
57261
57262/*
57263** This function is called just before writing a set of frames to the log
57264** file (see sqlite3WalFrames()). It checks to see if, instead of appending
57265** to the current log file, it is possible to overwrite the start of the
57266** existing log file with the new frames (i.e. "reset" the log). If so,
57267** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
57268** unchanged.
57269**
57270** SQLITE_OK is returned if no error is encountered (regardless of whether
57271** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
57272** if an error occurs.
57273*/
57274static int walRestartLog(Wal *pWal){
57275  int rc = SQLITE_OK;
57276  int cnt;
57277
57278  if( pWal->readLock==0 ){
57279    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
57280    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
57281    if( pInfo->nBackfill>0 ){
57282      u32 salt1;
57283      sqlite3_randomness(4, &salt1);
57284      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
57285      if( rc==SQLITE_OK ){
57286        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
57287        ** readers are currently using the WAL), then the transactions
57288        ** frames will overwrite the start of the existing log. Update the
57289        ** wal-index header to reflect this.
57290        **
57291        ** In theory it would be Ok to update the cache of the header only
57292        ** at this point. But updating the actual wal-index header is also
57293        ** safe and means there is no special case for sqlite3WalUndo()
57294        ** to handle if this transaction is rolled back.  */
57295        walRestartHdr(pWal, salt1);
57296        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
57297      }else if( rc!=SQLITE_BUSY ){
57298        return rc;
57299      }
57300    }
57301    walUnlockShared(pWal, WAL_READ_LOCK(0));
57302    pWal->readLock = -1;
57303    cnt = 0;
57304    do{
57305      int notUsed;
57306      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
57307    }while( rc==WAL_RETRY );
57308    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
57309    testcase( (rc&0xff)==SQLITE_IOERR );
57310    testcase( rc==SQLITE_PROTOCOL );
57311    testcase( rc==SQLITE_OK );
57312  }
57313  return rc;
57314}
57315
57316/*
57317** Information about the current state of the WAL file and where
57318** the next fsync should occur - passed from sqlite3WalFrames() into
57319** walWriteToLog().
57320*/
57321typedef struct WalWriter {
57322  Wal *pWal;                   /* The complete WAL information */
57323  sqlite3_file *pFd;           /* The WAL file to which we write */
57324  sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
57325  int syncFlags;               /* Flags for the fsync */
57326  int szPage;                  /* Size of one page */
57327} WalWriter;
57328
57329/*
57330** Write iAmt bytes of content into the WAL file beginning at iOffset.
57331** Do a sync when crossing the p->iSyncPoint boundary.
57332**
57333** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
57334** first write the part before iSyncPoint, then sync, then write the
57335** rest.
57336*/
57337static int walWriteToLog(
57338  WalWriter *p,              /* WAL to write to */
57339  void *pContent,            /* Content to be written */
57340  int iAmt,                  /* Number of bytes to write */
57341  sqlite3_int64 iOffset      /* Start writing at this offset */
57342){
57343  int rc;
57344  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
57345    int iFirstAmt = (int)(p->iSyncPoint - iOffset);
57346    rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
57347    if( rc ) return rc;
57348    iOffset += iFirstAmt;
57349    iAmt -= iFirstAmt;
57350    pContent = (void*)(iFirstAmt + (char*)pContent);
57351    assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
57352    rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
57353    if( iAmt==0 || rc ) return rc;
57354  }
57355  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
57356  return rc;
57357}
57358
57359/*
57360** Write out a single frame of the WAL
57361*/
57362static int walWriteOneFrame(
57363  WalWriter *p,               /* Where to write the frame */
57364  PgHdr *pPage,               /* The page of the frame to be written */
57365  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
57366  sqlite3_int64 iOffset       /* Byte offset at which to write */
57367){
57368  int rc;                         /* Result code from subfunctions */
57369  void *pData;                    /* Data actually written */
57370  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
57371#if defined(SQLITE_HAS_CODEC)
57372  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
57373#else
57374  pData = pPage->pData;
57375#endif
57376  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
57377  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
57378  if( rc ) return rc;
57379  /* Write the page data */
57380  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
57381  return rc;
57382}
57383
57384/*
57385** This function is called as part of committing a transaction within which
57386** one or more frames have been overwritten. It updates the checksums for
57387** all frames written to the wal file by the current transaction starting
57388** with the earliest to have been overwritten.
57389**
57390** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
57391*/
57392static int walRewriteChecksums(Wal *pWal, u32 iLast){
57393  const int szPage = pWal->szPage;/* Database page size */
57394  int rc = SQLITE_OK;             /* Return code */
57395  u8 *aBuf;                       /* Buffer to load data from wal file into */
57396  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-headers in */
57397  u32 iRead;                      /* Next frame to read from wal file */
57398  i64 iCksumOff;
57399
57400  aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
57401  if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
57402
57403  /* Find the checksum values to use as input for the recalculating the
57404  ** first checksum. If the first frame is frame 1 (implying that the current
57405  ** transaction restarted the wal file), these values must be read from the
57406  ** wal-file header. Otherwise, read them from the frame header of the
57407  ** previous frame.  */
57408  assert( pWal->iReCksum>0 );
57409  if( pWal->iReCksum==1 ){
57410    iCksumOff = 24;
57411  }else{
57412    iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
57413  }
57414  rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
57415  pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
57416  pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
57417
57418  iRead = pWal->iReCksum;
57419  pWal->iReCksum = 0;
57420  for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
57421    i64 iOff = walFrameOffset(iRead, szPage);
57422    rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
57423    if( rc==SQLITE_OK ){
57424      u32 iPgno, nDbSize;
57425      iPgno = sqlite3Get4byte(aBuf);
57426      nDbSize = sqlite3Get4byte(&aBuf[4]);
57427
57428      walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
57429      rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
57430    }
57431  }
57432
57433  sqlite3_free(aBuf);
57434  return rc;
57435}
57436
57437/*
57438** Write a set of frames to the log. The caller must hold the write-lock
57439** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
57440*/
57441SQLITE_PRIVATE int sqlite3WalFrames(
57442  Wal *pWal,                      /* Wal handle to write to */
57443  int szPage,                     /* Database page-size in bytes */
57444  PgHdr *pList,                   /* List of dirty pages to write */
57445  Pgno nTruncate,                 /* Database size after this commit */
57446  int isCommit,                   /* True if this is a commit */
57447  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
57448){
57449  int rc;                         /* Used to catch return codes */
57450  u32 iFrame;                     /* Next frame address */
57451  PgHdr *p;                       /* Iterator to run through pList with. */
57452  PgHdr *pLast = 0;               /* Last frame in list */
57453  int nExtra = 0;                 /* Number of extra copies of last page */
57454  int szFrame;                    /* The size of a single frame */
57455  i64 iOffset;                    /* Next byte to write in WAL file */
57456  WalWriter w;                    /* The writer */
57457  u32 iFirst = 0;                 /* First frame that may be overwritten */
57458  WalIndexHdr *pLive;             /* Pointer to shared header */
57459
57460  assert( pList );
57461  assert( pWal->writeLock );
57462
57463  /* If this frame set completes a transaction, then nTruncate>0.  If
57464  ** nTruncate==0 then this frame set does not complete the transaction. */
57465  assert( (isCommit!=0)==(nTruncate!=0) );
57466
57467#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
57468  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
57469    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
57470              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
57471  }
57472#endif
57473
57474  pLive = (WalIndexHdr*)walIndexHdr(pWal);
57475  if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
57476    iFirst = pLive->mxFrame+1;
57477  }
57478
57479  /* See if it is possible to write these frames into the start of the
57480  ** log file, instead of appending to it at pWal->hdr.mxFrame.
57481  */
57482  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
57483    return rc;
57484  }
57485
57486  /* If this is the first frame written into the log, write the WAL
57487  ** header to the start of the WAL file. See comments at the top of
57488  ** this source file for a description of the WAL header format.
57489  */
57490  iFrame = pWal->hdr.mxFrame;
57491  if( iFrame==0 ){
57492    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
57493    u32 aCksum[2];                /* Checksum for wal-header */
57494
57495    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
57496    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
57497    sqlite3Put4byte(&aWalHdr[8], szPage);
57498    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
57499    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
57500    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
57501    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
57502    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
57503    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
57504
57505    pWal->szPage = szPage;
57506    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
57507    pWal->hdr.aFrameCksum[0] = aCksum[0];
57508    pWal->hdr.aFrameCksum[1] = aCksum[1];
57509    pWal->truncateOnCommit = 1;
57510
57511    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
57512    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
57513    if( rc!=SQLITE_OK ){
57514      return rc;
57515    }
57516
57517    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
57518    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
57519    ** an out-of-order write following a WAL restart could result in
57520    ** database corruption.  See the ticket:
57521    **
57522    **     http://localhost:591/sqlite/info/ff5be73dee
57523    */
57524    if( pWal->syncHeader && sync_flags ){
57525      rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
57526      if( rc ) return rc;
57527    }
57528  }
57529  assert( (int)pWal->szPage==szPage );
57530
57531  /* Setup information needed to write frames into the WAL */
57532  w.pWal = pWal;
57533  w.pFd = pWal->pWalFd;
57534  w.iSyncPoint = 0;
57535  w.syncFlags = sync_flags;
57536  w.szPage = szPage;
57537  iOffset = walFrameOffset(iFrame+1, szPage);
57538  szFrame = szPage + WAL_FRAME_HDRSIZE;
57539
57540  /* Write all frames into the log file exactly once */
57541  for(p=pList; p; p=p->pDirty){
57542    int nDbSize;   /* 0 normally.  Positive == commit flag */
57543
57544    /* Check if this page has already been written into the wal file by
57545    ** the current transaction. If so, overwrite the existing frame and
57546    ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
57547    ** checksums must be recomputed when the transaction is committed.  */
57548    if( iFirst && (p->pDirty || isCommit==0) ){
57549      u32 iWrite = 0;
57550      VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
57551      assert( rc==SQLITE_OK || iWrite==0 );
57552      if( iWrite>=iFirst ){
57553        i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
57554        void *pData;
57555        if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
57556          pWal->iReCksum = iWrite;
57557        }
57558#if defined(SQLITE_HAS_CODEC)
57559        if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
57560#else
57561        pData = p->pData;
57562#endif
57563        rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
57564        if( rc ) return rc;
57565        p->flags &= ~PGHDR_WAL_APPEND;
57566        continue;
57567      }
57568    }
57569
57570    iFrame++;
57571    assert( iOffset==walFrameOffset(iFrame, szPage) );
57572    nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
57573    rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
57574    if( rc ) return rc;
57575    pLast = p;
57576    iOffset += szFrame;
57577    p->flags |= PGHDR_WAL_APPEND;
57578  }
57579
57580  /* Recalculate checksums within the wal file if required. */
57581  if( isCommit && pWal->iReCksum ){
57582    rc = walRewriteChecksums(pWal, iFrame);
57583    if( rc ) return rc;
57584  }
57585
57586  /* If this is the end of a transaction, then we might need to pad
57587  ** the transaction and/or sync the WAL file.
57588  **
57589  ** Padding and syncing only occur if this set of frames complete a
57590  ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
57591  ** or synchronous==OFF, then no padding or syncing are needed.
57592  **
57593  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
57594  ** needed and only the sync is done.  If padding is needed, then the
57595  ** final frame is repeated (with its commit mark) until the next sector
57596  ** boundary is crossed.  Only the part of the WAL prior to the last
57597  ** sector boundary is synced; the part of the last frame that extends
57598  ** past the sector boundary is written after the sync.
57599  */
57600  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
57601    int bSync = 1;
57602    if( pWal->padToSectorBoundary ){
57603      int sectorSize = sqlite3SectorSize(pWal->pWalFd);
57604      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
57605      bSync = (w.iSyncPoint==iOffset);
57606      testcase( bSync );
57607      while( iOffset<w.iSyncPoint ){
57608        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
57609        if( rc ) return rc;
57610        iOffset += szFrame;
57611        nExtra++;
57612      }
57613    }
57614    if( bSync ){
57615      assert( rc==SQLITE_OK );
57616      rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
57617    }
57618  }
57619
57620  /* If this frame set completes the first transaction in the WAL and
57621  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
57622  ** journal size limit, if possible.
57623  */
57624  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
57625    i64 sz = pWal->mxWalSize;
57626    if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
57627      sz = walFrameOffset(iFrame+nExtra+1, szPage);
57628    }
57629    walLimitSize(pWal, sz);
57630    pWal->truncateOnCommit = 0;
57631  }
57632
57633  /* Append data to the wal-index. It is not necessary to lock the
57634  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
57635  ** guarantees that there are no other writers, and no data that may
57636  ** be in use by existing readers is being overwritten.
57637  */
57638  iFrame = pWal->hdr.mxFrame;
57639  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
57640    if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
57641    iFrame++;
57642    rc = walIndexAppend(pWal, iFrame, p->pgno);
57643  }
57644  while( rc==SQLITE_OK && nExtra>0 ){
57645    iFrame++;
57646    nExtra--;
57647    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
57648  }
57649
57650  if( rc==SQLITE_OK ){
57651    /* Update the private copy of the header. */
57652    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
57653    testcase( szPage<=32768 );
57654    testcase( szPage>=65536 );
57655    pWal->hdr.mxFrame = iFrame;
57656    if( isCommit ){
57657      pWal->hdr.iChange++;
57658      pWal->hdr.nPage = nTruncate;
57659    }
57660    /* If this is a commit, update the wal-index header too. */
57661    if( isCommit ){
57662      walIndexWriteHdr(pWal);
57663      pWal->iCallback = iFrame;
57664    }
57665  }
57666
57667  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
57668  return rc;
57669}
57670
57671/*
57672** This routine is called to implement sqlite3_wal_checkpoint() and
57673** related interfaces.
57674**
57675** Obtain a CHECKPOINT lock and then backfill as much information as
57676** we can from WAL into the database.
57677**
57678** If parameter xBusy is not NULL, it is a pointer to a busy-handler
57679** callback. In this case this function runs a blocking checkpoint.
57680*/
57681SQLITE_PRIVATE int sqlite3WalCheckpoint(
57682  Wal *pWal,                      /* Wal connection */
57683  sqlite3 *db,                    /* Check this handle's interrupt flag */
57684  int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
57685  int (*xBusy)(void*),            /* Function to call when busy */
57686  void *pBusyArg,                 /* Context argument for xBusyHandler */
57687  int sync_flags,                 /* Flags to sync db file with (or 0) */
57688  int nBuf,                       /* Size of temporary buffer */
57689  u8 *zBuf,                       /* Temporary buffer to use */
57690  int *pnLog,                     /* OUT: Number of frames in WAL */
57691  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
57692){
57693  int rc;                         /* Return code */
57694  int isChanged = 0;              /* True if a new wal-index header is loaded */
57695  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
57696  int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
57697
57698  assert( pWal->ckptLock==0 );
57699  assert( pWal->writeLock==0 );
57700
57701  /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
57702  ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
57703  assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
57704
57705  if( pWal->readOnly ) return SQLITE_READONLY;
57706  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
57707
57708  /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
57709  ** "checkpoint" lock on the database file. */
57710  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
57711  if( rc ){
57712    /* EVIDENCE-OF: R-10421-19736 If any other process is running a
57713    ** checkpoint operation at the same time, the lock cannot be obtained and
57714    ** SQLITE_BUSY is returned.
57715    ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
57716    ** it will not be invoked in this case.
57717    */
57718    testcase( rc==SQLITE_BUSY );
57719    testcase( xBusy!=0 );
57720    return rc;
57721  }
57722  pWal->ckptLock = 1;
57723
57724  /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
57725  ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
57726  ** file.
57727  **
57728  ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
57729  ** immediately, and a busy-handler is configured, it is invoked and the
57730  ** writer lock retried until either the busy-handler returns 0 or the
57731  ** lock is successfully obtained.
57732  */
57733  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
57734    rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
57735    if( rc==SQLITE_OK ){
57736      pWal->writeLock = 1;
57737    }else if( rc==SQLITE_BUSY ){
57738      eMode2 = SQLITE_CHECKPOINT_PASSIVE;
57739      xBusy2 = 0;
57740      rc = SQLITE_OK;
57741    }
57742  }
57743
57744  /* Read the wal-index header. */
57745  if( rc==SQLITE_OK ){
57746    rc = walIndexReadHdr(pWal, &isChanged);
57747    if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
57748      sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
57749    }
57750  }
57751
57752  /* Copy data from the log to the database file. */
57753  if( rc==SQLITE_OK ){
57754
57755    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
57756      rc = SQLITE_CORRUPT_BKPT;
57757    }else{
57758      rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
57759    }
57760
57761    /* If no error occurred, set the output variables. */
57762    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
57763      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
57764      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
57765    }
57766  }
57767
57768  if( isChanged ){
57769    /* If a new wal-index header was loaded before the checkpoint was
57770    ** performed, then the pager-cache associated with pWal is now
57771    ** out of date. So zero the cached wal-index header to ensure that
57772    ** next time the pager opens a snapshot on this database it knows that
57773    ** the cache needs to be reset.
57774    */
57775    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
57776  }
57777
57778  /* Release the locks. */
57779  sqlite3WalEndWriteTransaction(pWal);
57780  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
57781  pWal->ckptLock = 0;
57782  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
57783  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
57784}
57785
57786/* Return the value to pass to a sqlite3_wal_hook callback, the
57787** number of frames in the WAL at the point of the last commit since
57788** sqlite3WalCallback() was called.  If no commits have occurred since
57789** the last call, then return 0.
57790*/
57791SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
57792  u32 ret = 0;
57793  if( pWal ){
57794    ret = pWal->iCallback;
57795    pWal->iCallback = 0;
57796  }
57797  return (int)ret;
57798}
57799
57800/*
57801** This function is called to change the WAL subsystem into or out
57802** of locking_mode=EXCLUSIVE.
57803**
57804** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
57805** into locking_mode=NORMAL.  This means that we must acquire a lock
57806** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
57807** or if the acquisition of the lock fails, then return 0.  If the
57808** transition out of exclusive-mode is successful, return 1.  This
57809** operation must occur while the pager is still holding the exclusive
57810** lock on the main database file.
57811**
57812** If op is one, then change from locking_mode=NORMAL into
57813** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
57814** be released.  Return 1 if the transition is made and 0 if the
57815** WAL is already in exclusive-locking mode - meaning that this
57816** routine is a no-op.  The pager must already hold the exclusive lock
57817** on the main database file before invoking this operation.
57818**
57819** If op is negative, then do a dry-run of the op==1 case but do
57820** not actually change anything. The pager uses this to see if it
57821** should acquire the database exclusive lock prior to invoking
57822** the op==1 case.
57823*/
57824SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
57825  int rc;
57826  assert( pWal->writeLock==0 );
57827  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
57828
57829  /* pWal->readLock is usually set, but might be -1 if there was a
57830  ** prior error while attempting to acquire are read-lock. This cannot
57831  ** happen if the connection is actually in exclusive mode (as no xShmLock
57832  ** locks are taken in this case). Nor should the pager attempt to
57833  ** upgrade to exclusive-mode following such an error.
57834  */
57835  assert( pWal->readLock>=0 || pWal->lockError );
57836  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
57837
57838  if( op==0 ){
57839    if( pWal->exclusiveMode ){
57840      pWal->exclusiveMode = 0;
57841      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
57842        pWal->exclusiveMode = 1;
57843      }
57844      rc = pWal->exclusiveMode==0;
57845    }else{
57846      /* Already in locking_mode=NORMAL */
57847      rc = 0;
57848    }
57849  }else if( op>0 ){
57850    assert( pWal->exclusiveMode==0 );
57851    assert( pWal->readLock>=0 );
57852    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
57853    pWal->exclusiveMode = 1;
57854    rc = 1;
57855  }else{
57856    rc = pWal->exclusiveMode==0;
57857  }
57858  return rc;
57859}
57860
57861/*
57862** Return true if the argument is non-NULL and the WAL module is using
57863** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
57864** WAL module is using shared-memory, return false.
57865*/
57866SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
57867  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
57868}
57869
57870#ifdef SQLITE_ENABLE_SNAPSHOT
57871/* Create a snapshot object.  The content of a snapshot is opaque to
57872** every other subsystem, so the WAL module can put whatever it needs
57873** in the object.
57874*/
57875SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
57876  int rc = SQLITE_OK;
57877  WalIndexHdr *pRet;
57878  static const u32 aZero[4] = { 0, 0, 0, 0 };
57879
57880  assert( pWal->readLock>=0 && pWal->writeLock==0 );
57881
57882  if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
57883    *ppSnapshot = 0;
57884    return SQLITE_ERROR;
57885  }
57886  pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
57887  if( pRet==0 ){
57888    rc = SQLITE_NOMEM_BKPT;
57889  }else{
57890    memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
57891    *ppSnapshot = (sqlite3_snapshot*)pRet;
57892  }
57893
57894  return rc;
57895}
57896
57897/* Try to open on pSnapshot when the next read-transaction starts
57898*/
57899SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
57900  pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
57901}
57902
57903/*
57904** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
57905** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
57906*/
57907SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
57908  WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
57909  WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
57910
57911  /* aSalt[0] is a copy of the value stored in the wal file header. It
57912  ** is incremented each time the wal file is restarted.  */
57913  if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
57914  if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
57915  if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
57916  if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
57917  return 0;
57918}
57919#endif /* SQLITE_ENABLE_SNAPSHOT */
57920
57921#ifdef SQLITE_ENABLE_ZIPVFS
57922/*
57923** If the argument is not NULL, it points to a Wal object that holds a
57924** read-lock. This function returns the database page-size if it is known,
57925** or zero if it is not (or if pWal is NULL).
57926*/
57927SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
57928  assert( pWal==0 || pWal->readLock>=0 );
57929  return (pWal ? pWal->szPage : 0);
57930}
57931#endif
57932
57933/* Return the sqlite3_file object for the WAL file
57934*/
57935SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
57936  return pWal->pWalFd;
57937}
57938
57939#endif /* #ifndef SQLITE_OMIT_WAL */
57940
57941/************** End of wal.c *************************************************/
57942/************** Begin file btmutex.c *****************************************/
57943/*
57944** 2007 August 27
57945**
57946** The author disclaims copyright to this source code.  In place of
57947** a legal notice, here is a blessing:
57948**
57949**    May you do good and not evil.
57950**    May you find forgiveness for yourself and forgive others.
57951**    May you share freely, never taking more than you give.
57952**
57953*************************************************************************
57954**
57955** This file contains code used to implement mutexes on Btree objects.
57956** This code really belongs in btree.c.  But btree.c is getting too
57957** big and we want to break it down some.  This packaged seemed like
57958** a good breakout.
57959*/
57960/************** Include btreeInt.h in the middle of btmutex.c ****************/
57961/************** Begin file btreeInt.h ****************************************/
57962/*
57963** 2004 April 6
57964**
57965** The author disclaims copyright to this source code.  In place of
57966** a legal notice, here is a blessing:
57967**
57968**    May you do good and not evil.
57969**    May you find forgiveness for yourself and forgive others.
57970**    May you share freely, never taking more than you give.
57971**
57972*************************************************************************
57973** This file implements an external (disk-based) database using BTrees.
57974** For a detailed discussion of BTrees, refer to
57975**
57976**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
57977**     "Sorting And Searching", pages 473-480. Addison-Wesley
57978**     Publishing Company, Reading, Massachusetts.
57979**
57980** The basic idea is that each page of the file contains N database
57981** entries and N+1 pointers to subpages.
57982**
57983**   ----------------------------------------------------------------
57984**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
57985**   ----------------------------------------------------------------
57986**
57987** All of the keys on the page that Ptr(0) points to have values less
57988** than Key(0).  All of the keys on page Ptr(1) and its subpages have
57989** values greater than Key(0) and less than Key(1).  All of the keys
57990** on Ptr(N) and its subpages have values greater than Key(N-1).  And
57991** so forth.
57992**
57993** Finding a particular key requires reading O(log(M)) pages from the
57994** disk where M is the number of entries in the tree.
57995**
57996** In this implementation, a single file can hold one or more separate
57997** BTrees.  Each BTree is identified by the index of its root page.  The
57998** key and data for any entry are combined to form the "payload".  A
57999** fixed amount of payload can be carried directly on the database
58000** page.  If the payload is larger than the preset amount then surplus
58001** bytes are stored on overflow pages.  The payload for an entry
58002** and the preceding pointer are combined to form a "Cell".  Each
58003** page has a small header which contains the Ptr(N) pointer and other
58004** information such as the size of key and data.
58005**
58006** FORMAT DETAILS
58007**
58008** The file is divided into pages.  The first page is called page 1,
58009** the second is page 2, and so forth.  A page number of zero indicates
58010** "no such page".  The page size can be any power of 2 between 512 and 65536.
58011** Each page can be either a btree page, a freelist page, an overflow
58012** page, or a pointer-map page.
58013**
58014** The first page is always a btree page.  The first 100 bytes of the first
58015** page contain a special header (the "file header") that describes the file.
58016** The format of the file header is as follows:
58017**
58018**   OFFSET   SIZE    DESCRIPTION
58019**      0      16     Header string: "SQLite format 3\000"
58020**     16       2     Page size in bytes.  (1 means 65536)
58021**     18       1     File format write version
58022**     19       1     File format read version
58023**     20       1     Bytes of unused space at the end of each page
58024**     21       1     Max embedded payload fraction (must be 64)
58025**     22       1     Min embedded payload fraction (must be 32)
58026**     23       1     Min leaf payload fraction (must be 32)
58027**     24       4     File change counter
58028**     28       4     Reserved for future use
58029**     32       4     First freelist page
58030**     36       4     Number of freelist pages in the file
58031**     40      60     15 4-byte meta values passed to higher layers
58032**
58033**     40       4     Schema cookie
58034**     44       4     File format of schema layer
58035**     48       4     Size of page cache
58036**     52       4     Largest root-page (auto/incr_vacuum)
58037**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
58038**     60       4     User version
58039**     64       4     Incremental vacuum mode
58040**     68       4     Application-ID
58041**     72      20     unused
58042**     92       4     The version-valid-for number
58043**     96       4     SQLITE_VERSION_NUMBER
58044**
58045** All of the integer values are big-endian (most significant byte first).
58046**
58047** The file change counter is incremented when the database is changed
58048** This counter allows other processes to know when the file has changed
58049** and thus when they need to flush their cache.
58050**
58051** The max embedded payload fraction is the amount of the total usable
58052** space in a page that can be consumed by a single cell for standard
58053** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
58054** is to limit the maximum cell size so that at least 4 cells will fit
58055** on one page.  Thus the default max embedded payload fraction is 64.
58056**
58057** If the payload for a cell is larger than the max payload, then extra
58058** payload is spilled to overflow pages.  Once an overflow page is allocated,
58059** as many bytes as possible are moved into the overflow pages without letting
58060** the cell size drop below the min embedded payload fraction.
58061**
58062** The min leaf payload fraction is like the min embedded payload fraction
58063** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
58064** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
58065** not specified in the header.
58066**
58067** Each btree pages is divided into three sections:  The header, the
58068** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
58069** file header that occurs before the page header.
58070**
58071**      |----------------|
58072**      | file header    |   100 bytes.  Page 1 only.
58073**      |----------------|
58074**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
58075**      |----------------|
58076**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
58077**      | array          |   |  Grows downward
58078**      |                |   v
58079**      |----------------|
58080**      | unallocated    |
58081**      | space          |
58082**      |----------------|   ^  Grows upwards
58083**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
58084**      | area           |   |  and free space fragments.
58085**      |----------------|
58086**
58087** The page headers looks like this:
58088**
58089**   OFFSET   SIZE     DESCRIPTION
58090**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
58091**      1       2      byte offset to the first freeblock
58092**      3       2      number of cells on this page
58093**      5       2      first byte of the cell content area
58094**      7       1      number of fragmented free bytes
58095**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
58096**
58097** The flags define the format of this btree page.  The leaf flag means that
58098** this page has no children.  The zerodata flag means that this page carries
58099** only keys and no data.  The intkey flag means that the key is an integer
58100** which is stored in the key size entry of the cell header rather than in
58101** the payload area.
58102**
58103** The cell pointer array begins on the first byte after the page header.
58104** The cell pointer array contains zero or more 2-byte numbers which are
58105** offsets from the beginning of the page to the cell content in the cell
58106** content area.  The cell pointers occur in sorted order.  The system strives
58107** to keep free space after the last cell pointer so that new cells can
58108** be easily added without having to defragment the page.
58109**
58110** Cell content is stored at the very end of the page and grows toward the
58111** beginning of the page.
58112**
58113** Unused space within the cell content area is collected into a linked list of
58114** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
58115** to the first freeblock is given in the header.  Freeblocks occur in
58116** increasing order.  Because a freeblock must be at least 4 bytes in size,
58117** any group of 3 or fewer unused bytes in the cell content area cannot
58118** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
58119** a fragment.  The total number of bytes in all fragments is recorded.
58120** in the page header at offset 7.
58121**
58122**    SIZE    DESCRIPTION
58123**      2     Byte offset of the next freeblock
58124**      2     Bytes in this freeblock
58125**
58126** Cells are of variable length.  Cells are stored in the cell content area at
58127** the end of the page.  Pointers to the cells are in the cell pointer array
58128** that immediately follows the page header.  Cells is not necessarily
58129** contiguous or in order, but cell pointers are contiguous and in order.
58130**
58131** Cell content makes use of variable length integers.  A variable
58132** length integer is 1 to 9 bytes where the lower 7 bits of each
58133** byte are used.  The integer consists of all bytes that have bit 8 set and
58134** the first byte with bit 8 clear.  The most significant byte of the integer
58135** appears first.  A variable-length integer may not be more than 9 bytes long.
58136** As a special case, all 8 bytes of the 9th byte are used as data.  This
58137** allows a 64-bit integer to be encoded in 9 bytes.
58138**
58139**    0x00                      becomes  0x00000000
58140**    0x7f                      becomes  0x0000007f
58141**    0x81 0x00                 becomes  0x00000080
58142**    0x82 0x00                 becomes  0x00000100
58143**    0x80 0x7f                 becomes  0x0000007f
58144**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
58145**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
58146**
58147** Variable length integers are used for rowids and to hold the number of
58148** bytes of key and data in a btree cell.
58149**
58150** The content of a cell looks like this:
58151**
58152**    SIZE    DESCRIPTION
58153**      4     Page number of the left child. Omitted if leaf flag is set.
58154**     var    Number of bytes of data. Omitted if the zerodata flag is set.
58155**     var    Number of bytes of key. Or the key itself if intkey flag is set.
58156**      *     Payload
58157**      4     First page of the overflow chain.  Omitted if no overflow
58158**
58159** Overflow pages form a linked list.  Each page except the last is completely
58160** filled with data (pagesize - 4 bytes).  The last page can have as little
58161** as 1 byte of data.
58162**
58163**    SIZE    DESCRIPTION
58164**      4     Page number of next overflow page
58165**      *     Data
58166**
58167** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
58168** file header points to the first in a linked list of trunk page.  Each trunk
58169** page points to multiple leaf pages.  The content of a leaf page is
58170** unspecified.  A trunk page looks like this:
58171**
58172**    SIZE    DESCRIPTION
58173**      4     Page number of next trunk page
58174**      4     Number of leaf pointers on this page
58175**      *     zero or more pages numbers of leaves
58176*/
58177/* #include "sqliteInt.h" */
58178
58179
58180/* The following value is the maximum cell size assuming a maximum page
58181** size give above.
58182*/
58183#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
58184
58185/* The maximum number of cells on a single page of the database.  This
58186** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
58187** plus 2 bytes for the index to the cell in the page header).  Such
58188** small cells will be rare, but they are possible.
58189*/
58190#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
58191
58192/* Forward declarations */
58193typedef struct MemPage MemPage;
58194typedef struct BtLock BtLock;
58195typedef struct CellInfo CellInfo;
58196
58197/*
58198** This is a magic string that appears at the beginning of every
58199** SQLite database in order to identify the file as a real database.
58200**
58201** You can change this value at compile-time by specifying a
58202** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
58203** header must be exactly 16 bytes including the zero-terminator so
58204** the string itself should be 15 characters long.  If you change
58205** the header, then your custom library will not be able to read
58206** databases generated by the standard tools and the standard tools
58207** will not be able to read databases created by your custom library.
58208*/
58209#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
58210#  define SQLITE_FILE_HEADER "SQLite format 3"
58211#endif
58212
58213/*
58214** Page type flags.  An ORed combination of these flags appear as the
58215** first byte of on-disk image of every BTree page.
58216*/
58217#define PTF_INTKEY    0x01
58218#define PTF_ZERODATA  0x02
58219#define PTF_LEAFDATA  0x04
58220#define PTF_LEAF      0x08
58221
58222/*
58223** An instance of this object stores information about each a single database
58224** page that has been loaded into memory.  The information in this object
58225** is derived from the raw on-disk page content.
58226**
58227** As each database page is loaded into memory, the pager allocats an
58228** instance of this object and zeros the first 8 bytes.  (This is the
58229** "extra" information associated with each page of the pager.)
58230**
58231** Access to all fields of this structure is controlled by the mutex
58232** stored in MemPage.pBt->mutex.
58233*/
58234struct MemPage {
58235  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
58236  u8 bBusy;            /* Prevent endless loops on corrupt database files */
58237  u8 intKey;           /* True if table b-trees.  False for index b-trees */
58238  u8 intKeyLeaf;       /* True if the leaf of an intKey table */
58239  Pgno pgno;           /* Page number for this page */
58240  /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
58241  ** is allocated. All fields that follow must be initialized before use */
58242  u8 leaf;             /* True if a leaf page */
58243  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
58244  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
58245  u8 max1bytePayload;  /* min(maxLocal,127) */
58246  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
58247  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
58248  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
58249  u16 cellOffset;      /* Index in aData of first cell pointer */
58250  u16 nFree;           /* Number of free bytes on the page */
58251  u16 nCell;           /* Number of cells on this page, local and ovfl */
58252  u16 maskPage;        /* Mask for page offset */
58253  u16 aiOvfl[4];       /* Insert the i-th overflow cell before the aiOvfl-th
58254                       ** non-overflow cell */
58255  u8 *apOvfl[4];       /* Pointers to the body of overflow cells */
58256  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
58257  u8 *aData;           /* Pointer to disk image of the page data */
58258  u8 *aDataEnd;        /* One byte past the end of usable data */
58259  u8 *aCellIdx;        /* The cell index area */
58260  u8 *aDataOfst;       /* Same as aData for leaves.  aData+4 for interior */
58261  DbPage *pDbPage;     /* Pager page handle */
58262  u16 (*xCellSize)(MemPage*,u8*);             /* cellSizePtr method */
58263  void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
58264};
58265
58266/*
58267** A linked list of the following structures is stored at BtShared.pLock.
58268** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
58269** is opened on the table with root page BtShared.iTable. Locks are removed
58270** from this list when a transaction is committed or rolled back, or when
58271** a btree handle is closed.
58272*/
58273struct BtLock {
58274  Btree *pBtree;        /* Btree handle holding this lock */
58275  Pgno iTable;          /* Root page of table */
58276  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
58277  BtLock *pNext;        /* Next in BtShared.pLock list */
58278};
58279
58280/* Candidate values for BtLock.eLock */
58281#define READ_LOCK     1
58282#define WRITE_LOCK    2
58283
58284/* A Btree handle
58285**
58286** A database connection contains a pointer to an instance of
58287** this object for every database file that it has open.  This structure
58288** is opaque to the database connection.  The database connection cannot
58289** see the internals of this structure and only deals with pointers to
58290** this structure.
58291**
58292** For some database files, the same underlying database cache might be
58293** shared between multiple connections.  In that case, each connection
58294** has it own instance of this object.  But each instance of this object
58295** points to the same BtShared object.  The database cache and the
58296** schema associated with the database file are all contained within
58297** the BtShared object.
58298**
58299** All fields in this structure are accessed under sqlite3.mutex.
58300** The pBt pointer itself may not be changed while there exists cursors
58301** in the referenced BtShared that point back to this Btree since those
58302** cursors have to go through this Btree to find their BtShared and
58303** they often do so without holding sqlite3.mutex.
58304*/
58305struct Btree {
58306  sqlite3 *db;       /* The database connection holding this btree */
58307  BtShared *pBt;     /* Sharable content of this btree */
58308  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
58309  u8 sharable;       /* True if we can share pBt with another db */
58310  u8 locked;         /* True if db currently has pBt locked */
58311  u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
58312  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
58313  int nBackup;       /* Number of backup operations reading this btree */
58314  u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */
58315  Btree *pNext;      /* List of other sharable Btrees from the same db */
58316  Btree *pPrev;      /* Back pointer of the same list */
58317#ifndef SQLITE_OMIT_SHARED_CACHE
58318  BtLock lock;       /* Object used to lock page 1 */
58319#endif
58320};
58321
58322/*
58323** Btree.inTrans may take one of the following values.
58324**
58325** If the shared-data extension is enabled, there may be multiple users
58326** of the Btree structure. At most one of these may open a write transaction,
58327** but any number may have active read transactions.
58328*/
58329#define TRANS_NONE  0
58330#define TRANS_READ  1
58331#define TRANS_WRITE 2
58332
58333/*
58334** An instance of this object represents a single database file.
58335**
58336** A single database file can be in use at the same time by two
58337** or more database connections.  When two or more connections are
58338** sharing the same database file, each connection has it own
58339** private Btree object for the file and each of those Btrees points
58340** to this one BtShared object.  BtShared.nRef is the number of
58341** connections currently sharing this database file.
58342**
58343** Fields in this structure are accessed under the BtShared.mutex
58344** mutex, except for nRef and pNext which are accessed under the
58345** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
58346** may not be modified once it is initially set as long as nRef>0.
58347** The pSchema field may be set once under BtShared.mutex and
58348** thereafter is unchanged as long as nRef>0.
58349**
58350** isPending:
58351**
58352**   If a BtShared client fails to obtain a write-lock on a database
58353**   table (because there exists one or more read-locks on the table),
58354**   the shared-cache enters 'pending-lock' state and isPending is
58355**   set to true.
58356**
58357**   The shared-cache leaves the 'pending lock' state when either of
58358**   the following occur:
58359**
58360**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
58361**     2) The number of locks held by other connections drops to zero.
58362**
58363**   while in the 'pending-lock' state, no connection may start a new
58364**   transaction.
58365**
58366**   This feature is included to help prevent writer-starvation.
58367*/
58368struct BtShared {
58369  Pager *pPager;        /* The page cache */
58370  sqlite3 *db;          /* Database connection currently using this Btree */
58371  BtCursor *pCursor;    /* A list of all open cursors */
58372  MemPage *pPage1;      /* First page of the database */
58373  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
58374#ifndef SQLITE_OMIT_AUTOVACUUM
58375  u8 autoVacuum;        /* True if auto-vacuum is enabled */
58376  u8 incrVacuum;        /* True if incr-vacuum is enabled */
58377  u8 bDoTruncate;       /* True to truncate db on commit */
58378#endif
58379  u8 inTransaction;     /* Transaction state */
58380  u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
58381#ifdef SQLITE_HAS_CODEC
58382  u8 optimalReserve;    /* Desired amount of reserved space per page */
58383#endif
58384  u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
58385  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
58386  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
58387  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
58388  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
58389  u32 pageSize;         /* Total number of bytes on a page */
58390  u32 usableSize;       /* Number of usable bytes on each page */
58391  int nTransaction;     /* Number of open transactions (read + write) */
58392  u32 nPage;            /* Number of pages in the database */
58393  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
58394  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
58395  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
58396  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
58397#ifndef SQLITE_OMIT_SHARED_CACHE
58398  int nRef;             /* Number of references to this structure */
58399  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
58400  BtLock *pLock;        /* List of locks held on this shared-btree struct */
58401  Btree *pWriter;       /* Btree with currently open write transaction */
58402#endif
58403  u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
58404};
58405
58406/*
58407** Allowed values for BtShared.btsFlags
58408*/
58409#define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
58410#define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
58411#define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
58412#define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
58413#define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
58414#define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
58415#define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
58416
58417/*
58418** An instance of the following structure is used to hold information
58419** about a cell.  The parseCellPtr() function fills in this structure
58420** based on information extract from the raw disk page.
58421*/
58422struct CellInfo {
58423  i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
58424  u8 *pPayload;  /* Pointer to the start of payload */
58425  u32 nPayload;  /* Bytes of payload */
58426  u16 nLocal;    /* Amount of payload held locally, not on overflow */
58427  u16 nSize;     /* Size of the cell content on the main b-tree page */
58428};
58429
58430/*
58431** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
58432** this will be declared corrupt. This value is calculated based on a
58433** maximum database size of 2^31 pages a minimum fanout of 2 for a
58434** root-node and 3 for all other internal nodes.
58435**
58436** If a tree that appears to be taller than this is encountered, it is
58437** assumed that the database is corrupt.
58438*/
58439#define BTCURSOR_MAX_DEPTH 20
58440
58441/*
58442** A cursor is a pointer to a particular entry within a particular
58443** b-tree within a database file.
58444**
58445** The entry is identified by its MemPage and the index in
58446** MemPage.aCell[] of the entry.
58447**
58448** A single database file can be shared by two more database connections,
58449** but cursors cannot be shared.  Each cursor is associated with a
58450** particular database connection identified BtCursor.pBtree.db.
58451**
58452** Fields in this structure are accessed under the BtShared.mutex
58453** found at self->pBt->mutex.
58454**
58455** skipNext meaning:
58456**    eState==SKIPNEXT && skipNext>0:  Next sqlite3BtreeNext() is no-op.
58457**    eState==SKIPNEXT && skipNext<0:  Next sqlite3BtreePrevious() is no-op.
58458**    eState==FAULT:                   Cursor fault with skipNext as error code.
58459*/
58460struct BtCursor {
58461  Btree *pBtree;            /* The Btree to which this cursor belongs */
58462  BtShared *pBt;            /* The BtShared this cursor points to */
58463  BtCursor *pNext;          /* Forms a linked list of all cursors */
58464  Pgno *aOverflow;          /* Cache of overflow page locations */
58465  CellInfo info;            /* A parse of the cell we are pointing at */
58466  i64 nKey;                 /* Size of pKey, or last integer key */
58467  void *pKey;               /* Saved key that was cursor last known position */
58468  Pgno pgnoRoot;            /* The root page of this tree */
58469  int nOvflAlloc;           /* Allocated size of aOverflow[] array */
58470  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.
58471                   ** Error code if eState==CURSOR_FAULT */
58472  u8 curFlags;              /* zero or more BTCF_* flags defined below */
58473  u8 curPagerFlags;         /* Flags to send to sqlite3PagerGet() */
58474  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
58475  u8 hints;                 /* As configured by CursorSetHints() */
58476  /* All fields above are zeroed when the cursor is allocated.  See
58477  ** sqlite3BtreeCursorZero().  Fields that follow must be manually
58478  ** initialized. */
58479  i8 iPage;                 /* Index of current page in apPage */
58480  u8 curIntKey;             /* Value of apPage[0]->intKey */
58481  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
58482  void *padding1;           /* Make object size a multiple of 16 */
58483  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
58484  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
58485};
58486
58487/*
58488** Legal values for BtCursor.curFlags
58489*/
58490#define BTCF_WriteFlag    0x01   /* True if a write cursor */
58491#define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
58492#define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
58493#define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
58494#define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
58495#define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */
58496
58497/*
58498** Potential values for BtCursor.eState.
58499**
58500** CURSOR_INVALID:
58501**   Cursor does not point to a valid entry. This can happen (for example)
58502**   because the table is empty or because BtreeCursorFirst() has not been
58503**   called.
58504**
58505** CURSOR_VALID:
58506**   Cursor points to a valid entry. getPayload() etc. may be called.
58507**
58508** CURSOR_SKIPNEXT:
58509**   Cursor is valid except that the Cursor.skipNext field is non-zero
58510**   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
58511**   operation should be a no-op.
58512**
58513** CURSOR_REQUIRESEEK:
58514**   The table that this cursor was opened on still exists, but has been
58515**   modified since the cursor was last used. The cursor position is saved
58516**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
58517**   this state, restoreCursorPosition() can be called to attempt to
58518**   seek the cursor to the saved position.
58519**
58520** CURSOR_FAULT:
58521**   An unrecoverable error (an I/O error or a malloc failure) has occurred
58522**   on a different connection that shares the BtShared cache with this
58523**   cursor.  The error has left the cache in an inconsistent state.
58524**   Do nothing else with this cursor.  Any attempt to use the cursor
58525**   should return the error code stored in BtCursor.skipNext
58526*/
58527#define CURSOR_INVALID           0
58528#define CURSOR_VALID             1
58529#define CURSOR_SKIPNEXT          2
58530#define CURSOR_REQUIRESEEK       3
58531#define CURSOR_FAULT             4
58532
58533/*
58534** The database page the PENDING_BYTE occupies. This page is never used.
58535*/
58536# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
58537
58538/*
58539** These macros define the location of the pointer-map entry for a
58540** database page. The first argument to each is the number of usable
58541** bytes on each page of the database (often 1024). The second is the
58542** page number to look up in the pointer map.
58543**
58544** PTRMAP_PAGENO returns the database page number of the pointer-map
58545** page that stores the required pointer. PTRMAP_PTROFFSET returns
58546** the offset of the requested map entry.
58547**
58548** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
58549** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
58550** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
58551** this test.
58552*/
58553#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
58554#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
58555#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
58556
58557/*
58558** The pointer map is a lookup table that identifies the parent page for
58559** each child page in the database file.  The parent page is the page that
58560** contains a pointer to the child.  Every page in the database contains
58561** 0 or 1 parent pages.  (In this context 'database page' refers
58562** to any page that is not part of the pointer map itself.)  Each pointer map
58563** entry consists of a single byte 'type' and a 4 byte parent page number.
58564** The PTRMAP_XXX identifiers below are the valid types.
58565**
58566** The purpose of the pointer map is to facility moving pages from one
58567** position in the file to another as part of autovacuum.  When a page
58568** is moved, the pointer in its parent must be updated to point to the
58569** new location.  The pointer map is used to locate the parent page quickly.
58570**
58571** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
58572**                  used in this case.
58573**
58574** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
58575**                  is not used in this case.
58576**
58577** PTRMAP_OVERFLOW1: The database page is the first page in a list of
58578**                   overflow pages. The page number identifies the page that
58579**                   contains the cell with a pointer to this overflow page.
58580**
58581** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
58582**                   overflow pages. The page-number identifies the previous
58583**                   page in the overflow page list.
58584**
58585** PTRMAP_BTREE: The database page is a non-root btree page. The page number
58586**               identifies the parent page in the btree.
58587*/
58588#define PTRMAP_ROOTPAGE 1
58589#define PTRMAP_FREEPAGE 2
58590#define PTRMAP_OVERFLOW1 3
58591#define PTRMAP_OVERFLOW2 4
58592#define PTRMAP_BTREE 5
58593
58594/* A bunch of assert() statements to check the transaction state variables
58595** of handle p (type Btree*) are internally consistent.
58596*/
58597#define btreeIntegrity(p) \
58598  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
58599  assert( p->pBt->inTransaction>=p->inTrans );
58600
58601
58602/*
58603** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
58604** if the database supports auto-vacuum or not. Because it is used
58605** within an expression that is an argument to another macro
58606** (sqliteMallocRaw), it is not possible to use conditional compilation.
58607** So, this macro is defined instead.
58608*/
58609#ifndef SQLITE_OMIT_AUTOVACUUM
58610#define ISAUTOVACUUM (pBt->autoVacuum)
58611#else
58612#define ISAUTOVACUUM 0
58613#endif
58614
58615
58616/*
58617** This structure is passed around through all the sanity checking routines
58618** in order to keep track of some global state information.
58619**
58620** The aRef[] array is allocated so that there is 1 bit for each page in
58621** the database. As the integrity-check proceeds, for each page used in
58622** the database the corresponding bit is set. This allows integrity-check to
58623** detect pages that are used twice and orphaned pages (both of which
58624** indicate corruption).
58625*/
58626typedef struct IntegrityCk IntegrityCk;
58627struct IntegrityCk {
58628  BtShared *pBt;    /* The tree being checked out */
58629  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
58630  u8 *aPgRef;       /* 1 bit per page in the db (see above) */
58631  Pgno nPage;       /* Number of pages in the database */
58632  int mxErr;        /* Stop accumulating errors when this reaches zero */
58633  int nErr;         /* Number of messages written to zErrMsg so far */
58634  int mallocFailed; /* A memory allocation error has occurred */
58635  const char *zPfx; /* Error message prefix */
58636  int v1, v2;       /* Values for up to two %d fields in zPfx */
58637  StrAccum errMsg;  /* Accumulate the error message text here */
58638  u32 *heap;        /* Min-heap used for analyzing cell coverage */
58639};
58640
58641/*
58642** Routines to read or write a two- and four-byte big-endian integer values.
58643*/
58644#define get2byte(x)   ((x)[0]<<8 | (x)[1])
58645#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
58646#define get4byte sqlite3Get4byte
58647#define put4byte sqlite3Put4byte
58648
58649/*
58650** get2byteAligned(), unlike get2byte(), requires that its argument point to a
58651** two-byte aligned address.  get2bytea() is only used for accessing the
58652** cell addresses in a btree header.
58653*/
58654#if SQLITE_BYTEORDER==4321
58655# define get2byteAligned(x)  (*(u16*)(x))
58656#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
58657# define get2byteAligned(x)  __builtin_bswap16(*(u16*)(x))
58658#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
58659# define get2byteAligned(x)  _byteswap_ushort(*(u16*)(x))
58660#else
58661# define get2byteAligned(x)  ((x)[0]<<8 | (x)[1])
58662#endif
58663
58664/************** End of btreeInt.h ********************************************/
58665/************** Continuing where we left off in btmutex.c ********************/
58666#ifndef SQLITE_OMIT_SHARED_CACHE
58667#if SQLITE_THREADSAFE
58668
58669/*
58670** Obtain the BtShared mutex associated with B-Tree handle p. Also,
58671** set BtShared.db to the database handle associated with p and the
58672** p->locked boolean to true.
58673*/
58674static void lockBtreeMutex(Btree *p){
58675  assert( p->locked==0 );
58676  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
58677  assert( sqlite3_mutex_held(p->db->mutex) );
58678
58679  sqlite3_mutex_enter(p->pBt->mutex);
58680  p->pBt->db = p->db;
58681  p->locked = 1;
58682}
58683
58684/*
58685** Release the BtShared mutex associated with B-Tree handle p and
58686** clear the p->locked boolean.
58687*/
58688static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
58689  BtShared *pBt = p->pBt;
58690  assert( p->locked==1 );
58691  assert( sqlite3_mutex_held(pBt->mutex) );
58692  assert( sqlite3_mutex_held(p->db->mutex) );
58693  assert( p->db==pBt->db );
58694
58695  sqlite3_mutex_leave(pBt->mutex);
58696  p->locked = 0;
58697}
58698
58699/* Forward reference */
58700static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
58701
58702/*
58703** Enter a mutex on the given BTree object.
58704**
58705** If the object is not sharable, then no mutex is ever required
58706** and this routine is a no-op.  The underlying mutex is non-recursive.
58707** But we keep a reference count in Btree.wantToLock so the behavior
58708** of this interface is recursive.
58709**
58710** To avoid deadlocks, multiple Btrees are locked in the same order
58711** by all database connections.  The p->pNext is a list of other
58712** Btrees belonging to the same database connection as the p Btree
58713** which need to be locked after p.  If we cannot get a lock on
58714** p, then first unlock all of the others on p->pNext, then wait
58715** for the lock to become available on p, then relock all of the
58716** subsequent Btrees that desire a lock.
58717*/
58718SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
58719  /* Some basic sanity checking on the Btree.  The list of Btrees
58720  ** connected by pNext and pPrev should be in sorted order by
58721  ** Btree.pBt value. All elements of the list should belong to
58722  ** the same connection. Only shared Btrees are on the list. */
58723  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
58724  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
58725  assert( p->pNext==0 || p->pNext->db==p->db );
58726  assert( p->pPrev==0 || p->pPrev->db==p->db );
58727  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
58728
58729  /* Check for locking consistency */
58730  assert( !p->locked || p->wantToLock>0 );
58731  assert( p->sharable || p->wantToLock==0 );
58732
58733  /* We should already hold a lock on the database connection */
58734  assert( sqlite3_mutex_held(p->db->mutex) );
58735
58736  /* Unless the database is sharable and unlocked, then BtShared.db
58737  ** should already be set correctly. */
58738  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
58739
58740  if( !p->sharable ) return;
58741  p->wantToLock++;
58742  if( p->locked ) return;
58743  btreeLockCarefully(p);
58744}
58745
58746/* This is a helper function for sqlite3BtreeLock(). By moving
58747** complex, but seldom used logic, out of sqlite3BtreeLock() and
58748** into this routine, we avoid unnecessary stack pointer changes
58749** and thus help the sqlite3BtreeLock() routine to run much faster
58750** in the common case.
58751*/
58752static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
58753  Btree *pLater;
58754
58755  /* In most cases, we should be able to acquire the lock we
58756  ** want without having to go through the ascending lock
58757  ** procedure that follows.  Just be sure not to block.
58758  */
58759  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
58760    p->pBt->db = p->db;
58761    p->locked = 1;
58762    return;
58763  }
58764
58765  /* To avoid deadlock, first release all locks with a larger
58766  ** BtShared address.  Then acquire our lock.  Then reacquire
58767  ** the other BtShared locks that we used to hold in ascending
58768  ** order.
58769  */
58770  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
58771    assert( pLater->sharable );
58772    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
58773    assert( !pLater->locked || pLater->wantToLock>0 );
58774    if( pLater->locked ){
58775      unlockBtreeMutex(pLater);
58776    }
58777  }
58778  lockBtreeMutex(p);
58779  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
58780    if( pLater->wantToLock ){
58781      lockBtreeMutex(pLater);
58782    }
58783  }
58784}
58785
58786
58787/*
58788** Exit the recursive mutex on a Btree.
58789*/
58790SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
58791  assert( sqlite3_mutex_held(p->db->mutex) );
58792  if( p->sharable ){
58793    assert( p->wantToLock>0 );
58794    p->wantToLock--;
58795    if( p->wantToLock==0 ){
58796      unlockBtreeMutex(p);
58797    }
58798  }
58799}
58800
58801#ifndef NDEBUG
58802/*
58803** Return true if the BtShared mutex is held on the btree, or if the
58804** B-Tree is not marked as sharable.
58805**
58806** This routine is used only from within assert() statements.
58807*/
58808SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
58809  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
58810  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
58811  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
58812  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
58813
58814  return (p->sharable==0 || p->locked);
58815}
58816#endif
58817
58818
58819/*
58820** Enter the mutex on every Btree associated with a database
58821** connection.  This is needed (for example) prior to parsing
58822** a statement since we will be comparing table and column names
58823** against all schemas and we do not want those schemas being
58824** reset out from under us.
58825**
58826** There is a corresponding leave-all procedures.
58827**
58828** Enter the mutexes in accending order by BtShared pointer address
58829** to avoid the possibility of deadlock when two threads with
58830** two or more btrees in common both try to lock all their btrees
58831** at the same instant.
58832*/
58833static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
58834  int i;
58835  int skipOk = 1;
58836  Btree *p;
58837  assert( sqlite3_mutex_held(db->mutex) );
58838  for(i=0; i<db->nDb; i++){
58839    p = db->aDb[i].pBt;
58840    if( p && p->sharable ){
58841      sqlite3BtreeEnter(p);
58842      skipOk = 0;
58843    }
58844  }
58845  db->skipBtreeMutex = skipOk;
58846}
58847SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
58848  if( db->skipBtreeMutex==0 ) btreeEnterAll(db);
58849}
58850static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
58851  int i;
58852  Btree *p;
58853  assert( sqlite3_mutex_held(db->mutex) );
58854  for(i=0; i<db->nDb; i++){
58855    p = db->aDb[i].pBt;
58856    if( p ) sqlite3BtreeLeave(p);
58857  }
58858}
58859SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
58860  if( db->skipBtreeMutex==0 ) btreeLeaveAll(db);
58861}
58862
58863#ifndef NDEBUG
58864/*
58865** Return true if the current thread holds the database connection
58866** mutex and all required BtShared mutexes.
58867**
58868** This routine is used inside assert() statements only.
58869*/
58870SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
58871  int i;
58872  if( !sqlite3_mutex_held(db->mutex) ){
58873    return 0;
58874  }
58875  for(i=0; i<db->nDb; i++){
58876    Btree *p;
58877    p = db->aDb[i].pBt;
58878    if( p && p->sharable &&
58879         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
58880      return 0;
58881    }
58882  }
58883  return 1;
58884}
58885#endif /* NDEBUG */
58886
58887#ifndef NDEBUG
58888/*
58889** Return true if the correct mutexes are held for accessing the
58890** db->aDb[iDb].pSchema structure.  The mutexes required for schema
58891** access are:
58892**
58893**   (1) The mutex on db
58894**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
58895**
58896** If pSchema is not NULL, then iDb is computed from pSchema and
58897** db using sqlite3SchemaToIndex().
58898*/
58899SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
58900  Btree *p;
58901  assert( db!=0 );
58902  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
58903  assert( iDb>=0 && iDb<db->nDb );
58904  if( !sqlite3_mutex_held(db->mutex) ) return 0;
58905  if( iDb==1 ) return 1;
58906  p = db->aDb[iDb].pBt;
58907  assert( p!=0 );
58908  return p->sharable==0 || p->locked==1;
58909}
58910#endif /* NDEBUG */
58911
58912#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
58913/*
58914** The following are special cases for mutex enter routines for use
58915** in single threaded applications that use shared cache.  Except for
58916** these two routines, all mutex operations are no-ops in that case and
58917** are null #defines in btree.h.
58918**
58919** If shared cache is disabled, then all btree mutex routines, including
58920** the ones below, are no-ops and are null #defines in btree.h.
58921*/
58922
58923SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
58924  p->pBt->db = p->db;
58925}
58926SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
58927  int i;
58928  for(i=0; i<db->nDb; i++){
58929    Btree *p = db->aDb[i].pBt;
58930    if( p ){
58931      p->pBt->db = p->db;
58932    }
58933  }
58934}
58935#endif /* if SQLITE_THREADSAFE */
58936
58937#ifndef SQLITE_OMIT_INCRBLOB
58938/*
58939** Enter a mutex on a Btree given a cursor owned by that Btree.
58940**
58941** These entry points are used by incremental I/O only. Enter() is required
58942** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
58943** the build is threadsafe. Leave() is only required by threadsafe builds.
58944*/
58945SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
58946  sqlite3BtreeEnter(pCur->pBtree);
58947}
58948# if SQLITE_THREADSAFE
58949SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
58950  sqlite3BtreeLeave(pCur->pBtree);
58951}
58952# endif
58953#endif /* ifndef SQLITE_OMIT_INCRBLOB */
58954
58955#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
58956
58957/************** End of btmutex.c *********************************************/
58958/************** Begin file btree.c *******************************************/
58959/*
58960** 2004 April 6
58961**
58962** The author disclaims copyright to this source code.  In place of
58963** a legal notice, here is a blessing:
58964**
58965**    May you do good and not evil.
58966**    May you find forgiveness for yourself and forgive others.
58967**    May you share freely, never taking more than you give.
58968**
58969*************************************************************************
58970** This file implements an external (disk-based) database using BTrees.
58971** See the header comment on "btreeInt.h" for additional information.
58972** Including a description of file format and an overview of operation.
58973*/
58974/* #include "btreeInt.h" */
58975
58976/*
58977** The header string that appears at the beginning of every
58978** SQLite database.
58979*/
58980static const char zMagicHeader[] = SQLITE_FILE_HEADER;
58981
58982/*
58983** Set this global variable to 1 to enable tracing using the TRACE
58984** macro.
58985*/
58986#if 0
58987int sqlite3BtreeTrace=1;  /* True to enable tracing */
58988# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
58989#else
58990# define TRACE(X)
58991#endif
58992
58993/*
58994** Extract a 2-byte big-endian integer from an array of unsigned bytes.
58995** But if the value is zero, make it 65536.
58996**
58997** This routine is used to extract the "offset to cell content area" value
58998** from the header of a btree page.  If the page size is 65536 and the page
58999** is empty, the offset should be 65536, but the 2-byte value stores zero.
59000** This routine makes the necessary adjustment to 65536.
59001*/
59002#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
59003
59004/*
59005** Values passed as the 5th argument to allocateBtreePage()
59006*/
59007#define BTALLOC_ANY   0           /* Allocate any page */
59008#define BTALLOC_EXACT 1           /* Allocate exact page if possible */
59009#define BTALLOC_LE    2           /* Allocate any page <= the parameter */
59010
59011/*
59012** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
59013** defined, or 0 if it is. For example:
59014**
59015**   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
59016*/
59017#ifndef SQLITE_OMIT_AUTOVACUUM
59018#define IfNotOmitAV(expr) (expr)
59019#else
59020#define IfNotOmitAV(expr) 0
59021#endif
59022
59023#ifndef SQLITE_OMIT_SHARED_CACHE
59024/*
59025** A list of BtShared objects that are eligible for participation
59026** in shared cache.  This variable has file scope during normal builds,
59027** but the test harness needs to access it so we make it global for
59028** test builds.
59029**
59030** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
59031*/
59032#ifdef SQLITE_TEST
59033SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
59034#else
59035static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
59036#endif
59037#endif /* SQLITE_OMIT_SHARED_CACHE */
59038
59039#ifndef SQLITE_OMIT_SHARED_CACHE
59040/*
59041** Enable or disable the shared pager and schema features.
59042**
59043** This routine has no effect on existing database connections.
59044** The shared cache setting effects only future calls to
59045** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
59046*/
59047SQLITE_API int sqlite3_enable_shared_cache(int enable){
59048  sqlite3GlobalConfig.sharedCacheEnabled = enable;
59049  return SQLITE_OK;
59050}
59051#endif
59052
59053
59054
59055#ifdef SQLITE_OMIT_SHARED_CACHE
59056  /*
59057  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
59058  ** and clearAllSharedCacheTableLocks()
59059  ** manipulate entries in the BtShared.pLock linked list used to store
59060  ** shared-cache table level locks. If the library is compiled with the
59061  ** shared-cache feature disabled, then there is only ever one user
59062  ** of each BtShared structure and so this locking is not necessary.
59063  ** So define the lock related functions as no-ops.
59064  */
59065  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
59066  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
59067  #define clearAllSharedCacheTableLocks(a)
59068  #define downgradeAllSharedCacheTableLocks(a)
59069  #define hasSharedCacheTableLock(a,b,c,d) 1
59070  #define hasReadConflicts(a, b) 0
59071#endif
59072
59073#ifndef SQLITE_OMIT_SHARED_CACHE
59074
59075#ifdef SQLITE_DEBUG
59076/*
59077**** This function is only used as part of an assert() statement. ***
59078**
59079** Check to see if pBtree holds the required locks to read or write to the
59080** table with root page iRoot.   Return 1 if it does and 0 if not.
59081**
59082** For example, when writing to a table with root-page iRoot via
59083** Btree connection pBtree:
59084**
59085**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
59086**
59087** When writing to an index that resides in a sharable database, the
59088** caller should have first obtained a lock specifying the root page of
59089** the corresponding table. This makes things a bit more complicated,
59090** as this module treats each table as a separate structure. To determine
59091** the table corresponding to the index being written, this
59092** function has to search through the database schema.
59093**
59094** Instead of a lock on the table/index rooted at page iRoot, the caller may
59095** hold a write-lock on the schema table (root page 1). This is also
59096** acceptable.
59097*/
59098static int hasSharedCacheTableLock(
59099  Btree *pBtree,         /* Handle that must hold lock */
59100  Pgno iRoot,            /* Root page of b-tree */
59101  int isIndex,           /* True if iRoot is the root of an index b-tree */
59102  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
59103){
59104  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
59105  Pgno iTab = 0;
59106  BtLock *pLock;
59107
59108  /* If this database is not shareable, or if the client is reading
59109  ** and has the read-uncommitted flag set, then no lock is required.
59110  ** Return true immediately.
59111  */
59112  if( (pBtree->sharable==0)
59113   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
59114  ){
59115    return 1;
59116  }
59117
59118  /* If the client is reading  or writing an index and the schema is
59119  ** not loaded, then it is too difficult to actually check to see if
59120  ** the correct locks are held.  So do not bother - just return true.
59121  ** This case does not come up very often anyhow.
59122  */
59123  if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
59124    return 1;
59125  }
59126
59127  /* Figure out the root-page that the lock should be held on. For table
59128  ** b-trees, this is just the root page of the b-tree being read or
59129  ** written. For index b-trees, it is the root page of the associated
59130  ** table.  */
59131  if( isIndex ){
59132    HashElem *p;
59133    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
59134      Index *pIdx = (Index *)sqliteHashData(p);
59135      if( pIdx->tnum==(int)iRoot ){
59136        if( iTab ){
59137          /* Two or more indexes share the same root page.  There must
59138          ** be imposter tables.  So just return true.  The assert is not
59139          ** useful in that case. */
59140          return 1;
59141        }
59142        iTab = pIdx->pTable->tnum;
59143      }
59144    }
59145  }else{
59146    iTab = iRoot;
59147  }
59148
59149  /* Search for the required lock. Either a write-lock on root-page iTab, a
59150  ** write-lock on the schema table, or (if the client is reading) a
59151  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
59152  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
59153    if( pLock->pBtree==pBtree
59154     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
59155     && pLock->eLock>=eLockType
59156    ){
59157      return 1;
59158    }
59159  }
59160
59161  /* Failed to find the required lock. */
59162  return 0;
59163}
59164#endif /* SQLITE_DEBUG */
59165
59166#ifdef SQLITE_DEBUG
59167/*
59168**** This function may be used as part of assert() statements only. ****
59169**
59170** Return true if it would be illegal for pBtree to write into the
59171** table or index rooted at iRoot because other shared connections are
59172** simultaneously reading that same table or index.
59173**
59174** It is illegal for pBtree to write if some other Btree object that
59175** shares the same BtShared object is currently reading or writing
59176** the iRoot table.  Except, if the other Btree object has the
59177** read-uncommitted flag set, then it is OK for the other object to
59178** have a read cursor.
59179**
59180** For example, before writing to any part of the table or index
59181** rooted at page iRoot, one should call:
59182**
59183**    assert( !hasReadConflicts(pBtree, iRoot) );
59184*/
59185static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
59186  BtCursor *p;
59187  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
59188    if( p->pgnoRoot==iRoot
59189     && p->pBtree!=pBtree
59190     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
59191    ){
59192      return 1;
59193    }
59194  }
59195  return 0;
59196}
59197#endif    /* #ifdef SQLITE_DEBUG */
59198
59199/*
59200** Query to see if Btree handle p may obtain a lock of type eLock
59201** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
59202** SQLITE_OK if the lock may be obtained (by calling
59203** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
59204*/
59205static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
59206  BtShared *pBt = p->pBt;
59207  BtLock *pIter;
59208
59209  assert( sqlite3BtreeHoldsMutex(p) );
59210  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
59211  assert( p->db!=0 );
59212  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
59213
59214  /* If requesting a write-lock, then the Btree must have an open write
59215  ** transaction on this file. And, obviously, for this to be so there
59216  ** must be an open write transaction on the file itself.
59217  */
59218  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
59219  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
59220
59221  /* This routine is a no-op if the shared-cache is not enabled */
59222  if( !p->sharable ){
59223    return SQLITE_OK;
59224  }
59225
59226  /* If some other connection is holding an exclusive lock, the
59227  ** requested lock may not be obtained.
59228  */
59229  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
59230    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
59231    return SQLITE_LOCKED_SHAREDCACHE;
59232  }
59233
59234  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
59235    /* The condition (pIter->eLock!=eLock) in the following if(...)
59236    ** statement is a simplification of:
59237    **
59238    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
59239    **
59240    ** since we know that if eLock==WRITE_LOCK, then no other connection
59241    ** may hold a WRITE_LOCK on any table in this file (since there can
59242    ** only be a single writer).
59243    */
59244    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
59245    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
59246    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
59247      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
59248      if( eLock==WRITE_LOCK ){
59249        assert( p==pBt->pWriter );
59250        pBt->btsFlags |= BTS_PENDING;
59251      }
59252      return SQLITE_LOCKED_SHAREDCACHE;
59253    }
59254  }
59255  return SQLITE_OK;
59256}
59257#endif /* !SQLITE_OMIT_SHARED_CACHE */
59258
59259#ifndef SQLITE_OMIT_SHARED_CACHE
59260/*
59261** Add a lock on the table with root-page iTable to the shared-btree used
59262** by Btree handle p. Parameter eLock must be either READ_LOCK or
59263** WRITE_LOCK.
59264**
59265** This function assumes the following:
59266**
59267**   (a) The specified Btree object p is connected to a sharable
59268**       database (one with the BtShared.sharable flag set), and
59269**
59270**   (b) No other Btree objects hold a lock that conflicts
59271**       with the requested lock (i.e. querySharedCacheTableLock() has
59272**       already been called and returned SQLITE_OK).
59273**
59274** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
59275** is returned if a malloc attempt fails.
59276*/
59277static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
59278  BtShared *pBt = p->pBt;
59279  BtLock *pLock = 0;
59280  BtLock *pIter;
59281
59282  assert( sqlite3BtreeHoldsMutex(p) );
59283  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
59284  assert( p->db!=0 );
59285
59286  /* A connection with the read-uncommitted flag set will never try to
59287  ** obtain a read-lock using this function. The only read-lock obtained
59288  ** by a connection in read-uncommitted mode is on the sqlite_master
59289  ** table, and that lock is obtained in BtreeBeginTrans().  */
59290  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
59291
59292  /* This function should only be called on a sharable b-tree after it
59293  ** has been determined that no other b-tree holds a conflicting lock.  */
59294  assert( p->sharable );
59295  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
59296
59297  /* First search the list for an existing lock on this table. */
59298  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
59299    if( pIter->iTable==iTable && pIter->pBtree==p ){
59300      pLock = pIter;
59301      break;
59302    }
59303  }
59304
59305  /* If the above search did not find a BtLock struct associating Btree p
59306  ** with table iTable, allocate one and link it into the list.
59307  */
59308  if( !pLock ){
59309    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
59310    if( !pLock ){
59311      return SQLITE_NOMEM_BKPT;
59312    }
59313    pLock->iTable = iTable;
59314    pLock->pBtree = p;
59315    pLock->pNext = pBt->pLock;
59316    pBt->pLock = pLock;
59317  }
59318
59319  /* Set the BtLock.eLock variable to the maximum of the current lock
59320  ** and the requested lock. This means if a write-lock was already held
59321  ** and a read-lock requested, we don't incorrectly downgrade the lock.
59322  */
59323  assert( WRITE_LOCK>READ_LOCK );
59324  if( eLock>pLock->eLock ){
59325    pLock->eLock = eLock;
59326  }
59327
59328  return SQLITE_OK;
59329}
59330#endif /* !SQLITE_OMIT_SHARED_CACHE */
59331
59332#ifndef SQLITE_OMIT_SHARED_CACHE
59333/*
59334** Release all the table locks (locks obtained via calls to
59335** the setSharedCacheTableLock() procedure) held by Btree object p.
59336**
59337** This function assumes that Btree p has an open read or write
59338** transaction. If it does not, then the BTS_PENDING flag
59339** may be incorrectly cleared.
59340*/
59341static void clearAllSharedCacheTableLocks(Btree *p){
59342  BtShared *pBt = p->pBt;
59343  BtLock **ppIter = &pBt->pLock;
59344
59345  assert( sqlite3BtreeHoldsMutex(p) );
59346  assert( p->sharable || 0==*ppIter );
59347  assert( p->inTrans>0 );
59348
59349  while( *ppIter ){
59350    BtLock *pLock = *ppIter;
59351    assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
59352    assert( pLock->pBtree->inTrans>=pLock->eLock );
59353    if( pLock->pBtree==p ){
59354      *ppIter = pLock->pNext;
59355      assert( pLock->iTable!=1 || pLock==&p->lock );
59356      if( pLock->iTable!=1 ){
59357        sqlite3_free(pLock);
59358      }
59359    }else{
59360      ppIter = &pLock->pNext;
59361    }
59362  }
59363
59364  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
59365  if( pBt->pWriter==p ){
59366    pBt->pWriter = 0;
59367    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
59368  }else if( pBt->nTransaction==2 ){
59369    /* This function is called when Btree p is concluding its
59370    ** transaction. If there currently exists a writer, and p is not
59371    ** that writer, then the number of locks held by connections other
59372    ** than the writer must be about to drop to zero. In this case
59373    ** set the BTS_PENDING flag to 0.
59374    **
59375    ** If there is not currently a writer, then BTS_PENDING must
59376    ** be zero already. So this next line is harmless in that case.
59377    */
59378    pBt->btsFlags &= ~BTS_PENDING;
59379  }
59380}
59381
59382/*
59383** This function changes all write-locks held by Btree p into read-locks.
59384*/
59385static void downgradeAllSharedCacheTableLocks(Btree *p){
59386  BtShared *pBt = p->pBt;
59387  if( pBt->pWriter==p ){
59388    BtLock *pLock;
59389    pBt->pWriter = 0;
59390    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
59391    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
59392      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
59393      pLock->eLock = READ_LOCK;
59394    }
59395  }
59396}
59397
59398#endif /* SQLITE_OMIT_SHARED_CACHE */
59399
59400static void releasePage(MemPage *pPage);  /* Forward reference */
59401
59402/*
59403***** This routine is used inside of assert() only ****
59404**
59405** Verify that the cursor holds the mutex on its BtShared
59406*/
59407#ifdef SQLITE_DEBUG
59408static int cursorHoldsMutex(BtCursor *p){
59409  return sqlite3_mutex_held(p->pBt->mutex);
59410}
59411
59412/* Verify that the cursor and the BtShared agree about what is the current
59413** database connetion. This is important in shared-cache mode. If the database
59414** connection pointers get out-of-sync, it is possible for routines like
59415** btreeInitPage() to reference an stale connection pointer that references a
59416** a connection that has already closed.  This routine is used inside assert()
59417** statements only and for the purpose of double-checking that the btree code
59418** does keep the database connection pointers up-to-date.
59419*/
59420static int cursorOwnsBtShared(BtCursor *p){
59421  assert( cursorHoldsMutex(p) );
59422  return (p->pBtree->db==p->pBt->db);
59423}
59424#endif
59425
59426/*
59427** Invalidate the overflow cache of the cursor passed as the first argument.
59428** on the shared btree structure pBt.
59429*/
59430#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
59431
59432/*
59433** Invalidate the overflow page-list cache for all cursors opened
59434** on the shared btree structure pBt.
59435*/
59436static void invalidateAllOverflowCache(BtShared *pBt){
59437  BtCursor *p;
59438  assert( sqlite3_mutex_held(pBt->mutex) );
59439  for(p=pBt->pCursor; p; p=p->pNext){
59440    invalidateOverflowCache(p);
59441  }
59442}
59443
59444#ifndef SQLITE_OMIT_INCRBLOB
59445/*
59446** This function is called before modifying the contents of a table
59447** to invalidate any incrblob cursors that are open on the
59448** row or one of the rows being modified.
59449**
59450** If argument isClearTable is true, then the entire contents of the
59451** table is about to be deleted. In this case invalidate all incrblob
59452** cursors open on any row within the table with root-page pgnoRoot.
59453**
59454** Otherwise, if argument isClearTable is false, then the row with
59455** rowid iRow is being replaced or deleted. In this case invalidate
59456** only those incrblob cursors open on that specific row.
59457*/
59458static void invalidateIncrblobCursors(
59459  Btree *pBtree,          /* The database file to check */
59460  i64 iRow,               /* The rowid that might be changing */
59461  int isClearTable        /* True if all rows are being deleted */
59462){
59463  BtCursor *p;
59464  if( pBtree->hasIncrblobCur==0 ) return;
59465  assert( sqlite3BtreeHoldsMutex(pBtree) );
59466  pBtree->hasIncrblobCur = 0;
59467  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
59468    if( (p->curFlags & BTCF_Incrblob)!=0 ){
59469      pBtree->hasIncrblobCur = 1;
59470      if( isClearTable || p->info.nKey==iRow ){
59471        p->eState = CURSOR_INVALID;
59472      }
59473    }
59474  }
59475}
59476
59477#else
59478  /* Stub function when INCRBLOB is omitted */
59479  #define invalidateIncrblobCursors(x,y,z)
59480#endif /* SQLITE_OMIT_INCRBLOB */
59481
59482/*
59483** Set bit pgno of the BtShared.pHasContent bitvec. This is called
59484** when a page that previously contained data becomes a free-list leaf
59485** page.
59486**
59487** The BtShared.pHasContent bitvec exists to work around an obscure
59488** bug caused by the interaction of two useful IO optimizations surrounding
59489** free-list leaf pages:
59490**
59491**   1) When all data is deleted from a page and the page becomes
59492**      a free-list leaf page, the page is not written to the database
59493**      (as free-list leaf pages contain no meaningful data). Sometimes
59494**      such a page is not even journalled (as it will not be modified,
59495**      why bother journalling it?).
59496**
59497**   2) When a free-list leaf page is reused, its content is not read
59498**      from the database or written to the journal file (why should it
59499**      be, if it is not at all meaningful?).
59500**
59501** By themselves, these optimizations work fine and provide a handy
59502** performance boost to bulk delete or insert operations. However, if
59503** a page is moved to the free-list and then reused within the same
59504** transaction, a problem comes up. If the page is not journalled when
59505** it is moved to the free-list and it is also not journalled when it
59506** is extracted from the free-list and reused, then the original data
59507** may be lost. In the event of a rollback, it may not be possible
59508** to restore the database to its original configuration.
59509**
59510** The solution is the BtShared.pHasContent bitvec. Whenever a page is
59511** moved to become a free-list leaf page, the corresponding bit is
59512** set in the bitvec. Whenever a leaf page is extracted from the free-list,
59513** optimization 2 above is omitted if the corresponding bit is already
59514** set in BtShared.pHasContent. The contents of the bitvec are cleared
59515** at the end of every transaction.
59516*/
59517static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
59518  int rc = SQLITE_OK;
59519  if( !pBt->pHasContent ){
59520    assert( pgno<=pBt->nPage );
59521    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
59522    if( !pBt->pHasContent ){
59523      rc = SQLITE_NOMEM_BKPT;
59524    }
59525  }
59526  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
59527    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
59528  }
59529  return rc;
59530}
59531
59532/*
59533** Query the BtShared.pHasContent vector.
59534**
59535** This function is called when a free-list leaf page is removed from the
59536** free-list for reuse. It returns false if it is safe to retrieve the
59537** page from the pager layer with the 'no-content' flag set. True otherwise.
59538*/
59539static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
59540  Bitvec *p = pBt->pHasContent;
59541  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
59542}
59543
59544/*
59545** Clear (destroy) the BtShared.pHasContent bitvec. This should be
59546** invoked at the conclusion of each write-transaction.
59547*/
59548static void btreeClearHasContent(BtShared *pBt){
59549  sqlite3BitvecDestroy(pBt->pHasContent);
59550  pBt->pHasContent = 0;
59551}
59552
59553/*
59554** Release all of the apPage[] pages for a cursor.
59555*/
59556static void btreeReleaseAllCursorPages(BtCursor *pCur){
59557  int i;
59558  for(i=0; i<=pCur->iPage; i++){
59559    releasePage(pCur->apPage[i]);
59560    pCur->apPage[i] = 0;
59561  }
59562  pCur->iPage = -1;
59563}
59564
59565/*
59566** The cursor passed as the only argument must point to a valid entry
59567** when this function is called (i.e. have eState==CURSOR_VALID). This
59568** function saves the current cursor key in variables pCur->nKey and
59569** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
59570** code otherwise.
59571**
59572** If the cursor is open on an intkey table, then the integer key
59573** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
59574** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
59575** set to point to a malloced buffer pCur->nKey bytes in size containing
59576** the key.
59577*/
59578static int saveCursorKey(BtCursor *pCur){
59579  int rc = SQLITE_OK;
59580  assert( CURSOR_VALID==pCur->eState );
59581  assert( 0==pCur->pKey );
59582  assert( cursorHoldsMutex(pCur) );
59583
59584  if( pCur->curIntKey ){
59585    /* Only the rowid is required for a table btree */
59586    pCur->nKey = sqlite3BtreeIntegerKey(pCur);
59587  }else{
59588    /* For an index btree, save the complete key content */
59589    void *pKey;
59590    pCur->nKey = sqlite3BtreePayloadSize(pCur);
59591    pKey = sqlite3Malloc( pCur->nKey );
59592    if( pKey ){
59593      rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
59594      if( rc==SQLITE_OK ){
59595        pCur->pKey = pKey;
59596      }else{
59597        sqlite3_free(pKey);
59598      }
59599    }else{
59600      rc = SQLITE_NOMEM_BKPT;
59601    }
59602  }
59603  assert( !pCur->curIntKey || !pCur->pKey );
59604  return rc;
59605}
59606
59607/*
59608** Save the current cursor position in the variables BtCursor.nKey
59609** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
59610**
59611** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
59612** prior to calling this routine.
59613*/
59614static int saveCursorPosition(BtCursor *pCur){
59615  int rc;
59616
59617  assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
59618  assert( 0==pCur->pKey );
59619  assert( cursorHoldsMutex(pCur) );
59620
59621  if( pCur->eState==CURSOR_SKIPNEXT ){
59622    pCur->eState = CURSOR_VALID;
59623  }else{
59624    pCur->skipNext = 0;
59625  }
59626
59627  rc = saveCursorKey(pCur);
59628  if( rc==SQLITE_OK ){
59629    btreeReleaseAllCursorPages(pCur);
59630    pCur->eState = CURSOR_REQUIRESEEK;
59631  }
59632
59633  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
59634  return rc;
59635}
59636
59637/* Forward reference */
59638static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
59639
59640/*
59641** Save the positions of all cursors (except pExcept) that are open on
59642** the table with root-page iRoot.  "Saving the cursor position" means that
59643** the location in the btree is remembered in such a way that it can be
59644** moved back to the same spot after the btree has been modified.  This
59645** routine is called just before cursor pExcept is used to modify the
59646** table, for example in BtreeDelete() or BtreeInsert().
59647**
59648** If there are two or more cursors on the same btree, then all such
59649** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
59650** routine enforces that rule.  This routine only needs to be called in
59651** the uncommon case when pExpect has the BTCF_Multiple flag set.
59652**
59653** If pExpect!=NULL and if no other cursors are found on the same root-page,
59654** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
59655** pointless call to this routine.
59656**
59657** Implementation note:  This routine merely checks to see if any cursors
59658** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
59659** event that cursors are in need to being saved.
59660*/
59661static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
59662  BtCursor *p;
59663  assert( sqlite3_mutex_held(pBt->mutex) );
59664  assert( pExcept==0 || pExcept->pBt==pBt );
59665  for(p=pBt->pCursor; p; p=p->pNext){
59666    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
59667  }
59668  if( p ) return saveCursorsOnList(p, iRoot, pExcept);
59669  if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
59670  return SQLITE_OK;
59671}
59672
59673/* This helper routine to saveAllCursors does the actual work of saving
59674** the cursors if and when a cursor is found that actually requires saving.
59675** The common case is that no cursors need to be saved, so this routine is
59676** broken out from its caller to avoid unnecessary stack pointer movement.
59677*/
59678static int SQLITE_NOINLINE saveCursorsOnList(
59679  BtCursor *p,         /* The first cursor that needs saving */
59680  Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
59681  BtCursor *pExcept    /* Do not save this cursor */
59682){
59683  do{
59684    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
59685      if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
59686        int rc = saveCursorPosition(p);
59687        if( SQLITE_OK!=rc ){
59688          return rc;
59689        }
59690      }else{
59691        testcase( p->iPage>0 );
59692        btreeReleaseAllCursorPages(p);
59693      }
59694    }
59695    p = p->pNext;
59696  }while( p );
59697  return SQLITE_OK;
59698}
59699
59700/*
59701** Clear the current cursor position.
59702*/
59703SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
59704  assert( cursorHoldsMutex(pCur) );
59705  sqlite3_free(pCur->pKey);
59706  pCur->pKey = 0;
59707  pCur->eState = CURSOR_INVALID;
59708}
59709
59710/*
59711** In this version of BtreeMoveto, pKey is a packed index record
59712** such as is generated by the OP_MakeRecord opcode.  Unpack the
59713** record and then call BtreeMovetoUnpacked() to do the work.
59714*/
59715static int btreeMoveto(
59716  BtCursor *pCur,     /* Cursor open on the btree to be searched */
59717  const void *pKey,   /* Packed key if the btree is an index */
59718  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
59719  int bias,           /* Bias search to the high end */
59720  int *pRes           /* Write search results here */
59721){
59722  int rc;                    /* Status code */
59723  UnpackedRecord *pIdxKey;   /* Unpacked index key */
59724
59725  if( pKey ){
59726    assert( nKey==(i64)(int)nKey );
59727    pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
59728    if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
59729    sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
59730    if( pIdxKey->nField==0 ){
59731      rc = SQLITE_CORRUPT_BKPT;
59732      goto moveto_done;
59733    }
59734  }else{
59735    pIdxKey = 0;
59736  }
59737  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
59738moveto_done:
59739  if( pIdxKey ){
59740    sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
59741  }
59742  return rc;
59743}
59744
59745/*
59746** Restore the cursor to the position it was in (or as close to as possible)
59747** when saveCursorPosition() was called. Note that this call deletes the
59748** saved position info stored by saveCursorPosition(), so there can be
59749** at most one effective restoreCursorPosition() call after each
59750** saveCursorPosition().
59751*/
59752static int btreeRestoreCursorPosition(BtCursor *pCur){
59753  int rc;
59754  int skipNext;
59755  assert( cursorOwnsBtShared(pCur) );
59756  assert( pCur->eState>=CURSOR_REQUIRESEEK );
59757  if( pCur->eState==CURSOR_FAULT ){
59758    return pCur->skipNext;
59759  }
59760  pCur->eState = CURSOR_INVALID;
59761  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
59762  if( rc==SQLITE_OK ){
59763    sqlite3_free(pCur->pKey);
59764    pCur->pKey = 0;
59765    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
59766    pCur->skipNext |= skipNext;
59767    if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
59768      pCur->eState = CURSOR_SKIPNEXT;
59769    }
59770  }
59771  return rc;
59772}
59773
59774#define restoreCursorPosition(p) \
59775  (p->eState>=CURSOR_REQUIRESEEK ? \
59776         btreeRestoreCursorPosition(p) : \
59777         SQLITE_OK)
59778
59779/*
59780** Determine whether or not a cursor has moved from the position where
59781** it was last placed, or has been invalidated for any other reason.
59782** Cursors can move when the row they are pointing at is deleted out
59783** from under them, for example.  Cursor might also move if a btree
59784** is rebalanced.
59785**
59786** Calling this routine with a NULL cursor pointer returns false.
59787**
59788** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
59789** back to where it ought to be if this routine returns true.
59790*/
59791SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
59792  return pCur->eState!=CURSOR_VALID;
59793}
59794
59795/*
59796** This routine restores a cursor back to its original position after it
59797** has been moved by some outside activity (such as a btree rebalance or
59798** a row having been deleted out from under the cursor).
59799**
59800** On success, the *pDifferentRow parameter is false if the cursor is left
59801** pointing at exactly the same row.  *pDifferntRow is the row the cursor
59802** was pointing to has been deleted, forcing the cursor to point to some
59803** nearby row.
59804**
59805** This routine should only be called for a cursor that just returned
59806** TRUE from sqlite3BtreeCursorHasMoved().
59807*/
59808SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
59809  int rc;
59810
59811  assert( pCur!=0 );
59812  assert( pCur->eState!=CURSOR_VALID );
59813  rc = restoreCursorPosition(pCur);
59814  if( rc ){
59815    *pDifferentRow = 1;
59816    return rc;
59817  }
59818  if( pCur->eState!=CURSOR_VALID ){
59819    *pDifferentRow = 1;
59820  }else{
59821    assert( pCur->skipNext==0 );
59822    *pDifferentRow = 0;
59823  }
59824  return SQLITE_OK;
59825}
59826
59827#ifdef SQLITE_ENABLE_CURSOR_HINTS
59828/*
59829** Provide hints to the cursor.  The particular hint given (and the type
59830** and number of the varargs parameters) is determined by the eHintType
59831** parameter.  See the definitions of the BTREE_HINT_* macros for details.
59832*/
59833SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
59834  /* Used only by system that substitute their own storage engine */
59835}
59836#endif
59837
59838/*
59839** Provide flag hints to the cursor.
59840*/
59841SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
59842  assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
59843  pCur->hints = x;
59844}
59845
59846
59847#ifndef SQLITE_OMIT_AUTOVACUUM
59848/*
59849** Given a page number of a regular database page, return the page
59850** number for the pointer-map page that contains the entry for the
59851** input page number.
59852**
59853** Return 0 (not a valid page) for pgno==1 since there is
59854** no pointer map associated with page 1.  The integrity_check logic
59855** requires that ptrmapPageno(*,1)!=1.
59856*/
59857static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
59858  int nPagesPerMapPage;
59859  Pgno iPtrMap, ret;
59860  assert( sqlite3_mutex_held(pBt->mutex) );
59861  if( pgno<2 ) return 0;
59862  nPagesPerMapPage = (pBt->usableSize/5)+1;
59863  iPtrMap = (pgno-2)/nPagesPerMapPage;
59864  ret = (iPtrMap*nPagesPerMapPage) + 2;
59865  if( ret==PENDING_BYTE_PAGE(pBt) ){
59866    ret++;
59867  }
59868  return ret;
59869}
59870
59871/*
59872** Write an entry into the pointer map.
59873**
59874** This routine updates the pointer map entry for page number 'key'
59875** so that it maps to type 'eType' and parent page number 'pgno'.
59876**
59877** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
59878** a no-op.  If an error occurs, the appropriate error code is written
59879** into *pRC.
59880*/
59881static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
59882  DbPage *pDbPage;  /* The pointer map page */
59883  u8 *pPtrmap;      /* The pointer map data */
59884  Pgno iPtrmap;     /* The pointer map page number */
59885  int offset;       /* Offset in pointer map page */
59886  int rc;           /* Return code from subfunctions */
59887
59888  if( *pRC ) return;
59889
59890  assert( sqlite3_mutex_held(pBt->mutex) );
59891  /* The master-journal page number must never be used as a pointer map page */
59892  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
59893
59894  assert( pBt->autoVacuum );
59895  if( key==0 ){
59896    *pRC = SQLITE_CORRUPT_BKPT;
59897    return;
59898  }
59899  iPtrmap = PTRMAP_PAGENO(pBt, key);
59900  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
59901  if( rc!=SQLITE_OK ){
59902    *pRC = rc;
59903    return;
59904  }
59905  offset = PTRMAP_PTROFFSET(iPtrmap, key);
59906  if( offset<0 ){
59907    *pRC = SQLITE_CORRUPT_BKPT;
59908    goto ptrmap_exit;
59909  }
59910  assert( offset <= (int)pBt->usableSize-5 );
59911  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
59912
59913  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
59914    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
59915    *pRC= rc = sqlite3PagerWrite(pDbPage);
59916    if( rc==SQLITE_OK ){
59917      pPtrmap[offset] = eType;
59918      put4byte(&pPtrmap[offset+1], parent);
59919    }
59920  }
59921
59922ptrmap_exit:
59923  sqlite3PagerUnref(pDbPage);
59924}
59925
59926/*
59927** Read an entry from the pointer map.
59928**
59929** This routine retrieves the pointer map entry for page 'key', writing
59930** the type and parent page number to *pEType and *pPgno respectively.
59931** An error code is returned if something goes wrong, otherwise SQLITE_OK.
59932*/
59933static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
59934  DbPage *pDbPage;   /* The pointer map page */
59935  int iPtrmap;       /* Pointer map page index */
59936  u8 *pPtrmap;       /* Pointer map page data */
59937  int offset;        /* Offset of entry in pointer map */
59938  int rc;
59939
59940  assert( sqlite3_mutex_held(pBt->mutex) );
59941
59942  iPtrmap = PTRMAP_PAGENO(pBt, key);
59943  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
59944  if( rc!=0 ){
59945    return rc;
59946  }
59947  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
59948
59949  offset = PTRMAP_PTROFFSET(iPtrmap, key);
59950  if( offset<0 ){
59951    sqlite3PagerUnref(pDbPage);
59952    return SQLITE_CORRUPT_BKPT;
59953  }
59954  assert( offset <= (int)pBt->usableSize-5 );
59955  assert( pEType!=0 );
59956  *pEType = pPtrmap[offset];
59957  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
59958
59959  sqlite3PagerUnref(pDbPage);
59960  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
59961  return SQLITE_OK;
59962}
59963
59964#else /* if defined SQLITE_OMIT_AUTOVACUUM */
59965  #define ptrmapPut(w,x,y,z,rc)
59966  #define ptrmapGet(w,x,y,z) SQLITE_OK
59967  #define ptrmapPutOvflPtr(x, y, rc)
59968#endif
59969
59970/*
59971** Given a btree page and a cell index (0 means the first cell on
59972** the page, 1 means the second cell, and so forth) return a pointer
59973** to the cell content.
59974**
59975** findCellPastPtr() does the same except it skips past the initial
59976** 4-byte child pointer found on interior pages, if there is one.
59977**
59978** This routine works only for pages that do not contain overflow cells.
59979*/
59980#define findCell(P,I) \
59981  ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
59982#define findCellPastPtr(P,I) \
59983  ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
59984
59985
59986/*
59987** This is common tail processing for btreeParseCellPtr() and
59988** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
59989** on a single B-tree page.  Make necessary adjustments to the CellInfo
59990** structure.
59991*/
59992static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
59993  MemPage *pPage,         /* Page containing the cell */
59994  u8 *pCell,              /* Pointer to the cell text. */
59995  CellInfo *pInfo         /* Fill in this structure */
59996){
59997  /* If the payload will not fit completely on the local page, we have
59998  ** to decide how much to store locally and how much to spill onto
59999  ** overflow pages.  The strategy is to minimize the amount of unused
60000  ** space on overflow pages while keeping the amount of local storage
60001  ** in between minLocal and maxLocal.
60002  **
60003  ** Warning:  changing the way overflow payload is distributed in any
60004  ** way will result in an incompatible file format.
60005  */
60006  int minLocal;  /* Minimum amount of payload held locally */
60007  int maxLocal;  /* Maximum amount of payload held locally */
60008  int surplus;   /* Overflow payload available for local storage */
60009
60010  minLocal = pPage->minLocal;
60011  maxLocal = pPage->maxLocal;
60012  surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
60013  testcase( surplus==maxLocal );
60014  testcase( surplus==maxLocal+1 );
60015  if( surplus <= maxLocal ){
60016    pInfo->nLocal = (u16)surplus;
60017  }else{
60018    pInfo->nLocal = (u16)minLocal;
60019  }
60020  pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
60021}
60022
60023/*
60024** The following routines are implementations of the MemPage.xParseCell()
60025** method.
60026**
60027** Parse a cell content block and fill in the CellInfo structure.
60028**
60029** btreeParseCellPtr()        =>   table btree leaf nodes
60030** btreeParseCellNoPayload()  =>   table btree internal nodes
60031** btreeParseCellPtrIndex()   =>   index btree nodes
60032**
60033** There is also a wrapper function btreeParseCell() that works for
60034** all MemPage types and that references the cell by index rather than
60035** by pointer.
60036*/
60037static void btreeParseCellPtrNoPayload(
60038  MemPage *pPage,         /* Page containing the cell */
60039  u8 *pCell,              /* Pointer to the cell text. */
60040  CellInfo *pInfo         /* Fill in this structure */
60041){
60042  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60043  assert( pPage->leaf==0 );
60044  assert( pPage->childPtrSize==4 );
60045#ifndef SQLITE_DEBUG
60046  UNUSED_PARAMETER(pPage);
60047#endif
60048  pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
60049  pInfo->nPayload = 0;
60050  pInfo->nLocal = 0;
60051  pInfo->pPayload = 0;
60052  return;
60053}
60054static void btreeParseCellPtr(
60055  MemPage *pPage,         /* Page containing the cell */
60056  u8 *pCell,              /* Pointer to the cell text. */
60057  CellInfo *pInfo         /* Fill in this structure */
60058){
60059  u8 *pIter;              /* For scanning through pCell */
60060  u32 nPayload;           /* Number of bytes of cell payload */
60061  u64 iKey;               /* Extracted Key value */
60062
60063  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60064  assert( pPage->leaf==0 || pPage->leaf==1 );
60065  assert( pPage->intKeyLeaf );
60066  assert( pPage->childPtrSize==0 );
60067  pIter = pCell;
60068
60069  /* The next block of code is equivalent to:
60070  **
60071  **     pIter += getVarint32(pIter, nPayload);
60072  **
60073  ** The code is inlined to avoid a function call.
60074  */
60075  nPayload = *pIter;
60076  if( nPayload>=0x80 ){
60077    u8 *pEnd = &pIter[8];
60078    nPayload &= 0x7f;
60079    do{
60080      nPayload = (nPayload<<7) | (*++pIter & 0x7f);
60081    }while( (*pIter)>=0x80 && pIter<pEnd );
60082  }
60083  pIter++;
60084
60085  /* The next block of code is equivalent to:
60086  **
60087  **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
60088  **
60089  ** The code is inlined to avoid a function call.
60090  */
60091  iKey = *pIter;
60092  if( iKey>=0x80 ){
60093    u8 *pEnd = &pIter[7];
60094    iKey &= 0x7f;
60095    while(1){
60096      iKey = (iKey<<7) | (*++pIter & 0x7f);
60097      if( (*pIter)<0x80 ) break;
60098      if( pIter>=pEnd ){
60099        iKey = (iKey<<8) | *++pIter;
60100        break;
60101      }
60102    }
60103  }
60104  pIter++;
60105
60106  pInfo->nKey = *(i64*)&iKey;
60107  pInfo->nPayload = nPayload;
60108  pInfo->pPayload = pIter;
60109  testcase( nPayload==pPage->maxLocal );
60110  testcase( nPayload==pPage->maxLocal+1 );
60111  if( nPayload<=pPage->maxLocal ){
60112    /* This is the (easy) common case where the entire payload fits
60113    ** on the local page.  No overflow is required.
60114    */
60115    pInfo->nSize = nPayload + (u16)(pIter - pCell);
60116    if( pInfo->nSize<4 ) pInfo->nSize = 4;
60117    pInfo->nLocal = (u16)nPayload;
60118  }else{
60119    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
60120  }
60121}
60122static void btreeParseCellPtrIndex(
60123  MemPage *pPage,         /* Page containing the cell */
60124  u8 *pCell,              /* Pointer to the cell text. */
60125  CellInfo *pInfo         /* Fill in this structure */
60126){
60127  u8 *pIter;              /* For scanning through pCell */
60128  u32 nPayload;           /* Number of bytes of cell payload */
60129
60130  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60131  assert( pPage->leaf==0 || pPage->leaf==1 );
60132  assert( pPage->intKeyLeaf==0 );
60133  pIter = pCell + pPage->childPtrSize;
60134  nPayload = *pIter;
60135  if( nPayload>=0x80 ){
60136    u8 *pEnd = &pIter[8];
60137    nPayload &= 0x7f;
60138    do{
60139      nPayload = (nPayload<<7) | (*++pIter & 0x7f);
60140    }while( *(pIter)>=0x80 && pIter<pEnd );
60141  }
60142  pIter++;
60143  pInfo->nKey = nPayload;
60144  pInfo->nPayload = nPayload;
60145  pInfo->pPayload = pIter;
60146  testcase( nPayload==pPage->maxLocal );
60147  testcase( nPayload==pPage->maxLocal+1 );
60148  if( nPayload<=pPage->maxLocal ){
60149    /* This is the (easy) common case where the entire payload fits
60150    ** on the local page.  No overflow is required.
60151    */
60152    pInfo->nSize = nPayload + (u16)(pIter - pCell);
60153    if( pInfo->nSize<4 ) pInfo->nSize = 4;
60154    pInfo->nLocal = (u16)nPayload;
60155  }else{
60156    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
60157  }
60158}
60159static void btreeParseCell(
60160  MemPage *pPage,         /* Page containing the cell */
60161  int iCell,              /* The cell index.  First cell is 0 */
60162  CellInfo *pInfo         /* Fill in this structure */
60163){
60164  pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
60165}
60166
60167/*
60168** The following routines are implementations of the MemPage.xCellSize
60169** method.
60170**
60171** Compute the total number of bytes that a Cell needs in the cell
60172** data area of the btree-page.  The return number includes the cell
60173** data header and the local payload, but not any overflow page or
60174** the space used by the cell pointer.
60175**
60176** cellSizePtrNoPayload()    =>   table internal nodes
60177** cellSizePtr()             =>   all index nodes & table leaf nodes
60178*/
60179static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
60180  u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
60181  u8 *pEnd;                                /* End mark for a varint */
60182  u32 nSize;                               /* Size value to return */
60183
60184#ifdef SQLITE_DEBUG
60185  /* The value returned by this function should always be the same as
60186  ** the (CellInfo.nSize) value found by doing a full parse of the
60187  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
60188  ** this function verifies that this invariant is not violated. */
60189  CellInfo debuginfo;
60190  pPage->xParseCell(pPage, pCell, &debuginfo);
60191#endif
60192
60193  nSize = *pIter;
60194  if( nSize>=0x80 ){
60195    pEnd = &pIter[8];
60196    nSize &= 0x7f;
60197    do{
60198      nSize = (nSize<<7) | (*++pIter & 0x7f);
60199    }while( *(pIter)>=0x80 && pIter<pEnd );
60200  }
60201  pIter++;
60202  if( pPage->intKey ){
60203    /* pIter now points at the 64-bit integer key value, a variable length
60204    ** integer. The following block moves pIter to point at the first byte
60205    ** past the end of the key value. */
60206    pEnd = &pIter[9];
60207    while( (*pIter++)&0x80 && pIter<pEnd );
60208  }
60209  testcase( nSize==pPage->maxLocal );
60210  testcase( nSize==pPage->maxLocal+1 );
60211  if( nSize<=pPage->maxLocal ){
60212    nSize += (u32)(pIter - pCell);
60213    if( nSize<4 ) nSize = 4;
60214  }else{
60215    int minLocal = pPage->minLocal;
60216    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
60217    testcase( nSize==pPage->maxLocal );
60218    testcase( nSize==pPage->maxLocal+1 );
60219    if( nSize>pPage->maxLocal ){
60220      nSize = minLocal;
60221    }
60222    nSize += 4 + (u16)(pIter - pCell);
60223  }
60224  assert( nSize==debuginfo.nSize || CORRUPT_DB );
60225  return (u16)nSize;
60226}
60227static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
60228  u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
60229  u8 *pEnd;              /* End mark for a varint */
60230
60231#ifdef SQLITE_DEBUG
60232  /* The value returned by this function should always be the same as
60233  ** the (CellInfo.nSize) value found by doing a full parse of the
60234  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
60235  ** this function verifies that this invariant is not violated. */
60236  CellInfo debuginfo;
60237  pPage->xParseCell(pPage, pCell, &debuginfo);
60238#else
60239  UNUSED_PARAMETER(pPage);
60240#endif
60241
60242  assert( pPage->childPtrSize==4 );
60243  pEnd = pIter + 9;
60244  while( (*pIter++)&0x80 && pIter<pEnd );
60245  assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
60246  return (u16)(pIter - pCell);
60247}
60248
60249
60250#ifdef SQLITE_DEBUG
60251/* This variation on cellSizePtr() is used inside of assert() statements
60252** only. */
60253static u16 cellSize(MemPage *pPage, int iCell){
60254  return pPage->xCellSize(pPage, findCell(pPage, iCell));
60255}
60256#endif
60257
60258#ifndef SQLITE_OMIT_AUTOVACUUM
60259/*
60260** If the cell pCell, part of page pPage contains a pointer
60261** to an overflow page, insert an entry into the pointer-map
60262** for the overflow page.
60263*/
60264static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
60265  CellInfo info;
60266  if( *pRC ) return;
60267  assert( pCell!=0 );
60268  pPage->xParseCell(pPage, pCell, &info);
60269  if( info.nLocal<info.nPayload ){
60270    Pgno ovfl = get4byte(&pCell[info.nSize-4]);
60271    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
60272  }
60273}
60274#endif
60275
60276
60277/*
60278** Defragment the page given. This routine reorganizes cells within the
60279** page so that there are no free-blocks on the free-block list.
60280**
60281** Parameter nMaxFrag is the maximum amount of fragmented space that may be
60282** present in the page after this routine returns.
60283**
60284** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
60285** b-tree page so that there are no freeblocks or fragment bytes, all
60286** unused bytes are contained in the unallocated space region, and all
60287** cells are packed tightly at the end of the page.
60288*/
60289static int defragmentPage(MemPage *pPage, int nMaxFrag){
60290  int i;                     /* Loop counter */
60291  int pc;                    /* Address of the i-th cell */
60292  int hdr;                   /* Offset to the page header */
60293  int size;                  /* Size of a cell */
60294  int usableSize;            /* Number of usable bytes on a page */
60295  int cellOffset;            /* Offset to the cell pointer array */
60296  int cbrk;                  /* Offset to the cell content area */
60297  int nCell;                 /* Number of cells on the page */
60298  unsigned char *data;       /* The page data */
60299  unsigned char *temp;       /* Temp area for cell content */
60300  unsigned char *src;        /* Source of content */
60301  int iCellFirst;            /* First allowable cell index */
60302  int iCellLast;             /* Last possible cell index */
60303
60304  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60305  assert( pPage->pBt!=0 );
60306  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
60307  assert( pPage->nOverflow==0 );
60308  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60309  temp = 0;
60310  src = data = pPage->aData;
60311  hdr = pPage->hdrOffset;
60312  cellOffset = pPage->cellOffset;
60313  nCell = pPage->nCell;
60314  assert( nCell==get2byte(&data[hdr+3]) );
60315  iCellFirst = cellOffset + 2*nCell;
60316  usableSize = pPage->pBt->usableSize;
60317
60318  /* This block handles pages with two or fewer free blocks and nMaxFrag
60319  ** or fewer fragmented bytes. In this case it is faster to move the
60320  ** two (or one) blocks of cells using memmove() and add the required
60321  ** offsets to each pointer in the cell-pointer array than it is to
60322  ** reconstruct the entire page.  */
60323  if( (int)data[hdr+7]<=nMaxFrag ){
60324    int iFree = get2byte(&data[hdr+1]);
60325    if( iFree ){
60326      int iFree2 = get2byte(&data[iFree]);
60327
60328      /* pageFindSlot() has already verified that free blocks are sorted
60329      ** in order of offset within the page, and that no block extends
60330      ** past the end of the page. Provided the two free slots do not
60331      ** overlap, this guarantees that the memmove() calls below will not
60332      ** overwrite the usableSize byte buffer, even if the database page
60333      ** is corrupt.  */
60334      assert( iFree2==0 || iFree2>iFree );
60335      assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
60336      assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
60337
60338      if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
60339        u8 *pEnd = &data[cellOffset + nCell*2];
60340        u8 *pAddr;
60341        int sz2 = 0;
60342        int sz = get2byte(&data[iFree+2]);
60343        int top = get2byte(&data[hdr+5]);
60344        if( iFree2 ){
60345          if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_BKPT;
60346          sz2 = get2byte(&data[iFree2+2]);
60347          assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
60348          memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
60349          sz += sz2;
60350        }
60351        cbrk = top+sz;
60352        assert( cbrk+(iFree-top) <= usableSize );
60353        memmove(&data[cbrk], &data[top], iFree-top);
60354        for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
60355          pc = get2byte(pAddr);
60356          if( pc<iFree ){ put2byte(pAddr, pc+sz); }
60357          else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
60358        }
60359        goto defragment_out;
60360      }
60361    }
60362  }
60363
60364  cbrk = usableSize;
60365  iCellLast = usableSize - 4;
60366  for(i=0; i<nCell; i++){
60367    u8 *pAddr;     /* The i-th cell pointer */
60368    pAddr = &data[cellOffset + i*2];
60369    pc = get2byte(pAddr);
60370    testcase( pc==iCellFirst );
60371    testcase( pc==iCellLast );
60372    /* These conditions have already been verified in btreeInitPage()
60373    ** if PRAGMA cell_size_check=ON.
60374    */
60375    if( pc<iCellFirst || pc>iCellLast ){
60376      return SQLITE_CORRUPT_BKPT;
60377    }
60378    assert( pc>=iCellFirst && pc<=iCellLast );
60379    size = pPage->xCellSize(pPage, &src[pc]);
60380    cbrk -= size;
60381    if( cbrk<iCellFirst || pc+size>usableSize ){
60382      return SQLITE_CORRUPT_BKPT;
60383    }
60384    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
60385    testcase( cbrk+size==usableSize );
60386    testcase( pc+size==usableSize );
60387    put2byte(pAddr, cbrk);
60388    if( temp==0 ){
60389      int x;
60390      if( cbrk==pc ) continue;
60391      temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
60392      x = get2byte(&data[hdr+5]);
60393      memcpy(&temp[x], &data[x], (cbrk+size) - x);
60394      src = temp;
60395    }
60396    memcpy(&data[cbrk], &src[pc], size);
60397  }
60398  data[hdr+7] = 0;
60399
60400 defragment_out:
60401  if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
60402    return SQLITE_CORRUPT_BKPT;
60403  }
60404  assert( cbrk>=iCellFirst );
60405  put2byte(&data[hdr+5], cbrk);
60406  data[hdr+1] = 0;
60407  data[hdr+2] = 0;
60408  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
60409  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60410  return SQLITE_OK;
60411}
60412
60413/*
60414** Search the free-list on page pPg for space to store a cell nByte bytes in
60415** size. If one can be found, return a pointer to the space and remove it
60416** from the free-list.
60417**
60418** If no suitable space can be found on the free-list, return NULL.
60419**
60420** This function may detect corruption within pPg.  If corruption is
60421** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
60422**
60423** Slots on the free list that are between 1 and 3 bytes larger than nByte
60424** will be ignored if adding the extra space to the fragmentation count
60425** causes the fragmentation count to exceed 60.
60426*/
60427static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
60428  const int hdr = pPg->hdrOffset;
60429  u8 * const aData = pPg->aData;
60430  int iAddr = hdr + 1;
60431  int pc = get2byte(&aData[iAddr]);
60432  int x;
60433  int usableSize = pPg->pBt->usableSize;
60434
60435  assert( pc>0 );
60436  do{
60437    int size;            /* Size of the free slot */
60438    /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
60439    ** increasing offset. */
60440    if( pc>usableSize-4 || pc<iAddr+4 ){
60441      *pRc = SQLITE_CORRUPT_BKPT;
60442      return 0;
60443    }
60444    /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
60445    ** freeblock form a big-endian integer which is the size of the freeblock
60446    ** in bytes, including the 4-byte header. */
60447    size = get2byte(&aData[pc+2]);
60448    if( (x = size - nByte)>=0 ){
60449      testcase( x==4 );
60450      testcase( x==3 );
60451      if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
60452        *pRc = SQLITE_CORRUPT_BKPT;
60453        return 0;
60454      }else if( x<4 ){
60455        /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
60456        ** number of bytes in fragments may not exceed 60. */
60457        if( aData[hdr+7]>57 ) return 0;
60458
60459        /* Remove the slot from the free-list. Update the number of
60460        ** fragmented bytes within the page. */
60461        memcpy(&aData[iAddr], &aData[pc], 2);
60462        aData[hdr+7] += (u8)x;
60463      }else{
60464        /* The slot remains on the free-list. Reduce its size to account
60465         ** for the portion used by the new allocation. */
60466        put2byte(&aData[pc+2], x);
60467      }
60468      return &aData[pc + x];
60469    }
60470    iAddr = pc;
60471    pc = get2byte(&aData[pc]);
60472  }while( pc );
60473
60474  return 0;
60475}
60476
60477/*
60478** Allocate nByte bytes of space from within the B-Tree page passed
60479** as the first argument. Write into *pIdx the index into pPage->aData[]
60480** of the first byte of allocated space. Return either SQLITE_OK or
60481** an error code (usually SQLITE_CORRUPT).
60482**
60483** The caller guarantees that there is sufficient space to make the
60484** allocation.  This routine might need to defragment in order to bring
60485** all the space together, however.  This routine will avoid using
60486** the first two bytes past the cell pointer area since presumably this
60487** allocation is being made in order to insert a new cell, so we will
60488** also end up needing a new cell pointer.
60489*/
60490static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
60491  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
60492  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
60493  int top;                             /* First byte of cell content area */
60494  int rc = SQLITE_OK;                  /* Integer return code */
60495  int gap;        /* First byte of gap between cell pointers and cell content */
60496
60497  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60498  assert( pPage->pBt );
60499  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60500  assert( nByte>=0 );  /* Minimum cell size is 4 */
60501  assert( pPage->nFree>=nByte );
60502  assert( pPage->nOverflow==0 );
60503  assert( nByte < (int)(pPage->pBt->usableSize-8) );
60504
60505  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
60506  gap = pPage->cellOffset + 2*pPage->nCell;
60507  assert( gap<=65536 );
60508  /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
60509  ** and the reserved space is zero (the usual value for reserved space)
60510  ** then the cell content offset of an empty page wants to be 65536.
60511  ** However, that integer is too large to be stored in a 2-byte unsigned
60512  ** integer, so a value of 0 is used in its place. */
60513  top = get2byte(&data[hdr+5]);
60514  assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
60515  if( gap>top ){
60516    if( top==0 && pPage->pBt->usableSize==65536 ){
60517      top = 65536;
60518    }else{
60519      return SQLITE_CORRUPT_BKPT;
60520    }
60521  }
60522
60523  /* If there is enough space between gap and top for one more cell pointer
60524  ** array entry offset, and if the freelist is not empty, then search the
60525  ** freelist looking for a free slot big enough to satisfy the request.
60526  */
60527  testcase( gap+2==top );
60528  testcase( gap+1==top );
60529  testcase( gap==top );
60530  if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
60531    u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
60532    if( pSpace ){
60533      assert( pSpace>=data && (pSpace - data)<65536 );
60534      *pIdx = (int)(pSpace - data);
60535      return SQLITE_OK;
60536    }else if( rc ){
60537      return rc;
60538    }
60539  }
60540
60541  /* The request could not be fulfilled using a freelist slot.  Check
60542  ** to see if defragmentation is necessary.
60543  */
60544  testcase( gap+2+nByte==top );
60545  if( gap+2+nByte>top ){
60546    assert( pPage->nCell>0 || CORRUPT_DB );
60547    rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
60548    if( rc ) return rc;
60549    top = get2byteNotZero(&data[hdr+5]);
60550    assert( gap+2+nByte<=top );
60551  }
60552
60553
60554  /* Allocate memory from the gap in between the cell pointer array
60555  ** and the cell content area.  The btreeInitPage() call has already
60556  ** validated the freelist.  Given that the freelist is valid, there
60557  ** is no way that the allocation can extend off the end of the page.
60558  ** The assert() below verifies the previous sentence.
60559  */
60560  top -= nByte;
60561  put2byte(&data[hdr+5], top);
60562  assert( top+nByte <= (int)pPage->pBt->usableSize );
60563  *pIdx = top;
60564  return SQLITE_OK;
60565}
60566
60567/*
60568** Return a section of the pPage->aData to the freelist.
60569** The first byte of the new free block is pPage->aData[iStart]
60570** and the size of the block is iSize bytes.
60571**
60572** Adjacent freeblocks are coalesced.
60573**
60574** Note that even though the freeblock list was checked by btreeInitPage(),
60575** that routine will not detect overlap between cells or freeblocks.  Nor
60576** does it detect cells or freeblocks that encrouch into the reserved bytes
60577** at the end of the page.  So do additional corruption checks inside this
60578** routine and return SQLITE_CORRUPT if any problems are found.
60579*/
60580static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
60581  u16 iPtr;                             /* Address of ptr to next freeblock */
60582  u16 iFreeBlk;                         /* Address of the next freeblock */
60583  u8 hdr;                               /* Page header size.  0 or 100 */
60584  u8 nFrag = 0;                         /* Reduction in fragmentation */
60585  u16 iOrigSize = iSize;                /* Original value of iSize */
60586  u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
60587  u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
60588  unsigned char *data = pPage->aData;   /* Page content */
60589
60590  assert( pPage->pBt!=0 );
60591  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60592  assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
60593  assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
60594  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60595  assert( iSize>=4 );   /* Minimum cell size is 4 */
60596  assert( iStart<=iLast );
60597
60598  /* Overwrite deleted information with zeros when the secure_delete
60599  ** option is enabled */
60600  if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
60601    memset(&data[iStart], 0, iSize);
60602  }
60603
60604  /* The list of freeblocks must be in ascending order.  Find the
60605  ** spot on the list where iStart should be inserted.
60606  */
60607  hdr = pPage->hdrOffset;
60608  iPtr = hdr + 1;
60609  if( data[iPtr+1]==0 && data[iPtr]==0 ){
60610    iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
60611  }else{
60612    while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
60613      if( iFreeBlk<iPtr+4 ){
60614        if( iFreeBlk==0 ) break;
60615        return SQLITE_CORRUPT_BKPT;
60616      }
60617      iPtr = iFreeBlk;
60618    }
60619    if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
60620    assert( iFreeBlk>iPtr || iFreeBlk==0 );
60621
60622    /* At this point:
60623    **    iFreeBlk:   First freeblock after iStart, or zero if none
60624    **    iPtr:       The address of a pointer to iFreeBlk
60625    **
60626    ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
60627    */
60628    if( iFreeBlk && iEnd+3>=iFreeBlk ){
60629      nFrag = iFreeBlk - iEnd;
60630      if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
60631      iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
60632      if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
60633      iSize = iEnd - iStart;
60634      iFreeBlk = get2byte(&data[iFreeBlk]);
60635    }
60636
60637    /* If iPtr is another freeblock (that is, if iPtr is not the freelist
60638    ** pointer in the page header) then check to see if iStart should be
60639    ** coalesced onto the end of iPtr.
60640    */
60641    if( iPtr>hdr+1 ){
60642      int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
60643      if( iPtrEnd+3>=iStart ){
60644        if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
60645        nFrag += iStart - iPtrEnd;
60646        iSize = iEnd - iPtr;
60647        iStart = iPtr;
60648      }
60649    }
60650    if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
60651    data[hdr+7] -= nFrag;
60652  }
60653  if( iStart==get2byte(&data[hdr+5]) ){
60654    /* The new freeblock is at the beginning of the cell content area,
60655    ** so just extend the cell content area rather than create another
60656    ** freelist entry */
60657    if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
60658    put2byte(&data[hdr+1], iFreeBlk);
60659    put2byte(&data[hdr+5], iEnd);
60660  }else{
60661    /* Insert the new freeblock into the freelist */
60662    put2byte(&data[iPtr], iStart);
60663    put2byte(&data[iStart], iFreeBlk);
60664    put2byte(&data[iStart+2], iSize);
60665  }
60666  pPage->nFree += iOrigSize;
60667  return SQLITE_OK;
60668}
60669
60670/*
60671** Decode the flags byte (the first byte of the header) for a page
60672** and initialize fields of the MemPage structure accordingly.
60673**
60674** Only the following combinations are supported.  Anything different
60675** indicates a corrupt database files:
60676**
60677**         PTF_ZERODATA
60678**         PTF_ZERODATA | PTF_LEAF
60679**         PTF_LEAFDATA | PTF_INTKEY
60680**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
60681*/
60682static int decodeFlags(MemPage *pPage, int flagByte){
60683  BtShared *pBt;     /* A copy of pPage->pBt */
60684
60685  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
60686  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60687  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
60688  flagByte &= ~PTF_LEAF;
60689  pPage->childPtrSize = 4-4*pPage->leaf;
60690  pPage->xCellSize = cellSizePtr;
60691  pBt = pPage->pBt;
60692  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
60693    /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
60694    ** interior table b-tree page. */
60695    assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
60696    /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
60697    ** leaf table b-tree page. */
60698    assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
60699    pPage->intKey = 1;
60700    if( pPage->leaf ){
60701      pPage->intKeyLeaf = 1;
60702      pPage->xParseCell = btreeParseCellPtr;
60703    }else{
60704      pPage->intKeyLeaf = 0;
60705      pPage->xCellSize = cellSizePtrNoPayload;
60706      pPage->xParseCell = btreeParseCellPtrNoPayload;
60707    }
60708    pPage->maxLocal = pBt->maxLeaf;
60709    pPage->minLocal = pBt->minLeaf;
60710  }else if( flagByte==PTF_ZERODATA ){
60711    /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
60712    ** interior index b-tree page. */
60713    assert( (PTF_ZERODATA)==2 );
60714    /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
60715    ** leaf index b-tree page. */
60716    assert( (PTF_ZERODATA|PTF_LEAF)==10 );
60717    pPage->intKey = 0;
60718    pPage->intKeyLeaf = 0;
60719    pPage->xParseCell = btreeParseCellPtrIndex;
60720    pPage->maxLocal = pBt->maxLocal;
60721    pPage->minLocal = pBt->minLocal;
60722  }else{
60723    /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
60724    ** an error. */
60725    return SQLITE_CORRUPT_BKPT;
60726  }
60727  pPage->max1bytePayload = pBt->max1bytePayload;
60728  return SQLITE_OK;
60729}
60730
60731/*
60732** Initialize the auxiliary information for a disk block.
60733**
60734** Return SQLITE_OK on success.  If we see that the page does
60735** not contain a well-formed database page, then return
60736** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
60737** guarantee that the page is well-formed.  It only shows that
60738** we failed to detect any corruption.
60739*/
60740static int btreeInitPage(MemPage *pPage){
60741
60742  assert( pPage->pBt!=0 );
60743  assert( pPage->pBt->db!=0 );
60744  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60745  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
60746  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
60747  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
60748
60749  if( !pPage->isInit ){
60750    int pc;            /* Address of a freeblock within pPage->aData[] */
60751    u8 hdr;            /* Offset to beginning of page header */
60752    u8 *data;          /* Equal to pPage->aData */
60753    BtShared *pBt;        /* The main btree structure */
60754    int usableSize;    /* Amount of usable space on each page */
60755    u16 cellOffset;    /* Offset from start of page to first cell pointer */
60756    int nFree;         /* Number of unused bytes on the page */
60757    int top;           /* First byte of the cell content area */
60758    int iCellFirst;    /* First allowable cell or freeblock offset */
60759    int iCellLast;     /* Last possible cell or freeblock offset */
60760
60761    pBt = pPage->pBt;
60762
60763    hdr = pPage->hdrOffset;
60764    data = pPage->aData;
60765    /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
60766    ** the b-tree page type. */
60767    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
60768    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
60769    pPage->maskPage = (u16)(pBt->pageSize - 1);
60770    pPage->nOverflow = 0;
60771    usableSize = pBt->usableSize;
60772    pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
60773    pPage->aDataEnd = &data[usableSize];
60774    pPage->aCellIdx = &data[cellOffset];
60775    pPage->aDataOfst = &data[pPage->childPtrSize];
60776    /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
60777    ** the start of the cell content area. A zero value for this integer is
60778    ** interpreted as 65536. */
60779    top = get2byteNotZero(&data[hdr+5]);
60780    /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
60781    ** number of cells on the page. */
60782    pPage->nCell = get2byte(&data[hdr+3]);
60783    if( pPage->nCell>MX_CELL(pBt) ){
60784      /* To many cells for a single page.  The page must be corrupt */
60785      return SQLITE_CORRUPT_BKPT;
60786    }
60787    testcase( pPage->nCell==MX_CELL(pBt) );
60788    /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
60789    ** possible for a root page of a table that contains no rows) then the
60790    ** offset to the cell content area will equal the page size minus the
60791    ** bytes of reserved space. */
60792    assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
60793
60794    /* A malformed database page might cause us to read past the end
60795    ** of page when parsing a cell.
60796    **
60797    ** The following block of code checks early to see if a cell extends
60798    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
60799    ** returned if it does.
60800    */
60801    iCellFirst = cellOffset + 2*pPage->nCell;
60802    iCellLast = usableSize - 4;
60803    if( pBt->db->flags & SQLITE_CellSizeCk ){
60804      int i;            /* Index into the cell pointer array */
60805      int sz;           /* Size of a cell */
60806
60807      if( !pPage->leaf ) iCellLast--;
60808      for(i=0; i<pPage->nCell; i++){
60809        pc = get2byteAligned(&data[cellOffset+i*2]);
60810        testcase( pc==iCellFirst );
60811        testcase( pc==iCellLast );
60812        if( pc<iCellFirst || pc>iCellLast ){
60813          return SQLITE_CORRUPT_BKPT;
60814        }
60815        sz = pPage->xCellSize(pPage, &data[pc]);
60816        testcase( pc+sz==usableSize );
60817        if( pc+sz>usableSize ){
60818          return SQLITE_CORRUPT_BKPT;
60819        }
60820      }
60821      if( !pPage->leaf ) iCellLast++;
60822    }
60823
60824    /* Compute the total free space on the page
60825    ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
60826    ** start of the first freeblock on the page, or is zero if there are no
60827    ** freeblocks. */
60828    pc = get2byte(&data[hdr+1]);
60829    nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
60830    if( pc>0 ){
60831      u32 next, size;
60832      if( pc<iCellFirst ){
60833        /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
60834        ** always be at least one cell before the first freeblock.
60835        */
60836        return SQLITE_CORRUPT_BKPT;
60837      }
60838      while( 1 ){
60839        if( pc>iCellLast ){
60840          return SQLITE_CORRUPT_BKPT; /* Freeblock off the end of the page */
60841        }
60842        next = get2byte(&data[pc]);
60843        size = get2byte(&data[pc+2]);
60844        nFree = nFree + size;
60845        if( next<=pc+size+3 ) break;
60846        pc = next;
60847      }
60848      if( next>0 ){
60849        return SQLITE_CORRUPT_BKPT;  /* Freeblock not in ascending order */
60850      }
60851      if( pc+size>(unsigned int)usableSize ){
60852        return SQLITE_CORRUPT_BKPT;  /* Last freeblock extends past page end */
60853      }
60854    }
60855
60856    /* At this point, nFree contains the sum of the offset to the start
60857    ** of the cell-content area plus the number of free bytes within
60858    ** the cell-content area. If this is greater than the usable-size
60859    ** of the page, then the page must be corrupted. This check also
60860    ** serves to verify that the offset to the start of the cell-content
60861    ** area, according to the page header, lies within the page.
60862    */
60863    if( nFree>usableSize ){
60864      return SQLITE_CORRUPT_BKPT;
60865    }
60866    pPage->nFree = (u16)(nFree - iCellFirst);
60867    pPage->isInit = 1;
60868  }
60869  return SQLITE_OK;
60870}
60871
60872/*
60873** Set up a raw page so that it looks like a database page holding
60874** no entries.
60875*/
60876static void zeroPage(MemPage *pPage, int flags){
60877  unsigned char *data = pPage->aData;
60878  BtShared *pBt = pPage->pBt;
60879  u8 hdr = pPage->hdrOffset;
60880  u16 first;
60881
60882  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
60883  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
60884  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
60885  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60886  assert( sqlite3_mutex_held(pBt->mutex) );
60887  if( pBt->btsFlags & BTS_SECURE_DELETE ){
60888    memset(&data[hdr], 0, pBt->usableSize - hdr);
60889  }
60890  data[hdr] = (char)flags;
60891  first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
60892  memset(&data[hdr+1], 0, 4);
60893  data[hdr+7] = 0;
60894  put2byte(&data[hdr+5], pBt->usableSize);
60895  pPage->nFree = (u16)(pBt->usableSize - first);
60896  decodeFlags(pPage, flags);
60897  pPage->cellOffset = first;
60898  pPage->aDataEnd = &data[pBt->usableSize];
60899  pPage->aCellIdx = &data[first];
60900  pPage->aDataOfst = &data[pPage->childPtrSize];
60901  pPage->nOverflow = 0;
60902  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
60903  pPage->maskPage = (u16)(pBt->pageSize - 1);
60904  pPage->nCell = 0;
60905  pPage->isInit = 1;
60906}
60907
60908
60909/*
60910** Convert a DbPage obtained from the pager into a MemPage used by
60911** the btree layer.
60912*/
60913static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
60914  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
60915  if( pgno!=pPage->pgno ){
60916    pPage->aData = sqlite3PagerGetData(pDbPage);
60917    pPage->pDbPage = pDbPage;
60918    pPage->pBt = pBt;
60919    pPage->pgno = pgno;
60920    pPage->hdrOffset = pgno==1 ? 100 : 0;
60921  }
60922  assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
60923  return pPage;
60924}
60925
60926/*
60927** Get a page from the pager.  Initialize the MemPage.pBt and
60928** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
60929**
60930** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
60931** about the content of the page at this time.  So do not go to the disk
60932** to fetch the content.  Just fill in the content with zeros for now.
60933** If in the future we call sqlite3PagerWrite() on this page, that
60934** means we have started to be concerned about content and the disk
60935** read should occur at that point.
60936*/
60937static int btreeGetPage(
60938  BtShared *pBt,       /* The btree */
60939  Pgno pgno,           /* Number of the page to fetch */
60940  MemPage **ppPage,    /* Return the page in this parameter */
60941  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
60942){
60943  int rc;
60944  DbPage *pDbPage;
60945
60946  assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
60947  assert( sqlite3_mutex_held(pBt->mutex) );
60948  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
60949  if( rc ) return rc;
60950  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
60951  return SQLITE_OK;
60952}
60953
60954/*
60955** Retrieve a page from the pager cache. If the requested page is not
60956** already in the pager cache return NULL. Initialize the MemPage.pBt and
60957** MemPage.aData elements if needed.
60958*/
60959static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
60960  DbPage *pDbPage;
60961  assert( sqlite3_mutex_held(pBt->mutex) );
60962  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
60963  if( pDbPage ){
60964    return btreePageFromDbPage(pDbPage, pgno, pBt);
60965  }
60966  return 0;
60967}
60968
60969/*
60970** Return the size of the database file in pages. If there is any kind of
60971** error, return ((unsigned int)-1).
60972*/
60973static Pgno btreePagecount(BtShared *pBt){
60974  return pBt->nPage;
60975}
60976SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
60977  assert( sqlite3BtreeHoldsMutex(p) );
60978  assert( ((p->pBt->nPage)&0x8000000)==0 );
60979  return btreePagecount(p->pBt);
60980}
60981
60982/*
60983** Get a page from the pager and initialize it.
60984**
60985** If pCur!=0 then the page is being fetched as part of a moveToChild()
60986** call.  Do additional sanity checking on the page in this case.
60987** And if the fetch fails, this routine must decrement pCur->iPage.
60988**
60989** The page is fetched as read-write unless pCur is not NULL and is
60990** a read-only cursor.
60991**
60992** If an error occurs, then *ppPage is undefined. It
60993** may remain unchanged, or it may be set to an invalid value.
60994*/
60995static int getAndInitPage(
60996  BtShared *pBt,                  /* The database file */
60997  Pgno pgno,                      /* Number of the page to get */
60998  MemPage **ppPage,               /* Write the page pointer here */
60999  BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
61000  int bReadOnly                   /* True for a read-only page */
61001){
61002  int rc;
61003  DbPage *pDbPage;
61004  assert( sqlite3_mutex_held(pBt->mutex) );
61005  assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
61006  assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
61007  assert( pCur==0 || pCur->iPage>0 );
61008
61009  if( pgno>btreePagecount(pBt) ){
61010    rc = SQLITE_CORRUPT_BKPT;
61011    goto getAndInitPage_error;
61012  }
61013  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
61014  if( rc ){
61015    goto getAndInitPage_error;
61016  }
61017  *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
61018  if( (*ppPage)->isInit==0 ){
61019    btreePageFromDbPage(pDbPage, pgno, pBt);
61020    rc = btreeInitPage(*ppPage);
61021    if( rc!=SQLITE_OK ){
61022      releasePage(*ppPage);
61023      goto getAndInitPage_error;
61024    }
61025  }
61026  assert( (*ppPage)->pgno==pgno );
61027  assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
61028
61029  /* If obtaining a child page for a cursor, we must verify that the page is
61030  ** compatible with the root page. */
61031  if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
61032    rc = SQLITE_CORRUPT_BKPT;
61033    releasePage(*ppPage);
61034    goto getAndInitPage_error;
61035  }
61036  return SQLITE_OK;
61037
61038getAndInitPage_error:
61039  if( pCur ) pCur->iPage--;
61040  testcase( pgno==0 );
61041  assert( pgno!=0 || rc==SQLITE_CORRUPT );
61042  return rc;
61043}
61044
61045/*
61046** Release a MemPage.  This should be called once for each prior
61047** call to btreeGetPage.
61048*/
61049static void releasePageNotNull(MemPage *pPage){
61050  assert( pPage->aData );
61051  assert( pPage->pBt );
61052  assert( pPage->pDbPage!=0 );
61053  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
61054  assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
61055  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61056  sqlite3PagerUnrefNotNull(pPage->pDbPage);
61057}
61058static void releasePage(MemPage *pPage){
61059  if( pPage ) releasePageNotNull(pPage);
61060}
61061
61062/*
61063** Get an unused page.
61064**
61065** This works just like btreeGetPage() with the addition:
61066**
61067**   *  If the page is already in use for some other purpose, immediately
61068**      release it and return an SQLITE_CURRUPT error.
61069**   *  Make sure the isInit flag is clear
61070*/
61071static int btreeGetUnusedPage(
61072  BtShared *pBt,       /* The btree */
61073  Pgno pgno,           /* Number of the page to fetch */
61074  MemPage **ppPage,    /* Return the page in this parameter */
61075  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
61076){
61077  int rc = btreeGetPage(pBt, pgno, ppPage, flags);
61078  if( rc==SQLITE_OK ){
61079    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
61080      releasePage(*ppPage);
61081      *ppPage = 0;
61082      return SQLITE_CORRUPT_BKPT;
61083    }
61084    (*ppPage)->isInit = 0;
61085  }else{
61086    *ppPage = 0;
61087  }
61088  return rc;
61089}
61090
61091
61092/*
61093** During a rollback, when the pager reloads information into the cache
61094** so that the cache is restored to its original state at the start of
61095** the transaction, for each page restored this routine is called.
61096**
61097** This routine needs to reset the extra data section at the end of the
61098** page to agree with the restored data.
61099*/
61100static void pageReinit(DbPage *pData){
61101  MemPage *pPage;
61102  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
61103  assert( sqlite3PagerPageRefcount(pData)>0 );
61104  if( pPage->isInit ){
61105    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61106    pPage->isInit = 0;
61107    if( sqlite3PagerPageRefcount(pData)>1 ){
61108      /* pPage might not be a btree page;  it might be an overflow page
61109      ** or ptrmap page or a free page.  In those cases, the following
61110      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
61111      ** But no harm is done by this.  And it is very important that
61112      ** btreeInitPage() be called on every btree page so we make
61113      ** the call for every page that comes in for re-initing. */
61114      btreeInitPage(pPage);
61115    }
61116  }
61117}
61118
61119/*
61120** Invoke the busy handler for a btree.
61121*/
61122static int btreeInvokeBusyHandler(void *pArg){
61123  BtShared *pBt = (BtShared*)pArg;
61124  assert( pBt->db );
61125  assert( sqlite3_mutex_held(pBt->db->mutex) );
61126  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
61127}
61128
61129/*
61130** Open a database file.
61131**
61132** zFilename is the name of the database file.  If zFilename is NULL
61133** then an ephemeral database is created.  The ephemeral database might
61134** be exclusively in memory, or it might use a disk-based memory cache.
61135** Either way, the ephemeral database will be automatically deleted
61136** when sqlite3BtreeClose() is called.
61137**
61138** If zFilename is ":memory:" then an in-memory database is created
61139** that is automatically destroyed when it is closed.
61140**
61141** The "flags" parameter is a bitmask that might contain bits like
61142** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
61143**
61144** If the database is already opened in the same database connection
61145** and we are in shared cache mode, then the open will fail with an
61146** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
61147** objects in the same database connection since doing so will lead
61148** to problems with locking.
61149*/
61150SQLITE_PRIVATE int sqlite3BtreeOpen(
61151  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
61152  const char *zFilename,  /* Name of the file containing the BTree database */
61153  sqlite3 *db,            /* Associated database handle */
61154  Btree **ppBtree,        /* Pointer to new Btree object written here */
61155  int flags,              /* Options */
61156  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
61157){
61158  BtShared *pBt = 0;             /* Shared part of btree structure */
61159  Btree *p;                      /* Handle to return */
61160  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
61161  int rc = SQLITE_OK;            /* Result code from this function */
61162  u8 nReserve;                   /* Byte of unused space on each page */
61163  unsigned char zDbHeader[100];  /* Database header content */
61164
61165  /* True if opening an ephemeral, temporary database */
61166  const int isTempDb = zFilename==0 || zFilename[0]==0;
61167
61168  /* Set the variable isMemdb to true for an in-memory database, or
61169  ** false for a file-based database.
61170  */
61171#ifdef SQLITE_OMIT_MEMORYDB
61172  const int isMemdb = 0;
61173#else
61174  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
61175                       || (isTempDb && sqlite3TempInMemory(db))
61176                       || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
61177#endif
61178
61179  assert( db!=0 );
61180  assert( pVfs!=0 );
61181  assert( sqlite3_mutex_held(db->mutex) );
61182  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
61183
61184  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
61185  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
61186
61187  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
61188  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
61189
61190  if( isMemdb ){
61191    flags |= BTREE_MEMORY;
61192  }
61193  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
61194    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
61195  }
61196  p = sqlite3MallocZero(sizeof(Btree));
61197  if( !p ){
61198    return SQLITE_NOMEM_BKPT;
61199  }
61200  p->inTrans = TRANS_NONE;
61201  p->db = db;
61202#ifndef SQLITE_OMIT_SHARED_CACHE
61203  p->lock.pBtree = p;
61204  p->lock.iTable = 1;
61205#endif
61206
61207#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
61208  /*
61209  ** If this Btree is a candidate for shared cache, try to find an
61210  ** existing BtShared object that we can share with
61211  */
61212  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
61213    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
61214      int nFilename = sqlite3Strlen30(zFilename)+1;
61215      int nFullPathname = pVfs->mxPathname+1;
61216      char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
61217      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
61218
61219      p->sharable = 1;
61220      if( !zFullPathname ){
61221        sqlite3_free(p);
61222        return SQLITE_NOMEM_BKPT;
61223      }
61224      if( isMemdb ){
61225        memcpy(zFullPathname, zFilename, nFilename);
61226      }else{
61227        rc = sqlite3OsFullPathname(pVfs, zFilename,
61228                                   nFullPathname, zFullPathname);
61229        if( rc ){
61230          sqlite3_free(zFullPathname);
61231          sqlite3_free(p);
61232          return rc;
61233        }
61234      }
61235#if SQLITE_THREADSAFE
61236      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
61237      sqlite3_mutex_enter(mutexOpen);
61238      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
61239      sqlite3_mutex_enter(mutexShared);
61240#endif
61241      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
61242        assert( pBt->nRef>0 );
61243        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
61244                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
61245          int iDb;
61246          for(iDb=db->nDb-1; iDb>=0; iDb--){
61247            Btree *pExisting = db->aDb[iDb].pBt;
61248            if( pExisting && pExisting->pBt==pBt ){
61249              sqlite3_mutex_leave(mutexShared);
61250              sqlite3_mutex_leave(mutexOpen);
61251              sqlite3_free(zFullPathname);
61252              sqlite3_free(p);
61253              return SQLITE_CONSTRAINT;
61254            }
61255          }
61256          p->pBt = pBt;
61257          pBt->nRef++;
61258          break;
61259        }
61260      }
61261      sqlite3_mutex_leave(mutexShared);
61262      sqlite3_free(zFullPathname);
61263    }
61264#ifdef SQLITE_DEBUG
61265    else{
61266      /* In debug mode, we mark all persistent databases as sharable
61267      ** even when they are not.  This exercises the locking code and
61268      ** gives more opportunity for asserts(sqlite3_mutex_held())
61269      ** statements to find locking problems.
61270      */
61271      p->sharable = 1;
61272    }
61273#endif
61274  }
61275#endif
61276  if( pBt==0 ){
61277    /*
61278    ** The following asserts make sure that structures used by the btree are
61279    ** the right size.  This is to guard against size changes that result
61280    ** when compiling on a different architecture.
61281    */
61282    assert( sizeof(i64)==8 );
61283    assert( sizeof(u64)==8 );
61284    assert( sizeof(u32)==4 );
61285    assert( sizeof(u16)==2 );
61286    assert( sizeof(Pgno)==4 );
61287
61288    pBt = sqlite3MallocZero( sizeof(*pBt) );
61289    if( pBt==0 ){
61290      rc = SQLITE_NOMEM_BKPT;
61291      goto btree_open_out;
61292    }
61293    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
61294                          sizeof(MemPage), flags, vfsFlags, pageReinit);
61295    if( rc==SQLITE_OK ){
61296      sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
61297      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
61298    }
61299    if( rc!=SQLITE_OK ){
61300      goto btree_open_out;
61301    }
61302    pBt->openFlags = (u8)flags;
61303    pBt->db = db;
61304    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
61305    p->pBt = pBt;
61306
61307    pBt->pCursor = 0;
61308    pBt->pPage1 = 0;
61309    if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
61310#ifdef SQLITE_SECURE_DELETE
61311    pBt->btsFlags |= BTS_SECURE_DELETE;
61312#endif
61313    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
61314    ** determined by the 2-byte integer located at an offset of 16 bytes from
61315    ** the beginning of the database file. */
61316    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
61317    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
61318         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
61319      pBt->pageSize = 0;
61320#ifndef SQLITE_OMIT_AUTOVACUUM
61321      /* If the magic name ":memory:" will create an in-memory database, then
61322      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
61323      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
61324      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
61325      ** regular file-name. In this case the auto-vacuum applies as per normal.
61326      */
61327      if( zFilename && !isMemdb ){
61328        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
61329        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
61330      }
61331#endif
61332      nReserve = 0;
61333    }else{
61334      /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
61335      ** determined by the one-byte unsigned integer found at an offset of 20
61336      ** into the database file header. */
61337      nReserve = zDbHeader[20];
61338      pBt->btsFlags |= BTS_PAGESIZE_FIXED;
61339#ifndef SQLITE_OMIT_AUTOVACUUM
61340      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
61341      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
61342#endif
61343    }
61344    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
61345    if( rc ) goto btree_open_out;
61346    pBt->usableSize = pBt->pageSize - nReserve;
61347    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
61348
61349#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
61350    /* Add the new BtShared object to the linked list sharable BtShareds.
61351    */
61352    pBt->nRef = 1;
61353    if( p->sharable ){
61354      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
61355      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
61356      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
61357        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
61358        if( pBt->mutex==0 ){
61359          rc = SQLITE_NOMEM_BKPT;
61360          goto btree_open_out;
61361        }
61362      }
61363      sqlite3_mutex_enter(mutexShared);
61364      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
61365      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
61366      sqlite3_mutex_leave(mutexShared);
61367    }
61368#endif
61369  }
61370
61371#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
61372  /* If the new Btree uses a sharable pBtShared, then link the new
61373  ** Btree into the list of all sharable Btrees for the same connection.
61374  ** The list is kept in ascending order by pBt address.
61375  */
61376  if( p->sharable ){
61377    int i;
61378    Btree *pSib;
61379    for(i=0; i<db->nDb; i++){
61380      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
61381        while( pSib->pPrev ){ pSib = pSib->pPrev; }
61382        if( (uptr)p->pBt<(uptr)pSib->pBt ){
61383          p->pNext = pSib;
61384          p->pPrev = 0;
61385          pSib->pPrev = p;
61386        }else{
61387          while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
61388            pSib = pSib->pNext;
61389          }
61390          p->pNext = pSib->pNext;
61391          p->pPrev = pSib;
61392          if( p->pNext ){
61393            p->pNext->pPrev = p;
61394          }
61395          pSib->pNext = p;
61396        }
61397        break;
61398      }
61399    }
61400  }
61401#endif
61402  *ppBtree = p;
61403
61404btree_open_out:
61405  if( rc!=SQLITE_OK ){
61406    if( pBt && pBt->pPager ){
61407      sqlite3PagerClose(pBt->pPager, 0);
61408    }
61409    sqlite3_free(pBt);
61410    sqlite3_free(p);
61411    *ppBtree = 0;
61412  }else{
61413    sqlite3_file *pFile;
61414
61415    /* If the B-Tree was successfully opened, set the pager-cache size to the
61416    ** default value. Except, when opening on an existing shared pager-cache,
61417    ** do not change the pager-cache size.
61418    */
61419    if( sqlite3BtreeSchema(p, 0, 0)==0 ){
61420      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
61421    }
61422
61423    pFile = sqlite3PagerFile(pBt->pPager);
61424    if( pFile->pMethods ){
61425      sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
61426    }
61427  }
61428  if( mutexOpen ){
61429    assert( sqlite3_mutex_held(mutexOpen) );
61430    sqlite3_mutex_leave(mutexOpen);
61431  }
61432  assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
61433  return rc;
61434}
61435
61436/*
61437** Decrement the BtShared.nRef counter.  When it reaches zero,
61438** remove the BtShared structure from the sharing list.  Return
61439** true if the BtShared.nRef counter reaches zero and return
61440** false if it is still positive.
61441*/
61442static int removeFromSharingList(BtShared *pBt){
61443#ifndef SQLITE_OMIT_SHARED_CACHE
61444  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
61445  BtShared *pList;
61446  int removed = 0;
61447
61448  assert( sqlite3_mutex_notheld(pBt->mutex) );
61449  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
61450  sqlite3_mutex_enter(pMaster);
61451  pBt->nRef--;
61452  if( pBt->nRef<=0 ){
61453    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
61454      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
61455    }else{
61456      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
61457      while( ALWAYS(pList) && pList->pNext!=pBt ){
61458        pList=pList->pNext;
61459      }
61460      if( ALWAYS(pList) ){
61461        pList->pNext = pBt->pNext;
61462      }
61463    }
61464    if( SQLITE_THREADSAFE ){
61465      sqlite3_mutex_free(pBt->mutex);
61466    }
61467    removed = 1;
61468  }
61469  sqlite3_mutex_leave(pMaster);
61470  return removed;
61471#else
61472  return 1;
61473#endif
61474}
61475
61476/*
61477** Make sure pBt->pTmpSpace points to an allocation of
61478** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
61479** pointer.
61480*/
61481static void allocateTempSpace(BtShared *pBt){
61482  if( !pBt->pTmpSpace ){
61483    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
61484
61485    /* One of the uses of pBt->pTmpSpace is to format cells before
61486    ** inserting them into a leaf page (function fillInCell()). If
61487    ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
61488    ** by the various routines that manipulate binary cells. Which
61489    ** can mean that fillInCell() only initializes the first 2 or 3
61490    ** bytes of pTmpSpace, but that the first 4 bytes are copied from
61491    ** it into a database page. This is not actually a problem, but it
61492    ** does cause a valgrind error when the 1 or 2 bytes of unitialized
61493    ** data is passed to system call write(). So to avoid this error,
61494    ** zero the first 4 bytes of temp space here.
61495    **
61496    ** Also:  Provide four bytes of initialized space before the
61497    ** beginning of pTmpSpace as an area available to prepend the
61498    ** left-child pointer to the beginning of a cell.
61499    */
61500    if( pBt->pTmpSpace ){
61501      memset(pBt->pTmpSpace, 0, 8);
61502      pBt->pTmpSpace += 4;
61503    }
61504  }
61505}
61506
61507/*
61508** Free the pBt->pTmpSpace allocation
61509*/
61510static void freeTempSpace(BtShared *pBt){
61511  if( pBt->pTmpSpace ){
61512    pBt->pTmpSpace -= 4;
61513    sqlite3PageFree(pBt->pTmpSpace);
61514    pBt->pTmpSpace = 0;
61515  }
61516}
61517
61518/*
61519** Close an open database and invalidate all cursors.
61520*/
61521SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
61522  BtShared *pBt = p->pBt;
61523  BtCursor *pCur;
61524
61525  /* Close all cursors opened via this handle.  */
61526  assert( sqlite3_mutex_held(p->db->mutex) );
61527  sqlite3BtreeEnter(p);
61528  pCur = pBt->pCursor;
61529  while( pCur ){
61530    BtCursor *pTmp = pCur;
61531    pCur = pCur->pNext;
61532    if( pTmp->pBtree==p ){
61533      sqlite3BtreeCloseCursor(pTmp);
61534    }
61535  }
61536
61537  /* Rollback any active transaction and free the handle structure.
61538  ** The call to sqlite3BtreeRollback() drops any table-locks held by
61539  ** this handle.
61540  */
61541  sqlite3BtreeRollback(p, SQLITE_OK, 0);
61542  sqlite3BtreeLeave(p);
61543
61544  /* If there are still other outstanding references to the shared-btree
61545  ** structure, return now. The remainder of this procedure cleans
61546  ** up the shared-btree.
61547  */
61548  assert( p->wantToLock==0 && p->locked==0 );
61549  if( !p->sharable || removeFromSharingList(pBt) ){
61550    /* The pBt is no longer on the sharing list, so we can access
61551    ** it without having to hold the mutex.
61552    **
61553    ** Clean out and delete the BtShared object.
61554    */
61555    assert( !pBt->pCursor );
61556    sqlite3PagerClose(pBt->pPager, p->db);
61557    if( pBt->xFreeSchema && pBt->pSchema ){
61558      pBt->xFreeSchema(pBt->pSchema);
61559    }
61560    sqlite3DbFree(0, pBt->pSchema);
61561    freeTempSpace(pBt);
61562    sqlite3_free(pBt);
61563  }
61564
61565#ifndef SQLITE_OMIT_SHARED_CACHE
61566  assert( p->wantToLock==0 );
61567  assert( p->locked==0 );
61568  if( p->pPrev ) p->pPrev->pNext = p->pNext;
61569  if( p->pNext ) p->pNext->pPrev = p->pPrev;
61570#endif
61571
61572  sqlite3_free(p);
61573  return SQLITE_OK;
61574}
61575
61576/*
61577** Change the "soft" limit on the number of pages in the cache.
61578** Unused and unmodified pages will be recycled when the number of
61579** pages in the cache exceeds this soft limit.  But the size of the
61580** cache is allowed to grow larger than this limit if it contains
61581** dirty pages or pages still in active use.
61582*/
61583SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
61584  BtShared *pBt = p->pBt;
61585  assert( sqlite3_mutex_held(p->db->mutex) );
61586  sqlite3BtreeEnter(p);
61587  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
61588  sqlite3BtreeLeave(p);
61589  return SQLITE_OK;
61590}
61591
61592/*
61593** Change the "spill" limit on the number of pages in the cache.
61594** If the number of pages exceeds this limit during a write transaction,
61595** the pager might attempt to "spill" pages to the journal early in
61596** order to free up memory.
61597**
61598** The value returned is the current spill size.  If zero is passed
61599** as an argument, no changes are made to the spill size setting, so
61600** using mxPage of 0 is a way to query the current spill size.
61601*/
61602SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
61603  BtShared *pBt = p->pBt;
61604  int res;
61605  assert( sqlite3_mutex_held(p->db->mutex) );
61606  sqlite3BtreeEnter(p);
61607  res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
61608  sqlite3BtreeLeave(p);
61609  return res;
61610}
61611
61612#if SQLITE_MAX_MMAP_SIZE>0
61613/*
61614** Change the limit on the amount of the database file that may be
61615** memory mapped.
61616*/
61617SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
61618  BtShared *pBt = p->pBt;
61619  assert( sqlite3_mutex_held(p->db->mutex) );
61620  sqlite3BtreeEnter(p);
61621  sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
61622  sqlite3BtreeLeave(p);
61623  return SQLITE_OK;
61624}
61625#endif /* SQLITE_MAX_MMAP_SIZE>0 */
61626
61627/*
61628** Change the way data is synced to disk in order to increase or decrease
61629** how well the database resists damage due to OS crashes and power
61630** failures.  Level 1 is the same as asynchronous (no syncs() occur and
61631** there is a high probability of damage)  Level 2 is the default.  There
61632** is a very low but non-zero probability of damage.  Level 3 reduces the
61633** probability of damage to near zero but with a write performance reduction.
61634*/
61635#ifndef SQLITE_OMIT_PAGER_PRAGMAS
61636SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
61637  Btree *p,              /* The btree to set the safety level on */
61638  unsigned pgFlags       /* Various PAGER_* flags */
61639){
61640  BtShared *pBt = p->pBt;
61641  assert( sqlite3_mutex_held(p->db->mutex) );
61642  sqlite3BtreeEnter(p);
61643  sqlite3PagerSetFlags(pBt->pPager, pgFlags);
61644  sqlite3BtreeLeave(p);
61645  return SQLITE_OK;
61646}
61647#endif
61648
61649/*
61650** Change the default pages size and the number of reserved bytes per page.
61651** Or, if the page size has already been fixed, return SQLITE_READONLY
61652** without changing anything.
61653**
61654** The page size must be a power of 2 between 512 and 65536.  If the page
61655** size supplied does not meet this constraint then the page size is not
61656** changed.
61657**
61658** Page sizes are constrained to be a power of two so that the region
61659** of the database file used for locking (beginning at PENDING_BYTE,
61660** the first byte past the 1GB boundary, 0x40000000) needs to occur
61661** at the beginning of a page.
61662**
61663** If parameter nReserve is less than zero, then the number of reserved
61664** bytes per page is left unchanged.
61665**
61666** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
61667** and autovacuum mode can no longer be changed.
61668*/
61669SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
61670  int rc = SQLITE_OK;
61671  BtShared *pBt = p->pBt;
61672  assert( nReserve>=-1 && nReserve<=255 );
61673  sqlite3BtreeEnter(p);
61674#if SQLITE_HAS_CODEC
61675  if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
61676#endif
61677  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
61678    sqlite3BtreeLeave(p);
61679    return SQLITE_READONLY;
61680  }
61681  if( nReserve<0 ){
61682    nReserve = pBt->pageSize - pBt->usableSize;
61683  }
61684  assert( nReserve>=0 && nReserve<=255 );
61685  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
61686        ((pageSize-1)&pageSize)==0 ){
61687    assert( (pageSize & 7)==0 );
61688    assert( !pBt->pCursor );
61689    pBt->pageSize = (u32)pageSize;
61690    freeTempSpace(pBt);
61691  }
61692  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
61693  pBt->usableSize = pBt->pageSize - (u16)nReserve;
61694  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
61695  sqlite3BtreeLeave(p);
61696  return rc;
61697}
61698
61699/*
61700** Return the currently defined page size
61701*/
61702SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
61703  return p->pBt->pageSize;
61704}
61705
61706/*
61707** This function is similar to sqlite3BtreeGetReserve(), except that it
61708** may only be called if it is guaranteed that the b-tree mutex is already
61709** held.
61710**
61711** This is useful in one special case in the backup API code where it is
61712** known that the shared b-tree mutex is held, but the mutex on the
61713** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
61714** were to be called, it might collide with some other operation on the
61715** database handle that owns *p, causing undefined behavior.
61716*/
61717SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
61718  int n;
61719  assert( sqlite3_mutex_held(p->pBt->mutex) );
61720  n = p->pBt->pageSize - p->pBt->usableSize;
61721  return n;
61722}
61723
61724/*
61725** Return the number of bytes of space at the end of every page that
61726** are intentually left unused.  This is the "reserved" space that is
61727** sometimes used by extensions.
61728**
61729** If SQLITE_HAS_MUTEX is defined then the number returned is the
61730** greater of the current reserved space and the maximum requested
61731** reserve space.
61732*/
61733SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
61734  int n;
61735  sqlite3BtreeEnter(p);
61736  n = sqlite3BtreeGetReserveNoMutex(p);
61737#ifdef SQLITE_HAS_CODEC
61738  if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
61739#endif
61740  sqlite3BtreeLeave(p);
61741  return n;
61742}
61743
61744
61745/*
61746** Set the maximum page count for a database if mxPage is positive.
61747** No changes are made if mxPage is 0 or negative.
61748** Regardless of the value of mxPage, return the maximum page count.
61749*/
61750SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
61751  int n;
61752  sqlite3BtreeEnter(p);
61753  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
61754  sqlite3BtreeLeave(p);
61755  return n;
61756}
61757
61758/*
61759** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
61760** then make no changes.  Always return the value of the BTS_SECURE_DELETE
61761** setting after the change.
61762*/
61763SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
61764  int b;
61765  if( p==0 ) return 0;
61766  sqlite3BtreeEnter(p);
61767  if( newFlag>=0 ){
61768    p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
61769    if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
61770  }
61771  b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
61772  sqlite3BtreeLeave(p);
61773  return b;
61774}
61775
61776/*
61777** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
61778** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
61779** is disabled. The default value for the auto-vacuum property is
61780** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
61781*/
61782SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
61783#ifdef SQLITE_OMIT_AUTOVACUUM
61784  return SQLITE_READONLY;
61785#else
61786  BtShared *pBt = p->pBt;
61787  int rc = SQLITE_OK;
61788  u8 av = (u8)autoVacuum;
61789
61790  sqlite3BtreeEnter(p);
61791  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
61792    rc = SQLITE_READONLY;
61793  }else{
61794    pBt->autoVacuum = av ?1:0;
61795    pBt->incrVacuum = av==2 ?1:0;
61796  }
61797  sqlite3BtreeLeave(p);
61798  return rc;
61799#endif
61800}
61801
61802/*
61803** Return the value of the 'auto-vacuum' property. If auto-vacuum is
61804** enabled 1 is returned. Otherwise 0.
61805*/
61806SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
61807#ifdef SQLITE_OMIT_AUTOVACUUM
61808  return BTREE_AUTOVACUUM_NONE;
61809#else
61810  int rc;
61811  sqlite3BtreeEnter(p);
61812  rc = (
61813    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
61814    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
61815    BTREE_AUTOVACUUM_INCR
61816  );
61817  sqlite3BtreeLeave(p);
61818  return rc;
61819#endif
61820}
61821
61822/*
61823** If the user has not set the safety-level for this database connection
61824** using "PRAGMA synchronous", and if the safety-level is not already
61825** set to the value passed to this function as the second parameter,
61826** set it so.
61827*/
61828#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
61829static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
61830  sqlite3 *db;
61831  Db *pDb;
61832  if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
61833    while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
61834    if( pDb->bSyncSet==0
61835     && pDb->safety_level!=safety_level
61836     && pDb!=&db->aDb[1]
61837    ){
61838      pDb->safety_level = safety_level;
61839      sqlite3PagerSetFlags(pBt->pPager,
61840          pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
61841    }
61842  }
61843}
61844#else
61845# define setDefaultSyncFlag(pBt,safety_level)
61846#endif
61847
61848/*
61849** Get a reference to pPage1 of the database file.  This will
61850** also acquire a readlock on that file.
61851**
61852** SQLITE_OK is returned on success.  If the file is not a
61853** well-formed database file, then SQLITE_CORRUPT is returned.
61854** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
61855** is returned if we run out of memory.
61856*/
61857static int lockBtree(BtShared *pBt){
61858  int rc;              /* Result code from subfunctions */
61859  MemPage *pPage1;     /* Page 1 of the database file */
61860  int nPage;           /* Number of pages in the database */
61861  int nPageFile = 0;   /* Number of pages in the database file */
61862  int nPageHeader;     /* Number of pages in the database according to hdr */
61863
61864  assert( sqlite3_mutex_held(pBt->mutex) );
61865  assert( pBt->pPage1==0 );
61866  rc = sqlite3PagerSharedLock(pBt->pPager);
61867  if( rc!=SQLITE_OK ) return rc;
61868  rc = btreeGetPage(pBt, 1, &pPage1, 0);
61869  if( rc!=SQLITE_OK ) return rc;
61870
61871  /* Do some checking to help insure the file we opened really is
61872  ** a valid database file.
61873  */
61874  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
61875  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
61876  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
61877    nPage = nPageFile;
61878  }
61879  if( nPage>0 ){
61880    u32 pageSize;
61881    u32 usableSize;
61882    u8 *page1 = pPage1->aData;
61883    rc = SQLITE_NOTADB;
61884    /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
61885    ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
61886    ** 61 74 20 33 00. */
61887    if( memcmp(page1, zMagicHeader, 16)!=0 ){
61888      goto page1_init_failed;
61889    }
61890
61891#ifdef SQLITE_OMIT_WAL
61892    if( page1[18]>1 ){
61893      pBt->btsFlags |= BTS_READ_ONLY;
61894    }
61895    if( page1[19]>1 ){
61896      goto page1_init_failed;
61897    }
61898#else
61899    if( page1[18]>2 ){
61900      pBt->btsFlags |= BTS_READ_ONLY;
61901    }
61902    if( page1[19]>2 ){
61903      goto page1_init_failed;
61904    }
61905
61906    /* If the write version is set to 2, this database should be accessed
61907    ** in WAL mode. If the log is not already open, open it now. Then
61908    ** return SQLITE_OK and return without populating BtShared.pPage1.
61909    ** The caller detects this and calls this function again. This is
61910    ** required as the version of page 1 currently in the page1 buffer
61911    ** may not be the latest version - there may be a newer one in the log
61912    ** file.
61913    */
61914    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
61915      int isOpen = 0;
61916      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
61917      if( rc!=SQLITE_OK ){
61918        goto page1_init_failed;
61919      }else{
61920        setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
61921        if( isOpen==0 ){
61922          releasePage(pPage1);
61923          return SQLITE_OK;
61924        }
61925      }
61926      rc = SQLITE_NOTADB;
61927    }else{
61928      setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
61929    }
61930#endif
61931
61932    /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
61933    ** fractions and the leaf payload fraction values must be 64, 32, and 32.
61934    **
61935    ** The original design allowed these amounts to vary, but as of
61936    ** version 3.6.0, we require them to be fixed.
61937    */
61938    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
61939      goto page1_init_failed;
61940    }
61941    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
61942    ** determined by the 2-byte integer located at an offset of 16 bytes from
61943    ** the beginning of the database file. */
61944    pageSize = (page1[16]<<8) | (page1[17]<<16);
61945    /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
61946    ** between 512 and 65536 inclusive. */
61947    if( ((pageSize-1)&pageSize)!=0
61948     || pageSize>SQLITE_MAX_PAGE_SIZE
61949     || pageSize<=256
61950    ){
61951      goto page1_init_failed;
61952    }
61953    assert( (pageSize & 7)==0 );
61954    /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
61955    ** integer at offset 20 is the number of bytes of space at the end of
61956    ** each page to reserve for extensions.
61957    **
61958    ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
61959    ** determined by the one-byte unsigned integer found at an offset of 20
61960    ** into the database file header. */
61961    usableSize = pageSize - page1[20];
61962    if( (u32)pageSize!=pBt->pageSize ){
61963      /* After reading the first page of the database assuming a page size
61964      ** of BtShared.pageSize, we have discovered that the page-size is
61965      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
61966      ** zero and return SQLITE_OK. The caller will call this function
61967      ** again with the correct page-size.
61968      */
61969      releasePage(pPage1);
61970      pBt->usableSize = usableSize;
61971      pBt->pageSize = pageSize;
61972      freeTempSpace(pBt);
61973      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
61974                                   pageSize-usableSize);
61975      return rc;
61976    }
61977    if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
61978      rc = SQLITE_CORRUPT_BKPT;
61979      goto page1_init_failed;
61980    }
61981    /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
61982    ** be less than 480. In other words, if the page size is 512, then the
61983    ** reserved space size cannot exceed 32. */
61984    if( usableSize<480 ){
61985      goto page1_init_failed;
61986    }
61987    pBt->pageSize = pageSize;
61988    pBt->usableSize = usableSize;
61989#ifndef SQLITE_OMIT_AUTOVACUUM
61990    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
61991    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
61992#endif
61993  }
61994
61995  /* maxLocal is the maximum amount of payload to store locally for
61996  ** a cell.  Make sure it is small enough so that at least minFanout
61997  ** cells can will fit on one page.  We assume a 10-byte page header.
61998  ** Besides the payload, the cell must store:
61999  **     2-byte pointer to the cell
62000  **     4-byte child pointer
62001  **     9-byte nKey value
62002  **     4-byte nData value
62003  **     4-byte overflow page pointer
62004  ** So a cell consists of a 2-byte pointer, a header which is as much as
62005  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
62006  ** page pointer.
62007  */
62008  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
62009  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
62010  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
62011  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
62012  if( pBt->maxLocal>127 ){
62013    pBt->max1bytePayload = 127;
62014  }else{
62015    pBt->max1bytePayload = (u8)pBt->maxLocal;
62016  }
62017  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
62018  pBt->pPage1 = pPage1;
62019  pBt->nPage = nPage;
62020  return SQLITE_OK;
62021
62022page1_init_failed:
62023  releasePage(pPage1);
62024  pBt->pPage1 = 0;
62025  return rc;
62026}
62027
62028#ifndef NDEBUG
62029/*
62030** Return the number of cursors open on pBt. This is for use
62031** in assert() expressions, so it is only compiled if NDEBUG is not
62032** defined.
62033**
62034** Only write cursors are counted if wrOnly is true.  If wrOnly is
62035** false then all cursors are counted.
62036**
62037** For the purposes of this routine, a cursor is any cursor that
62038** is capable of reading or writing to the database.  Cursors that
62039** have been tripped into the CURSOR_FAULT state are not counted.
62040*/
62041static int countValidCursors(BtShared *pBt, int wrOnly){
62042  BtCursor *pCur;
62043  int r = 0;
62044  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
62045    if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
62046     && pCur->eState!=CURSOR_FAULT ) r++;
62047  }
62048  return r;
62049}
62050#endif
62051
62052/*
62053** If there are no outstanding cursors and we are not in the middle
62054** of a transaction but there is a read lock on the database, then
62055** this routine unrefs the first page of the database file which
62056** has the effect of releasing the read lock.
62057**
62058** If there is a transaction in progress, this routine is a no-op.
62059*/
62060static void unlockBtreeIfUnused(BtShared *pBt){
62061  assert( sqlite3_mutex_held(pBt->mutex) );
62062  assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
62063  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
62064    MemPage *pPage1 = pBt->pPage1;
62065    assert( pPage1->aData );
62066    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
62067    pBt->pPage1 = 0;
62068    releasePageNotNull(pPage1);
62069  }
62070}
62071
62072/*
62073** If pBt points to an empty file then convert that empty file
62074** into a new empty database by initializing the first page of
62075** the database.
62076*/
62077static int newDatabase(BtShared *pBt){
62078  MemPage *pP1;
62079  unsigned char *data;
62080  int rc;
62081
62082  assert( sqlite3_mutex_held(pBt->mutex) );
62083  if( pBt->nPage>0 ){
62084    return SQLITE_OK;
62085  }
62086  pP1 = pBt->pPage1;
62087  assert( pP1!=0 );
62088  data = pP1->aData;
62089  rc = sqlite3PagerWrite(pP1->pDbPage);
62090  if( rc ) return rc;
62091  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
62092  assert( sizeof(zMagicHeader)==16 );
62093  data[16] = (u8)((pBt->pageSize>>8)&0xff);
62094  data[17] = (u8)((pBt->pageSize>>16)&0xff);
62095  data[18] = 1;
62096  data[19] = 1;
62097  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
62098  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
62099  data[21] = 64;
62100  data[22] = 32;
62101  data[23] = 32;
62102  memset(&data[24], 0, 100-24);
62103  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
62104  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
62105#ifndef SQLITE_OMIT_AUTOVACUUM
62106  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
62107  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
62108  put4byte(&data[36 + 4*4], pBt->autoVacuum);
62109  put4byte(&data[36 + 7*4], pBt->incrVacuum);
62110#endif
62111  pBt->nPage = 1;
62112  data[31] = 1;
62113  return SQLITE_OK;
62114}
62115
62116/*
62117** Initialize the first page of the database file (creating a database
62118** consisting of a single page and no schema objects). Return SQLITE_OK
62119** if successful, or an SQLite error code otherwise.
62120*/
62121SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
62122  int rc;
62123  sqlite3BtreeEnter(p);
62124  p->pBt->nPage = 0;
62125  rc = newDatabase(p->pBt);
62126  sqlite3BtreeLeave(p);
62127  return rc;
62128}
62129
62130/*
62131** Attempt to start a new transaction. A write-transaction
62132** is started if the second argument is nonzero, otherwise a read-
62133** transaction.  If the second argument is 2 or more and exclusive
62134** transaction is started, meaning that no other process is allowed
62135** to access the database.  A preexisting transaction may not be
62136** upgraded to exclusive by calling this routine a second time - the
62137** exclusivity flag only works for a new transaction.
62138**
62139** A write-transaction must be started before attempting any
62140** changes to the database.  None of the following routines
62141** will work unless a transaction is started first:
62142**
62143**      sqlite3BtreeCreateTable()
62144**      sqlite3BtreeCreateIndex()
62145**      sqlite3BtreeClearTable()
62146**      sqlite3BtreeDropTable()
62147**      sqlite3BtreeInsert()
62148**      sqlite3BtreeDelete()
62149**      sqlite3BtreeUpdateMeta()
62150**
62151** If an initial attempt to acquire the lock fails because of lock contention
62152** and the database was previously unlocked, then invoke the busy handler
62153** if there is one.  But if there was previously a read-lock, do not
62154** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
62155** returned when there is already a read-lock in order to avoid a deadlock.
62156**
62157** Suppose there are two processes A and B.  A has a read lock and B has
62158** a reserved lock.  B tries to promote to exclusive but is blocked because
62159** of A's read lock.  A tries to promote to reserved but is blocked by B.
62160** One or the other of the two processes must give way or there can be
62161** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
62162** when A already has a read lock, we encourage A to give up and let B
62163** proceed.
62164*/
62165SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
62166  BtShared *pBt = p->pBt;
62167  int rc = SQLITE_OK;
62168
62169  sqlite3BtreeEnter(p);
62170  btreeIntegrity(p);
62171
62172  /* If the btree is already in a write-transaction, or it
62173  ** is already in a read-transaction and a read-transaction
62174  ** is requested, this is a no-op.
62175  */
62176  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
62177    goto trans_begun;
62178  }
62179  assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
62180
62181  /* Write transactions are not possible on a read-only database */
62182  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
62183    rc = SQLITE_READONLY;
62184    goto trans_begun;
62185  }
62186
62187#ifndef SQLITE_OMIT_SHARED_CACHE
62188  {
62189    sqlite3 *pBlock = 0;
62190    /* If another database handle has already opened a write transaction
62191    ** on this shared-btree structure and a second write transaction is
62192    ** requested, return SQLITE_LOCKED.
62193    */
62194    if( (wrflag && pBt->inTransaction==TRANS_WRITE)
62195     || (pBt->btsFlags & BTS_PENDING)!=0
62196    ){
62197      pBlock = pBt->pWriter->db;
62198    }else if( wrflag>1 ){
62199      BtLock *pIter;
62200      for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
62201        if( pIter->pBtree!=p ){
62202          pBlock = pIter->pBtree->db;
62203          break;
62204        }
62205      }
62206    }
62207    if( pBlock ){
62208      sqlite3ConnectionBlocked(p->db, pBlock);
62209      rc = SQLITE_LOCKED_SHAREDCACHE;
62210      goto trans_begun;
62211    }
62212  }
62213#endif
62214
62215  /* Any read-only or read-write transaction implies a read-lock on
62216  ** page 1. So if some other shared-cache client already has a write-lock
62217  ** on page 1, the transaction cannot be opened. */
62218  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
62219  if( SQLITE_OK!=rc ) goto trans_begun;
62220
62221  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
62222  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
62223  do {
62224    /* Call lockBtree() until either pBt->pPage1 is populated or
62225    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
62226    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
62227    ** reading page 1 it discovers that the page-size of the database
62228    ** file is not pBt->pageSize. In this case lockBtree() will update
62229    ** pBt->pageSize to the page-size of the file on disk.
62230    */
62231    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
62232
62233    if( rc==SQLITE_OK && wrflag ){
62234      if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
62235        rc = SQLITE_READONLY;
62236      }else{
62237        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
62238        if( rc==SQLITE_OK ){
62239          rc = newDatabase(pBt);
62240        }
62241      }
62242    }
62243
62244    if( rc!=SQLITE_OK ){
62245      unlockBtreeIfUnused(pBt);
62246    }
62247  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
62248          btreeInvokeBusyHandler(pBt) );
62249
62250  if( rc==SQLITE_OK ){
62251    if( p->inTrans==TRANS_NONE ){
62252      pBt->nTransaction++;
62253#ifndef SQLITE_OMIT_SHARED_CACHE
62254      if( p->sharable ){
62255        assert( p->lock.pBtree==p && p->lock.iTable==1 );
62256        p->lock.eLock = READ_LOCK;
62257        p->lock.pNext = pBt->pLock;
62258        pBt->pLock = &p->lock;
62259      }
62260#endif
62261    }
62262    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
62263    if( p->inTrans>pBt->inTransaction ){
62264      pBt->inTransaction = p->inTrans;
62265    }
62266    if( wrflag ){
62267      MemPage *pPage1 = pBt->pPage1;
62268#ifndef SQLITE_OMIT_SHARED_CACHE
62269      assert( !pBt->pWriter );
62270      pBt->pWriter = p;
62271      pBt->btsFlags &= ~BTS_EXCLUSIVE;
62272      if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
62273#endif
62274
62275      /* If the db-size header field is incorrect (as it may be if an old
62276      ** client has been writing the database file), update it now. Doing
62277      ** this sooner rather than later means the database size can safely
62278      ** re-read the database size from page 1 if a savepoint or transaction
62279      ** rollback occurs within the transaction.
62280      */
62281      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
62282        rc = sqlite3PagerWrite(pPage1->pDbPage);
62283        if( rc==SQLITE_OK ){
62284          put4byte(&pPage1->aData[28], pBt->nPage);
62285        }
62286      }
62287    }
62288  }
62289
62290
62291trans_begun:
62292  if( rc==SQLITE_OK && wrflag ){
62293    /* This call makes sure that the pager has the correct number of
62294    ** open savepoints. If the second parameter is greater than 0 and
62295    ** the sub-journal is not already open, then it will be opened here.
62296    */
62297    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
62298  }
62299
62300  btreeIntegrity(p);
62301  sqlite3BtreeLeave(p);
62302  return rc;
62303}
62304
62305#ifndef SQLITE_OMIT_AUTOVACUUM
62306
62307/*
62308** Set the pointer-map entries for all children of page pPage. Also, if
62309** pPage contains cells that point to overflow pages, set the pointer
62310** map entries for the overflow pages as well.
62311*/
62312static int setChildPtrmaps(MemPage *pPage){
62313  int i;                             /* Counter variable */
62314  int nCell;                         /* Number of cells in page pPage */
62315  int rc;                            /* Return code */
62316  BtShared *pBt = pPage->pBt;
62317  Pgno pgno = pPage->pgno;
62318
62319  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
62320  rc = btreeInitPage(pPage);
62321  if( rc!=SQLITE_OK ) return rc;
62322  nCell = pPage->nCell;
62323
62324  for(i=0; i<nCell; i++){
62325    u8 *pCell = findCell(pPage, i);
62326
62327    ptrmapPutOvflPtr(pPage, pCell, &rc);
62328
62329    if( !pPage->leaf ){
62330      Pgno childPgno = get4byte(pCell);
62331      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
62332    }
62333  }
62334
62335  if( !pPage->leaf ){
62336    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
62337    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
62338  }
62339
62340  return rc;
62341}
62342
62343/*
62344** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
62345** that it points to iTo. Parameter eType describes the type of pointer to
62346** be modified, as  follows:
62347**
62348** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
62349**                   page of pPage.
62350**
62351** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
62352**                   page pointed to by one of the cells on pPage.
62353**
62354** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
62355**                   overflow page in the list.
62356*/
62357static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
62358  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
62359  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
62360  if( eType==PTRMAP_OVERFLOW2 ){
62361    /* The pointer is always the first 4 bytes of the page in this case.  */
62362    if( get4byte(pPage->aData)!=iFrom ){
62363      return SQLITE_CORRUPT_BKPT;
62364    }
62365    put4byte(pPage->aData, iTo);
62366  }else{
62367    int i;
62368    int nCell;
62369    int rc;
62370
62371    rc = btreeInitPage(pPage);
62372    if( rc ) return rc;
62373    nCell = pPage->nCell;
62374
62375    for(i=0; i<nCell; i++){
62376      u8 *pCell = findCell(pPage, i);
62377      if( eType==PTRMAP_OVERFLOW1 ){
62378        CellInfo info;
62379        pPage->xParseCell(pPage, pCell, &info);
62380        if( info.nLocal<info.nPayload ){
62381          if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
62382            return SQLITE_CORRUPT_BKPT;
62383          }
62384          if( iFrom==get4byte(pCell+info.nSize-4) ){
62385            put4byte(pCell+info.nSize-4, iTo);
62386            break;
62387          }
62388        }
62389      }else{
62390        if( get4byte(pCell)==iFrom ){
62391          put4byte(pCell, iTo);
62392          break;
62393        }
62394      }
62395    }
62396
62397    if( i==nCell ){
62398      if( eType!=PTRMAP_BTREE ||
62399          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
62400        return SQLITE_CORRUPT_BKPT;
62401      }
62402      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
62403    }
62404  }
62405  return SQLITE_OK;
62406}
62407
62408
62409/*
62410** Move the open database page pDbPage to location iFreePage in the
62411** database. The pDbPage reference remains valid.
62412**
62413** The isCommit flag indicates that there is no need to remember that
62414** the journal needs to be sync()ed before database page pDbPage->pgno
62415** can be written to. The caller has already promised not to write to that
62416** page.
62417*/
62418static int relocatePage(
62419  BtShared *pBt,           /* Btree */
62420  MemPage *pDbPage,        /* Open page to move */
62421  u8 eType,                /* Pointer map 'type' entry for pDbPage */
62422  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
62423  Pgno iFreePage,          /* The location to move pDbPage to */
62424  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
62425){
62426  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
62427  Pgno iDbPage = pDbPage->pgno;
62428  Pager *pPager = pBt->pPager;
62429  int rc;
62430
62431  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
62432      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
62433  assert( sqlite3_mutex_held(pBt->mutex) );
62434  assert( pDbPage->pBt==pBt );
62435
62436  /* Move page iDbPage from its current location to page number iFreePage */
62437  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
62438      iDbPage, iFreePage, iPtrPage, eType));
62439  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
62440  if( rc!=SQLITE_OK ){
62441    return rc;
62442  }
62443  pDbPage->pgno = iFreePage;
62444
62445  /* If pDbPage was a btree-page, then it may have child pages and/or cells
62446  ** that point to overflow pages. The pointer map entries for all these
62447  ** pages need to be changed.
62448  **
62449  ** If pDbPage is an overflow page, then the first 4 bytes may store a
62450  ** pointer to a subsequent overflow page. If this is the case, then
62451  ** the pointer map needs to be updated for the subsequent overflow page.
62452  */
62453  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
62454    rc = setChildPtrmaps(pDbPage);
62455    if( rc!=SQLITE_OK ){
62456      return rc;
62457    }
62458  }else{
62459    Pgno nextOvfl = get4byte(pDbPage->aData);
62460    if( nextOvfl!=0 ){
62461      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
62462      if( rc!=SQLITE_OK ){
62463        return rc;
62464      }
62465    }
62466  }
62467
62468  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
62469  ** that it points at iFreePage. Also fix the pointer map entry for
62470  ** iPtrPage.
62471  */
62472  if( eType!=PTRMAP_ROOTPAGE ){
62473    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
62474    if( rc!=SQLITE_OK ){
62475      return rc;
62476    }
62477    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
62478    if( rc!=SQLITE_OK ){
62479      releasePage(pPtrPage);
62480      return rc;
62481    }
62482    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
62483    releasePage(pPtrPage);
62484    if( rc==SQLITE_OK ){
62485      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
62486    }
62487  }
62488  return rc;
62489}
62490
62491/* Forward declaration required by incrVacuumStep(). */
62492static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
62493
62494/*
62495** Perform a single step of an incremental-vacuum. If successful, return
62496** SQLITE_OK. If there is no work to do (and therefore no point in
62497** calling this function again), return SQLITE_DONE. Or, if an error
62498** occurs, return some other error code.
62499**
62500** More specifically, this function attempts to re-organize the database so
62501** that the last page of the file currently in use is no longer in use.
62502**
62503** Parameter nFin is the number of pages that this database would contain
62504** were this function called until it returns SQLITE_DONE.
62505**
62506** If the bCommit parameter is non-zero, this function assumes that the
62507** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
62508** or an error. bCommit is passed true for an auto-vacuum-on-commit
62509** operation, or false for an incremental vacuum.
62510*/
62511static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
62512  Pgno nFreeList;           /* Number of pages still on the free-list */
62513  int rc;
62514
62515  assert( sqlite3_mutex_held(pBt->mutex) );
62516  assert( iLastPg>nFin );
62517
62518  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
62519    u8 eType;
62520    Pgno iPtrPage;
62521
62522    nFreeList = get4byte(&pBt->pPage1->aData[36]);
62523    if( nFreeList==0 ){
62524      return SQLITE_DONE;
62525    }
62526
62527    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
62528    if( rc!=SQLITE_OK ){
62529      return rc;
62530    }
62531    if( eType==PTRMAP_ROOTPAGE ){
62532      return SQLITE_CORRUPT_BKPT;
62533    }
62534
62535    if( eType==PTRMAP_FREEPAGE ){
62536      if( bCommit==0 ){
62537        /* Remove the page from the files free-list. This is not required
62538        ** if bCommit is non-zero. In that case, the free-list will be
62539        ** truncated to zero after this function returns, so it doesn't
62540        ** matter if it still contains some garbage entries.
62541        */
62542        Pgno iFreePg;
62543        MemPage *pFreePg;
62544        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
62545        if( rc!=SQLITE_OK ){
62546          return rc;
62547        }
62548        assert( iFreePg==iLastPg );
62549        releasePage(pFreePg);
62550      }
62551    } else {
62552      Pgno iFreePg;             /* Index of free page to move pLastPg to */
62553      MemPage *pLastPg;
62554      u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
62555      Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
62556
62557      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
62558      if( rc!=SQLITE_OK ){
62559        return rc;
62560      }
62561
62562      /* If bCommit is zero, this loop runs exactly once and page pLastPg
62563      ** is swapped with the first free page pulled off the free list.
62564      **
62565      ** On the other hand, if bCommit is greater than zero, then keep
62566      ** looping until a free-page located within the first nFin pages
62567      ** of the file is found.
62568      */
62569      if( bCommit==0 ){
62570        eMode = BTALLOC_LE;
62571        iNear = nFin;
62572      }
62573      do {
62574        MemPage *pFreePg;
62575        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
62576        if( rc!=SQLITE_OK ){
62577          releasePage(pLastPg);
62578          return rc;
62579        }
62580        releasePage(pFreePg);
62581      }while( bCommit && iFreePg>nFin );
62582      assert( iFreePg<iLastPg );
62583
62584      rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
62585      releasePage(pLastPg);
62586      if( rc!=SQLITE_OK ){
62587        return rc;
62588      }
62589    }
62590  }
62591
62592  if( bCommit==0 ){
62593    do {
62594      iLastPg--;
62595    }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
62596    pBt->bDoTruncate = 1;
62597    pBt->nPage = iLastPg;
62598  }
62599  return SQLITE_OK;
62600}
62601
62602/*
62603** The database opened by the first argument is an auto-vacuum database
62604** nOrig pages in size containing nFree free pages. Return the expected
62605** size of the database in pages following an auto-vacuum operation.
62606*/
62607static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
62608  int nEntry;                     /* Number of entries on one ptrmap page */
62609  Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
62610  Pgno nFin;                      /* Return value */
62611
62612  nEntry = pBt->usableSize/5;
62613  nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
62614  nFin = nOrig - nFree - nPtrmap;
62615  if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
62616    nFin--;
62617  }
62618  while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
62619    nFin--;
62620  }
62621
62622  return nFin;
62623}
62624
62625/*
62626** A write-transaction must be opened before calling this function.
62627** It performs a single unit of work towards an incremental vacuum.
62628**
62629** If the incremental vacuum is finished after this function has run,
62630** SQLITE_DONE is returned. If it is not finished, but no error occurred,
62631** SQLITE_OK is returned. Otherwise an SQLite error code.
62632*/
62633SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
62634  int rc;
62635  BtShared *pBt = p->pBt;
62636
62637  sqlite3BtreeEnter(p);
62638  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
62639  if( !pBt->autoVacuum ){
62640    rc = SQLITE_DONE;
62641  }else{
62642    Pgno nOrig = btreePagecount(pBt);
62643    Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
62644    Pgno nFin = finalDbSize(pBt, nOrig, nFree);
62645
62646    if( nOrig<nFin ){
62647      rc = SQLITE_CORRUPT_BKPT;
62648    }else if( nFree>0 ){
62649      rc = saveAllCursors(pBt, 0, 0);
62650      if( rc==SQLITE_OK ){
62651        invalidateAllOverflowCache(pBt);
62652        rc = incrVacuumStep(pBt, nFin, nOrig, 0);
62653      }
62654      if( rc==SQLITE_OK ){
62655        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
62656        put4byte(&pBt->pPage1->aData[28], pBt->nPage);
62657      }
62658    }else{
62659      rc = SQLITE_DONE;
62660    }
62661  }
62662  sqlite3BtreeLeave(p);
62663  return rc;
62664}
62665
62666/*
62667** This routine is called prior to sqlite3PagerCommit when a transaction
62668** is committed for an auto-vacuum database.
62669**
62670** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
62671** the database file should be truncated to during the commit process.
62672** i.e. the database has been reorganized so that only the first *pnTrunc
62673** pages are in use.
62674*/
62675static int autoVacuumCommit(BtShared *pBt){
62676  int rc = SQLITE_OK;
62677  Pager *pPager = pBt->pPager;
62678  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
62679
62680  assert( sqlite3_mutex_held(pBt->mutex) );
62681  invalidateAllOverflowCache(pBt);
62682  assert(pBt->autoVacuum);
62683  if( !pBt->incrVacuum ){
62684    Pgno nFin;         /* Number of pages in database after autovacuuming */
62685    Pgno nFree;        /* Number of pages on the freelist initially */
62686    Pgno iFree;        /* The next page to be freed */
62687    Pgno nOrig;        /* Database size before freeing */
62688
62689    nOrig = btreePagecount(pBt);
62690    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
62691      /* It is not possible to create a database for which the final page
62692      ** is either a pointer-map page or the pending-byte page. If one
62693      ** is encountered, this indicates corruption.
62694      */
62695      return SQLITE_CORRUPT_BKPT;
62696    }
62697
62698    nFree = get4byte(&pBt->pPage1->aData[36]);
62699    nFin = finalDbSize(pBt, nOrig, nFree);
62700    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
62701    if( nFin<nOrig ){
62702      rc = saveAllCursors(pBt, 0, 0);
62703    }
62704    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
62705      rc = incrVacuumStep(pBt, nFin, iFree, 1);
62706    }
62707    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
62708      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
62709      put4byte(&pBt->pPage1->aData[32], 0);
62710      put4byte(&pBt->pPage1->aData[36], 0);
62711      put4byte(&pBt->pPage1->aData[28], nFin);
62712      pBt->bDoTruncate = 1;
62713      pBt->nPage = nFin;
62714    }
62715    if( rc!=SQLITE_OK ){
62716      sqlite3PagerRollback(pPager);
62717    }
62718  }
62719
62720  assert( nRef>=sqlite3PagerRefcount(pPager) );
62721  return rc;
62722}
62723
62724#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
62725# define setChildPtrmaps(x) SQLITE_OK
62726#endif
62727
62728/*
62729** This routine does the first phase of a two-phase commit.  This routine
62730** causes a rollback journal to be created (if it does not already exist)
62731** and populated with enough information so that if a power loss occurs
62732** the database can be restored to its original state by playing back
62733** the journal.  Then the contents of the journal are flushed out to
62734** the disk.  After the journal is safely on oxide, the changes to the
62735** database are written into the database file and flushed to oxide.
62736** At the end of this call, the rollback journal still exists on the
62737** disk and we are still holding all locks, so the transaction has not
62738** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
62739** commit process.
62740**
62741** This call is a no-op if no write-transaction is currently active on pBt.
62742**
62743** Otherwise, sync the database file for the btree pBt. zMaster points to
62744** the name of a master journal file that should be written into the
62745** individual journal file, or is NULL, indicating no master journal file
62746** (single database transaction).
62747**
62748** When this is called, the master journal should already have been
62749** created, populated with this journal pointer and synced to disk.
62750**
62751** Once this is routine has returned, the only thing required to commit
62752** the write-transaction for this database file is to delete the journal.
62753*/
62754SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
62755  int rc = SQLITE_OK;
62756  if( p->inTrans==TRANS_WRITE ){
62757    BtShared *pBt = p->pBt;
62758    sqlite3BtreeEnter(p);
62759#ifndef SQLITE_OMIT_AUTOVACUUM
62760    if( pBt->autoVacuum ){
62761      rc = autoVacuumCommit(pBt);
62762      if( rc!=SQLITE_OK ){
62763        sqlite3BtreeLeave(p);
62764        return rc;
62765      }
62766    }
62767    if( pBt->bDoTruncate ){
62768      sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
62769    }
62770#endif
62771    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
62772    sqlite3BtreeLeave(p);
62773  }
62774  return rc;
62775}
62776
62777/*
62778** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
62779** at the conclusion of a transaction.
62780*/
62781static void btreeEndTransaction(Btree *p){
62782  BtShared *pBt = p->pBt;
62783  sqlite3 *db = p->db;
62784  assert( sqlite3BtreeHoldsMutex(p) );
62785
62786#ifndef SQLITE_OMIT_AUTOVACUUM
62787  pBt->bDoTruncate = 0;
62788#endif
62789  if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
62790    /* If there are other active statements that belong to this database
62791    ** handle, downgrade to a read-only transaction. The other statements
62792    ** may still be reading from the database.  */
62793    downgradeAllSharedCacheTableLocks(p);
62794    p->inTrans = TRANS_READ;
62795  }else{
62796    /* If the handle had any kind of transaction open, decrement the
62797    ** transaction count of the shared btree. If the transaction count
62798    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
62799    ** call below will unlock the pager.  */
62800    if( p->inTrans!=TRANS_NONE ){
62801      clearAllSharedCacheTableLocks(p);
62802      pBt->nTransaction--;
62803      if( 0==pBt->nTransaction ){
62804        pBt->inTransaction = TRANS_NONE;
62805      }
62806    }
62807
62808    /* Set the current transaction state to TRANS_NONE and unlock the
62809    ** pager if this call closed the only read or write transaction.  */
62810    p->inTrans = TRANS_NONE;
62811    unlockBtreeIfUnused(pBt);
62812  }
62813
62814  btreeIntegrity(p);
62815}
62816
62817/*
62818** Commit the transaction currently in progress.
62819**
62820** This routine implements the second phase of a 2-phase commit.  The
62821** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
62822** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
62823** routine did all the work of writing information out to disk and flushing the
62824** contents so that they are written onto the disk platter.  All this
62825** routine has to do is delete or truncate or zero the header in the
62826** the rollback journal (which causes the transaction to commit) and
62827** drop locks.
62828**
62829** Normally, if an error occurs while the pager layer is attempting to
62830** finalize the underlying journal file, this function returns an error and
62831** the upper layer will attempt a rollback. However, if the second argument
62832** is non-zero then this b-tree transaction is part of a multi-file
62833** transaction. In this case, the transaction has already been committed
62834** (by deleting a master journal file) and the caller will ignore this
62835** functions return code. So, even if an error occurs in the pager layer,
62836** reset the b-tree objects internal state to indicate that the write
62837** transaction has been closed. This is quite safe, as the pager will have
62838** transitioned to the error state.
62839**
62840** This will release the write lock on the database file.  If there
62841** are no active cursors, it also releases the read lock.
62842*/
62843SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
62844
62845  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
62846  sqlite3BtreeEnter(p);
62847  btreeIntegrity(p);
62848
62849  /* If the handle has a write-transaction open, commit the shared-btrees
62850  ** transaction and set the shared state to TRANS_READ.
62851  */
62852  if( p->inTrans==TRANS_WRITE ){
62853    int rc;
62854    BtShared *pBt = p->pBt;
62855    assert( pBt->inTransaction==TRANS_WRITE );
62856    assert( pBt->nTransaction>0 );
62857    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
62858    if( rc!=SQLITE_OK && bCleanup==0 ){
62859      sqlite3BtreeLeave(p);
62860      return rc;
62861    }
62862    p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
62863    pBt->inTransaction = TRANS_READ;
62864    btreeClearHasContent(pBt);
62865  }
62866
62867  btreeEndTransaction(p);
62868  sqlite3BtreeLeave(p);
62869  return SQLITE_OK;
62870}
62871
62872/*
62873** Do both phases of a commit.
62874*/
62875SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
62876  int rc;
62877  sqlite3BtreeEnter(p);
62878  rc = sqlite3BtreeCommitPhaseOne(p, 0);
62879  if( rc==SQLITE_OK ){
62880    rc = sqlite3BtreeCommitPhaseTwo(p, 0);
62881  }
62882  sqlite3BtreeLeave(p);
62883  return rc;
62884}
62885
62886/*
62887** This routine sets the state to CURSOR_FAULT and the error
62888** code to errCode for every cursor on any BtShared that pBtree
62889** references.  Or if the writeOnly flag is set to 1, then only
62890** trip write cursors and leave read cursors unchanged.
62891**
62892** Every cursor is a candidate to be tripped, including cursors
62893** that belong to other database connections that happen to be
62894** sharing the cache with pBtree.
62895**
62896** This routine gets called when a rollback occurs. If the writeOnly
62897** flag is true, then only write-cursors need be tripped - read-only
62898** cursors save their current positions so that they may continue
62899** following the rollback. Or, if writeOnly is false, all cursors are
62900** tripped. In general, writeOnly is false if the transaction being
62901** rolled back modified the database schema. In this case b-tree root
62902** pages may be moved or deleted from the database altogether, making
62903** it unsafe for read cursors to continue.
62904**
62905** If the writeOnly flag is true and an error is encountered while
62906** saving the current position of a read-only cursor, all cursors,
62907** including all read-cursors are tripped.
62908**
62909** SQLITE_OK is returned if successful, or if an error occurs while
62910** saving a cursor position, an SQLite error code.
62911*/
62912SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
62913  BtCursor *p;
62914  int rc = SQLITE_OK;
62915
62916  assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
62917  if( pBtree ){
62918    sqlite3BtreeEnter(pBtree);
62919    for(p=pBtree->pBt->pCursor; p; p=p->pNext){
62920      int i;
62921      if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
62922        if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
62923          rc = saveCursorPosition(p);
62924          if( rc!=SQLITE_OK ){
62925            (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
62926            break;
62927          }
62928        }
62929      }else{
62930        sqlite3BtreeClearCursor(p);
62931        p->eState = CURSOR_FAULT;
62932        p->skipNext = errCode;
62933      }
62934      for(i=0; i<=p->iPage; i++){
62935        releasePage(p->apPage[i]);
62936        p->apPage[i] = 0;
62937      }
62938    }
62939    sqlite3BtreeLeave(pBtree);
62940  }
62941  return rc;
62942}
62943
62944/*
62945** Rollback the transaction in progress.
62946**
62947** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
62948** Only write cursors are tripped if writeOnly is true but all cursors are
62949** tripped if writeOnly is false.  Any attempt to use
62950** a tripped cursor will result in an error.
62951**
62952** This will release the write lock on the database file.  If there
62953** are no active cursors, it also releases the read lock.
62954*/
62955SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
62956  int rc;
62957  BtShared *pBt = p->pBt;
62958  MemPage *pPage1;
62959
62960  assert( writeOnly==1 || writeOnly==0 );
62961  assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
62962  sqlite3BtreeEnter(p);
62963  if( tripCode==SQLITE_OK ){
62964    rc = tripCode = saveAllCursors(pBt, 0, 0);
62965    if( rc ) writeOnly = 0;
62966  }else{
62967    rc = SQLITE_OK;
62968  }
62969  if( tripCode ){
62970    int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
62971    assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
62972    if( rc2!=SQLITE_OK ) rc = rc2;
62973  }
62974  btreeIntegrity(p);
62975
62976  if( p->inTrans==TRANS_WRITE ){
62977    int rc2;
62978
62979    assert( TRANS_WRITE==pBt->inTransaction );
62980    rc2 = sqlite3PagerRollback(pBt->pPager);
62981    if( rc2!=SQLITE_OK ){
62982      rc = rc2;
62983    }
62984
62985    /* The rollback may have destroyed the pPage1->aData value.  So
62986    ** call btreeGetPage() on page 1 again to make
62987    ** sure pPage1->aData is set correctly. */
62988    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
62989      int nPage = get4byte(28+(u8*)pPage1->aData);
62990      testcase( nPage==0 );
62991      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
62992      testcase( pBt->nPage!=nPage );
62993      pBt->nPage = nPage;
62994      releasePage(pPage1);
62995    }
62996    assert( countValidCursors(pBt, 1)==0 );
62997    pBt->inTransaction = TRANS_READ;
62998    btreeClearHasContent(pBt);
62999  }
63000
63001  btreeEndTransaction(p);
63002  sqlite3BtreeLeave(p);
63003  return rc;
63004}
63005
63006/*
63007** Start a statement subtransaction. The subtransaction can be rolled
63008** back independently of the main transaction. You must start a transaction
63009** before starting a subtransaction. The subtransaction is ended automatically
63010** if the main transaction commits or rolls back.
63011**
63012** Statement subtransactions are used around individual SQL statements
63013** that are contained within a BEGIN...COMMIT block.  If a constraint
63014** error occurs within the statement, the effect of that one statement
63015** can be rolled back without having to rollback the entire transaction.
63016**
63017** A statement sub-transaction is implemented as an anonymous savepoint. The
63018** value passed as the second parameter is the total number of savepoints,
63019** including the new anonymous savepoint, open on the B-Tree. i.e. if there
63020** are no active savepoints and no other statement-transactions open,
63021** iStatement is 1. This anonymous savepoint can be released or rolled back
63022** using the sqlite3BtreeSavepoint() function.
63023*/
63024SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
63025  int rc;
63026  BtShared *pBt = p->pBt;
63027  sqlite3BtreeEnter(p);
63028  assert( p->inTrans==TRANS_WRITE );
63029  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
63030  assert( iStatement>0 );
63031  assert( iStatement>p->db->nSavepoint );
63032  assert( pBt->inTransaction==TRANS_WRITE );
63033  /* At the pager level, a statement transaction is a savepoint with
63034  ** an index greater than all savepoints created explicitly using
63035  ** SQL statements. It is illegal to open, release or rollback any
63036  ** such savepoints while the statement transaction savepoint is active.
63037  */
63038  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
63039  sqlite3BtreeLeave(p);
63040  return rc;
63041}
63042
63043/*
63044** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
63045** or SAVEPOINT_RELEASE. This function either releases or rolls back the
63046** savepoint identified by parameter iSavepoint, depending on the value
63047** of op.
63048**
63049** Normally, iSavepoint is greater than or equal to zero. However, if op is
63050** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
63051** contents of the entire transaction are rolled back. This is different
63052** from a normal transaction rollback, as no locks are released and the
63053** transaction remains open.
63054*/
63055SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
63056  int rc = SQLITE_OK;
63057  if( p && p->inTrans==TRANS_WRITE ){
63058    BtShared *pBt = p->pBt;
63059    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
63060    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
63061    sqlite3BtreeEnter(p);
63062    if( op==SAVEPOINT_ROLLBACK ){
63063      rc = saveAllCursors(pBt, 0, 0);
63064    }
63065    if( rc==SQLITE_OK ){
63066      rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
63067    }
63068    if( rc==SQLITE_OK ){
63069      if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
63070        pBt->nPage = 0;
63071      }
63072      rc = newDatabase(pBt);
63073      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
63074
63075      /* The database size was written into the offset 28 of the header
63076      ** when the transaction started, so we know that the value at offset
63077      ** 28 is nonzero. */
63078      assert( pBt->nPage>0 );
63079    }
63080    sqlite3BtreeLeave(p);
63081  }
63082  return rc;
63083}
63084
63085/*
63086** Create a new cursor for the BTree whose root is on the page
63087** iTable. If a read-only cursor is requested, it is assumed that
63088** the caller already has at least a read-only transaction open
63089** on the database already. If a write-cursor is requested, then
63090** the caller is assumed to have an open write transaction.
63091**
63092** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
63093** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
63094** can be used for reading or for writing if other conditions for writing
63095** are also met.  These are the conditions that must be met in order
63096** for writing to be allowed:
63097**
63098** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
63099**
63100** 2:  Other database connections that share the same pager cache
63101**     but which are not in the READ_UNCOMMITTED state may not have
63102**     cursors open with wrFlag==0 on the same table.  Otherwise
63103**     the changes made by this write cursor would be visible to
63104**     the read cursors in the other database connection.
63105**
63106** 3:  The database must be writable (not on read-only media)
63107**
63108** 4:  There must be an active transaction.
63109**
63110** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
63111** is set.  If FORDELETE is set, that is a hint to the implementation that
63112** this cursor will only be used to seek to and delete entries of an index
63113** as part of a larger DELETE statement.  The FORDELETE hint is not used by
63114** this implementation.  But in a hypothetical alternative storage engine
63115** in which index entries are automatically deleted when corresponding table
63116** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
63117** operations on this cursor can be no-ops and all READ operations can
63118** return a null row (2-bytes: 0x01 0x00).
63119**
63120** No checking is done to make sure that page iTable really is the
63121** root page of a b-tree.  If it is not, then the cursor acquired
63122** will not work correctly.
63123**
63124** It is assumed that the sqlite3BtreeCursorZero() has been called
63125** on pCur to initialize the memory space prior to invoking this routine.
63126*/
63127static int btreeCursor(
63128  Btree *p,                              /* The btree */
63129  int iTable,                            /* Root page of table to open */
63130  int wrFlag,                            /* 1 to write. 0 read-only */
63131  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
63132  BtCursor *pCur                         /* Space for new cursor */
63133){
63134  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
63135  BtCursor *pX;                          /* Looping over other all cursors */
63136
63137  assert( sqlite3BtreeHoldsMutex(p) );
63138  assert( wrFlag==0
63139       || wrFlag==BTREE_WRCSR
63140       || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
63141  );
63142
63143  /* The following assert statements verify that if this is a sharable
63144  ** b-tree database, the connection is holding the required table locks,
63145  ** and that no other connection has any open cursor that conflicts with
63146  ** this lock.  */
63147  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
63148  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
63149
63150  /* Assert that the caller has opened the required transaction. */
63151  assert( p->inTrans>TRANS_NONE );
63152  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
63153  assert( pBt->pPage1 && pBt->pPage1->aData );
63154  assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
63155
63156  if( wrFlag ){
63157    allocateTempSpace(pBt);
63158    if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
63159  }
63160  if( iTable==1 && btreePagecount(pBt)==0 ){
63161    assert( wrFlag==0 );
63162    iTable = 0;
63163  }
63164
63165  /* Now that no other errors can occur, finish filling in the BtCursor
63166  ** variables and link the cursor into the BtShared list.  */
63167  pCur->pgnoRoot = (Pgno)iTable;
63168  pCur->iPage = -1;
63169  pCur->pKeyInfo = pKeyInfo;
63170  pCur->pBtree = p;
63171  pCur->pBt = pBt;
63172  pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
63173  pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
63174  /* If there are two or more cursors on the same btree, then all such
63175  ** cursors *must* have the BTCF_Multiple flag set. */
63176  for(pX=pBt->pCursor; pX; pX=pX->pNext){
63177    if( pX->pgnoRoot==(Pgno)iTable ){
63178      pX->curFlags |= BTCF_Multiple;
63179      pCur->curFlags |= BTCF_Multiple;
63180    }
63181  }
63182  pCur->pNext = pBt->pCursor;
63183  pBt->pCursor = pCur;
63184  pCur->eState = CURSOR_INVALID;
63185  return SQLITE_OK;
63186}
63187SQLITE_PRIVATE int sqlite3BtreeCursor(
63188  Btree *p,                                   /* The btree */
63189  int iTable,                                 /* Root page of table to open */
63190  int wrFlag,                                 /* 1 to write. 0 read-only */
63191  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
63192  BtCursor *pCur                              /* Write new cursor here */
63193){
63194  int rc;
63195  if( iTable<1 ){
63196    rc = SQLITE_CORRUPT_BKPT;
63197  }else{
63198    sqlite3BtreeEnter(p);
63199    rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
63200    sqlite3BtreeLeave(p);
63201  }
63202  return rc;
63203}
63204
63205/*
63206** Return the size of a BtCursor object in bytes.
63207**
63208** This interfaces is needed so that users of cursors can preallocate
63209** sufficient storage to hold a cursor.  The BtCursor object is opaque
63210** to users so they cannot do the sizeof() themselves - they must call
63211** this routine.
63212*/
63213SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
63214  return ROUND8(sizeof(BtCursor));
63215}
63216
63217/*
63218** Initialize memory that will be converted into a BtCursor object.
63219**
63220** The simple approach here would be to memset() the entire object
63221** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
63222** do not need to be zeroed and they are large, so we can save a lot
63223** of run-time by skipping the initialization of those elements.
63224*/
63225SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
63226  memset(p, 0, offsetof(BtCursor, iPage));
63227}
63228
63229/*
63230** Close a cursor.  The read lock on the database file is released
63231** when the last cursor is closed.
63232*/
63233SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
63234  Btree *pBtree = pCur->pBtree;
63235  if( pBtree ){
63236    int i;
63237    BtShared *pBt = pCur->pBt;
63238    sqlite3BtreeEnter(pBtree);
63239    sqlite3BtreeClearCursor(pCur);
63240    assert( pBt->pCursor!=0 );
63241    if( pBt->pCursor==pCur ){
63242      pBt->pCursor = pCur->pNext;
63243    }else{
63244      BtCursor *pPrev = pBt->pCursor;
63245      do{
63246        if( pPrev->pNext==pCur ){
63247          pPrev->pNext = pCur->pNext;
63248          break;
63249        }
63250        pPrev = pPrev->pNext;
63251      }while( ALWAYS(pPrev) );
63252    }
63253    for(i=0; i<=pCur->iPage; i++){
63254      releasePage(pCur->apPage[i]);
63255    }
63256    unlockBtreeIfUnused(pBt);
63257    sqlite3_free(pCur->aOverflow);
63258    /* sqlite3_free(pCur); */
63259    sqlite3BtreeLeave(pBtree);
63260  }
63261  return SQLITE_OK;
63262}
63263
63264/*
63265** Make sure the BtCursor* given in the argument has a valid
63266** BtCursor.info structure.  If it is not already valid, call
63267** btreeParseCell() to fill it in.
63268**
63269** BtCursor.info is a cache of the information in the current cell.
63270** Using this cache reduces the number of calls to btreeParseCell().
63271*/
63272#ifndef NDEBUG
63273  static void assertCellInfo(BtCursor *pCur){
63274    CellInfo info;
63275    int iPage = pCur->iPage;
63276    memset(&info, 0, sizeof(info));
63277    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
63278    assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
63279  }
63280#else
63281  #define assertCellInfo(x)
63282#endif
63283static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
63284  if( pCur->info.nSize==0 ){
63285    int iPage = pCur->iPage;
63286    pCur->curFlags |= BTCF_ValidNKey;
63287    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
63288  }else{
63289    assertCellInfo(pCur);
63290  }
63291}
63292
63293#ifndef NDEBUG  /* The next routine used only within assert() statements */
63294/*
63295** Return true if the given BtCursor is valid.  A valid cursor is one
63296** that is currently pointing to a row in a (non-empty) table.
63297** This is a verification routine is used only within assert() statements.
63298*/
63299SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
63300  return pCur && pCur->eState==CURSOR_VALID;
63301}
63302#endif /* NDEBUG */
63303SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
63304  assert( pCur!=0 );
63305  return pCur->eState==CURSOR_VALID;
63306}
63307
63308/*
63309** Return the value of the integer key or "rowid" for a table btree.
63310** This routine is only valid for a cursor that is pointing into a
63311** ordinary table btree.  If the cursor points to an index btree or
63312** is invalid, the result of this routine is undefined.
63313*/
63314SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
63315  assert( cursorHoldsMutex(pCur) );
63316  assert( pCur->eState==CURSOR_VALID );
63317  assert( pCur->curIntKey );
63318  getCellInfo(pCur);
63319  return pCur->info.nKey;
63320}
63321
63322/*
63323** Return the number of bytes of payload for the entry that pCur is
63324** currently pointing to.  For table btrees, this will be the amount
63325** of data.  For index btrees, this will be the size of the key.
63326**
63327** The caller must guarantee that the cursor is pointing to a non-NULL
63328** valid entry.  In other words, the calling procedure must guarantee
63329** that the cursor has Cursor.eState==CURSOR_VALID.
63330*/
63331SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
63332  assert( cursorHoldsMutex(pCur) );
63333  assert( pCur->eState==CURSOR_VALID );
63334  getCellInfo(pCur);
63335  return pCur->info.nPayload;
63336}
63337
63338/*
63339** Given the page number of an overflow page in the database (parameter
63340** ovfl), this function finds the page number of the next page in the
63341** linked list of overflow pages. If possible, it uses the auto-vacuum
63342** pointer-map data instead of reading the content of page ovfl to do so.
63343**
63344** If an error occurs an SQLite error code is returned. Otherwise:
63345**
63346** The page number of the next overflow page in the linked list is
63347** written to *pPgnoNext. If page ovfl is the last page in its linked
63348** list, *pPgnoNext is set to zero.
63349**
63350** If ppPage is not NULL, and a reference to the MemPage object corresponding
63351** to page number pOvfl was obtained, then *ppPage is set to point to that
63352** reference. It is the responsibility of the caller to call releasePage()
63353** on *ppPage to free the reference. In no reference was obtained (because
63354** the pointer-map was used to obtain the value for *pPgnoNext), then
63355** *ppPage is set to zero.
63356*/
63357static int getOverflowPage(
63358  BtShared *pBt,               /* The database file */
63359  Pgno ovfl,                   /* Current overflow page number */
63360  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
63361  Pgno *pPgnoNext              /* OUT: Next overflow page number */
63362){
63363  Pgno next = 0;
63364  MemPage *pPage = 0;
63365  int rc = SQLITE_OK;
63366
63367  assert( sqlite3_mutex_held(pBt->mutex) );
63368  assert(pPgnoNext);
63369
63370#ifndef SQLITE_OMIT_AUTOVACUUM
63371  /* Try to find the next page in the overflow list using the
63372  ** autovacuum pointer-map pages. Guess that the next page in
63373  ** the overflow list is page number (ovfl+1). If that guess turns
63374  ** out to be wrong, fall back to loading the data of page
63375  ** number ovfl to determine the next page number.
63376  */
63377  if( pBt->autoVacuum ){
63378    Pgno pgno;
63379    Pgno iGuess = ovfl+1;
63380    u8 eType;
63381
63382    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
63383      iGuess++;
63384    }
63385
63386    if( iGuess<=btreePagecount(pBt) ){
63387      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
63388      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
63389        next = iGuess;
63390        rc = SQLITE_DONE;
63391      }
63392    }
63393  }
63394#endif
63395
63396  assert( next==0 || rc==SQLITE_DONE );
63397  if( rc==SQLITE_OK ){
63398    rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
63399    assert( rc==SQLITE_OK || pPage==0 );
63400    if( rc==SQLITE_OK ){
63401      next = get4byte(pPage->aData);
63402    }
63403  }
63404
63405  *pPgnoNext = next;
63406  if( ppPage ){
63407    *ppPage = pPage;
63408  }else{
63409    releasePage(pPage);
63410  }
63411  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
63412}
63413
63414/*
63415** Copy data from a buffer to a page, or from a page to a buffer.
63416**
63417** pPayload is a pointer to data stored on database page pDbPage.
63418** If argument eOp is false, then nByte bytes of data are copied
63419** from pPayload to the buffer pointed at by pBuf. If eOp is true,
63420** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
63421** of data are copied from the buffer pBuf to pPayload.
63422**
63423** SQLITE_OK is returned on success, otherwise an error code.
63424*/
63425static int copyPayload(
63426  void *pPayload,           /* Pointer to page data */
63427  void *pBuf,               /* Pointer to buffer */
63428  int nByte,                /* Number of bytes to copy */
63429  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
63430  DbPage *pDbPage           /* Page containing pPayload */
63431){
63432  if( eOp ){
63433    /* Copy data from buffer to page (a write operation) */
63434    int rc = sqlite3PagerWrite(pDbPage);
63435    if( rc!=SQLITE_OK ){
63436      return rc;
63437    }
63438    memcpy(pPayload, pBuf, nByte);
63439  }else{
63440    /* Copy data from page to buffer (a read operation) */
63441    memcpy(pBuf, pPayload, nByte);
63442  }
63443  return SQLITE_OK;
63444}
63445
63446/*
63447** This function is used to read or overwrite payload information
63448** for the entry that the pCur cursor is pointing to. The eOp
63449** argument is interpreted as follows:
63450**
63451**   0: The operation is a read. Populate the overflow cache.
63452**   1: The operation is a write. Populate the overflow cache.
63453**
63454** A total of "amt" bytes are read or written beginning at "offset".
63455** Data is read to or from the buffer pBuf.
63456**
63457** The content being read or written might appear on the main page
63458** or be scattered out on multiple overflow pages.
63459**
63460** If the current cursor entry uses one or more overflow pages
63461** this function may allocate space for and lazily populate
63462** the overflow page-list cache array (BtCursor.aOverflow).
63463** Subsequent calls use this cache to make seeking to the supplied offset
63464** more efficient.
63465**
63466** Once an overflow page-list cache has been allocated, it must be
63467** invalidated if some other cursor writes to the same table, or if
63468** the cursor is moved to a different row. Additionally, in auto-vacuum
63469** mode, the following events may invalidate an overflow page-list cache.
63470**
63471**   * An incremental vacuum,
63472**   * A commit in auto_vacuum="full" mode,
63473**   * Creating a table (may require moving an overflow page).
63474*/
63475static int accessPayload(
63476  BtCursor *pCur,      /* Cursor pointing to entry to read from */
63477  u32 offset,          /* Begin reading this far into payload */
63478  u32 amt,             /* Read this many bytes */
63479  unsigned char *pBuf, /* Write the bytes into this buffer */
63480  int eOp              /* zero to read. non-zero to write. */
63481){
63482  unsigned char *aPayload;
63483  int rc = SQLITE_OK;
63484  int iIdx = 0;
63485  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
63486  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
63487#ifdef SQLITE_DIRECT_OVERFLOW_READ
63488  unsigned char * const pBufStart = pBuf;     /* Start of original out buffer */
63489#endif
63490
63491  assert( pPage );
63492  assert( eOp==0 || eOp==1 );
63493  assert( pCur->eState==CURSOR_VALID );
63494  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
63495  assert( cursorHoldsMutex(pCur) );
63496
63497  getCellInfo(pCur);
63498  aPayload = pCur->info.pPayload;
63499  assert( offset+amt <= pCur->info.nPayload );
63500
63501  assert( aPayload > pPage->aData );
63502  if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
63503    /* Trying to read or write past the end of the data is an error.  The
63504    ** conditional above is really:
63505    **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
63506    ** but is recast into its current form to avoid integer overflow problems
63507    */
63508    return SQLITE_CORRUPT_BKPT;
63509  }
63510
63511  /* Check if data must be read/written to/from the btree page itself. */
63512  if( offset<pCur->info.nLocal ){
63513    int a = amt;
63514    if( a+offset>pCur->info.nLocal ){
63515      a = pCur->info.nLocal - offset;
63516    }
63517    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
63518    offset = 0;
63519    pBuf += a;
63520    amt -= a;
63521  }else{
63522    offset -= pCur->info.nLocal;
63523  }
63524
63525
63526  if( rc==SQLITE_OK && amt>0 ){
63527    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
63528    Pgno nextPage;
63529
63530    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
63531
63532    /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
63533    **
63534    ** The aOverflow[] array is sized at one entry for each overflow page
63535    ** in the overflow chain. The page number of the first overflow page is
63536    ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
63537    ** means "not yet known" (the cache is lazily populated).
63538    */
63539    if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
63540      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
63541      if( nOvfl>pCur->nOvflAlloc ){
63542        Pgno *aNew = (Pgno*)sqlite3Realloc(
63543            pCur->aOverflow, nOvfl*2*sizeof(Pgno)
63544        );
63545        if( aNew==0 ){
63546          return SQLITE_NOMEM_BKPT;
63547        }else{
63548          pCur->nOvflAlloc = nOvfl*2;
63549          pCur->aOverflow = aNew;
63550        }
63551      }
63552      memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
63553      pCur->curFlags |= BTCF_ValidOvfl;
63554    }else{
63555      /* If the overflow page-list cache has been allocated and the
63556      ** entry for the first required overflow page is valid, skip
63557      ** directly to it.
63558      */
63559      if( pCur->aOverflow[offset/ovflSize] ){
63560        iIdx = (offset/ovflSize);
63561        nextPage = pCur->aOverflow[iIdx];
63562        offset = (offset%ovflSize);
63563      }
63564    }
63565
63566    assert( rc==SQLITE_OK && amt>0 );
63567    while( nextPage ){
63568      /* If required, populate the overflow page-list cache. */
63569      assert( pCur->aOverflow[iIdx]==0
63570              || pCur->aOverflow[iIdx]==nextPage
63571              || CORRUPT_DB );
63572      pCur->aOverflow[iIdx] = nextPage;
63573
63574      if( offset>=ovflSize ){
63575        /* The only reason to read this page is to obtain the page
63576        ** number for the next page in the overflow chain. The page
63577        ** data is not required. So first try to lookup the overflow
63578        ** page-list cache, if any, then fall back to the getOverflowPage()
63579        ** function.
63580        */
63581        assert( pCur->curFlags & BTCF_ValidOvfl );
63582        assert( pCur->pBtree->db==pBt->db );
63583        if( pCur->aOverflow[iIdx+1] ){
63584          nextPage = pCur->aOverflow[iIdx+1];
63585        }else{
63586          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
63587        }
63588        offset -= ovflSize;
63589      }else{
63590        /* Need to read this page properly. It contains some of the
63591        ** range of data that is being read (eOp==0) or written (eOp!=0).
63592        */
63593#ifdef SQLITE_DIRECT_OVERFLOW_READ
63594        sqlite3_file *fd;      /* File from which to do direct overflow read */
63595#endif
63596        int a = amt;
63597        if( a + offset > ovflSize ){
63598          a = ovflSize - offset;
63599        }
63600
63601#ifdef SQLITE_DIRECT_OVERFLOW_READ
63602        /* If all the following are true:
63603        **
63604        **   1) this is a read operation, and
63605        **   2) data is required from the start of this overflow page, and
63606        **   3) there is no open write-transaction, and
63607        **   4) the database is file-backed, and
63608        **   5) the page is not in the WAL file
63609        **   6) at least 4 bytes have already been read into the output buffer
63610        **
63611        ** then data can be read directly from the database file into the
63612        ** output buffer, bypassing the page-cache altogether. This speeds
63613        ** up loading large records that span many overflow pages.
63614        */
63615        if( eOp==0                                             /* (1) */
63616         && offset==0                                          /* (2) */
63617         && pBt->inTransaction==TRANS_READ                     /* (3) */
63618         && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (4) */
63619         && 0==sqlite3PagerUseWal(pBt->pPager, nextPage)       /* (5) */
63620         && &pBuf[-4]>=pBufStart                               /* (6) */
63621        ){
63622          u8 aSave[4];
63623          u8 *aWrite = &pBuf[-4];
63624          assert( aWrite>=pBufStart );                         /* due to (6) */
63625          memcpy(aSave, aWrite, 4);
63626          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
63627          nextPage = get4byte(aWrite);
63628          memcpy(aWrite, aSave, 4);
63629        }else
63630#endif
63631
63632        {
63633          DbPage *pDbPage;
63634          rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
63635              (eOp==0 ? PAGER_GET_READONLY : 0)
63636          );
63637          if( rc==SQLITE_OK ){
63638            aPayload = sqlite3PagerGetData(pDbPage);
63639            nextPage = get4byte(aPayload);
63640            rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
63641            sqlite3PagerUnref(pDbPage);
63642            offset = 0;
63643          }
63644        }
63645        amt -= a;
63646        if( amt==0 ) return rc;
63647        pBuf += a;
63648      }
63649      if( rc ) break;
63650      iIdx++;
63651    }
63652  }
63653
63654  if( rc==SQLITE_OK && amt>0 ){
63655    return SQLITE_CORRUPT_BKPT; /* Overflow chain ends prematurely */
63656  }
63657  return rc;
63658}
63659
63660/*
63661** Read part of the payload for the row at which that cursor pCur is currently
63662** pointing.  "amt" bytes will be transferred into pBuf[].  The transfer
63663** begins at "offset".
63664**
63665** pCur can be pointing to either a table or an index b-tree.
63666** If pointing to a table btree, then the content section is read.  If
63667** pCur is pointing to an index b-tree then the key section is read.
63668**
63669** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
63670** to a valid row in the table.  For sqlite3BtreePayloadChecked(), the
63671** cursor might be invalid or might need to be restored before being read.
63672**
63673** Return SQLITE_OK on success or an error code if anything goes
63674** wrong.  An error is returned if "offset+amt" is larger than
63675** the available payload.
63676*/
63677SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
63678  assert( cursorHoldsMutex(pCur) );
63679  assert( pCur->eState==CURSOR_VALID );
63680  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
63681  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
63682  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
63683}
63684
63685/*
63686** This variant of sqlite3BtreePayload() works even if the cursor has not
63687** in the CURSOR_VALID state.  It is only used by the sqlite3_blob_read()
63688** interface.
63689*/
63690#ifndef SQLITE_OMIT_INCRBLOB
63691static SQLITE_NOINLINE int accessPayloadChecked(
63692  BtCursor *pCur,
63693  u32 offset,
63694  u32 amt,
63695  void *pBuf
63696){
63697  int rc;
63698  if ( pCur->eState==CURSOR_INVALID ){
63699    return SQLITE_ABORT;
63700  }
63701  assert( cursorOwnsBtShared(pCur) );
63702  rc = btreeRestoreCursorPosition(pCur);
63703  return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
63704}
63705SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
63706  if( pCur->eState==CURSOR_VALID ){
63707    assert( cursorOwnsBtShared(pCur) );
63708    return accessPayload(pCur, offset, amt, pBuf, 0);
63709  }else{
63710    return accessPayloadChecked(pCur, offset, amt, pBuf);
63711  }
63712}
63713#endif /* SQLITE_OMIT_INCRBLOB */
63714
63715/*
63716** Return a pointer to payload information from the entry that the
63717** pCur cursor is pointing to.  The pointer is to the beginning of
63718** the key if index btrees (pPage->intKey==0) and is the data for
63719** table btrees (pPage->intKey==1). The number of bytes of available
63720** key/data is written into *pAmt.  If *pAmt==0, then the value
63721** returned will not be a valid pointer.
63722**
63723** This routine is an optimization.  It is common for the entire key
63724** and data to fit on the local page and for there to be no overflow
63725** pages.  When that is so, this routine can be used to access the
63726** key and data without making a copy.  If the key and/or data spills
63727** onto overflow pages, then accessPayload() must be used to reassemble
63728** the key/data and copy it into a preallocated buffer.
63729**
63730** The pointer returned by this routine looks directly into the cached
63731** page of the database.  The data might change or move the next time
63732** any btree routine is called.
63733*/
63734static const void *fetchPayload(
63735  BtCursor *pCur,      /* Cursor pointing to entry to read from */
63736  u32 *pAmt            /* Write the number of available bytes here */
63737){
63738  u32 amt;
63739  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
63740  assert( pCur->eState==CURSOR_VALID );
63741  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63742  assert( cursorOwnsBtShared(pCur) );
63743  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
63744  assert( pCur->info.nSize>0 );
63745  assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
63746  assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
63747  amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
63748  if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
63749  *pAmt = amt;
63750  return (void*)pCur->info.pPayload;
63751}
63752
63753
63754/*
63755** For the entry that cursor pCur is point to, return as
63756** many bytes of the key or data as are available on the local
63757** b-tree page.  Write the number of available bytes into *pAmt.
63758**
63759** The pointer returned is ephemeral.  The key/data may move
63760** or be destroyed on the next call to any Btree routine,
63761** including calls from other threads against the same cache.
63762** Hence, a mutex on the BtShared should be held prior to calling
63763** this routine.
63764**
63765** These routines is used to get quick access to key and data
63766** in the common case where no overflow pages are used.
63767*/
63768SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
63769  return fetchPayload(pCur, pAmt);
63770}
63771
63772
63773/*
63774** Move the cursor down to a new child page.  The newPgno argument is the
63775** page number of the child page to move to.
63776**
63777** This function returns SQLITE_CORRUPT if the page-header flags field of
63778** the new child page does not match the flags field of the parent (i.e.
63779** if an intkey page appears to be the parent of a non-intkey page, or
63780** vice-versa).
63781*/
63782static int moveToChild(BtCursor *pCur, u32 newPgno){
63783  BtShared *pBt = pCur->pBt;
63784
63785  assert( cursorOwnsBtShared(pCur) );
63786  assert( pCur->eState==CURSOR_VALID );
63787  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
63788  assert( pCur->iPage>=0 );
63789  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
63790    return SQLITE_CORRUPT_BKPT;
63791  }
63792  pCur->info.nSize = 0;
63793  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
63794  pCur->iPage++;
63795  pCur->aiIdx[pCur->iPage] = 0;
63796  return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
63797                        pCur, pCur->curPagerFlags);
63798}
63799
63800#ifdef SQLITE_DEBUG
63801/*
63802** Page pParent is an internal (non-leaf) tree page. This function
63803** asserts that page number iChild is the left-child if the iIdx'th
63804** cell in page pParent. Or, if iIdx is equal to the total number of
63805** cells in pParent, that page number iChild is the right-child of
63806** the page.
63807*/
63808static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
63809  if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
63810                            ** in a corrupt database */
63811  assert( iIdx<=pParent->nCell );
63812  if( iIdx==pParent->nCell ){
63813    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
63814  }else{
63815    assert( get4byte(findCell(pParent, iIdx))==iChild );
63816  }
63817}
63818#else
63819#  define assertParentIndex(x,y,z)
63820#endif
63821
63822/*
63823** Move the cursor up to the parent page.
63824**
63825** pCur->idx is set to the cell index that contains the pointer
63826** to the page we are coming from.  If we are coming from the
63827** right-most child page then pCur->idx is set to one more than
63828** the largest cell index.
63829*/
63830static void moveToParent(BtCursor *pCur){
63831  assert( cursorOwnsBtShared(pCur) );
63832  assert( pCur->eState==CURSOR_VALID );
63833  assert( pCur->iPage>0 );
63834  assert( pCur->apPage[pCur->iPage] );
63835  assertParentIndex(
63836    pCur->apPage[pCur->iPage-1],
63837    pCur->aiIdx[pCur->iPage-1],
63838    pCur->apPage[pCur->iPage]->pgno
63839  );
63840  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
63841  pCur->info.nSize = 0;
63842  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
63843  releasePageNotNull(pCur->apPage[pCur->iPage--]);
63844}
63845
63846/*
63847** Move the cursor to point to the root page of its b-tree structure.
63848**
63849** If the table has a virtual root page, then the cursor is moved to point
63850** to the virtual root page instead of the actual root page. A table has a
63851** virtual root page when the actual root page contains no cells and a
63852** single child page. This can only happen with the table rooted at page 1.
63853**
63854** If the b-tree structure is empty, the cursor state is set to
63855** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
63856** cell located on the root (or virtual root) page and the cursor state
63857** is set to CURSOR_VALID.
63858**
63859** If this function returns successfully, it may be assumed that the
63860** page-header flags indicate that the [virtual] root-page is the expected
63861** kind of b-tree page (i.e. if when opening the cursor the caller did not
63862** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
63863** indicating a table b-tree, or if the caller did specify a KeyInfo
63864** structure the flags byte is set to 0x02 or 0x0A, indicating an index
63865** b-tree).
63866*/
63867static int moveToRoot(BtCursor *pCur){
63868  MemPage *pRoot;
63869  int rc = SQLITE_OK;
63870
63871  assert( cursorOwnsBtShared(pCur) );
63872  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
63873  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
63874  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
63875  if( pCur->eState>=CURSOR_REQUIRESEEK ){
63876    if( pCur->eState==CURSOR_FAULT ){
63877      assert( pCur->skipNext!=SQLITE_OK );
63878      return pCur->skipNext;
63879    }
63880    sqlite3BtreeClearCursor(pCur);
63881  }
63882
63883  if( pCur->iPage>=0 ){
63884    if( pCur->iPage ){
63885      do{
63886        assert( pCur->apPage[pCur->iPage]!=0 );
63887        releasePageNotNull(pCur->apPage[pCur->iPage--]);
63888      }while( pCur->iPage);
63889      goto skip_init;
63890    }
63891  }else if( pCur->pgnoRoot==0 ){
63892    pCur->eState = CURSOR_INVALID;
63893    return SQLITE_OK;
63894  }else{
63895    assert( pCur->iPage==(-1) );
63896    rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
63897                        0, pCur->curPagerFlags);
63898    if( rc!=SQLITE_OK ){
63899      pCur->eState = CURSOR_INVALID;
63900       return rc;
63901    }
63902    pCur->iPage = 0;
63903    pCur->curIntKey = pCur->apPage[0]->intKey;
63904  }
63905  pRoot = pCur->apPage[0];
63906  assert( pRoot->pgno==pCur->pgnoRoot );
63907
63908  /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
63909  ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
63910  ** NULL, the caller expects a table b-tree. If this is not the case,
63911  ** return an SQLITE_CORRUPT error.
63912  **
63913  ** Earlier versions of SQLite assumed that this test could not fail
63914  ** if the root page was already loaded when this function was called (i.e.
63915  ** if pCur->iPage>=0). But this is not so if the database is corrupted
63916  ** in such a way that page pRoot is linked into a second b-tree table
63917  ** (or the freelist).  */
63918  assert( pRoot->intKey==1 || pRoot->intKey==0 );
63919  if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
63920    return SQLITE_CORRUPT_BKPT;
63921  }
63922
63923skip_init:
63924  pCur->aiIdx[0] = 0;
63925  pCur->info.nSize = 0;
63926  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
63927
63928  pRoot = pCur->apPage[0];
63929  if( pRoot->nCell>0 ){
63930    pCur->eState = CURSOR_VALID;
63931  }else if( !pRoot->leaf ){
63932    Pgno subpage;
63933    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
63934    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
63935    pCur->eState = CURSOR_VALID;
63936    rc = moveToChild(pCur, subpage);
63937  }else{
63938    pCur->eState = CURSOR_INVALID;
63939  }
63940  return rc;
63941}
63942
63943/*
63944** Move the cursor down to the left-most leaf entry beneath the
63945** entry to which it is currently pointing.
63946**
63947** The left-most leaf is the one with the smallest key - the first
63948** in ascending order.
63949*/
63950static int moveToLeftmost(BtCursor *pCur){
63951  Pgno pgno;
63952  int rc = SQLITE_OK;
63953  MemPage *pPage;
63954
63955  assert( cursorOwnsBtShared(pCur) );
63956  assert( pCur->eState==CURSOR_VALID );
63957  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
63958    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
63959    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
63960    rc = moveToChild(pCur, pgno);
63961  }
63962  return rc;
63963}
63964
63965/*
63966** Move the cursor down to the right-most leaf entry beneath the
63967** page to which it is currently pointing.  Notice the difference
63968** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
63969** finds the left-most entry beneath the *entry* whereas moveToRightmost()
63970** finds the right-most entry beneath the *page*.
63971**
63972** The right-most entry is the one with the largest key - the last
63973** key in ascending order.
63974*/
63975static int moveToRightmost(BtCursor *pCur){
63976  Pgno pgno;
63977  int rc = SQLITE_OK;
63978  MemPage *pPage = 0;
63979
63980  assert( cursorOwnsBtShared(pCur) );
63981  assert( pCur->eState==CURSOR_VALID );
63982  while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
63983    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
63984    pCur->aiIdx[pCur->iPage] = pPage->nCell;
63985    rc = moveToChild(pCur, pgno);
63986    if( rc ) return rc;
63987  }
63988  pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
63989  assert( pCur->info.nSize==0 );
63990  assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
63991  return SQLITE_OK;
63992}
63993
63994/* Move the cursor to the first entry in the table.  Return SQLITE_OK
63995** on success.  Set *pRes to 0 if the cursor actually points to something
63996** or set *pRes to 1 if the table is empty.
63997*/
63998SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
63999  int rc;
64000
64001  assert( cursorOwnsBtShared(pCur) );
64002  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
64003  rc = moveToRoot(pCur);
64004  if( rc==SQLITE_OK ){
64005    if( pCur->eState==CURSOR_INVALID ){
64006      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
64007      *pRes = 1;
64008    }else{
64009      assert( pCur->apPage[pCur->iPage]->nCell>0 );
64010      *pRes = 0;
64011      rc = moveToLeftmost(pCur);
64012    }
64013  }
64014  return rc;
64015}
64016
64017/* Move the cursor to the last entry in the table.  Return SQLITE_OK
64018** on success.  Set *pRes to 0 if the cursor actually points to something
64019** or set *pRes to 1 if the table is empty.
64020*/
64021SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
64022  int rc;
64023
64024  assert( cursorOwnsBtShared(pCur) );
64025  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
64026
64027  /* If the cursor already points to the last entry, this is a no-op. */
64028  if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
64029#ifdef SQLITE_DEBUG
64030    /* This block serves to assert() that the cursor really does point
64031    ** to the last entry in the b-tree. */
64032    int ii;
64033    for(ii=0; ii<pCur->iPage; ii++){
64034      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
64035    }
64036    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
64037    assert( pCur->apPage[pCur->iPage]->leaf );
64038#endif
64039    return SQLITE_OK;
64040  }
64041
64042  rc = moveToRoot(pCur);
64043  if( rc==SQLITE_OK ){
64044    if( CURSOR_INVALID==pCur->eState ){
64045      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
64046      *pRes = 1;
64047    }else{
64048      assert( pCur->eState==CURSOR_VALID );
64049      *pRes = 0;
64050      rc = moveToRightmost(pCur);
64051      if( rc==SQLITE_OK ){
64052        pCur->curFlags |= BTCF_AtLast;
64053      }else{
64054        pCur->curFlags &= ~BTCF_AtLast;
64055      }
64056
64057    }
64058  }
64059  return rc;
64060}
64061
64062/* Move the cursor so that it points to an entry near the key
64063** specified by pIdxKey or intKey.   Return a success code.
64064**
64065** For INTKEY tables, the intKey parameter is used.  pIdxKey
64066** must be NULL.  For index tables, pIdxKey is used and intKey
64067** is ignored.
64068**
64069** If an exact match is not found, then the cursor is always
64070** left pointing at a leaf page which would hold the entry if it
64071** were present.  The cursor might point to an entry that comes
64072** before or after the key.
64073**
64074** An integer is written into *pRes which is the result of
64075** comparing the key with the entry to which the cursor is
64076** pointing.  The meaning of the integer written into
64077** *pRes is as follows:
64078**
64079**     *pRes<0      The cursor is left pointing at an entry that
64080**                  is smaller than intKey/pIdxKey or if the table is empty
64081**                  and the cursor is therefore left point to nothing.
64082**
64083**     *pRes==0     The cursor is left pointing at an entry that
64084**                  exactly matches intKey/pIdxKey.
64085**
64086**     *pRes>0      The cursor is left pointing at an entry that
64087**                  is larger than intKey/pIdxKey.
64088**
64089** For index tables, the pIdxKey->eqSeen field is set to 1 if there
64090** exists an entry in the table that exactly matches pIdxKey.
64091*/
64092SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
64093  BtCursor *pCur,          /* The cursor to be moved */
64094  UnpackedRecord *pIdxKey, /* Unpacked index key */
64095  i64 intKey,              /* The table key */
64096  int biasRight,           /* If true, bias the search to the high end */
64097  int *pRes                /* Write search results here */
64098){
64099  int rc;
64100  RecordCompare xRecordCompare;
64101
64102  assert( cursorOwnsBtShared(pCur) );
64103  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
64104  assert( pRes );
64105  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
64106  assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
64107
64108  /* If the cursor is already positioned at the point we are trying
64109  ** to move to, then just return without doing any work */
64110  if( pIdxKey==0
64111   && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
64112  ){
64113    if( pCur->info.nKey==intKey ){
64114      *pRes = 0;
64115      return SQLITE_OK;
64116    }
64117    if( pCur->info.nKey<intKey ){
64118      if( (pCur->curFlags & BTCF_AtLast)!=0 ){
64119        *pRes = -1;
64120        return SQLITE_OK;
64121      }
64122      /* If the requested key is one more than the previous key, then
64123      ** try to get there using sqlite3BtreeNext() rather than a full
64124      ** binary search.  This is an optimization only.  The correct answer
64125      ** is still obtained without this ase, only a little more slowely */
64126      if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
64127        *pRes = 0;
64128        rc = sqlite3BtreeNext(pCur, pRes);
64129        if( rc ) return rc;
64130        if( *pRes==0 ){
64131          getCellInfo(pCur);
64132          if( pCur->info.nKey==intKey ){
64133            return SQLITE_OK;
64134          }
64135        }
64136      }
64137    }
64138  }
64139
64140  if( pIdxKey ){
64141    xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
64142    pIdxKey->errCode = 0;
64143    assert( pIdxKey->default_rc==1
64144         || pIdxKey->default_rc==0
64145         || pIdxKey->default_rc==-1
64146    );
64147  }else{
64148    xRecordCompare = 0; /* All keys are integers */
64149  }
64150
64151  rc = moveToRoot(pCur);
64152  if( rc ){
64153    return rc;
64154  }
64155  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
64156  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
64157  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
64158  if( pCur->eState==CURSOR_INVALID ){
64159    *pRes = -1;
64160    assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
64161    return SQLITE_OK;
64162  }
64163  assert( pCur->apPage[0]->intKey==pCur->curIntKey );
64164  assert( pCur->curIntKey || pIdxKey );
64165  for(;;){
64166    int lwr, upr, idx, c;
64167    Pgno chldPg;
64168    MemPage *pPage = pCur->apPage[pCur->iPage];
64169    u8 *pCell;                          /* Pointer to current cell in pPage */
64170
64171    /* pPage->nCell must be greater than zero. If this is the root-page
64172    ** the cursor would have been INVALID above and this for(;;) loop
64173    ** not run. If this is not the root-page, then the moveToChild() routine
64174    ** would have already detected db corruption. Similarly, pPage must
64175    ** be the right kind (index or table) of b-tree page. Otherwise
64176    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
64177    assert( pPage->nCell>0 );
64178    assert( pPage->intKey==(pIdxKey==0) );
64179    lwr = 0;
64180    upr = pPage->nCell-1;
64181    assert( biasRight==0 || biasRight==1 );
64182    idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
64183    pCur->aiIdx[pCur->iPage] = (u16)idx;
64184    if( xRecordCompare==0 ){
64185      for(;;){
64186        i64 nCellKey;
64187        pCell = findCellPastPtr(pPage, idx);
64188        if( pPage->intKeyLeaf ){
64189          while( 0x80 <= *(pCell++) ){
64190            if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
64191          }
64192        }
64193        getVarint(pCell, (u64*)&nCellKey);
64194        if( nCellKey<intKey ){
64195          lwr = idx+1;
64196          if( lwr>upr ){ c = -1; break; }
64197        }else if( nCellKey>intKey ){
64198          upr = idx-1;
64199          if( lwr>upr ){ c = +1; break; }
64200        }else{
64201          assert( nCellKey==intKey );
64202          pCur->aiIdx[pCur->iPage] = (u16)idx;
64203          if( !pPage->leaf ){
64204            lwr = idx;
64205            goto moveto_next_layer;
64206          }else{
64207            pCur->curFlags |= BTCF_ValidNKey;
64208            pCur->info.nKey = nCellKey;
64209            pCur->info.nSize = 0;
64210            *pRes = 0;
64211            return SQLITE_OK;
64212          }
64213        }
64214        assert( lwr+upr>=0 );
64215        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
64216      }
64217    }else{
64218      for(;;){
64219        int nCell;  /* Size of the pCell cell in bytes */
64220        pCell = findCellPastPtr(pPage, idx);
64221
64222        /* The maximum supported page-size is 65536 bytes. This means that
64223        ** the maximum number of record bytes stored on an index B-Tree
64224        ** page is less than 16384 bytes and may be stored as a 2-byte
64225        ** varint. This information is used to attempt to avoid parsing
64226        ** the entire cell by checking for the cases where the record is
64227        ** stored entirely within the b-tree page by inspecting the first
64228        ** 2 bytes of the cell.
64229        */
64230        nCell = pCell[0];
64231        if( nCell<=pPage->max1bytePayload ){
64232          /* This branch runs if the record-size field of the cell is a
64233          ** single byte varint and the record fits entirely on the main
64234          ** b-tree page.  */
64235          testcase( pCell+nCell+1==pPage->aDataEnd );
64236          c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
64237        }else if( !(pCell[1] & 0x80)
64238          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
64239        ){
64240          /* The record-size field is a 2 byte varint and the record
64241          ** fits entirely on the main b-tree page.  */
64242          testcase( pCell+nCell+2==pPage->aDataEnd );
64243          c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
64244        }else{
64245          /* The record flows over onto one or more overflow pages. In
64246          ** this case the whole cell needs to be parsed, a buffer allocated
64247          ** and accessPayload() used to retrieve the record into the
64248          ** buffer before VdbeRecordCompare() can be called.
64249          **
64250          ** If the record is corrupt, the xRecordCompare routine may read
64251          ** up to two varints past the end of the buffer. An extra 18
64252          ** bytes of padding is allocated at the end of the buffer in
64253          ** case this happens.  */
64254          void *pCellKey;
64255          u8 * const pCellBody = pCell - pPage->childPtrSize;
64256          pPage->xParseCell(pPage, pCellBody, &pCur->info);
64257          nCell = (int)pCur->info.nKey;
64258          testcase( nCell<0 );   /* True if key size is 2^32 or more */
64259          testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
64260          testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
64261          testcase( nCell==2 );  /* Minimum legal index key size */
64262          if( nCell<2 ){
64263            rc = SQLITE_CORRUPT_BKPT;
64264            goto moveto_finish;
64265          }
64266          pCellKey = sqlite3Malloc( nCell+18 );
64267          if( pCellKey==0 ){
64268            rc = SQLITE_NOMEM_BKPT;
64269            goto moveto_finish;
64270          }
64271          pCur->aiIdx[pCur->iPage] = (u16)idx;
64272          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
64273          pCur->curFlags &= ~BTCF_ValidOvfl;
64274          if( rc ){
64275            sqlite3_free(pCellKey);
64276            goto moveto_finish;
64277          }
64278          c = xRecordCompare(nCell, pCellKey, pIdxKey);
64279          sqlite3_free(pCellKey);
64280        }
64281        assert(
64282            (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
64283         && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
64284        );
64285        if( c<0 ){
64286          lwr = idx+1;
64287        }else if( c>0 ){
64288          upr = idx-1;
64289        }else{
64290          assert( c==0 );
64291          *pRes = 0;
64292          rc = SQLITE_OK;
64293          pCur->aiIdx[pCur->iPage] = (u16)idx;
64294          if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
64295          goto moveto_finish;
64296        }
64297        if( lwr>upr ) break;
64298        assert( lwr+upr>=0 );
64299        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
64300      }
64301    }
64302    assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
64303    assert( pPage->isInit );
64304    if( pPage->leaf ){
64305      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
64306      pCur->aiIdx[pCur->iPage] = (u16)idx;
64307      *pRes = c;
64308      rc = SQLITE_OK;
64309      goto moveto_finish;
64310    }
64311moveto_next_layer:
64312    if( lwr>=pPage->nCell ){
64313      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
64314    }else{
64315      chldPg = get4byte(findCell(pPage, lwr));
64316    }
64317    pCur->aiIdx[pCur->iPage] = (u16)lwr;
64318    rc = moveToChild(pCur, chldPg);
64319    if( rc ) break;
64320  }
64321moveto_finish:
64322  pCur->info.nSize = 0;
64323  assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
64324  return rc;
64325}
64326
64327
64328/*
64329** Return TRUE if the cursor is not pointing at an entry of the table.
64330**
64331** TRUE will be returned after a call to sqlite3BtreeNext() moves
64332** past the last entry in the table or sqlite3BtreePrev() moves past
64333** the first entry.  TRUE is also returned if the table is empty.
64334*/
64335SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
64336  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
64337  ** have been deleted? This API will need to change to return an error code
64338  ** as well as the boolean result value.
64339  */
64340  return (CURSOR_VALID!=pCur->eState);
64341}
64342
64343/*
64344** Return an estimate for the number of rows in the table that pCur is
64345** pointing to.  Return a negative number if no estimate is currently
64346** available.
64347*/
64348SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
64349  i64 n;
64350  u8 i;
64351
64352  assert( cursorOwnsBtShared(pCur) );
64353  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
64354
64355  /* Currently this interface is only called by the OP_IfSmaller
64356  ** opcode, and it that case the cursor will always be valid and
64357  ** will always point to a leaf node. */
64358  if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
64359  if( NEVER(pCur->apPage[pCur->iPage]->leaf==0) ) return -1;
64360
64361  for(n=1, i=0; i<=pCur->iPage; i++){
64362    n *= pCur->apPage[i]->nCell;
64363  }
64364  return n;
64365}
64366
64367/*
64368** Advance the cursor to the next entry in the database.  If
64369** successful then set *pRes=0.  If the cursor
64370** was already pointing to the last entry in the database before
64371** this routine was called, then set *pRes=1.
64372**
64373** The main entry point is sqlite3BtreeNext().  That routine is optimized
64374** for the common case of merely incrementing the cell counter BtCursor.aiIdx
64375** to the next cell on the current page.  The (slower) btreeNext() helper
64376** routine is called when it is necessary to move to a different page or
64377** to restore the cursor.
64378**
64379** The calling function will set *pRes to 0 or 1.  The initial *pRes value
64380** will be 1 if the cursor being stepped corresponds to an SQL index and
64381** if this routine could have been skipped if that SQL index had been
64382** a unique index.  Otherwise the caller will have set *pRes to zero.
64383** Zero is the common case. The btree implementation is free to use the
64384** initial *pRes value as a hint to improve performance, but the current
64385** SQLite btree implementation does not. (Note that the comdb2 btree
64386** implementation does use this hint, however.)
64387*/
64388static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
64389  int rc;
64390  int idx;
64391  MemPage *pPage;
64392
64393  assert( cursorOwnsBtShared(pCur) );
64394  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
64395  assert( *pRes==0 );
64396  if( pCur->eState!=CURSOR_VALID ){
64397    assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
64398    rc = restoreCursorPosition(pCur);
64399    if( rc!=SQLITE_OK ){
64400      return rc;
64401    }
64402    if( CURSOR_INVALID==pCur->eState ){
64403      *pRes = 1;
64404      return SQLITE_OK;
64405    }
64406    if( pCur->skipNext ){
64407      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
64408      pCur->eState = CURSOR_VALID;
64409      if( pCur->skipNext>0 ){
64410        pCur->skipNext = 0;
64411        return SQLITE_OK;
64412      }
64413      pCur->skipNext = 0;
64414    }
64415  }
64416
64417  pPage = pCur->apPage[pCur->iPage];
64418  idx = ++pCur->aiIdx[pCur->iPage];
64419  assert( pPage->isInit );
64420
64421  /* If the database file is corrupt, it is possible for the value of idx
64422  ** to be invalid here. This can only occur if a second cursor modifies
64423  ** the page while cursor pCur is holding a reference to it. Which can
64424  ** only happen if the database is corrupt in such a way as to link the
64425  ** page into more than one b-tree structure. */
64426  testcase( idx>pPage->nCell );
64427
64428  if( idx>=pPage->nCell ){
64429    if( !pPage->leaf ){
64430      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
64431      if( rc ) return rc;
64432      return moveToLeftmost(pCur);
64433    }
64434    do{
64435      if( pCur->iPage==0 ){
64436        *pRes = 1;
64437        pCur->eState = CURSOR_INVALID;
64438        return SQLITE_OK;
64439      }
64440      moveToParent(pCur);
64441      pPage = pCur->apPage[pCur->iPage];
64442    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
64443    if( pPage->intKey ){
64444      return sqlite3BtreeNext(pCur, pRes);
64445    }else{
64446      return SQLITE_OK;
64447    }
64448  }
64449  if( pPage->leaf ){
64450    return SQLITE_OK;
64451  }else{
64452    return moveToLeftmost(pCur);
64453  }
64454}
64455SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
64456  MemPage *pPage;
64457  assert( cursorOwnsBtShared(pCur) );
64458  assert( pRes!=0 );
64459  assert( *pRes==0 || *pRes==1 );
64460  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
64461  pCur->info.nSize = 0;
64462  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
64463  *pRes = 0;
64464  if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
64465  pPage = pCur->apPage[pCur->iPage];
64466  if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
64467    pCur->aiIdx[pCur->iPage]--;
64468    return btreeNext(pCur, pRes);
64469  }
64470  if( pPage->leaf ){
64471    return SQLITE_OK;
64472  }else{
64473    return moveToLeftmost(pCur);
64474  }
64475}
64476
64477/*
64478** Step the cursor to the back to the previous entry in the database.  If
64479** successful then set *pRes=0.  If the cursor
64480** was already pointing to the first entry in the database before
64481** this routine was called, then set *pRes=1.
64482**
64483** The main entry point is sqlite3BtreePrevious().  That routine is optimized
64484** for the common case of merely decrementing the cell counter BtCursor.aiIdx
64485** to the previous cell on the current page.  The (slower) btreePrevious()
64486** helper routine is called when it is necessary to move to a different page
64487** or to restore the cursor.
64488**
64489** The calling function will set *pRes to 0 or 1.  The initial *pRes value
64490** will be 1 if the cursor being stepped corresponds to an SQL index and
64491** if this routine could have been skipped if that SQL index had been
64492** a unique index.  Otherwise the caller will have set *pRes to zero.
64493** Zero is the common case. The btree implementation is free to use the
64494** initial *pRes value as a hint to improve performance, but the current
64495** SQLite btree implementation does not. (Note that the comdb2 btree
64496** implementation does use this hint, however.)
64497*/
64498static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
64499  int rc;
64500  MemPage *pPage;
64501
64502  assert( cursorOwnsBtShared(pCur) );
64503  assert( pRes!=0 );
64504  assert( *pRes==0 );
64505  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
64506  assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
64507  assert( pCur->info.nSize==0 );
64508  if( pCur->eState!=CURSOR_VALID ){
64509    rc = restoreCursorPosition(pCur);
64510    if( rc!=SQLITE_OK ){
64511      return rc;
64512    }
64513    if( CURSOR_INVALID==pCur->eState ){
64514      *pRes = 1;
64515      return SQLITE_OK;
64516    }
64517    if( pCur->skipNext ){
64518      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
64519      pCur->eState = CURSOR_VALID;
64520      if( pCur->skipNext<0 ){
64521        pCur->skipNext = 0;
64522        return SQLITE_OK;
64523      }
64524      pCur->skipNext = 0;
64525    }
64526  }
64527
64528  pPage = pCur->apPage[pCur->iPage];
64529  assert( pPage->isInit );
64530  if( !pPage->leaf ){
64531    int idx = pCur->aiIdx[pCur->iPage];
64532    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
64533    if( rc ) return rc;
64534    rc = moveToRightmost(pCur);
64535  }else{
64536    while( pCur->aiIdx[pCur->iPage]==0 ){
64537      if( pCur->iPage==0 ){
64538        pCur->eState = CURSOR_INVALID;
64539        *pRes = 1;
64540        return SQLITE_OK;
64541      }
64542      moveToParent(pCur);
64543    }
64544    assert( pCur->info.nSize==0 );
64545    assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
64546
64547    pCur->aiIdx[pCur->iPage]--;
64548    pPage = pCur->apPage[pCur->iPage];
64549    if( pPage->intKey && !pPage->leaf ){
64550      rc = sqlite3BtreePrevious(pCur, pRes);
64551    }else{
64552      rc = SQLITE_OK;
64553    }
64554  }
64555  return rc;
64556}
64557SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
64558  assert( cursorOwnsBtShared(pCur) );
64559  assert( pRes!=0 );
64560  assert( *pRes==0 || *pRes==1 );
64561  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
64562  *pRes = 0;
64563  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
64564  pCur->info.nSize = 0;
64565  if( pCur->eState!=CURSOR_VALID
64566   || pCur->aiIdx[pCur->iPage]==0
64567   || pCur->apPage[pCur->iPage]->leaf==0
64568  ){
64569    return btreePrevious(pCur, pRes);
64570  }
64571  pCur->aiIdx[pCur->iPage]--;
64572  return SQLITE_OK;
64573}
64574
64575/*
64576** Allocate a new page from the database file.
64577**
64578** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
64579** has already been called on the new page.)  The new page has also
64580** been referenced and the calling routine is responsible for calling
64581** sqlite3PagerUnref() on the new page when it is done.
64582**
64583** SQLITE_OK is returned on success.  Any other return value indicates
64584** an error.  *ppPage is set to NULL in the event of an error.
64585**
64586** If the "nearby" parameter is not 0, then an effort is made to
64587** locate a page close to the page number "nearby".  This can be used in an
64588** attempt to keep related pages close to each other in the database file,
64589** which in turn can make database access faster.
64590**
64591** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
64592** anywhere on the free-list, then it is guaranteed to be returned.  If
64593** eMode is BTALLOC_LT then the page returned will be less than or equal
64594** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
64595** are no restrictions on which page is returned.
64596*/
64597static int allocateBtreePage(
64598  BtShared *pBt,         /* The btree */
64599  MemPage **ppPage,      /* Store pointer to the allocated page here */
64600  Pgno *pPgno,           /* Store the page number here */
64601  Pgno nearby,           /* Search for a page near this one */
64602  u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
64603){
64604  MemPage *pPage1;
64605  int rc;
64606  u32 n;     /* Number of pages on the freelist */
64607  u32 k;     /* Number of leaves on the trunk of the freelist */
64608  MemPage *pTrunk = 0;
64609  MemPage *pPrevTrunk = 0;
64610  Pgno mxPage;     /* Total size of the database file */
64611
64612  assert( sqlite3_mutex_held(pBt->mutex) );
64613  assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
64614  pPage1 = pBt->pPage1;
64615  mxPage = btreePagecount(pBt);
64616  /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
64617  ** stores stores the total number of pages on the freelist. */
64618  n = get4byte(&pPage1->aData[36]);
64619  testcase( n==mxPage-1 );
64620  if( n>=mxPage ){
64621    return SQLITE_CORRUPT_BKPT;
64622  }
64623  if( n>0 ){
64624    /* There are pages on the freelist.  Reuse one of those pages. */
64625    Pgno iTrunk;
64626    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
64627    u32 nSearch = 0;   /* Count of the number of search attempts */
64628
64629    /* If eMode==BTALLOC_EXACT and a query of the pointer-map
64630    ** shows that the page 'nearby' is somewhere on the free-list, then
64631    ** the entire-list will be searched for that page.
64632    */
64633#ifndef SQLITE_OMIT_AUTOVACUUM
64634    if( eMode==BTALLOC_EXACT ){
64635      if( nearby<=mxPage ){
64636        u8 eType;
64637        assert( nearby>0 );
64638        assert( pBt->autoVacuum );
64639        rc = ptrmapGet(pBt, nearby, &eType, 0);
64640        if( rc ) return rc;
64641        if( eType==PTRMAP_FREEPAGE ){
64642          searchList = 1;
64643        }
64644      }
64645    }else if( eMode==BTALLOC_LE ){
64646      searchList = 1;
64647    }
64648#endif
64649
64650    /* Decrement the free-list count by 1. Set iTrunk to the index of the
64651    ** first free-list trunk page. iPrevTrunk is initially 1.
64652    */
64653    rc = sqlite3PagerWrite(pPage1->pDbPage);
64654    if( rc ) return rc;
64655    put4byte(&pPage1->aData[36], n-1);
64656
64657    /* The code within this loop is run only once if the 'searchList' variable
64658    ** is not true. Otherwise, it runs once for each trunk-page on the
64659    ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
64660    ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
64661    */
64662    do {
64663      pPrevTrunk = pTrunk;
64664      if( pPrevTrunk ){
64665        /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
64666        ** is the page number of the next freelist trunk page in the list or
64667        ** zero if this is the last freelist trunk page. */
64668        iTrunk = get4byte(&pPrevTrunk->aData[0]);
64669      }else{
64670        /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
64671        ** stores the page number of the first page of the freelist, or zero if
64672        ** the freelist is empty. */
64673        iTrunk = get4byte(&pPage1->aData[32]);
64674      }
64675      testcase( iTrunk==mxPage );
64676      if( iTrunk>mxPage || nSearch++ > n ){
64677        rc = SQLITE_CORRUPT_BKPT;
64678      }else{
64679        rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
64680      }
64681      if( rc ){
64682        pTrunk = 0;
64683        goto end_allocate_page;
64684      }
64685      assert( pTrunk!=0 );
64686      assert( pTrunk->aData!=0 );
64687      /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
64688      ** is the number of leaf page pointers to follow. */
64689      k = get4byte(&pTrunk->aData[4]);
64690      if( k==0 && !searchList ){
64691        /* The trunk has no leaves and the list is not being searched.
64692        ** So extract the trunk page itself and use it as the newly
64693        ** allocated page */
64694        assert( pPrevTrunk==0 );
64695        rc = sqlite3PagerWrite(pTrunk->pDbPage);
64696        if( rc ){
64697          goto end_allocate_page;
64698        }
64699        *pPgno = iTrunk;
64700        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
64701        *ppPage = pTrunk;
64702        pTrunk = 0;
64703        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
64704      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
64705        /* Value of k is out of range.  Database corruption */
64706        rc = SQLITE_CORRUPT_BKPT;
64707        goto end_allocate_page;
64708#ifndef SQLITE_OMIT_AUTOVACUUM
64709      }else if( searchList
64710            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
64711      ){
64712        /* The list is being searched and this trunk page is the page
64713        ** to allocate, regardless of whether it has leaves.
64714        */
64715        *pPgno = iTrunk;
64716        *ppPage = pTrunk;
64717        searchList = 0;
64718        rc = sqlite3PagerWrite(pTrunk->pDbPage);
64719        if( rc ){
64720          goto end_allocate_page;
64721        }
64722        if( k==0 ){
64723          if( !pPrevTrunk ){
64724            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
64725          }else{
64726            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
64727            if( rc!=SQLITE_OK ){
64728              goto end_allocate_page;
64729            }
64730            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
64731          }
64732        }else{
64733          /* The trunk page is required by the caller but it contains
64734          ** pointers to free-list leaves. The first leaf becomes a trunk
64735          ** page in this case.
64736          */
64737          MemPage *pNewTrunk;
64738          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
64739          if( iNewTrunk>mxPage ){
64740            rc = SQLITE_CORRUPT_BKPT;
64741            goto end_allocate_page;
64742          }
64743          testcase( iNewTrunk==mxPage );
64744          rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
64745          if( rc!=SQLITE_OK ){
64746            goto end_allocate_page;
64747          }
64748          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
64749          if( rc!=SQLITE_OK ){
64750            releasePage(pNewTrunk);
64751            goto end_allocate_page;
64752          }
64753          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
64754          put4byte(&pNewTrunk->aData[4], k-1);
64755          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
64756          releasePage(pNewTrunk);
64757          if( !pPrevTrunk ){
64758            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
64759            put4byte(&pPage1->aData[32], iNewTrunk);
64760          }else{
64761            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
64762            if( rc ){
64763              goto end_allocate_page;
64764            }
64765            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
64766          }
64767        }
64768        pTrunk = 0;
64769        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
64770#endif
64771      }else if( k>0 ){
64772        /* Extract a leaf from the trunk */
64773        u32 closest;
64774        Pgno iPage;
64775        unsigned char *aData = pTrunk->aData;
64776        if( nearby>0 ){
64777          u32 i;
64778          closest = 0;
64779          if( eMode==BTALLOC_LE ){
64780            for(i=0; i<k; i++){
64781              iPage = get4byte(&aData[8+i*4]);
64782              if( iPage<=nearby ){
64783                closest = i;
64784                break;
64785              }
64786            }
64787          }else{
64788            int dist;
64789            dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
64790            for(i=1; i<k; i++){
64791              int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
64792              if( d2<dist ){
64793                closest = i;
64794                dist = d2;
64795              }
64796            }
64797          }
64798        }else{
64799          closest = 0;
64800        }
64801
64802        iPage = get4byte(&aData[8+closest*4]);
64803        testcase( iPage==mxPage );
64804        if( iPage>mxPage ){
64805          rc = SQLITE_CORRUPT_BKPT;
64806          goto end_allocate_page;
64807        }
64808        testcase( iPage==mxPage );
64809        if( !searchList
64810         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
64811        ){
64812          int noContent;
64813          *pPgno = iPage;
64814          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
64815                 ": %d more free pages\n",
64816                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
64817          rc = sqlite3PagerWrite(pTrunk->pDbPage);
64818          if( rc ) goto end_allocate_page;
64819          if( closest<k-1 ){
64820            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
64821          }
64822          put4byte(&aData[4], k-1);
64823          noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
64824          rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
64825          if( rc==SQLITE_OK ){
64826            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
64827            if( rc!=SQLITE_OK ){
64828              releasePage(*ppPage);
64829              *ppPage = 0;
64830            }
64831          }
64832          searchList = 0;
64833        }
64834      }
64835      releasePage(pPrevTrunk);
64836      pPrevTrunk = 0;
64837    }while( searchList );
64838  }else{
64839    /* There are no pages on the freelist, so append a new page to the
64840    ** database image.
64841    **
64842    ** Normally, new pages allocated by this block can be requested from the
64843    ** pager layer with the 'no-content' flag set. This prevents the pager
64844    ** from trying to read the pages content from disk. However, if the
64845    ** current transaction has already run one or more incremental-vacuum
64846    ** steps, then the page we are about to allocate may contain content
64847    ** that is required in the event of a rollback. In this case, do
64848    ** not set the no-content flag. This causes the pager to load and journal
64849    ** the current page content before overwriting it.
64850    **
64851    ** Note that the pager will not actually attempt to load or journal
64852    ** content for any page that really does lie past the end of the database
64853    ** file on disk. So the effects of disabling the no-content optimization
64854    ** here are confined to those pages that lie between the end of the
64855    ** database image and the end of the database file.
64856    */
64857    int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
64858
64859    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
64860    if( rc ) return rc;
64861    pBt->nPage++;
64862    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
64863
64864#ifndef SQLITE_OMIT_AUTOVACUUM
64865    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
64866      /* If *pPgno refers to a pointer-map page, allocate two new pages
64867      ** at the end of the file instead of one. The first allocated page
64868      ** becomes a new pointer-map page, the second is used by the caller.
64869      */
64870      MemPage *pPg = 0;
64871      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
64872      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
64873      rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
64874      if( rc==SQLITE_OK ){
64875        rc = sqlite3PagerWrite(pPg->pDbPage);
64876        releasePage(pPg);
64877      }
64878      if( rc ) return rc;
64879      pBt->nPage++;
64880      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
64881    }
64882#endif
64883    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
64884    *pPgno = pBt->nPage;
64885
64886    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
64887    rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
64888    if( rc ) return rc;
64889    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
64890    if( rc!=SQLITE_OK ){
64891      releasePage(*ppPage);
64892      *ppPage = 0;
64893    }
64894    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
64895  }
64896
64897  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
64898
64899end_allocate_page:
64900  releasePage(pTrunk);
64901  releasePage(pPrevTrunk);
64902  assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
64903  assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
64904  return rc;
64905}
64906
64907/*
64908** This function is used to add page iPage to the database file free-list.
64909** It is assumed that the page is not already a part of the free-list.
64910**
64911** The value passed as the second argument to this function is optional.
64912** If the caller happens to have a pointer to the MemPage object
64913** corresponding to page iPage handy, it may pass it as the second value.
64914** Otherwise, it may pass NULL.
64915**
64916** If a pointer to a MemPage object is passed as the second argument,
64917** its reference count is not altered by this function.
64918*/
64919static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
64920  MemPage *pTrunk = 0;                /* Free-list trunk page */
64921  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
64922  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
64923  MemPage *pPage;                     /* Page being freed. May be NULL. */
64924  int rc;                             /* Return Code */
64925  int nFree;                          /* Initial number of pages on free-list */
64926
64927  assert( sqlite3_mutex_held(pBt->mutex) );
64928  assert( CORRUPT_DB || iPage>1 );
64929  assert( !pMemPage || pMemPage->pgno==iPage );
64930
64931  if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
64932  if( pMemPage ){
64933    pPage = pMemPage;
64934    sqlite3PagerRef(pPage->pDbPage);
64935  }else{
64936    pPage = btreePageLookup(pBt, iPage);
64937  }
64938
64939  /* Increment the free page count on pPage1 */
64940  rc = sqlite3PagerWrite(pPage1->pDbPage);
64941  if( rc ) goto freepage_out;
64942  nFree = get4byte(&pPage1->aData[36]);
64943  put4byte(&pPage1->aData[36], nFree+1);
64944
64945  if( pBt->btsFlags & BTS_SECURE_DELETE ){
64946    /* If the secure_delete option is enabled, then
64947    ** always fully overwrite deleted information with zeros.
64948    */
64949    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
64950     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
64951    ){
64952      goto freepage_out;
64953    }
64954    memset(pPage->aData, 0, pPage->pBt->pageSize);
64955  }
64956
64957  /* If the database supports auto-vacuum, write an entry in the pointer-map
64958  ** to indicate that the page is free.
64959  */
64960  if( ISAUTOVACUUM ){
64961    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
64962    if( rc ) goto freepage_out;
64963  }
64964
64965  /* Now manipulate the actual database free-list structure. There are two
64966  ** possibilities. If the free-list is currently empty, or if the first
64967  ** trunk page in the free-list is full, then this page will become a
64968  ** new free-list trunk page. Otherwise, it will become a leaf of the
64969  ** first trunk page in the current free-list. This block tests if it
64970  ** is possible to add the page as a new free-list leaf.
64971  */
64972  if( nFree!=0 ){
64973    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
64974
64975    iTrunk = get4byte(&pPage1->aData[32]);
64976    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
64977    if( rc!=SQLITE_OK ){
64978      goto freepage_out;
64979    }
64980
64981    nLeaf = get4byte(&pTrunk->aData[4]);
64982    assert( pBt->usableSize>32 );
64983    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
64984      rc = SQLITE_CORRUPT_BKPT;
64985      goto freepage_out;
64986    }
64987    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
64988      /* In this case there is room on the trunk page to insert the page
64989      ** being freed as a new leaf.
64990      **
64991      ** Note that the trunk page is not really full until it contains
64992      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
64993      ** coded.  But due to a coding error in versions of SQLite prior to
64994      ** 3.6.0, databases with freelist trunk pages holding more than
64995      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
64996      ** to maintain backwards compatibility with older versions of SQLite,
64997      ** we will continue to restrict the number of entries to usableSize/4 - 8
64998      ** for now.  At some point in the future (once everyone has upgraded
64999      ** to 3.6.0 or later) we should consider fixing the conditional above
65000      ** to read "usableSize/4-2" instead of "usableSize/4-8".
65001      **
65002      ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
65003      ** avoid using the last six entries in the freelist trunk page array in
65004      ** order that database files created by newer versions of SQLite can be
65005      ** read by older versions of SQLite.
65006      */
65007      rc = sqlite3PagerWrite(pTrunk->pDbPage);
65008      if( rc==SQLITE_OK ){
65009        put4byte(&pTrunk->aData[4], nLeaf+1);
65010        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
65011        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
65012          sqlite3PagerDontWrite(pPage->pDbPage);
65013        }
65014        rc = btreeSetHasContent(pBt, iPage);
65015      }
65016      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
65017      goto freepage_out;
65018    }
65019  }
65020
65021  /* If control flows to this point, then it was not possible to add the
65022  ** the page being freed as a leaf page of the first trunk in the free-list.
65023  ** Possibly because the free-list is empty, or possibly because the
65024  ** first trunk in the free-list is full. Either way, the page being freed
65025  ** will become the new first trunk page in the free-list.
65026  */
65027  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
65028    goto freepage_out;
65029  }
65030  rc = sqlite3PagerWrite(pPage->pDbPage);
65031  if( rc!=SQLITE_OK ){
65032    goto freepage_out;
65033  }
65034  put4byte(pPage->aData, iTrunk);
65035  put4byte(&pPage->aData[4], 0);
65036  put4byte(&pPage1->aData[32], iPage);
65037  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
65038
65039freepage_out:
65040  if( pPage ){
65041    pPage->isInit = 0;
65042  }
65043  releasePage(pPage);
65044  releasePage(pTrunk);
65045  return rc;
65046}
65047static void freePage(MemPage *pPage, int *pRC){
65048  if( (*pRC)==SQLITE_OK ){
65049    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
65050  }
65051}
65052
65053/*
65054** Free any overflow pages associated with the given Cell.  Write the
65055** local Cell size (the number of bytes on the original page, omitting
65056** overflow) into *pnSize.
65057*/
65058static int clearCell(
65059  MemPage *pPage,          /* The page that contains the Cell */
65060  unsigned char *pCell,    /* First byte of the Cell */
65061  CellInfo *pInfo          /* Size information about the cell */
65062){
65063  BtShared *pBt = pPage->pBt;
65064  Pgno ovflPgno;
65065  int rc;
65066  int nOvfl;
65067  u32 ovflPageSize;
65068
65069  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
65070  pPage->xParseCell(pPage, pCell, pInfo);
65071  if( pInfo->nLocal==pInfo->nPayload ){
65072    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
65073  }
65074  if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
65075    return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
65076  }
65077  ovflPgno = get4byte(pCell + pInfo->nSize - 4);
65078  assert( pBt->usableSize > 4 );
65079  ovflPageSize = pBt->usableSize - 4;
65080  nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
65081  assert( nOvfl>0 ||
65082    (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
65083  );
65084  while( nOvfl-- ){
65085    Pgno iNext = 0;
65086    MemPage *pOvfl = 0;
65087    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
65088      /* 0 is not a legal page number and page 1 cannot be an
65089      ** overflow page. Therefore if ovflPgno<2 or past the end of the
65090      ** file the database must be corrupt. */
65091      return SQLITE_CORRUPT_BKPT;
65092    }
65093    if( nOvfl ){
65094      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
65095      if( rc ) return rc;
65096    }
65097
65098    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
65099     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
65100    ){
65101      /* There is no reason any cursor should have an outstanding reference
65102      ** to an overflow page belonging to a cell that is being deleted/updated.
65103      ** So if there exists more than one reference to this page, then it
65104      ** must not really be an overflow page and the database must be corrupt.
65105      ** It is helpful to detect this before calling freePage2(), as
65106      ** freePage2() may zero the page contents if secure-delete mode is
65107      ** enabled. If this 'overflow' page happens to be a page that the
65108      ** caller is iterating through or using in some other way, this
65109      ** can be problematic.
65110      */
65111      rc = SQLITE_CORRUPT_BKPT;
65112    }else{
65113      rc = freePage2(pBt, pOvfl, ovflPgno);
65114    }
65115
65116    if( pOvfl ){
65117      sqlite3PagerUnref(pOvfl->pDbPage);
65118    }
65119    if( rc ) return rc;
65120    ovflPgno = iNext;
65121  }
65122  return SQLITE_OK;
65123}
65124
65125/*
65126** Create the byte sequence used to represent a cell on page pPage
65127** and write that byte sequence into pCell[].  Overflow pages are
65128** allocated and filled in as necessary.  The calling procedure
65129** is responsible for making sure sufficient space has been allocated
65130** for pCell[].
65131**
65132** Note that pCell does not necessary need to point to the pPage->aData
65133** area.  pCell might point to some temporary storage.  The cell will
65134** be constructed in this temporary area then copied into pPage->aData
65135** later.
65136*/
65137static int fillInCell(
65138  MemPage *pPage,                /* The page that contains the cell */
65139  unsigned char *pCell,          /* Complete text of the cell */
65140  const BtreePayload *pX,        /* Payload with which to construct the cell */
65141  int *pnSize                    /* Write cell size here */
65142){
65143  int nPayload;
65144  const u8 *pSrc;
65145  int nSrc, n, rc;
65146  int spaceLeft;
65147  MemPage *pOvfl = 0;
65148  MemPage *pToRelease = 0;
65149  unsigned char *pPrior;
65150  unsigned char *pPayload;
65151  BtShared *pBt = pPage->pBt;
65152  Pgno pgnoOvfl = 0;
65153  int nHeader;
65154
65155  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
65156
65157  /* pPage is not necessarily writeable since pCell might be auxiliary
65158  ** buffer space that is separate from the pPage buffer area */
65159  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
65160            || sqlite3PagerIswriteable(pPage->pDbPage) );
65161
65162  /* Fill in the header. */
65163  nHeader = pPage->childPtrSize;
65164  if( pPage->intKey ){
65165    nPayload = pX->nData + pX->nZero;
65166    pSrc = pX->pData;
65167    nSrc = pX->nData;
65168    assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
65169    nHeader += putVarint32(&pCell[nHeader], nPayload);
65170    nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
65171  }else{
65172    assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
65173    nSrc = nPayload = (int)pX->nKey;
65174    pSrc = pX->pKey;
65175    nHeader += putVarint32(&pCell[nHeader], nPayload);
65176  }
65177
65178  /* Fill in the payload */
65179  if( nPayload<=pPage->maxLocal ){
65180    n = nHeader + nPayload;
65181    testcase( n==3 );
65182    testcase( n==4 );
65183    if( n<4 ) n = 4;
65184    *pnSize = n;
65185    spaceLeft = nPayload;
65186    pPrior = pCell;
65187  }else{
65188    int mn = pPage->minLocal;
65189    n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
65190    testcase( n==pPage->maxLocal );
65191    testcase( n==pPage->maxLocal+1 );
65192    if( n > pPage->maxLocal ) n = mn;
65193    spaceLeft = n;
65194    *pnSize = n + nHeader + 4;
65195    pPrior = &pCell[nHeader+n];
65196  }
65197  pPayload = &pCell[nHeader];
65198
65199  /* At this point variables should be set as follows:
65200  **
65201  **   nPayload           Total payload size in bytes
65202  **   pPayload           Begin writing payload here
65203  **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
65204  **                      that means content must spill into overflow pages.
65205  **   *pnSize            Size of the local cell (not counting overflow pages)
65206  **   pPrior             Where to write the pgno of the first overflow page
65207  **
65208  ** Use a call to btreeParseCellPtr() to verify that the values above
65209  ** were computed correctly.
65210  */
65211#ifdef SQLITE_DEBUG
65212  {
65213    CellInfo info;
65214    pPage->xParseCell(pPage, pCell, &info);
65215    assert( nHeader==(int)(info.pPayload - pCell) );
65216    assert( info.nKey==pX->nKey );
65217    assert( *pnSize == info.nSize );
65218    assert( spaceLeft == info.nLocal );
65219  }
65220#endif
65221
65222  /* Write the payload into the local Cell and any extra into overflow pages */
65223  while( nPayload>0 ){
65224    if( spaceLeft==0 ){
65225#ifndef SQLITE_OMIT_AUTOVACUUM
65226      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
65227      if( pBt->autoVacuum ){
65228        do{
65229          pgnoOvfl++;
65230        } while(
65231          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
65232        );
65233      }
65234#endif
65235      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
65236#ifndef SQLITE_OMIT_AUTOVACUUM
65237      /* If the database supports auto-vacuum, and the second or subsequent
65238      ** overflow page is being allocated, add an entry to the pointer-map
65239      ** for that page now.
65240      **
65241      ** If this is the first overflow page, then write a partial entry
65242      ** to the pointer-map. If we write nothing to this pointer-map slot,
65243      ** then the optimistic overflow chain processing in clearCell()
65244      ** may misinterpret the uninitialized values and delete the
65245      ** wrong pages from the database.
65246      */
65247      if( pBt->autoVacuum && rc==SQLITE_OK ){
65248        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
65249        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
65250        if( rc ){
65251          releasePage(pOvfl);
65252        }
65253      }
65254#endif
65255      if( rc ){
65256        releasePage(pToRelease);
65257        return rc;
65258      }
65259
65260      /* If pToRelease is not zero than pPrior points into the data area
65261      ** of pToRelease.  Make sure pToRelease is still writeable. */
65262      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
65263
65264      /* If pPrior is part of the data area of pPage, then make sure pPage
65265      ** is still writeable */
65266      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
65267            || sqlite3PagerIswriteable(pPage->pDbPage) );
65268
65269      put4byte(pPrior, pgnoOvfl);
65270      releasePage(pToRelease);
65271      pToRelease = pOvfl;
65272      pPrior = pOvfl->aData;
65273      put4byte(pPrior, 0);
65274      pPayload = &pOvfl->aData[4];
65275      spaceLeft = pBt->usableSize - 4;
65276    }
65277    n = nPayload;
65278    if( n>spaceLeft ) n = spaceLeft;
65279
65280    /* If pToRelease is not zero than pPayload points into the data area
65281    ** of pToRelease.  Make sure pToRelease is still writeable. */
65282    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
65283
65284    /* If pPayload is part of the data area of pPage, then make sure pPage
65285    ** is still writeable */
65286    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
65287            || sqlite3PagerIswriteable(pPage->pDbPage) );
65288
65289    if( nSrc>0 ){
65290      if( n>nSrc ) n = nSrc;
65291      assert( pSrc );
65292      memcpy(pPayload, pSrc, n);
65293    }else{
65294      memset(pPayload, 0, n);
65295    }
65296    nPayload -= n;
65297    pPayload += n;
65298    pSrc += n;
65299    nSrc -= n;
65300    spaceLeft -= n;
65301  }
65302  releasePage(pToRelease);
65303  return SQLITE_OK;
65304}
65305
65306/*
65307** Remove the i-th cell from pPage.  This routine effects pPage only.
65308** The cell content is not freed or deallocated.  It is assumed that
65309** the cell content has been copied someplace else.  This routine just
65310** removes the reference to the cell from pPage.
65311**
65312** "sz" must be the number of bytes in the cell.
65313*/
65314static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
65315  u32 pc;         /* Offset to cell content of cell being deleted */
65316  u8 *data;       /* pPage->aData */
65317  u8 *ptr;        /* Used to move bytes around within data[] */
65318  int rc;         /* The return code */
65319  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
65320
65321  if( *pRC ) return;
65322  assert( idx>=0 && idx<pPage->nCell );
65323  assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
65324  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
65325  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
65326  data = pPage->aData;
65327  ptr = &pPage->aCellIdx[2*idx];
65328  pc = get2byte(ptr);
65329  hdr = pPage->hdrOffset;
65330  testcase( pc==get2byte(&data[hdr+5]) );
65331  testcase( pc+sz==pPage->pBt->usableSize );
65332  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
65333    *pRC = SQLITE_CORRUPT_BKPT;
65334    return;
65335  }
65336  rc = freeSpace(pPage, pc, sz);
65337  if( rc ){
65338    *pRC = rc;
65339    return;
65340  }
65341  pPage->nCell--;
65342  if( pPage->nCell==0 ){
65343    memset(&data[hdr+1], 0, 4);
65344    data[hdr+7] = 0;
65345    put2byte(&data[hdr+5], pPage->pBt->usableSize);
65346    pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
65347                       - pPage->childPtrSize - 8;
65348  }else{
65349    memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
65350    put2byte(&data[hdr+3], pPage->nCell);
65351    pPage->nFree += 2;
65352  }
65353}
65354
65355/*
65356** Insert a new cell on pPage at cell index "i".  pCell points to the
65357** content of the cell.
65358**
65359** If the cell content will fit on the page, then put it there.  If it
65360** will not fit, then make a copy of the cell content into pTemp if
65361** pTemp is not null.  Regardless of pTemp, allocate a new entry
65362** in pPage->apOvfl[] and make it point to the cell content (either
65363** in pTemp or the original pCell) and also record its index.
65364** Allocating a new entry in pPage->aCell[] implies that
65365** pPage->nOverflow is incremented.
65366**
65367** *pRC must be SQLITE_OK when this routine is called.
65368*/
65369static void insertCell(
65370  MemPage *pPage,   /* Page into which we are copying */
65371  int i,            /* New cell becomes the i-th cell of the page */
65372  u8 *pCell,        /* Content of the new cell */
65373  int sz,           /* Bytes of content in pCell */
65374  u8 *pTemp,        /* Temp storage space for pCell, if needed */
65375  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
65376  int *pRC          /* Read and write return code from here */
65377){
65378  int idx = 0;      /* Where to write new cell content in data[] */
65379  int j;            /* Loop counter */
65380  u8 *data;         /* The content of the whole page */
65381  u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
65382
65383  assert( *pRC==SQLITE_OK );
65384  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
65385  assert( MX_CELL(pPage->pBt)<=10921 );
65386  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
65387  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
65388  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
65389  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
65390  /* The cell should normally be sized correctly.  However, when moving a
65391  ** malformed cell from a leaf page to an interior page, if the cell size
65392  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
65393  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
65394  ** the term after the || in the following assert(). */
65395  assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
65396  if( pPage->nOverflow || sz+2>pPage->nFree ){
65397    if( pTemp ){
65398      memcpy(pTemp, pCell, sz);
65399      pCell = pTemp;
65400    }
65401    if( iChild ){
65402      put4byte(pCell, iChild);
65403    }
65404    j = pPage->nOverflow++;
65405    /* Comparison against ArraySize-1 since we hold back one extra slot
65406    ** as a contingency.  In other words, never need more than 3 overflow
65407    ** slots but 4 are allocated, just to be safe. */
65408    assert( j < ArraySize(pPage->apOvfl)-1 );
65409    pPage->apOvfl[j] = pCell;
65410    pPage->aiOvfl[j] = (u16)i;
65411
65412    /* When multiple overflows occur, they are always sequential and in
65413    ** sorted order.  This invariants arise because multiple overflows can
65414    ** only occur when inserting divider cells into the parent page during
65415    ** balancing, and the dividers are adjacent and sorted.
65416    */
65417    assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
65418    assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
65419  }else{
65420    int rc = sqlite3PagerWrite(pPage->pDbPage);
65421    if( rc!=SQLITE_OK ){
65422      *pRC = rc;
65423      return;
65424    }
65425    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
65426    data = pPage->aData;
65427    assert( &data[pPage->cellOffset]==pPage->aCellIdx );
65428    rc = allocateSpace(pPage, sz, &idx);
65429    if( rc ){ *pRC = rc; return; }
65430    /* The allocateSpace() routine guarantees the following properties
65431    ** if it returns successfully */
65432    assert( idx >= 0 );
65433    assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
65434    assert( idx+sz <= (int)pPage->pBt->usableSize );
65435    pPage->nFree -= (u16)(2 + sz);
65436    memcpy(&data[idx], pCell, sz);
65437    if( iChild ){
65438      put4byte(&data[idx], iChild);
65439    }
65440    pIns = pPage->aCellIdx + i*2;
65441    memmove(pIns+2, pIns, 2*(pPage->nCell - i));
65442    put2byte(pIns, idx);
65443    pPage->nCell++;
65444    /* increment the cell count */
65445    if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
65446    assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
65447#ifndef SQLITE_OMIT_AUTOVACUUM
65448    if( pPage->pBt->autoVacuum ){
65449      /* The cell may contain a pointer to an overflow page. If so, write
65450      ** the entry for the overflow page into the pointer map.
65451      */
65452      ptrmapPutOvflPtr(pPage, pCell, pRC);
65453    }
65454#endif
65455  }
65456}
65457
65458/*
65459** A CellArray object contains a cache of pointers and sizes for a
65460** consecutive sequence of cells that might be held on multiple pages.
65461*/
65462typedef struct CellArray CellArray;
65463struct CellArray {
65464  int nCell;              /* Number of cells in apCell[] */
65465  MemPage *pRef;          /* Reference page */
65466  u8 **apCell;            /* All cells begin balanced */
65467  u16 *szCell;            /* Local size of all cells in apCell[] */
65468};
65469
65470/*
65471** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
65472** computed.
65473*/
65474static void populateCellCache(CellArray *p, int idx, int N){
65475  assert( idx>=0 && idx+N<=p->nCell );
65476  while( N>0 ){
65477    assert( p->apCell[idx]!=0 );
65478    if( p->szCell[idx]==0 ){
65479      p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
65480    }else{
65481      assert( CORRUPT_DB ||
65482              p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
65483    }
65484    idx++;
65485    N--;
65486  }
65487}
65488
65489/*
65490** Return the size of the Nth element of the cell array
65491*/
65492static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
65493  assert( N>=0 && N<p->nCell );
65494  assert( p->szCell[N]==0 );
65495  p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
65496  return p->szCell[N];
65497}
65498static u16 cachedCellSize(CellArray *p, int N){
65499  assert( N>=0 && N<p->nCell );
65500  if( p->szCell[N] ) return p->szCell[N];
65501  return computeCellSize(p, N);
65502}
65503
65504/*
65505** Array apCell[] contains pointers to nCell b-tree page cells. The
65506** szCell[] array contains the size in bytes of each cell. This function
65507** replaces the current contents of page pPg with the contents of the cell
65508** array.
65509**
65510** Some of the cells in apCell[] may currently be stored in pPg. This
65511** function works around problems caused by this by making a copy of any
65512** such cells before overwriting the page data.
65513**
65514** The MemPage.nFree field is invalidated by this function. It is the
65515** responsibility of the caller to set it correctly.
65516*/
65517static int rebuildPage(
65518  MemPage *pPg,                   /* Edit this page */
65519  int nCell,                      /* Final number of cells on page */
65520  u8 **apCell,                    /* Array of cells */
65521  u16 *szCell                     /* Array of cell sizes */
65522){
65523  const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
65524  u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
65525  const int usableSize = pPg->pBt->usableSize;
65526  u8 * const pEnd = &aData[usableSize];
65527  int i;
65528  u8 *pCellptr = pPg->aCellIdx;
65529  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
65530  u8 *pData;
65531
65532  i = get2byte(&aData[hdr+5]);
65533  memcpy(&pTmp[i], &aData[i], usableSize - i);
65534
65535  pData = pEnd;
65536  for(i=0; i<nCell; i++){
65537    u8 *pCell = apCell[i];
65538    if( SQLITE_WITHIN(pCell,aData,pEnd) ){
65539      pCell = &pTmp[pCell - aData];
65540    }
65541    pData -= szCell[i];
65542    put2byte(pCellptr, (pData - aData));
65543    pCellptr += 2;
65544    if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
65545    memcpy(pData, pCell, szCell[i]);
65546    assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
65547    testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
65548  }
65549
65550  /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
65551  pPg->nCell = nCell;
65552  pPg->nOverflow = 0;
65553
65554  put2byte(&aData[hdr+1], 0);
65555  put2byte(&aData[hdr+3], pPg->nCell);
65556  put2byte(&aData[hdr+5], pData - aData);
65557  aData[hdr+7] = 0x00;
65558  return SQLITE_OK;
65559}
65560
65561/*
65562** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
65563** contains the size in bytes of each such cell. This function attempts to
65564** add the cells stored in the array to page pPg. If it cannot (because
65565** the page needs to be defragmented before the cells will fit), non-zero
65566** is returned. Otherwise, if the cells are added successfully, zero is
65567** returned.
65568**
65569** Argument pCellptr points to the first entry in the cell-pointer array
65570** (part of page pPg) to populate. After cell apCell[0] is written to the
65571** page body, a 16-bit offset is written to pCellptr. And so on, for each
65572** cell in the array. It is the responsibility of the caller to ensure
65573** that it is safe to overwrite this part of the cell-pointer array.
65574**
65575** When this function is called, *ppData points to the start of the
65576** content area on page pPg. If the size of the content area is extended,
65577** *ppData is updated to point to the new start of the content area
65578** before returning.
65579**
65580** Finally, argument pBegin points to the byte immediately following the
65581** end of the space required by this page for the cell-pointer area (for
65582** all cells - not just those inserted by the current call). If the content
65583** area must be extended to before this point in order to accomodate all
65584** cells in apCell[], then the cells do not fit and non-zero is returned.
65585*/
65586static int pageInsertArray(
65587  MemPage *pPg,                   /* Page to add cells to */
65588  u8 *pBegin,                     /* End of cell-pointer array */
65589  u8 **ppData,                    /* IN/OUT: Page content -area pointer */
65590  u8 *pCellptr,                   /* Pointer to cell-pointer area */
65591  int iFirst,                     /* Index of first cell to add */
65592  int nCell,                      /* Number of cells to add to pPg */
65593  CellArray *pCArray              /* Array of cells */
65594){
65595  int i;
65596  u8 *aData = pPg->aData;
65597  u8 *pData = *ppData;
65598  int iEnd = iFirst + nCell;
65599  assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
65600  for(i=iFirst; i<iEnd; i++){
65601    int sz, rc;
65602    u8 *pSlot;
65603    sz = cachedCellSize(pCArray, i);
65604    if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
65605      if( (pData - pBegin)<sz ) return 1;
65606      pData -= sz;
65607      pSlot = pData;
65608    }
65609    /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
65610    ** database.  But they might for a corrupt database.  Hence use memmove()
65611    ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
65612    assert( (pSlot+sz)<=pCArray->apCell[i]
65613         || pSlot>=(pCArray->apCell[i]+sz)
65614         || CORRUPT_DB );
65615    memmove(pSlot, pCArray->apCell[i], sz);
65616    put2byte(pCellptr, (pSlot - aData));
65617    pCellptr += 2;
65618  }
65619  *ppData = pData;
65620  return 0;
65621}
65622
65623/*
65624** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
65625** contains the size in bytes of each such cell. This function adds the
65626** space associated with each cell in the array that is currently stored
65627** within the body of pPg to the pPg free-list. The cell-pointers and other
65628** fields of the page are not updated.
65629**
65630** This function returns the total number of cells added to the free-list.
65631*/
65632static int pageFreeArray(
65633  MemPage *pPg,                   /* Page to edit */
65634  int iFirst,                     /* First cell to delete */
65635  int nCell,                      /* Cells to delete */
65636  CellArray *pCArray              /* Array of cells */
65637){
65638  u8 * const aData = pPg->aData;
65639  u8 * const pEnd = &aData[pPg->pBt->usableSize];
65640  u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
65641  int nRet = 0;
65642  int i;
65643  int iEnd = iFirst + nCell;
65644  u8 *pFree = 0;
65645  int szFree = 0;
65646
65647  for(i=iFirst; i<iEnd; i++){
65648    u8 *pCell = pCArray->apCell[i];
65649    if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
65650      int sz;
65651      /* No need to use cachedCellSize() here.  The sizes of all cells that
65652      ** are to be freed have already been computing while deciding which
65653      ** cells need freeing */
65654      sz = pCArray->szCell[i];  assert( sz>0 );
65655      if( pFree!=(pCell + sz) ){
65656        if( pFree ){
65657          assert( pFree>aData && (pFree - aData)<65536 );
65658          freeSpace(pPg, (u16)(pFree - aData), szFree);
65659        }
65660        pFree = pCell;
65661        szFree = sz;
65662        if( pFree+sz>pEnd ) return 0;
65663      }else{
65664        pFree = pCell;
65665        szFree += sz;
65666      }
65667      nRet++;
65668    }
65669  }
65670  if( pFree ){
65671    assert( pFree>aData && (pFree - aData)<65536 );
65672    freeSpace(pPg, (u16)(pFree - aData), szFree);
65673  }
65674  return nRet;
65675}
65676
65677/*
65678** apCell[] and szCell[] contains pointers to and sizes of all cells in the
65679** pages being balanced.  The current page, pPg, has pPg->nCell cells starting
65680** with apCell[iOld].  After balancing, this page should hold nNew cells
65681** starting at apCell[iNew].
65682**
65683** This routine makes the necessary adjustments to pPg so that it contains
65684** the correct cells after being balanced.
65685**
65686** The pPg->nFree field is invalid when this function returns. It is the
65687** responsibility of the caller to set it correctly.
65688*/
65689static int editPage(
65690  MemPage *pPg,                   /* Edit this page */
65691  int iOld,                       /* Index of first cell currently on page */
65692  int iNew,                       /* Index of new first cell on page */
65693  int nNew,                       /* Final number of cells on page */
65694  CellArray *pCArray              /* Array of cells and sizes */
65695){
65696  u8 * const aData = pPg->aData;
65697  const int hdr = pPg->hdrOffset;
65698  u8 *pBegin = &pPg->aCellIdx[nNew * 2];
65699  int nCell = pPg->nCell;       /* Cells stored on pPg */
65700  u8 *pData;
65701  u8 *pCellptr;
65702  int i;
65703  int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
65704  int iNewEnd = iNew + nNew;
65705
65706#ifdef SQLITE_DEBUG
65707  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
65708  memcpy(pTmp, aData, pPg->pBt->usableSize);
65709#endif
65710
65711  /* Remove cells from the start and end of the page */
65712  if( iOld<iNew ){
65713    int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
65714    memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
65715    nCell -= nShift;
65716  }
65717  if( iNewEnd < iOldEnd ){
65718    nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
65719  }
65720
65721  pData = &aData[get2byteNotZero(&aData[hdr+5])];
65722  if( pData<pBegin ) goto editpage_fail;
65723
65724  /* Add cells to the start of the page */
65725  if( iNew<iOld ){
65726    int nAdd = MIN(nNew,iOld-iNew);
65727    assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
65728    pCellptr = pPg->aCellIdx;
65729    memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
65730    if( pageInsertArray(
65731          pPg, pBegin, &pData, pCellptr,
65732          iNew, nAdd, pCArray
65733    ) ) goto editpage_fail;
65734    nCell += nAdd;
65735  }
65736
65737  /* Add any overflow cells */
65738  for(i=0; i<pPg->nOverflow; i++){
65739    int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
65740    if( iCell>=0 && iCell<nNew ){
65741      pCellptr = &pPg->aCellIdx[iCell * 2];
65742      memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
65743      nCell++;
65744      if( pageInsertArray(
65745            pPg, pBegin, &pData, pCellptr,
65746            iCell+iNew, 1, pCArray
65747      ) ) goto editpage_fail;
65748    }
65749  }
65750
65751  /* Append cells to the end of the page */
65752  pCellptr = &pPg->aCellIdx[nCell*2];
65753  if( pageInsertArray(
65754        pPg, pBegin, &pData, pCellptr,
65755        iNew+nCell, nNew-nCell, pCArray
65756  ) ) goto editpage_fail;
65757
65758  pPg->nCell = nNew;
65759  pPg->nOverflow = 0;
65760
65761  put2byte(&aData[hdr+3], pPg->nCell);
65762  put2byte(&aData[hdr+5], pData - aData);
65763
65764#ifdef SQLITE_DEBUG
65765  for(i=0; i<nNew && !CORRUPT_DB; i++){
65766    u8 *pCell = pCArray->apCell[i+iNew];
65767    int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
65768    if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
65769      pCell = &pTmp[pCell - aData];
65770    }
65771    assert( 0==memcmp(pCell, &aData[iOff],
65772            pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
65773  }
65774#endif
65775
65776  return SQLITE_OK;
65777 editpage_fail:
65778  /* Unable to edit this page. Rebuild it from scratch instead. */
65779  populateCellCache(pCArray, iNew, nNew);
65780  return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
65781}
65782
65783/*
65784** The following parameters determine how many adjacent pages get involved
65785** in a balancing operation.  NN is the number of neighbors on either side
65786** of the page that participate in the balancing operation.  NB is the
65787** total number of pages that participate, including the target page and
65788** NN neighbors on either side.
65789**
65790** The minimum value of NN is 1 (of course).  Increasing NN above 1
65791** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
65792** in exchange for a larger degradation in INSERT and UPDATE performance.
65793** The value of NN appears to give the best results overall.
65794*/
65795#define NN 1             /* Number of neighbors on either side of pPage */
65796#define NB (NN*2+1)      /* Total pages involved in the balance */
65797
65798
65799#ifndef SQLITE_OMIT_QUICKBALANCE
65800/*
65801** This version of balance() handles the common special case where
65802** a new entry is being inserted on the extreme right-end of the
65803** tree, in other words, when the new entry will become the largest
65804** entry in the tree.
65805**
65806** Instead of trying to balance the 3 right-most leaf pages, just add
65807** a new page to the right-hand side and put the one new entry in
65808** that page.  This leaves the right side of the tree somewhat
65809** unbalanced.  But odds are that we will be inserting new entries
65810** at the end soon afterwards so the nearly empty page will quickly
65811** fill up.  On average.
65812**
65813** pPage is the leaf page which is the right-most page in the tree.
65814** pParent is its parent.  pPage must have a single overflow entry
65815** which is also the right-most entry on the page.
65816**
65817** The pSpace buffer is used to store a temporary copy of the divider
65818** cell that will be inserted into pParent. Such a cell consists of a 4
65819** byte page number followed by a variable length integer. In other
65820** words, at most 13 bytes. Hence the pSpace buffer must be at
65821** least 13 bytes in size.
65822*/
65823static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
65824  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
65825  MemPage *pNew;                       /* Newly allocated page */
65826  int rc;                              /* Return Code */
65827  Pgno pgnoNew;                        /* Page number of pNew */
65828
65829  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
65830  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65831  assert( pPage->nOverflow==1 );
65832
65833  /* This error condition is now caught prior to reaching this function */
65834  if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
65835
65836  /* Allocate a new page. This page will become the right-sibling of
65837  ** pPage. Make the parent page writable, so that the new divider cell
65838  ** may be inserted. If both these operations are successful, proceed.
65839  */
65840  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
65841
65842  if( rc==SQLITE_OK ){
65843
65844    u8 *pOut = &pSpace[4];
65845    u8 *pCell = pPage->apOvfl[0];
65846    u16 szCell = pPage->xCellSize(pPage, pCell);
65847    u8 *pStop;
65848
65849    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
65850    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
65851    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
65852    rc = rebuildPage(pNew, 1, &pCell, &szCell);
65853    if( NEVER(rc) ) return rc;
65854    pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
65855
65856    /* If this is an auto-vacuum database, update the pointer map
65857    ** with entries for the new page, and any pointer from the
65858    ** cell on the page to an overflow page. If either of these
65859    ** operations fails, the return code is set, but the contents
65860    ** of the parent page are still manipulated by thh code below.
65861    ** That is Ok, at this point the parent page is guaranteed to
65862    ** be marked as dirty. Returning an error code will cause a
65863    ** rollback, undoing any changes made to the parent page.
65864    */
65865    if( ISAUTOVACUUM ){
65866      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
65867      if( szCell>pNew->minLocal ){
65868        ptrmapPutOvflPtr(pNew, pCell, &rc);
65869      }
65870    }
65871
65872    /* Create a divider cell to insert into pParent. The divider cell
65873    ** consists of a 4-byte page number (the page number of pPage) and
65874    ** a variable length key value (which must be the same value as the
65875    ** largest key on pPage).
65876    **
65877    ** To find the largest key value on pPage, first find the right-most
65878    ** cell on pPage. The first two fields of this cell are the
65879    ** record-length (a variable length integer at most 32-bits in size)
65880    ** and the key value (a variable length integer, may have any value).
65881    ** The first of the while(...) loops below skips over the record-length
65882    ** field. The second while(...) loop copies the key value from the
65883    ** cell on pPage into the pSpace buffer.
65884    */
65885    pCell = findCell(pPage, pPage->nCell-1);
65886    pStop = &pCell[9];
65887    while( (*(pCell++)&0x80) && pCell<pStop );
65888    pStop = &pCell[9];
65889    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
65890
65891    /* Insert the new divider cell into pParent. */
65892    if( rc==SQLITE_OK ){
65893      insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
65894                   0, pPage->pgno, &rc);
65895    }
65896
65897    /* Set the right-child pointer of pParent to point to the new page. */
65898    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
65899
65900    /* Release the reference to the new page. */
65901    releasePage(pNew);
65902  }
65903
65904  return rc;
65905}
65906#endif /* SQLITE_OMIT_QUICKBALANCE */
65907
65908#if 0
65909/*
65910** This function does not contribute anything to the operation of SQLite.
65911** it is sometimes activated temporarily while debugging code responsible
65912** for setting pointer-map entries.
65913*/
65914static int ptrmapCheckPages(MemPage **apPage, int nPage){
65915  int i, j;
65916  for(i=0; i<nPage; i++){
65917    Pgno n;
65918    u8 e;
65919    MemPage *pPage = apPage[i];
65920    BtShared *pBt = pPage->pBt;
65921    assert( pPage->isInit );
65922
65923    for(j=0; j<pPage->nCell; j++){
65924      CellInfo info;
65925      u8 *z;
65926
65927      z = findCell(pPage, j);
65928      pPage->xParseCell(pPage, z, &info);
65929      if( info.nLocal<info.nPayload ){
65930        Pgno ovfl = get4byte(&z[info.nSize-4]);
65931        ptrmapGet(pBt, ovfl, &e, &n);
65932        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
65933      }
65934      if( !pPage->leaf ){
65935        Pgno child = get4byte(z);
65936        ptrmapGet(pBt, child, &e, &n);
65937        assert( n==pPage->pgno && e==PTRMAP_BTREE );
65938      }
65939    }
65940    if( !pPage->leaf ){
65941      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
65942      ptrmapGet(pBt, child, &e, &n);
65943      assert( n==pPage->pgno && e==PTRMAP_BTREE );
65944    }
65945  }
65946  return 1;
65947}
65948#endif
65949
65950/*
65951** This function is used to copy the contents of the b-tree node stored
65952** on page pFrom to page pTo. If page pFrom was not a leaf page, then
65953** the pointer-map entries for each child page are updated so that the
65954** parent page stored in the pointer map is page pTo. If pFrom contained
65955** any cells with overflow page pointers, then the corresponding pointer
65956** map entries are also updated so that the parent page is page pTo.
65957**
65958** If pFrom is currently carrying any overflow cells (entries in the
65959** MemPage.apOvfl[] array), they are not copied to pTo.
65960**
65961** Before returning, page pTo is reinitialized using btreeInitPage().
65962**
65963** The performance of this function is not critical. It is only used by
65964** the balance_shallower() and balance_deeper() procedures, neither of
65965** which are called often under normal circumstances.
65966*/
65967static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
65968  if( (*pRC)==SQLITE_OK ){
65969    BtShared * const pBt = pFrom->pBt;
65970    u8 * const aFrom = pFrom->aData;
65971    u8 * const aTo = pTo->aData;
65972    int const iFromHdr = pFrom->hdrOffset;
65973    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
65974    int rc;
65975    int iData;
65976
65977
65978    assert( pFrom->isInit );
65979    assert( pFrom->nFree>=iToHdr );
65980    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
65981
65982    /* Copy the b-tree node content from page pFrom to page pTo. */
65983    iData = get2byte(&aFrom[iFromHdr+5]);
65984    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
65985    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
65986
65987    /* Reinitialize page pTo so that the contents of the MemPage structure
65988    ** match the new data. The initialization of pTo can actually fail under
65989    ** fairly obscure circumstances, even though it is a copy of initialized
65990    ** page pFrom.
65991    */
65992    pTo->isInit = 0;
65993    rc = btreeInitPage(pTo);
65994    if( rc!=SQLITE_OK ){
65995      *pRC = rc;
65996      return;
65997    }
65998
65999    /* If this is an auto-vacuum database, update the pointer-map entries
66000    ** for any b-tree or overflow pages that pTo now contains the pointers to.
66001    */
66002    if( ISAUTOVACUUM ){
66003      *pRC = setChildPtrmaps(pTo);
66004    }
66005  }
66006}
66007
66008/*
66009** This routine redistributes cells on the iParentIdx'th child of pParent
66010** (hereafter "the page") and up to 2 siblings so that all pages have about the
66011** same amount of free space. Usually a single sibling on either side of the
66012** page are used in the balancing, though both siblings might come from one
66013** side if the page is the first or last child of its parent. If the page
66014** has fewer than 2 siblings (something which can only happen if the page
66015** is a root page or a child of a root page) then all available siblings
66016** participate in the balancing.
66017**
66018** The number of siblings of the page might be increased or decreased by
66019** one or two in an effort to keep pages nearly full but not over full.
66020**
66021** Note that when this routine is called, some of the cells on the page
66022** might not actually be stored in MemPage.aData[]. This can happen
66023** if the page is overfull. This routine ensures that all cells allocated
66024** to the page and its siblings fit into MemPage.aData[] before returning.
66025**
66026** In the course of balancing the page and its siblings, cells may be
66027** inserted into or removed from the parent page (pParent). Doing so
66028** may cause the parent page to become overfull or underfull. If this
66029** happens, it is the responsibility of the caller to invoke the correct
66030** balancing routine to fix this problem (see the balance() routine).
66031**
66032** If this routine fails for any reason, it might leave the database
66033** in a corrupted state. So if this routine fails, the database should
66034** be rolled back.
66035**
66036** The third argument to this function, aOvflSpace, is a pointer to a
66037** buffer big enough to hold one page. If while inserting cells into the parent
66038** page (pParent) the parent page becomes overfull, this buffer is
66039** used to store the parent's overflow cells. Because this function inserts
66040** a maximum of four divider cells into the parent page, and the maximum
66041** size of a cell stored within an internal node is always less than 1/4
66042** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
66043** enough for all overflow cells.
66044**
66045** If aOvflSpace is set to a null pointer, this function returns
66046** SQLITE_NOMEM.
66047*/
66048static int balance_nonroot(
66049  MemPage *pParent,               /* Parent page of siblings being balanced */
66050  int iParentIdx,                 /* Index of "the page" in pParent */
66051  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
66052  int isRoot,                     /* True if pParent is a root-page */
66053  int bBulk                       /* True if this call is part of a bulk load */
66054){
66055  BtShared *pBt;               /* The whole database */
66056  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
66057  int nNew = 0;                /* Number of pages in apNew[] */
66058  int nOld;                    /* Number of pages in apOld[] */
66059  int i, j, k;                 /* Loop counters */
66060  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
66061  int rc = SQLITE_OK;          /* The return code */
66062  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
66063  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
66064  int usableSpace;             /* Bytes in pPage beyond the header */
66065  int pageFlags;               /* Value of pPage->aData[0] */
66066  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
66067  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
66068  int szScratch;               /* Size of scratch memory requested */
66069  MemPage *apOld[NB];          /* pPage and up to two siblings */
66070  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
66071  u8 *pRight;                  /* Location in parent of right-sibling pointer */
66072  u8 *apDiv[NB-1];             /* Divider cells in pParent */
66073  int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
66074  int cntOld[NB+2];            /* Old index in b.apCell[] */
66075  int szNew[NB+2];             /* Combined size of cells placed on i-th page */
66076  u8 *aSpace1;                 /* Space for copies of dividers cells */
66077  Pgno pgno;                   /* Temp var to store a page number in */
66078  u8 abDone[NB+2];             /* True after i'th new page is populated */
66079  Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
66080  Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
66081  u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
66082  CellArray b;                  /* Parsed information on cells being balanced */
66083
66084  memset(abDone, 0, sizeof(abDone));
66085  b.nCell = 0;
66086  b.apCell = 0;
66087  pBt = pParent->pBt;
66088  assert( sqlite3_mutex_held(pBt->mutex) );
66089  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
66090
66091#if 0
66092  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
66093#endif
66094
66095  /* At this point pParent may have at most one overflow cell. And if
66096  ** this overflow cell is present, it must be the cell with
66097  ** index iParentIdx. This scenario comes about when this function
66098  ** is called (indirectly) from sqlite3BtreeDelete().
66099  */
66100  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
66101  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
66102
66103  if( !aOvflSpace ){
66104    return SQLITE_NOMEM_BKPT;
66105  }
66106
66107  /* Find the sibling pages to balance. Also locate the cells in pParent
66108  ** that divide the siblings. An attempt is made to find NN siblings on
66109  ** either side of pPage. More siblings are taken from one side, however,
66110  ** if there are fewer than NN siblings on the other side. If pParent
66111  ** has NB or fewer children then all children of pParent are taken.
66112  **
66113  ** This loop also drops the divider cells from the parent page. This
66114  ** way, the remainder of the function does not have to deal with any
66115  ** overflow cells in the parent page, since if any existed they will
66116  ** have already been removed.
66117  */
66118  i = pParent->nOverflow + pParent->nCell;
66119  if( i<2 ){
66120    nxDiv = 0;
66121  }else{
66122    assert( bBulk==0 || bBulk==1 );
66123    if( iParentIdx==0 ){
66124      nxDiv = 0;
66125    }else if( iParentIdx==i ){
66126      nxDiv = i-2+bBulk;
66127    }else{
66128      nxDiv = iParentIdx-1;
66129    }
66130    i = 2-bBulk;
66131  }
66132  nOld = i+1;
66133  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
66134    pRight = &pParent->aData[pParent->hdrOffset+8];
66135  }else{
66136    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
66137  }
66138  pgno = get4byte(pRight);
66139  while( 1 ){
66140    rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
66141    if( rc ){
66142      memset(apOld, 0, (i+1)*sizeof(MemPage*));
66143      goto balance_cleanup;
66144    }
66145    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
66146    if( (i--)==0 ) break;
66147
66148    if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
66149      apDiv[i] = pParent->apOvfl[0];
66150      pgno = get4byte(apDiv[i]);
66151      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
66152      pParent->nOverflow = 0;
66153    }else{
66154      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
66155      pgno = get4byte(apDiv[i]);
66156      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
66157
66158      /* Drop the cell from the parent page. apDiv[i] still points to
66159      ** the cell within the parent, even though it has been dropped.
66160      ** This is safe because dropping a cell only overwrites the first
66161      ** four bytes of it, and this function does not need the first
66162      ** four bytes of the divider cell. So the pointer is safe to use
66163      ** later on.
66164      **
66165      ** But not if we are in secure-delete mode. In secure-delete mode,
66166      ** the dropCell() routine will overwrite the entire cell with zeroes.
66167      ** In this case, temporarily copy the cell into the aOvflSpace[]
66168      ** buffer. It will be copied out again as soon as the aSpace[] buffer
66169      ** is allocated.  */
66170      if( pBt->btsFlags & BTS_SECURE_DELETE ){
66171        int iOff;
66172
66173        iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
66174        if( (iOff+szNew[i])>(int)pBt->usableSize ){
66175          rc = SQLITE_CORRUPT_BKPT;
66176          memset(apOld, 0, (i+1)*sizeof(MemPage*));
66177          goto balance_cleanup;
66178        }else{
66179          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
66180          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
66181        }
66182      }
66183      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
66184    }
66185  }
66186
66187  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
66188  ** alignment */
66189  nMaxCells = (nMaxCells + 3)&~3;
66190
66191  /*
66192  ** Allocate space for memory structures
66193  */
66194  szScratch =
66195       nMaxCells*sizeof(u8*)                       /* b.apCell */
66196     + nMaxCells*sizeof(u16)                       /* b.szCell */
66197     + pBt->pageSize;                              /* aSpace1 */
66198
66199  /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
66200  ** that is more than 6 times the database page size. */
66201  assert( szScratch<=6*(int)pBt->pageSize );
66202  b.apCell = sqlite3ScratchMalloc( szScratch );
66203  if( b.apCell==0 ){
66204    rc = SQLITE_NOMEM_BKPT;
66205    goto balance_cleanup;
66206  }
66207  b.szCell = (u16*)&b.apCell[nMaxCells];
66208  aSpace1 = (u8*)&b.szCell[nMaxCells];
66209  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
66210
66211  /*
66212  ** Load pointers to all cells on sibling pages and the divider cells
66213  ** into the local b.apCell[] array.  Make copies of the divider cells
66214  ** into space obtained from aSpace1[]. The divider cells have already
66215  ** been removed from pParent.
66216  **
66217  ** If the siblings are on leaf pages, then the child pointers of the
66218  ** divider cells are stripped from the cells before they are copied
66219  ** into aSpace1[].  In this way, all cells in b.apCell[] are without
66220  ** child pointers.  If siblings are not leaves, then all cell in
66221  ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
66222  ** are alike.
66223  **
66224  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
66225  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
66226  */
66227  b.pRef = apOld[0];
66228  leafCorrection = b.pRef->leaf*4;
66229  leafData = b.pRef->intKeyLeaf;
66230  for(i=0; i<nOld; i++){
66231    MemPage *pOld = apOld[i];
66232    int limit = pOld->nCell;
66233    u8 *aData = pOld->aData;
66234    u16 maskPage = pOld->maskPage;
66235    u8 *piCell = aData + pOld->cellOffset;
66236    u8 *piEnd;
66237
66238    /* Verify that all sibling pages are of the same "type" (table-leaf,
66239    ** table-interior, index-leaf, or index-interior).
66240    */
66241    if( pOld->aData[0]!=apOld[0]->aData[0] ){
66242      rc = SQLITE_CORRUPT_BKPT;
66243      goto balance_cleanup;
66244    }
66245
66246    /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
66247    ** constains overflow cells, include them in the b.apCell[] array
66248    ** in the correct spot.
66249    **
66250    ** Note that when there are multiple overflow cells, it is always the
66251    ** case that they are sequential and adjacent.  This invariant arises
66252    ** because multiple overflows can only occurs when inserting divider
66253    ** cells into a parent on a prior balance, and divider cells are always
66254    ** adjacent and are inserted in order.  There is an assert() tagged
66255    ** with "NOTE 1" in the overflow cell insertion loop to prove this
66256    ** invariant.
66257    **
66258    ** This must be done in advance.  Once the balance starts, the cell
66259    ** offset section of the btree page will be overwritten and we will no
66260    ** long be able to find the cells if a pointer to each cell is not saved
66261    ** first.
66262    */
66263    memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
66264    if( pOld->nOverflow>0 ){
66265      limit = pOld->aiOvfl[0];
66266      for(j=0; j<limit; j++){
66267        b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
66268        piCell += 2;
66269        b.nCell++;
66270      }
66271      for(k=0; k<pOld->nOverflow; k++){
66272        assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
66273        b.apCell[b.nCell] = pOld->apOvfl[k];
66274        b.nCell++;
66275      }
66276    }
66277    piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
66278    while( piCell<piEnd ){
66279      assert( b.nCell<nMaxCells );
66280      b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
66281      piCell += 2;
66282      b.nCell++;
66283    }
66284
66285    cntOld[i] = b.nCell;
66286    if( i<nOld-1 && !leafData){
66287      u16 sz = (u16)szNew[i];
66288      u8 *pTemp;
66289      assert( b.nCell<nMaxCells );
66290      b.szCell[b.nCell] = sz;
66291      pTemp = &aSpace1[iSpace1];
66292      iSpace1 += sz;
66293      assert( sz<=pBt->maxLocal+23 );
66294      assert( iSpace1 <= (int)pBt->pageSize );
66295      memcpy(pTemp, apDiv[i], sz);
66296      b.apCell[b.nCell] = pTemp+leafCorrection;
66297      assert( leafCorrection==0 || leafCorrection==4 );
66298      b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
66299      if( !pOld->leaf ){
66300        assert( leafCorrection==0 );
66301        assert( pOld->hdrOffset==0 );
66302        /* The right pointer of the child page pOld becomes the left
66303        ** pointer of the divider cell */
66304        memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
66305      }else{
66306        assert( leafCorrection==4 );
66307        while( b.szCell[b.nCell]<4 ){
66308          /* Do not allow any cells smaller than 4 bytes. If a smaller cell
66309          ** does exist, pad it with 0x00 bytes. */
66310          assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
66311          assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
66312          aSpace1[iSpace1++] = 0x00;
66313          b.szCell[b.nCell]++;
66314        }
66315      }
66316      b.nCell++;
66317    }
66318  }
66319
66320  /*
66321  ** Figure out the number of pages needed to hold all b.nCell cells.
66322  ** Store this number in "k".  Also compute szNew[] which is the total
66323  ** size of all cells on the i-th page and cntNew[] which is the index
66324  ** in b.apCell[] of the cell that divides page i from page i+1.
66325  ** cntNew[k] should equal b.nCell.
66326  **
66327  ** Values computed by this block:
66328  **
66329  **           k: The total number of sibling pages
66330  **    szNew[i]: Spaced used on the i-th sibling page.
66331  **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
66332  **              the right of the i-th sibling page.
66333  ** usableSpace: Number of bytes of space available on each sibling.
66334  **
66335  */
66336  usableSpace = pBt->usableSize - 12 + leafCorrection;
66337  for(i=0; i<nOld; i++){
66338    MemPage *p = apOld[i];
66339    szNew[i] = usableSpace - p->nFree;
66340    for(j=0; j<p->nOverflow; j++){
66341      szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
66342    }
66343    cntNew[i] = cntOld[i];
66344  }
66345  k = nOld;
66346  for(i=0; i<k; i++){
66347    int sz;
66348    while( szNew[i]>usableSpace ){
66349      if( i+1>=k ){
66350        k = i+2;
66351        if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
66352        szNew[k-1] = 0;
66353        cntNew[k-1] = b.nCell;
66354      }
66355      sz = 2 + cachedCellSize(&b, cntNew[i]-1);
66356      szNew[i] -= sz;
66357      if( !leafData ){
66358        if( cntNew[i]<b.nCell ){
66359          sz = 2 + cachedCellSize(&b, cntNew[i]);
66360        }else{
66361          sz = 0;
66362        }
66363      }
66364      szNew[i+1] += sz;
66365      cntNew[i]--;
66366    }
66367    while( cntNew[i]<b.nCell ){
66368      sz = 2 + cachedCellSize(&b, cntNew[i]);
66369      if( szNew[i]+sz>usableSpace ) break;
66370      szNew[i] += sz;
66371      cntNew[i]++;
66372      if( !leafData ){
66373        if( cntNew[i]<b.nCell ){
66374          sz = 2 + cachedCellSize(&b, cntNew[i]);
66375        }else{
66376          sz = 0;
66377        }
66378      }
66379      szNew[i+1] -= sz;
66380    }
66381    if( cntNew[i]>=b.nCell ){
66382      k = i+1;
66383    }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
66384      rc = SQLITE_CORRUPT_BKPT;
66385      goto balance_cleanup;
66386    }
66387  }
66388
66389  /*
66390  ** The packing computed by the previous block is biased toward the siblings
66391  ** on the left side (siblings with smaller keys). The left siblings are
66392  ** always nearly full, while the right-most sibling might be nearly empty.
66393  ** The next block of code attempts to adjust the packing of siblings to
66394  ** get a better balance.
66395  **
66396  ** This adjustment is more than an optimization.  The packing above might
66397  ** be so out of balance as to be illegal.  For example, the right-most
66398  ** sibling might be completely empty.  This adjustment is not optional.
66399  */
66400  for(i=k-1; i>0; i--){
66401    int szRight = szNew[i];  /* Size of sibling on the right */
66402    int szLeft = szNew[i-1]; /* Size of sibling on the left */
66403    int r;              /* Index of right-most cell in left sibling */
66404    int d;              /* Index of first cell to the left of right sibling */
66405
66406    r = cntNew[i-1] - 1;
66407    d = r + 1 - leafData;
66408    (void)cachedCellSize(&b, d);
66409    do{
66410      assert( d<nMaxCells );
66411      assert( r<nMaxCells );
66412      (void)cachedCellSize(&b, r);
66413      if( szRight!=0
66414       && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
66415        break;
66416      }
66417      szRight += b.szCell[d] + 2;
66418      szLeft -= b.szCell[r] + 2;
66419      cntNew[i-1] = r;
66420      r--;
66421      d--;
66422    }while( r>=0 );
66423    szNew[i] = szRight;
66424    szNew[i-1] = szLeft;
66425    if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
66426      rc = SQLITE_CORRUPT_BKPT;
66427      goto balance_cleanup;
66428    }
66429  }
66430
66431  /* Sanity check:  For a non-corrupt database file one of the follwing
66432  ** must be true:
66433  **    (1) We found one or more cells (cntNew[0])>0), or
66434  **    (2) pPage is a virtual root page.  A virtual root page is when
66435  **        the real root page is page 1 and we are the only child of
66436  **        that page.
66437  */
66438  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
66439  TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
66440    apOld[0]->pgno, apOld[0]->nCell,
66441    nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
66442    nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
66443  ));
66444
66445  /*
66446  ** Allocate k new pages.  Reuse old pages where possible.
66447  */
66448  pageFlags = apOld[0]->aData[0];
66449  for(i=0; i<k; i++){
66450    MemPage *pNew;
66451    if( i<nOld ){
66452      pNew = apNew[i] = apOld[i];
66453      apOld[i] = 0;
66454      rc = sqlite3PagerWrite(pNew->pDbPage);
66455      nNew++;
66456      if( rc ) goto balance_cleanup;
66457    }else{
66458      assert( i>0 );
66459      rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
66460      if( rc ) goto balance_cleanup;
66461      zeroPage(pNew, pageFlags);
66462      apNew[i] = pNew;
66463      nNew++;
66464      cntOld[i] = b.nCell;
66465
66466      /* Set the pointer-map entry for the new sibling page. */
66467      if( ISAUTOVACUUM ){
66468        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
66469        if( rc!=SQLITE_OK ){
66470          goto balance_cleanup;
66471        }
66472      }
66473    }
66474  }
66475
66476  /*
66477  ** Reassign page numbers so that the new pages are in ascending order.
66478  ** This helps to keep entries in the disk file in order so that a scan
66479  ** of the table is closer to a linear scan through the file. That in turn
66480  ** helps the operating system to deliver pages from the disk more rapidly.
66481  **
66482  ** An O(n^2) insertion sort algorithm is used, but since n is never more
66483  ** than (NB+2) (a small constant), that should not be a problem.
66484  **
66485  ** When NB==3, this one optimization makes the database about 25% faster
66486  ** for large insertions and deletions.
66487  */
66488  for(i=0; i<nNew; i++){
66489    aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
66490    aPgFlags[i] = apNew[i]->pDbPage->flags;
66491    for(j=0; j<i; j++){
66492      if( aPgno[j]==aPgno[i] ){
66493        /* This branch is taken if the set of sibling pages somehow contains
66494        ** duplicate entries. This can happen if the database is corrupt.
66495        ** It would be simpler to detect this as part of the loop below, but
66496        ** we do the detection here in order to avoid populating the pager
66497        ** cache with two separate objects associated with the same
66498        ** page number.  */
66499        assert( CORRUPT_DB );
66500        rc = SQLITE_CORRUPT_BKPT;
66501        goto balance_cleanup;
66502      }
66503    }
66504  }
66505  for(i=0; i<nNew; i++){
66506    int iBest = 0;                /* aPgno[] index of page number to use */
66507    for(j=1; j<nNew; j++){
66508      if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
66509    }
66510    pgno = aPgOrder[iBest];
66511    aPgOrder[iBest] = 0xffffffff;
66512    if( iBest!=i ){
66513      if( iBest>i ){
66514        sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
66515      }
66516      sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
66517      apNew[i]->pgno = pgno;
66518    }
66519  }
66520
66521  TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
66522         "%d(%d nc=%d) %d(%d nc=%d)\n",
66523    apNew[0]->pgno, szNew[0], cntNew[0],
66524    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
66525    nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
66526    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
66527    nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
66528    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
66529    nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
66530    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
66531    nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
66532  ));
66533
66534  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
66535  put4byte(pRight, apNew[nNew-1]->pgno);
66536
66537  /* If the sibling pages are not leaves, ensure that the right-child pointer
66538  ** of the right-most new sibling page is set to the value that was
66539  ** originally in the same field of the right-most old sibling page. */
66540  if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
66541    MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
66542    memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
66543  }
66544
66545  /* Make any required updates to pointer map entries associated with
66546  ** cells stored on sibling pages following the balance operation. Pointer
66547  ** map entries associated with divider cells are set by the insertCell()
66548  ** routine. The associated pointer map entries are:
66549  **
66550  **   a) if the cell contains a reference to an overflow chain, the
66551  **      entry associated with the first page in the overflow chain, and
66552  **
66553  **   b) if the sibling pages are not leaves, the child page associated
66554  **      with the cell.
66555  **
66556  ** If the sibling pages are not leaves, then the pointer map entry
66557  ** associated with the right-child of each sibling may also need to be
66558  ** updated. This happens below, after the sibling pages have been
66559  ** populated, not here.
66560  */
66561  if( ISAUTOVACUUM ){
66562    MemPage *pNew = apNew[0];
66563    u8 *aOld = pNew->aData;
66564    int cntOldNext = pNew->nCell + pNew->nOverflow;
66565    int usableSize = pBt->usableSize;
66566    int iNew = 0;
66567    int iOld = 0;
66568
66569    for(i=0; i<b.nCell; i++){
66570      u8 *pCell = b.apCell[i];
66571      if( i==cntOldNext ){
66572        MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
66573        cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
66574        aOld = pOld->aData;
66575      }
66576      if( i==cntNew[iNew] ){
66577        pNew = apNew[++iNew];
66578        if( !leafData ) continue;
66579      }
66580
66581      /* Cell pCell is destined for new sibling page pNew. Originally, it
66582      ** was either part of sibling page iOld (possibly an overflow cell),
66583      ** or else the divider cell to the left of sibling page iOld. So,
66584      ** if sibling page iOld had the same page number as pNew, and if
66585      ** pCell really was a part of sibling page iOld (not a divider or
66586      ** overflow cell), we can skip updating the pointer map entries.  */
66587      if( iOld>=nNew
66588       || pNew->pgno!=aPgno[iOld]
66589       || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
66590      ){
66591        if( !leafCorrection ){
66592          ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
66593        }
66594        if( cachedCellSize(&b,i)>pNew->minLocal ){
66595          ptrmapPutOvflPtr(pNew, pCell, &rc);
66596        }
66597        if( rc ) goto balance_cleanup;
66598      }
66599    }
66600  }
66601
66602  /* Insert new divider cells into pParent. */
66603  for(i=0; i<nNew-1; i++){
66604    u8 *pCell;
66605    u8 *pTemp;
66606    int sz;
66607    MemPage *pNew = apNew[i];
66608    j = cntNew[i];
66609
66610    assert( j<nMaxCells );
66611    assert( b.apCell[j]!=0 );
66612    pCell = b.apCell[j];
66613    sz = b.szCell[j] + leafCorrection;
66614    pTemp = &aOvflSpace[iOvflSpace];
66615    if( !pNew->leaf ){
66616      memcpy(&pNew->aData[8], pCell, 4);
66617    }else if( leafData ){
66618      /* If the tree is a leaf-data tree, and the siblings are leaves,
66619      ** then there is no divider cell in b.apCell[]. Instead, the divider
66620      ** cell consists of the integer key for the right-most cell of
66621      ** the sibling-page assembled above only.
66622      */
66623      CellInfo info;
66624      j--;
66625      pNew->xParseCell(pNew, b.apCell[j], &info);
66626      pCell = pTemp;
66627      sz = 4 + putVarint(&pCell[4], info.nKey);
66628      pTemp = 0;
66629    }else{
66630      pCell -= 4;
66631      /* Obscure case for non-leaf-data trees: If the cell at pCell was
66632      ** previously stored on a leaf node, and its reported size was 4
66633      ** bytes, then it may actually be smaller than this
66634      ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
66635      ** any cell). But it is important to pass the correct size to
66636      ** insertCell(), so reparse the cell now.
66637      **
66638      ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
66639      ** and WITHOUT ROWID tables with exactly one column which is the
66640      ** primary key.
66641      */
66642      if( b.szCell[j]==4 ){
66643        assert(leafCorrection==4);
66644        sz = pParent->xCellSize(pParent, pCell);
66645      }
66646    }
66647    iOvflSpace += sz;
66648    assert( sz<=pBt->maxLocal+23 );
66649    assert( iOvflSpace <= (int)pBt->pageSize );
66650    insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
66651    if( rc!=SQLITE_OK ) goto balance_cleanup;
66652    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
66653  }
66654
66655  /* Now update the actual sibling pages. The order in which they are updated
66656  ** is important, as this code needs to avoid disrupting any page from which
66657  ** cells may still to be read. In practice, this means:
66658  **
66659  **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
66660  **      then it is not safe to update page apNew[iPg] until after
66661  **      the left-hand sibling apNew[iPg-1] has been updated.
66662  **
66663  **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
66664  **      then it is not safe to update page apNew[iPg] until after
66665  **      the right-hand sibling apNew[iPg+1] has been updated.
66666  **
66667  ** If neither of the above apply, the page is safe to update.
66668  **
66669  ** The iPg value in the following loop starts at nNew-1 goes down
66670  ** to 0, then back up to nNew-1 again, thus making two passes over
66671  ** the pages.  On the initial downward pass, only condition (1) above
66672  ** needs to be tested because (2) will always be true from the previous
66673  ** step.  On the upward pass, both conditions are always true, so the
66674  ** upwards pass simply processes pages that were missed on the downward
66675  ** pass.
66676  */
66677  for(i=1-nNew; i<nNew; i++){
66678    int iPg = i<0 ? -i : i;
66679    assert( iPg>=0 && iPg<nNew );
66680    if( abDone[iPg] ) continue;         /* Skip pages already processed */
66681    if( i>=0                            /* On the upwards pass, or... */
66682     || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
66683    ){
66684      int iNew;
66685      int iOld;
66686      int nNewCell;
66687
66688      /* Verify condition (1):  If cells are moving left, update iPg
66689      ** only after iPg-1 has already been updated. */
66690      assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
66691
66692      /* Verify condition (2):  If cells are moving right, update iPg
66693      ** only after iPg+1 has already been updated. */
66694      assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
66695
66696      if( iPg==0 ){
66697        iNew = iOld = 0;
66698        nNewCell = cntNew[0];
66699      }else{
66700        iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
66701        iNew = cntNew[iPg-1] + !leafData;
66702        nNewCell = cntNew[iPg] - iNew;
66703      }
66704
66705      rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
66706      if( rc ) goto balance_cleanup;
66707      abDone[iPg]++;
66708      apNew[iPg]->nFree = usableSpace-szNew[iPg];
66709      assert( apNew[iPg]->nOverflow==0 );
66710      assert( apNew[iPg]->nCell==nNewCell );
66711    }
66712  }
66713
66714  /* All pages have been processed exactly once */
66715  assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
66716
66717  assert( nOld>0 );
66718  assert( nNew>0 );
66719
66720  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
66721    /* The root page of the b-tree now contains no cells. The only sibling
66722    ** page is the right-child of the parent. Copy the contents of the
66723    ** child page into the parent, decreasing the overall height of the
66724    ** b-tree structure by one. This is described as the "balance-shallower"
66725    ** sub-algorithm in some documentation.
66726    **
66727    ** If this is an auto-vacuum database, the call to copyNodeContent()
66728    ** sets all pointer-map entries corresponding to database image pages
66729    ** for which the pointer is stored within the content being copied.
66730    **
66731    ** It is critical that the child page be defragmented before being
66732    ** copied into the parent, because if the parent is page 1 then it will
66733    ** by smaller than the child due to the database header, and so all the
66734    ** free space needs to be up front.
66735    */
66736    assert( nNew==1 || CORRUPT_DB );
66737    rc = defragmentPage(apNew[0], -1);
66738    testcase( rc!=SQLITE_OK );
66739    assert( apNew[0]->nFree ==
66740        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
66741      || rc!=SQLITE_OK
66742    );
66743    copyNodeContent(apNew[0], pParent, &rc);
66744    freePage(apNew[0], &rc);
66745  }else if( ISAUTOVACUUM && !leafCorrection ){
66746    /* Fix the pointer map entries associated with the right-child of each
66747    ** sibling page. All other pointer map entries have already been taken
66748    ** care of.  */
66749    for(i=0; i<nNew; i++){
66750      u32 key = get4byte(&apNew[i]->aData[8]);
66751      ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
66752    }
66753  }
66754
66755  assert( pParent->isInit );
66756  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
66757          nOld, nNew, b.nCell));
66758
66759  /* Free any old pages that were not reused as new pages.
66760  */
66761  for(i=nNew; i<nOld; i++){
66762    freePage(apOld[i], &rc);
66763  }
66764
66765#if 0
66766  if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
66767    /* The ptrmapCheckPages() contains assert() statements that verify that
66768    ** all pointer map pages are set correctly. This is helpful while
66769    ** debugging. This is usually disabled because a corrupt database may
66770    ** cause an assert() statement to fail.  */
66771    ptrmapCheckPages(apNew, nNew);
66772    ptrmapCheckPages(&pParent, 1);
66773  }
66774#endif
66775
66776  /*
66777  ** Cleanup before returning.
66778  */
66779balance_cleanup:
66780  sqlite3ScratchFree(b.apCell);
66781  for(i=0; i<nOld; i++){
66782    releasePage(apOld[i]);
66783  }
66784  for(i=0; i<nNew; i++){
66785    releasePage(apNew[i]);
66786  }
66787
66788  return rc;
66789}
66790
66791
66792/*
66793** This function is called when the root page of a b-tree structure is
66794** overfull (has one or more overflow pages).
66795**
66796** A new child page is allocated and the contents of the current root
66797** page, including overflow cells, are copied into the child. The root
66798** page is then overwritten to make it an empty page with the right-child
66799** pointer pointing to the new page.
66800**
66801** Before returning, all pointer-map entries corresponding to pages
66802** that the new child-page now contains pointers to are updated. The
66803** entry corresponding to the new right-child pointer of the root
66804** page is also updated.
66805**
66806** If successful, *ppChild is set to contain a reference to the child
66807** page and SQLITE_OK is returned. In this case the caller is required
66808** to call releasePage() on *ppChild exactly once. If an error occurs,
66809** an error code is returned and *ppChild is set to 0.
66810*/
66811static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
66812  int rc;                        /* Return value from subprocedures */
66813  MemPage *pChild = 0;           /* Pointer to a new child page */
66814  Pgno pgnoChild = 0;            /* Page number of the new child page */
66815  BtShared *pBt = pRoot->pBt;    /* The BTree */
66816
66817  assert( pRoot->nOverflow>0 );
66818  assert( sqlite3_mutex_held(pBt->mutex) );
66819
66820  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
66821  ** page that will become the new right-child of pPage. Copy the contents
66822  ** of the node stored on pRoot into the new child page.
66823  */
66824  rc = sqlite3PagerWrite(pRoot->pDbPage);
66825  if( rc==SQLITE_OK ){
66826    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
66827    copyNodeContent(pRoot, pChild, &rc);
66828    if( ISAUTOVACUUM ){
66829      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
66830    }
66831  }
66832  if( rc ){
66833    *ppChild = 0;
66834    releasePage(pChild);
66835    return rc;
66836  }
66837  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
66838  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
66839  assert( pChild->nCell==pRoot->nCell );
66840
66841  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
66842
66843  /* Copy the overflow cells from pRoot to pChild */
66844  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
66845         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
66846  memcpy(pChild->apOvfl, pRoot->apOvfl,
66847         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
66848  pChild->nOverflow = pRoot->nOverflow;
66849
66850  /* Zero the contents of pRoot. Then install pChild as the right-child. */
66851  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
66852  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
66853
66854  *ppChild = pChild;
66855  return SQLITE_OK;
66856}
66857
66858/*
66859** The page that pCur currently points to has just been modified in
66860** some way. This function figures out if this modification means the
66861** tree needs to be balanced, and if so calls the appropriate balancing
66862** routine. Balancing routines are:
66863**
66864**   balance_quick()
66865**   balance_deeper()
66866**   balance_nonroot()
66867*/
66868static int balance(BtCursor *pCur){
66869  int rc = SQLITE_OK;
66870  const int nMin = pCur->pBt->usableSize * 2 / 3;
66871  u8 aBalanceQuickSpace[13];
66872  u8 *pFree = 0;
66873
66874  VVA_ONLY( int balance_quick_called = 0 );
66875  VVA_ONLY( int balance_deeper_called = 0 );
66876
66877  do {
66878    int iPage = pCur->iPage;
66879    MemPage *pPage = pCur->apPage[iPage];
66880
66881    if( iPage==0 ){
66882      if( pPage->nOverflow ){
66883        /* The root page of the b-tree is overfull. In this case call the
66884        ** balance_deeper() function to create a new child for the root-page
66885        ** and copy the current contents of the root-page to it. The
66886        ** next iteration of the do-loop will balance the child page.
66887        */
66888        assert( balance_deeper_called==0 );
66889        VVA_ONLY( balance_deeper_called++ );
66890        rc = balance_deeper(pPage, &pCur->apPage[1]);
66891        if( rc==SQLITE_OK ){
66892          pCur->iPage = 1;
66893          pCur->aiIdx[0] = 0;
66894          pCur->aiIdx[1] = 0;
66895          assert( pCur->apPage[1]->nOverflow );
66896        }
66897      }else{
66898        break;
66899      }
66900    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
66901      break;
66902    }else{
66903      MemPage * const pParent = pCur->apPage[iPage-1];
66904      int const iIdx = pCur->aiIdx[iPage-1];
66905
66906      rc = sqlite3PagerWrite(pParent->pDbPage);
66907      if( rc==SQLITE_OK ){
66908#ifndef SQLITE_OMIT_QUICKBALANCE
66909        if( pPage->intKeyLeaf
66910         && pPage->nOverflow==1
66911         && pPage->aiOvfl[0]==pPage->nCell
66912         && pParent->pgno!=1
66913         && pParent->nCell==iIdx
66914        ){
66915          /* Call balance_quick() to create a new sibling of pPage on which
66916          ** to store the overflow cell. balance_quick() inserts a new cell
66917          ** into pParent, which may cause pParent overflow. If this
66918          ** happens, the next iteration of the do-loop will balance pParent
66919          ** use either balance_nonroot() or balance_deeper(). Until this
66920          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
66921          ** buffer.
66922          **
66923          ** The purpose of the following assert() is to check that only a
66924          ** single call to balance_quick() is made for each call to this
66925          ** function. If this were not verified, a subtle bug involving reuse
66926          ** of the aBalanceQuickSpace[] might sneak in.
66927          */
66928          assert( balance_quick_called==0 );
66929          VVA_ONLY( balance_quick_called++ );
66930          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
66931        }else
66932#endif
66933        {
66934          /* In this case, call balance_nonroot() to redistribute cells
66935          ** between pPage and up to 2 of its sibling pages. This involves
66936          ** modifying the contents of pParent, which may cause pParent to
66937          ** become overfull or underfull. The next iteration of the do-loop
66938          ** will balance the parent page to correct this.
66939          **
66940          ** If the parent page becomes overfull, the overflow cell or cells
66941          ** are stored in the pSpace buffer allocated immediately below.
66942          ** A subsequent iteration of the do-loop will deal with this by
66943          ** calling balance_nonroot() (balance_deeper() may be called first,
66944          ** but it doesn't deal with overflow cells - just moves them to a
66945          ** different page). Once this subsequent call to balance_nonroot()
66946          ** has completed, it is safe to release the pSpace buffer used by
66947          ** the previous call, as the overflow cell data will have been
66948          ** copied either into the body of a database page or into the new
66949          ** pSpace buffer passed to the latter call to balance_nonroot().
66950          */
66951          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
66952          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
66953                               pCur->hints&BTREE_BULKLOAD);
66954          if( pFree ){
66955            /* If pFree is not NULL, it points to the pSpace buffer used
66956            ** by a previous call to balance_nonroot(). Its contents are
66957            ** now stored either on real database pages or within the
66958            ** new pSpace buffer, so it may be safely freed here. */
66959            sqlite3PageFree(pFree);
66960          }
66961
66962          /* The pSpace buffer will be freed after the next call to
66963          ** balance_nonroot(), or just before this function returns, whichever
66964          ** comes first. */
66965          pFree = pSpace;
66966        }
66967      }
66968
66969      pPage->nOverflow = 0;
66970
66971      /* The next iteration of the do-loop balances the parent page. */
66972      releasePage(pPage);
66973      pCur->iPage--;
66974      assert( pCur->iPage>=0 );
66975    }
66976  }while( rc==SQLITE_OK );
66977
66978  if( pFree ){
66979    sqlite3PageFree(pFree);
66980  }
66981  return rc;
66982}
66983
66984
66985/*
66986** Insert a new record into the BTree.  The content of the new record
66987** is described by the pX object.  The pCur cursor is used only to
66988** define what table the record should be inserted into, and is left
66989** pointing at a random location.
66990**
66991** For a table btree (used for rowid tables), only the pX.nKey value of
66992** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
66993** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
66994** hold the content of the row.
66995**
66996** For an index btree (used for indexes and WITHOUT ROWID tables), the
66997** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The
66998** pX.pData,nData,nZero fields must be zero.
66999**
67000** If the seekResult parameter is non-zero, then a successful call to
67001** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
67002** been performed.  In other words, if seekResult!=0 then the cursor
67003** is currently pointing to a cell that will be adjacent to the cell
67004** to be inserted.  If seekResult<0 then pCur points to a cell that is
67005** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
67006** that is larger than (pKey,nKey).
67007**
67008** If seekResult==0, that means pCur is pointing at some unknown location.
67009** In that case, this routine must seek the cursor to the correct insertion
67010** point for (pKey,nKey) before doing the insertion.  For index btrees,
67011** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
67012** key values and pX->aMem can be used instead of pX->pKey to avoid having
67013** to decode the key.
67014*/
67015SQLITE_PRIVATE int sqlite3BtreeInsert(
67016  BtCursor *pCur,                /* Insert data into the table of this cursor */
67017  const BtreePayload *pX,        /* Content of the row to be inserted */
67018  int flags,                     /* True if this is likely an append */
67019  int seekResult                 /* Result of prior MovetoUnpacked() call */
67020){
67021  int rc;
67022  int loc = seekResult;          /* -1: before desired location  +1: after */
67023  int szNew = 0;
67024  int idx;
67025  MemPage *pPage;
67026  Btree *p = pCur->pBtree;
67027  BtShared *pBt = p->pBt;
67028  unsigned char *oldCell;
67029  unsigned char *newCell = 0;
67030
67031  assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
67032
67033  if( pCur->eState==CURSOR_FAULT ){
67034    assert( pCur->skipNext!=SQLITE_OK );
67035    return pCur->skipNext;
67036  }
67037
67038  assert( cursorOwnsBtShared(pCur) );
67039  assert( (pCur->curFlags & BTCF_WriteFlag)!=0
67040              && pBt->inTransaction==TRANS_WRITE
67041              && (pBt->btsFlags & BTS_READ_ONLY)==0 );
67042  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
67043
67044  /* Assert that the caller has been consistent. If this cursor was opened
67045  ** expecting an index b-tree, then the caller should be inserting blob
67046  ** keys with no associated data. If the cursor was opened expecting an
67047  ** intkey table, the caller should be inserting integer keys with a
67048  ** blob of associated data.  */
67049  assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
67050
67051  /* Save the positions of any other cursors open on this table.
67052  **
67053  ** In some cases, the call to btreeMoveto() below is a no-op. For
67054  ** example, when inserting data into a table with auto-generated integer
67055  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
67056  ** integer key to use. It then calls this function to actually insert the
67057  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
67058  ** that the cursor is already where it needs to be and returns without
67059  ** doing any work. To avoid thwarting these optimizations, it is important
67060  ** not to clear the cursor here.
67061  */
67062  if( pCur->curFlags & BTCF_Multiple ){
67063    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
67064    if( rc ) return rc;
67065  }
67066
67067  if( pCur->pKeyInfo==0 ){
67068    assert( pX->pKey==0 );
67069    /* If this is an insert into a table b-tree, invalidate any incrblob
67070    ** cursors open on the row being replaced */
67071    invalidateIncrblobCursors(p, pX->nKey, 0);
67072
67073    /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
67074    ** to a row with the same key as the new entry being inserted.  */
67075    assert( (flags & BTREE_SAVEPOSITION)==0 ||
67076            ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) );
67077
67078    /* If the cursor is currently on the last row and we are appending a
67079    ** new row onto the end, set the "loc" to avoid an unnecessary
67080    ** btreeMoveto() call */
67081    if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
67082      loc = 0;
67083    }else if( loc==0 ){
67084      rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
67085      if( rc ) return rc;
67086    }
67087  }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
67088    if( pX->nMem ){
67089      UnpackedRecord r;
67090      r.pKeyInfo = pCur->pKeyInfo;
67091      r.aMem = pX->aMem;
67092      r.nField = pX->nMem;
67093      r.default_rc = 0;
67094      r.errCode = 0;
67095      r.r1 = 0;
67096      r.r2 = 0;
67097      r.eqSeen = 0;
67098      rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
67099    }else{
67100      rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
67101    }
67102    if( rc ) return rc;
67103  }
67104  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
67105
67106  pPage = pCur->apPage[pCur->iPage];
67107  assert( pPage->intKey || pX->nKey>=0 );
67108  assert( pPage->leaf || !pPage->intKey );
67109
67110  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
67111          pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
67112          loc==0 ? "overwrite" : "new entry"));
67113  assert( pPage->isInit );
67114  newCell = pBt->pTmpSpace;
67115  assert( newCell!=0 );
67116  rc = fillInCell(pPage, newCell, pX, &szNew);
67117  if( rc ) goto end_insert;
67118  assert( szNew==pPage->xCellSize(pPage, newCell) );
67119  assert( szNew <= MX_CELL_SIZE(pBt) );
67120  idx = pCur->aiIdx[pCur->iPage];
67121  if( loc==0 ){
67122    CellInfo info;
67123    assert( idx<pPage->nCell );
67124    rc = sqlite3PagerWrite(pPage->pDbPage);
67125    if( rc ){
67126      goto end_insert;
67127    }
67128    oldCell = findCell(pPage, idx);
67129    if( !pPage->leaf ){
67130      memcpy(newCell, oldCell, 4);
67131    }
67132    rc = clearCell(pPage, oldCell, &info);
67133    if( info.nSize==szNew && info.nLocal==info.nPayload
67134     && (!ISAUTOVACUUM || szNew<pPage->minLocal)
67135    ){
67136      /* Overwrite the old cell with the new if they are the same size.
67137      ** We could also try to do this if the old cell is smaller, then add
67138      ** the leftover space to the free list.  But experiments show that
67139      ** doing that is no faster then skipping this optimization and just
67140      ** calling dropCell() and insertCell().
67141      **
67142      ** This optimization cannot be used on an autovacuum database if the
67143      ** new entry uses overflow pages, as the insertCell() call below is
67144      ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
67145      assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
67146      if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
67147      memcpy(oldCell, newCell, szNew);
67148      return SQLITE_OK;
67149    }
67150    dropCell(pPage, idx, info.nSize, &rc);
67151    if( rc ) goto end_insert;
67152  }else if( loc<0 && pPage->nCell>0 ){
67153    assert( pPage->leaf );
67154    idx = ++pCur->aiIdx[pCur->iPage];
67155  }else{
67156    assert( pPage->leaf );
67157  }
67158  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
67159  assert( pPage->nOverflow==0 || rc==SQLITE_OK );
67160  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
67161
67162  /* If no error has occurred and pPage has an overflow cell, call balance()
67163  ** to redistribute the cells within the tree. Since balance() may move
67164  ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
67165  ** variables.
67166  **
67167  ** Previous versions of SQLite called moveToRoot() to move the cursor
67168  ** back to the root page as balance() used to invalidate the contents
67169  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
67170  ** set the cursor state to "invalid". This makes common insert operations
67171  ** slightly faster.
67172  **
67173  ** There is a subtle but important optimization here too. When inserting
67174  ** multiple records into an intkey b-tree using a single cursor (as can
67175  ** happen while processing an "INSERT INTO ... SELECT" statement), it
67176  ** is advantageous to leave the cursor pointing to the last entry in
67177  ** the b-tree if possible. If the cursor is left pointing to the last
67178  ** entry in the table, and the next row inserted has an integer key
67179  ** larger than the largest existing key, it is possible to insert the
67180  ** row without seeking the cursor. This can be a big performance boost.
67181  */
67182  pCur->info.nSize = 0;
67183  if( pPage->nOverflow ){
67184    assert( rc==SQLITE_OK );
67185    pCur->curFlags &= ~(BTCF_ValidNKey);
67186    rc = balance(pCur);
67187
67188    /* Must make sure nOverflow is reset to zero even if the balance()
67189    ** fails. Internal data structure corruption will result otherwise.
67190    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
67191    ** from trying to save the current position of the cursor.  */
67192    pCur->apPage[pCur->iPage]->nOverflow = 0;
67193    pCur->eState = CURSOR_INVALID;
67194    if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
67195      rc = moveToRoot(pCur);
67196      if( pCur->pKeyInfo ){
67197        assert( pCur->pKey==0 );
67198        pCur->pKey = sqlite3Malloc( pX->nKey );
67199        if( pCur->pKey==0 ){
67200          rc = SQLITE_NOMEM;
67201        }else{
67202          memcpy(pCur->pKey, pX->pKey, pX->nKey);
67203        }
67204      }
67205      pCur->eState = CURSOR_REQUIRESEEK;
67206      pCur->nKey = pX->nKey;
67207    }
67208  }
67209  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
67210
67211end_insert:
67212  return rc;
67213}
67214
67215/*
67216** Delete the entry that the cursor is pointing to.
67217**
67218** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
67219** the cursor is left pointing at an arbitrary location after the delete.
67220** But if that bit is set, then the cursor is left in a state such that
67221** the next call to BtreeNext() or BtreePrev() moves it to the same row
67222** as it would have been on if the call to BtreeDelete() had been omitted.
67223**
67224** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
67225** associated with a single table entry and its indexes.  Only one of those
67226** deletes is considered the "primary" delete.  The primary delete occurs
67227** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
67228** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
67229** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
67230** but which might be used by alternative storage engines.
67231*/
67232SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
67233  Btree *p = pCur->pBtree;
67234  BtShared *pBt = p->pBt;
67235  int rc;                              /* Return code */
67236  MemPage *pPage;                      /* Page to delete cell from */
67237  unsigned char *pCell;                /* Pointer to cell to delete */
67238  int iCellIdx;                        /* Index of cell to delete */
67239  int iCellDepth;                      /* Depth of node containing pCell */
67240  CellInfo info;                       /* Size of the cell being deleted */
67241  int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
67242  u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
67243
67244  assert( cursorOwnsBtShared(pCur) );
67245  assert( pBt->inTransaction==TRANS_WRITE );
67246  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
67247  assert( pCur->curFlags & BTCF_WriteFlag );
67248  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
67249  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
67250  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
67251  assert( pCur->eState==CURSOR_VALID );
67252  assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
67253
67254  iCellDepth = pCur->iPage;
67255  iCellIdx = pCur->aiIdx[iCellDepth];
67256  pPage = pCur->apPage[iCellDepth];
67257  pCell = findCell(pPage, iCellIdx);
67258
67259  /* If the bPreserve flag is set to true, then the cursor position must
67260  ** be preserved following this delete operation. If the current delete
67261  ** will cause a b-tree rebalance, then this is done by saving the cursor
67262  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
67263  ** returning.
67264  **
67265  ** Or, if the current delete will not cause a rebalance, then the cursor
67266  ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
67267  ** before or after the deleted entry. In this case set bSkipnext to true.  */
67268  if( bPreserve ){
67269    if( !pPage->leaf
67270     || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
67271    ){
67272      /* A b-tree rebalance will be required after deleting this entry.
67273      ** Save the cursor key.  */
67274      rc = saveCursorKey(pCur);
67275      if( rc ) return rc;
67276    }else{
67277      bSkipnext = 1;
67278    }
67279  }
67280
67281  /* If the page containing the entry to delete is not a leaf page, move
67282  ** the cursor to the largest entry in the tree that is smaller than
67283  ** the entry being deleted. This cell will replace the cell being deleted
67284  ** from the internal node. The 'previous' entry is used for this instead
67285  ** of the 'next' entry, as the previous entry is always a part of the
67286  ** sub-tree headed by the child page of the cell being deleted. This makes
67287  ** balancing the tree following the delete operation easier.  */
67288  if( !pPage->leaf ){
67289    int notUsed = 0;
67290    rc = sqlite3BtreePrevious(pCur, &notUsed);
67291    if( rc ) return rc;
67292  }
67293
67294  /* Save the positions of any other cursors open on this table before
67295  ** making any modifications.  */
67296  if( pCur->curFlags & BTCF_Multiple ){
67297    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
67298    if( rc ) return rc;
67299  }
67300
67301  /* If this is a delete operation to remove a row from a table b-tree,
67302  ** invalidate any incrblob cursors open on the row being deleted.  */
67303  if( pCur->pKeyInfo==0 ){
67304    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
67305  }
67306
67307  /* Make the page containing the entry to be deleted writable. Then free any
67308  ** overflow pages associated with the entry and finally remove the cell
67309  ** itself from within the page.  */
67310  rc = sqlite3PagerWrite(pPage->pDbPage);
67311  if( rc ) return rc;
67312  rc = clearCell(pPage, pCell, &info);
67313  dropCell(pPage, iCellIdx, info.nSize, &rc);
67314  if( rc ) return rc;
67315
67316  /* If the cell deleted was not located on a leaf page, then the cursor
67317  ** is currently pointing to the largest entry in the sub-tree headed
67318  ** by the child-page of the cell that was just deleted from an internal
67319  ** node. The cell from the leaf node needs to be moved to the internal
67320  ** node to replace the deleted cell.  */
67321  if( !pPage->leaf ){
67322    MemPage *pLeaf = pCur->apPage[pCur->iPage];
67323    int nCell;
67324    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
67325    unsigned char *pTmp;
67326
67327    pCell = findCell(pLeaf, pLeaf->nCell-1);
67328    if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
67329    nCell = pLeaf->xCellSize(pLeaf, pCell);
67330    assert( MX_CELL_SIZE(pBt) >= nCell );
67331    pTmp = pBt->pTmpSpace;
67332    assert( pTmp!=0 );
67333    rc = sqlite3PagerWrite(pLeaf->pDbPage);
67334    if( rc==SQLITE_OK ){
67335      insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
67336    }
67337    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
67338    if( rc ) return rc;
67339  }
67340
67341  /* Balance the tree. If the entry deleted was located on a leaf page,
67342  ** then the cursor still points to that page. In this case the first
67343  ** call to balance() repairs the tree, and the if(...) condition is
67344  ** never true.
67345  **
67346  ** Otherwise, if the entry deleted was on an internal node page, then
67347  ** pCur is pointing to the leaf page from which a cell was removed to
67348  ** replace the cell deleted from the internal node. This is slightly
67349  ** tricky as the leaf node may be underfull, and the internal node may
67350  ** be either under or overfull. In this case run the balancing algorithm
67351  ** on the leaf node first. If the balance proceeds far enough up the
67352  ** tree that we can be sure that any problem in the internal node has
67353  ** been corrected, so be it. Otherwise, after balancing the leaf node,
67354  ** walk the cursor up the tree to the internal node and balance it as
67355  ** well.  */
67356  rc = balance(pCur);
67357  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
67358    while( pCur->iPage>iCellDepth ){
67359      releasePage(pCur->apPage[pCur->iPage--]);
67360    }
67361    rc = balance(pCur);
67362  }
67363
67364  if( rc==SQLITE_OK ){
67365    if( bSkipnext ){
67366      assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
67367      assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB );
67368      assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
67369      pCur->eState = CURSOR_SKIPNEXT;
67370      if( iCellIdx>=pPage->nCell ){
67371        pCur->skipNext = -1;
67372        pCur->aiIdx[iCellDepth] = pPage->nCell-1;
67373      }else{
67374        pCur->skipNext = 1;
67375      }
67376    }else{
67377      rc = moveToRoot(pCur);
67378      if( bPreserve ){
67379        pCur->eState = CURSOR_REQUIRESEEK;
67380      }
67381    }
67382  }
67383  return rc;
67384}
67385
67386/*
67387** Create a new BTree table.  Write into *piTable the page
67388** number for the root page of the new table.
67389**
67390** The type of type is determined by the flags parameter.  Only the
67391** following values of flags are currently in use.  Other values for
67392** flags might not work:
67393**
67394**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
67395**     BTREE_ZERODATA                  Used for SQL indices
67396*/
67397static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
67398  BtShared *pBt = p->pBt;
67399  MemPage *pRoot;
67400  Pgno pgnoRoot;
67401  int rc;
67402  int ptfFlags;          /* Page-type flage for the root page of new table */
67403
67404  assert( sqlite3BtreeHoldsMutex(p) );
67405  assert( pBt->inTransaction==TRANS_WRITE );
67406  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
67407
67408#ifdef SQLITE_OMIT_AUTOVACUUM
67409  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
67410  if( rc ){
67411    return rc;
67412  }
67413#else
67414  if( pBt->autoVacuum ){
67415    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
67416    MemPage *pPageMove; /* The page to move to. */
67417
67418    /* Creating a new table may probably require moving an existing database
67419    ** to make room for the new tables root page. In case this page turns
67420    ** out to be an overflow page, delete all overflow page-map caches
67421    ** held by open cursors.
67422    */
67423    invalidateAllOverflowCache(pBt);
67424
67425    /* Read the value of meta[3] from the database to determine where the
67426    ** root page of the new table should go. meta[3] is the largest root-page
67427    ** created so far, so the new root-page is (meta[3]+1).
67428    */
67429    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
67430    pgnoRoot++;
67431
67432    /* The new root-page may not be allocated on a pointer-map page, or the
67433    ** PENDING_BYTE page.
67434    */
67435    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
67436        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
67437      pgnoRoot++;
67438    }
67439    assert( pgnoRoot>=3 || CORRUPT_DB );
67440    testcase( pgnoRoot<3 );
67441
67442    /* Allocate a page. The page that currently resides at pgnoRoot will
67443    ** be moved to the allocated page (unless the allocated page happens
67444    ** to reside at pgnoRoot).
67445    */
67446    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
67447    if( rc!=SQLITE_OK ){
67448      return rc;
67449    }
67450
67451    if( pgnoMove!=pgnoRoot ){
67452      /* pgnoRoot is the page that will be used for the root-page of
67453      ** the new table (assuming an error did not occur). But we were
67454      ** allocated pgnoMove. If required (i.e. if it was not allocated
67455      ** by extending the file), the current page at position pgnoMove
67456      ** is already journaled.
67457      */
67458      u8 eType = 0;
67459      Pgno iPtrPage = 0;
67460
67461      /* Save the positions of any open cursors. This is required in
67462      ** case they are holding a reference to an xFetch reference
67463      ** corresponding to page pgnoRoot.  */
67464      rc = saveAllCursors(pBt, 0, 0);
67465      releasePage(pPageMove);
67466      if( rc!=SQLITE_OK ){
67467        return rc;
67468      }
67469
67470      /* Move the page currently at pgnoRoot to pgnoMove. */
67471      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
67472      if( rc!=SQLITE_OK ){
67473        return rc;
67474      }
67475      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
67476      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
67477        rc = SQLITE_CORRUPT_BKPT;
67478      }
67479      if( rc!=SQLITE_OK ){
67480        releasePage(pRoot);
67481        return rc;
67482      }
67483      assert( eType!=PTRMAP_ROOTPAGE );
67484      assert( eType!=PTRMAP_FREEPAGE );
67485      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
67486      releasePage(pRoot);
67487
67488      /* Obtain the page at pgnoRoot */
67489      if( rc!=SQLITE_OK ){
67490        return rc;
67491      }
67492      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
67493      if( rc!=SQLITE_OK ){
67494        return rc;
67495      }
67496      rc = sqlite3PagerWrite(pRoot->pDbPage);
67497      if( rc!=SQLITE_OK ){
67498        releasePage(pRoot);
67499        return rc;
67500      }
67501    }else{
67502      pRoot = pPageMove;
67503    }
67504
67505    /* Update the pointer-map and meta-data with the new root-page number. */
67506    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
67507    if( rc ){
67508      releasePage(pRoot);
67509      return rc;
67510    }
67511
67512    /* When the new root page was allocated, page 1 was made writable in
67513    ** order either to increase the database filesize, or to decrement the
67514    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
67515    */
67516    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
67517    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
67518    if( NEVER(rc) ){
67519      releasePage(pRoot);
67520      return rc;
67521    }
67522
67523  }else{
67524    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
67525    if( rc ) return rc;
67526  }
67527#endif
67528  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
67529  if( createTabFlags & BTREE_INTKEY ){
67530    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
67531  }else{
67532    ptfFlags = PTF_ZERODATA | PTF_LEAF;
67533  }
67534  zeroPage(pRoot, ptfFlags);
67535  sqlite3PagerUnref(pRoot->pDbPage);
67536  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
67537  *piTable = (int)pgnoRoot;
67538  return SQLITE_OK;
67539}
67540SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
67541  int rc;
67542  sqlite3BtreeEnter(p);
67543  rc = btreeCreateTable(p, piTable, flags);
67544  sqlite3BtreeLeave(p);
67545  return rc;
67546}
67547
67548/*
67549** Erase the given database page and all its children.  Return
67550** the page to the freelist.
67551*/
67552static int clearDatabasePage(
67553  BtShared *pBt,           /* The BTree that contains the table */
67554  Pgno pgno,               /* Page number to clear */
67555  int freePageFlag,        /* Deallocate page if true */
67556  int *pnChange            /* Add number of Cells freed to this counter */
67557){
67558  MemPage *pPage;
67559  int rc;
67560  unsigned char *pCell;
67561  int i;
67562  int hdr;
67563  CellInfo info;
67564
67565  assert( sqlite3_mutex_held(pBt->mutex) );
67566  if( pgno>btreePagecount(pBt) ){
67567    return SQLITE_CORRUPT_BKPT;
67568  }
67569  rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
67570  if( rc ) return rc;
67571  if( pPage->bBusy ){
67572    rc = SQLITE_CORRUPT_BKPT;
67573    goto cleardatabasepage_out;
67574  }
67575  pPage->bBusy = 1;
67576  hdr = pPage->hdrOffset;
67577  for(i=0; i<pPage->nCell; i++){
67578    pCell = findCell(pPage, i);
67579    if( !pPage->leaf ){
67580      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
67581      if( rc ) goto cleardatabasepage_out;
67582    }
67583    rc = clearCell(pPage, pCell, &info);
67584    if( rc ) goto cleardatabasepage_out;
67585  }
67586  if( !pPage->leaf ){
67587    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
67588    if( rc ) goto cleardatabasepage_out;
67589  }else if( pnChange ){
67590    assert( pPage->intKey || CORRUPT_DB );
67591    testcase( !pPage->intKey );
67592    *pnChange += pPage->nCell;
67593  }
67594  if( freePageFlag ){
67595    freePage(pPage, &rc);
67596  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
67597    zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
67598  }
67599
67600cleardatabasepage_out:
67601  pPage->bBusy = 0;
67602  releasePage(pPage);
67603  return rc;
67604}
67605
67606/*
67607** Delete all information from a single table in the database.  iTable is
67608** the page number of the root of the table.  After this routine returns,
67609** the root page is empty, but still exists.
67610**
67611** This routine will fail with SQLITE_LOCKED if there are any open
67612** read cursors on the table.  Open write cursors are moved to the
67613** root of the table.
67614**
67615** If pnChange is not NULL, then table iTable must be an intkey table. The
67616** integer value pointed to by pnChange is incremented by the number of
67617** entries in the table.
67618*/
67619SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
67620  int rc;
67621  BtShared *pBt = p->pBt;
67622  sqlite3BtreeEnter(p);
67623  assert( p->inTrans==TRANS_WRITE );
67624
67625  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
67626
67627  if( SQLITE_OK==rc ){
67628    /* Invalidate all incrblob cursors open on table iTable (assuming iTable
67629    ** is the root of a table b-tree - if it is not, the following call is
67630    ** a no-op).  */
67631    invalidateIncrblobCursors(p, 0, 1);
67632    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
67633  }
67634  sqlite3BtreeLeave(p);
67635  return rc;
67636}
67637
67638/*
67639** Delete all information from the single table that pCur is open on.
67640**
67641** This routine only work for pCur on an ephemeral table.
67642*/
67643SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
67644  return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
67645}
67646
67647/*
67648** Erase all information in a table and add the root of the table to
67649** the freelist.  Except, the root of the principle table (the one on
67650** page 1) is never added to the freelist.
67651**
67652** This routine will fail with SQLITE_LOCKED if there are any open
67653** cursors on the table.
67654**
67655** If AUTOVACUUM is enabled and the page at iTable is not the last
67656** root page in the database file, then the last root page
67657** in the database file is moved into the slot formerly occupied by
67658** iTable and that last slot formerly occupied by the last root page
67659** is added to the freelist instead of iTable.  In this say, all
67660** root pages are kept at the beginning of the database file, which
67661** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
67662** page number that used to be the last root page in the file before
67663** the move.  If no page gets moved, *piMoved is set to 0.
67664** The last root page is recorded in meta[3] and the value of
67665** meta[3] is updated by this procedure.
67666*/
67667static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
67668  int rc;
67669  MemPage *pPage = 0;
67670  BtShared *pBt = p->pBt;
67671
67672  assert( sqlite3BtreeHoldsMutex(p) );
67673  assert( p->inTrans==TRANS_WRITE );
67674  assert( iTable>=2 );
67675
67676  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
67677  if( rc ) return rc;
67678  rc = sqlite3BtreeClearTable(p, iTable, 0);
67679  if( rc ){
67680    releasePage(pPage);
67681    return rc;
67682  }
67683
67684  *piMoved = 0;
67685
67686#ifdef SQLITE_OMIT_AUTOVACUUM
67687  freePage(pPage, &rc);
67688  releasePage(pPage);
67689#else
67690  if( pBt->autoVacuum ){
67691    Pgno maxRootPgno;
67692    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
67693
67694    if( iTable==maxRootPgno ){
67695      /* If the table being dropped is the table with the largest root-page
67696      ** number in the database, put the root page on the free list.
67697      */
67698      freePage(pPage, &rc);
67699      releasePage(pPage);
67700      if( rc!=SQLITE_OK ){
67701        return rc;
67702      }
67703    }else{
67704      /* The table being dropped does not have the largest root-page
67705      ** number in the database. So move the page that does into the
67706      ** gap left by the deleted root-page.
67707      */
67708      MemPage *pMove;
67709      releasePage(pPage);
67710      rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
67711      if( rc!=SQLITE_OK ){
67712        return rc;
67713      }
67714      rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
67715      releasePage(pMove);
67716      if( rc!=SQLITE_OK ){
67717        return rc;
67718      }
67719      pMove = 0;
67720      rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
67721      freePage(pMove, &rc);
67722      releasePage(pMove);
67723      if( rc!=SQLITE_OK ){
67724        return rc;
67725      }
67726      *piMoved = maxRootPgno;
67727    }
67728
67729    /* Set the new 'max-root-page' value in the database header. This
67730    ** is the old value less one, less one more if that happens to
67731    ** be a root-page number, less one again if that is the
67732    ** PENDING_BYTE_PAGE.
67733    */
67734    maxRootPgno--;
67735    while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
67736           || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
67737      maxRootPgno--;
67738    }
67739    assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
67740
67741    rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
67742  }else{
67743    freePage(pPage, &rc);
67744    releasePage(pPage);
67745  }
67746#endif
67747  return rc;
67748}
67749SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
67750  int rc;
67751  sqlite3BtreeEnter(p);
67752  rc = btreeDropTable(p, iTable, piMoved);
67753  sqlite3BtreeLeave(p);
67754  return rc;
67755}
67756
67757
67758/*
67759** This function may only be called if the b-tree connection already
67760** has a read or write transaction open on the database.
67761**
67762** Read the meta-information out of a database file.  Meta[0]
67763** is the number of free pages currently in the database.  Meta[1]
67764** through meta[15] are available for use by higher layers.  Meta[0]
67765** is read-only, the others are read/write.
67766**
67767** The schema layer numbers meta values differently.  At the schema
67768** layer (and the SetCookie and ReadCookie opcodes) the number of
67769** free pages is not visible.  So Cookie[0] is the same as Meta[1].
67770**
67771** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
67772** of reading the value out of the header, it instead loads the "DataVersion"
67773** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
67774** database file.  It is a number computed by the pager.  But its access
67775** pattern is the same as header meta values, and so it is convenient to
67776** read it from this routine.
67777*/
67778SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
67779  BtShared *pBt = p->pBt;
67780
67781  sqlite3BtreeEnter(p);
67782  assert( p->inTrans>TRANS_NONE );
67783  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
67784  assert( pBt->pPage1 );
67785  assert( idx>=0 && idx<=15 );
67786
67787  if( idx==BTREE_DATA_VERSION ){
67788    *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
67789  }else{
67790    *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
67791  }
67792
67793  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
67794  ** database, mark the database as read-only.  */
67795#ifdef SQLITE_OMIT_AUTOVACUUM
67796  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
67797    pBt->btsFlags |= BTS_READ_ONLY;
67798  }
67799#endif
67800
67801  sqlite3BtreeLeave(p);
67802}
67803
67804/*
67805** Write meta-information back into the database.  Meta[0] is
67806** read-only and may not be written.
67807*/
67808SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
67809  BtShared *pBt = p->pBt;
67810  unsigned char *pP1;
67811  int rc;
67812  assert( idx>=1 && idx<=15 );
67813  sqlite3BtreeEnter(p);
67814  assert( p->inTrans==TRANS_WRITE );
67815  assert( pBt->pPage1!=0 );
67816  pP1 = pBt->pPage1->aData;
67817  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
67818  if( rc==SQLITE_OK ){
67819    put4byte(&pP1[36 + idx*4], iMeta);
67820#ifndef SQLITE_OMIT_AUTOVACUUM
67821    if( idx==BTREE_INCR_VACUUM ){
67822      assert( pBt->autoVacuum || iMeta==0 );
67823      assert( iMeta==0 || iMeta==1 );
67824      pBt->incrVacuum = (u8)iMeta;
67825    }
67826#endif
67827  }
67828  sqlite3BtreeLeave(p);
67829  return rc;
67830}
67831
67832#ifndef SQLITE_OMIT_BTREECOUNT
67833/*
67834** The first argument, pCur, is a cursor opened on some b-tree. Count the
67835** number of entries in the b-tree and write the result to *pnEntry.
67836**
67837** SQLITE_OK is returned if the operation is successfully executed.
67838** Otherwise, if an error is encountered (i.e. an IO error or database
67839** corruption) an SQLite error code is returned.
67840*/
67841SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
67842  i64 nEntry = 0;                      /* Value to return in *pnEntry */
67843  int rc;                              /* Return code */
67844
67845  if( pCur->pgnoRoot==0 ){
67846    *pnEntry = 0;
67847    return SQLITE_OK;
67848  }
67849  rc = moveToRoot(pCur);
67850
67851  /* Unless an error occurs, the following loop runs one iteration for each
67852  ** page in the B-Tree structure (not including overflow pages).
67853  */
67854  while( rc==SQLITE_OK ){
67855    int iIdx;                          /* Index of child node in parent */
67856    MemPage *pPage;                    /* Current page of the b-tree */
67857
67858    /* If this is a leaf page or the tree is not an int-key tree, then
67859    ** this page contains countable entries. Increment the entry counter
67860    ** accordingly.
67861    */
67862    pPage = pCur->apPage[pCur->iPage];
67863    if( pPage->leaf || !pPage->intKey ){
67864      nEntry += pPage->nCell;
67865    }
67866
67867    /* pPage is a leaf node. This loop navigates the cursor so that it
67868    ** points to the first interior cell that it points to the parent of
67869    ** the next page in the tree that has not yet been visited. The
67870    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
67871    ** of the page, or to the number of cells in the page if the next page
67872    ** to visit is the right-child of its parent.
67873    **
67874    ** If all pages in the tree have been visited, return SQLITE_OK to the
67875    ** caller.
67876    */
67877    if( pPage->leaf ){
67878      do {
67879        if( pCur->iPage==0 ){
67880          /* All pages of the b-tree have been visited. Return successfully. */
67881          *pnEntry = nEntry;
67882          return moveToRoot(pCur);
67883        }
67884        moveToParent(pCur);
67885      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
67886
67887      pCur->aiIdx[pCur->iPage]++;
67888      pPage = pCur->apPage[pCur->iPage];
67889    }
67890
67891    /* Descend to the child node of the cell that the cursor currently
67892    ** points at. This is the right-child if (iIdx==pPage->nCell).
67893    */
67894    iIdx = pCur->aiIdx[pCur->iPage];
67895    if( iIdx==pPage->nCell ){
67896      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
67897    }else{
67898      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
67899    }
67900  }
67901
67902  /* An error has occurred. Return an error code. */
67903  return rc;
67904}
67905#endif
67906
67907/*
67908** Return the pager associated with a BTree.  This routine is used for
67909** testing and debugging only.
67910*/
67911SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
67912  return p->pBt->pPager;
67913}
67914
67915#ifndef SQLITE_OMIT_INTEGRITY_CHECK
67916/*
67917** Append a message to the error message string.
67918*/
67919static void checkAppendMsg(
67920  IntegrityCk *pCheck,
67921  const char *zFormat,
67922  ...
67923){
67924  va_list ap;
67925  if( !pCheck->mxErr ) return;
67926  pCheck->mxErr--;
67927  pCheck->nErr++;
67928  va_start(ap, zFormat);
67929  if( pCheck->errMsg.nChar ){
67930    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
67931  }
67932  if( pCheck->zPfx ){
67933    sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
67934  }
67935  sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
67936  va_end(ap);
67937  if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
67938    pCheck->mallocFailed = 1;
67939  }
67940}
67941#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67942
67943#ifndef SQLITE_OMIT_INTEGRITY_CHECK
67944
67945/*
67946** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
67947** corresponds to page iPg is already set.
67948*/
67949static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
67950  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
67951  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
67952}
67953
67954/*
67955** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
67956*/
67957static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
67958  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
67959  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
67960}
67961
67962
67963/*
67964** Add 1 to the reference count for page iPage.  If this is the second
67965** reference to the page, add an error message to pCheck->zErrMsg.
67966** Return 1 if there are 2 or more references to the page and 0 if
67967** if this is the first reference to the page.
67968**
67969** Also check that the page number is in bounds.
67970*/
67971static int checkRef(IntegrityCk *pCheck, Pgno iPage){
67972  if( iPage==0 ) return 1;
67973  if( iPage>pCheck->nPage ){
67974    checkAppendMsg(pCheck, "invalid page number %d", iPage);
67975    return 1;
67976  }
67977  if( getPageReferenced(pCheck, iPage) ){
67978    checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
67979    return 1;
67980  }
67981  setPageReferenced(pCheck, iPage);
67982  return 0;
67983}
67984
67985#ifndef SQLITE_OMIT_AUTOVACUUM
67986/*
67987** Check that the entry in the pointer-map for page iChild maps to
67988** page iParent, pointer type ptrType. If not, append an error message
67989** to pCheck.
67990*/
67991static void checkPtrmap(
67992  IntegrityCk *pCheck,   /* Integrity check context */
67993  Pgno iChild,           /* Child page number */
67994  u8 eType,              /* Expected pointer map type */
67995  Pgno iParent           /* Expected pointer map parent page number */
67996){
67997  int rc;
67998  u8 ePtrmapType;
67999  Pgno iPtrmapParent;
68000
68001  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
68002  if( rc!=SQLITE_OK ){
68003    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
68004    checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
68005    return;
68006  }
68007
68008  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
68009    checkAppendMsg(pCheck,
68010      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
68011      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
68012  }
68013}
68014#endif
68015
68016/*
68017** Check the integrity of the freelist or of an overflow page list.
68018** Verify that the number of pages on the list is N.
68019*/
68020static void checkList(
68021  IntegrityCk *pCheck,  /* Integrity checking context */
68022  int isFreeList,       /* True for a freelist.  False for overflow page list */
68023  int iPage,            /* Page number for first page in the list */
68024  int N                 /* Expected number of pages in the list */
68025){
68026  int i;
68027  int expected = N;
68028  int iFirst = iPage;
68029  while( N-- > 0 && pCheck->mxErr ){
68030    DbPage *pOvflPage;
68031    unsigned char *pOvflData;
68032    if( iPage<1 ){
68033      checkAppendMsg(pCheck,
68034         "%d of %d pages missing from overflow list starting at %d",
68035          N+1, expected, iFirst);
68036      break;
68037    }
68038    if( checkRef(pCheck, iPage) ) break;
68039    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
68040      checkAppendMsg(pCheck, "failed to get page %d", iPage);
68041      break;
68042    }
68043    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
68044    if( isFreeList ){
68045      int n = get4byte(&pOvflData[4]);
68046#ifndef SQLITE_OMIT_AUTOVACUUM
68047      if( pCheck->pBt->autoVacuum ){
68048        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
68049      }
68050#endif
68051      if( n>(int)pCheck->pBt->usableSize/4-2 ){
68052        checkAppendMsg(pCheck,
68053           "freelist leaf count too big on page %d", iPage);
68054        N--;
68055      }else{
68056        for(i=0; i<n; i++){
68057          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
68058#ifndef SQLITE_OMIT_AUTOVACUUM
68059          if( pCheck->pBt->autoVacuum ){
68060            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
68061          }
68062#endif
68063          checkRef(pCheck, iFreePage);
68064        }
68065        N -= n;
68066      }
68067    }
68068#ifndef SQLITE_OMIT_AUTOVACUUM
68069    else{
68070      /* If this database supports auto-vacuum and iPage is not the last
68071      ** page in this overflow list, check that the pointer-map entry for
68072      ** the following page matches iPage.
68073      */
68074      if( pCheck->pBt->autoVacuum && N>0 ){
68075        i = get4byte(pOvflData);
68076        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
68077      }
68078    }
68079#endif
68080    iPage = get4byte(pOvflData);
68081    sqlite3PagerUnref(pOvflPage);
68082
68083    if( isFreeList && N<(iPage!=0) ){
68084      checkAppendMsg(pCheck, "free-page count in header is too small");
68085    }
68086  }
68087}
68088#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
68089
68090/*
68091** An implementation of a min-heap.
68092**
68093** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
68094** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
68095** and aHeap[N*2+1].
68096**
68097** The heap property is this:  Every node is less than or equal to both
68098** of its daughter nodes.  A consequence of the heap property is that the
68099** root node aHeap[1] is always the minimum value currently in the heap.
68100**
68101** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
68102** the heap, preserving the heap property.  The btreeHeapPull() routine
68103** removes the root element from the heap (the minimum value in the heap)
68104** and then moves other nodes around as necessary to preserve the heap
68105** property.
68106**
68107** This heap is used for cell overlap and coverage testing.  Each u32
68108** entry represents the span of a cell or freeblock on a btree page.
68109** The upper 16 bits are the index of the first byte of a range and the
68110** lower 16 bits are the index of the last byte of that range.
68111*/
68112static void btreeHeapInsert(u32 *aHeap, u32 x){
68113  u32 j, i = ++aHeap[0];
68114  aHeap[i] = x;
68115  while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
68116    x = aHeap[j];
68117    aHeap[j] = aHeap[i];
68118    aHeap[i] = x;
68119    i = j;
68120  }
68121}
68122static int btreeHeapPull(u32 *aHeap, u32 *pOut){
68123  u32 j, i, x;
68124  if( (x = aHeap[0])==0 ) return 0;
68125  *pOut = aHeap[1];
68126  aHeap[1] = aHeap[x];
68127  aHeap[x] = 0xffffffff;
68128  aHeap[0]--;
68129  i = 1;
68130  while( (j = i*2)<=aHeap[0] ){
68131    if( aHeap[j]>aHeap[j+1] ) j++;
68132    if( aHeap[i]<aHeap[j] ) break;
68133    x = aHeap[i];
68134    aHeap[i] = aHeap[j];
68135    aHeap[j] = x;
68136    i = j;
68137  }
68138  return 1;
68139}
68140
68141#ifndef SQLITE_OMIT_INTEGRITY_CHECK
68142/*
68143** Do various sanity checks on a single page of a tree.  Return
68144** the tree depth.  Root pages return 0.  Parents of root pages
68145** return 1, and so forth.
68146**
68147** These checks are done:
68148**
68149**      1.  Make sure that cells and freeblocks do not overlap
68150**          but combine to completely cover the page.
68151**      2.  Make sure integer cell keys are in order.
68152**      3.  Check the integrity of overflow pages.
68153**      4.  Recursively call checkTreePage on all children.
68154**      5.  Verify that the depth of all children is the same.
68155*/
68156static int checkTreePage(
68157  IntegrityCk *pCheck,  /* Context for the sanity check */
68158  int iPage,            /* Page number of the page to check */
68159  i64 *piMinKey,        /* Write minimum integer primary key here */
68160  i64 maxKey            /* Error if integer primary key greater than this */
68161){
68162  MemPage *pPage = 0;      /* The page being analyzed */
68163  int i;                   /* Loop counter */
68164  int rc;                  /* Result code from subroutine call */
68165  int depth = -1, d2;      /* Depth of a subtree */
68166  int pgno;                /* Page number */
68167  int nFrag;               /* Number of fragmented bytes on the page */
68168  int hdr;                 /* Offset to the page header */
68169  int cellStart;           /* Offset to the start of the cell pointer array */
68170  int nCell;               /* Number of cells */
68171  int doCoverageCheck = 1; /* True if cell coverage checking should be done */
68172  int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
68173                           ** False if IPK must be strictly less than maxKey */
68174  u8 *data;                /* Page content */
68175  u8 *pCell;               /* Cell content */
68176  u8 *pCellIdx;            /* Next element of the cell pointer array */
68177  BtShared *pBt;           /* The BtShared object that owns pPage */
68178  u32 pc;                  /* Address of a cell */
68179  u32 usableSize;          /* Usable size of the page */
68180  u32 contentOffset;       /* Offset to the start of the cell content area */
68181  u32 *heap = 0;           /* Min-heap used for checking cell coverage */
68182  u32 x, prev = 0;         /* Next and previous entry on the min-heap */
68183  const char *saved_zPfx = pCheck->zPfx;
68184  int saved_v1 = pCheck->v1;
68185  int saved_v2 = pCheck->v2;
68186  u8 savedIsInit = 0;
68187
68188  /* Check that the page exists
68189  */
68190  pBt = pCheck->pBt;
68191  usableSize = pBt->usableSize;
68192  if( iPage==0 ) return 0;
68193  if( checkRef(pCheck, iPage) ) return 0;
68194  pCheck->zPfx = "Page %d: ";
68195  pCheck->v1 = iPage;
68196  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
68197    checkAppendMsg(pCheck,
68198       "unable to get the page. error code=%d", rc);
68199    goto end_of_check;
68200  }
68201
68202  /* Clear MemPage.isInit to make sure the corruption detection code in
68203  ** btreeInitPage() is executed.  */
68204  savedIsInit = pPage->isInit;
68205  pPage->isInit = 0;
68206  if( (rc = btreeInitPage(pPage))!=0 ){
68207    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
68208    checkAppendMsg(pCheck,
68209                   "btreeInitPage() returns error code %d", rc);
68210    goto end_of_check;
68211  }
68212  data = pPage->aData;
68213  hdr = pPage->hdrOffset;
68214
68215  /* Set up for cell analysis */
68216  pCheck->zPfx = "On tree page %d cell %d: ";
68217  contentOffset = get2byteNotZero(&data[hdr+5]);
68218  assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
68219
68220  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
68221  ** number of cells on the page. */
68222  nCell = get2byte(&data[hdr+3]);
68223  assert( pPage->nCell==nCell );
68224
68225  /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
68226  ** immediately follows the b-tree page header. */
68227  cellStart = hdr + 12 - 4*pPage->leaf;
68228  assert( pPage->aCellIdx==&data[cellStart] );
68229  pCellIdx = &data[cellStart + 2*(nCell-1)];
68230
68231  if( !pPage->leaf ){
68232    /* Analyze the right-child page of internal pages */
68233    pgno = get4byte(&data[hdr+8]);
68234#ifndef SQLITE_OMIT_AUTOVACUUM
68235    if( pBt->autoVacuum ){
68236      pCheck->zPfx = "On page %d at right child: ";
68237      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
68238    }
68239#endif
68240    depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
68241    keyCanBeEqual = 0;
68242  }else{
68243    /* For leaf pages, the coverage check will occur in the same loop
68244    ** as the other cell checks, so initialize the heap.  */
68245    heap = pCheck->heap;
68246    heap[0] = 0;
68247  }
68248
68249  /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
68250  ** integer offsets to the cell contents. */
68251  for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
68252    CellInfo info;
68253
68254    /* Check cell size */
68255    pCheck->v2 = i;
68256    assert( pCellIdx==&data[cellStart + i*2] );
68257    pc = get2byteAligned(pCellIdx);
68258    pCellIdx -= 2;
68259    if( pc<contentOffset || pc>usableSize-4 ){
68260      checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
68261                             pc, contentOffset, usableSize-4);
68262      doCoverageCheck = 0;
68263      continue;
68264    }
68265    pCell = &data[pc];
68266    pPage->xParseCell(pPage, pCell, &info);
68267    if( pc+info.nSize>usableSize ){
68268      checkAppendMsg(pCheck, "Extends off end of page");
68269      doCoverageCheck = 0;
68270      continue;
68271    }
68272
68273    /* Check for integer primary key out of range */
68274    if( pPage->intKey ){
68275      if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
68276        checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
68277      }
68278      maxKey = info.nKey;
68279    }
68280
68281    /* Check the content overflow list */
68282    if( info.nPayload>info.nLocal ){
68283      int nPage;       /* Number of pages on the overflow chain */
68284      Pgno pgnoOvfl;   /* First page of the overflow chain */
68285      assert( pc + info.nSize - 4 <= usableSize );
68286      nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
68287      pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
68288#ifndef SQLITE_OMIT_AUTOVACUUM
68289      if( pBt->autoVacuum ){
68290        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
68291      }
68292#endif
68293      checkList(pCheck, 0, pgnoOvfl, nPage);
68294    }
68295
68296    if( !pPage->leaf ){
68297      /* Check sanity of left child page for internal pages */
68298      pgno = get4byte(pCell);
68299#ifndef SQLITE_OMIT_AUTOVACUUM
68300      if( pBt->autoVacuum ){
68301        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
68302      }
68303#endif
68304      d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
68305      keyCanBeEqual = 0;
68306      if( d2!=depth ){
68307        checkAppendMsg(pCheck, "Child page depth differs");
68308        depth = d2;
68309      }
68310    }else{
68311      /* Populate the coverage-checking heap for leaf pages */
68312      btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
68313    }
68314  }
68315  *piMinKey = maxKey;
68316
68317  /* Check for complete coverage of the page
68318  */
68319  pCheck->zPfx = 0;
68320  if( doCoverageCheck && pCheck->mxErr>0 ){
68321    /* For leaf pages, the min-heap has already been initialized and the
68322    ** cells have already been inserted.  But for internal pages, that has
68323    ** not yet been done, so do it now */
68324    if( !pPage->leaf ){
68325      heap = pCheck->heap;
68326      heap[0] = 0;
68327      for(i=nCell-1; i>=0; i--){
68328        u32 size;
68329        pc = get2byteAligned(&data[cellStart+i*2]);
68330        size = pPage->xCellSize(pPage, &data[pc]);
68331        btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
68332      }
68333    }
68334    /* Add the freeblocks to the min-heap
68335    **
68336    ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
68337    ** is the offset of the first freeblock, or zero if there are no
68338    ** freeblocks on the page.
68339    */
68340    i = get2byte(&data[hdr+1]);
68341    while( i>0 ){
68342      int size, j;
68343      assert( (u32)i<=usableSize-4 );     /* Enforced by btreeInitPage() */
68344      size = get2byte(&data[i+2]);
68345      assert( (u32)(i+size)<=usableSize );  /* Enforced by btreeInitPage() */
68346      btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
68347      /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
68348      ** big-endian integer which is the offset in the b-tree page of the next
68349      ** freeblock in the chain, or zero if the freeblock is the last on the
68350      ** chain. */
68351      j = get2byte(&data[i]);
68352      /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
68353      ** increasing offset. */
68354      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
68355      assert( (u32)j<=usableSize-4 );   /* Enforced by btreeInitPage() */
68356      i = j;
68357    }
68358    /* Analyze the min-heap looking for overlap between cells and/or
68359    ** freeblocks, and counting the number of untracked bytes in nFrag.
68360    **
68361    ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
68362    ** There is an implied first entry the covers the page header, the cell
68363    ** pointer index, and the gap between the cell pointer index and the start
68364    ** of cell content.
68365    **
68366    ** The loop below pulls entries from the min-heap in order and compares
68367    ** the start_address against the previous end_address.  If there is an
68368    ** overlap, that means bytes are used multiple times.  If there is a gap,
68369    ** that gap is added to the fragmentation count.
68370    */
68371    nFrag = 0;
68372    prev = contentOffset - 1;   /* Implied first min-heap entry */
68373    while( btreeHeapPull(heap,&x) ){
68374      if( (prev&0xffff)>=(x>>16) ){
68375        checkAppendMsg(pCheck,
68376          "Multiple uses for byte %u of page %d", x>>16, iPage);
68377        break;
68378      }else{
68379        nFrag += (x>>16) - (prev&0xffff) - 1;
68380        prev = x;
68381      }
68382    }
68383    nFrag += usableSize - (prev&0xffff) - 1;
68384    /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
68385    ** is stored in the fifth field of the b-tree page header.
68386    ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
68387    ** number of fragmented free bytes within the cell content area.
68388    */
68389    if( heap[0]==0 && nFrag!=data[hdr+7] ){
68390      checkAppendMsg(pCheck,
68391          "Fragmentation of %d bytes reported as %d on page %d",
68392          nFrag, data[hdr+7], iPage);
68393    }
68394  }
68395
68396end_of_check:
68397  if( !doCoverageCheck ) pPage->isInit = savedIsInit;
68398  releasePage(pPage);
68399  pCheck->zPfx = saved_zPfx;
68400  pCheck->v1 = saved_v1;
68401  pCheck->v2 = saved_v2;
68402  return depth+1;
68403}
68404#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
68405
68406#ifndef SQLITE_OMIT_INTEGRITY_CHECK
68407/*
68408** This routine does a complete check of the given BTree file.  aRoot[] is
68409** an array of pages numbers were each page number is the root page of
68410** a table.  nRoot is the number of entries in aRoot.
68411**
68412** A read-only or read-write transaction must be opened before calling
68413** this function.
68414**
68415** Write the number of error seen in *pnErr.  Except for some memory
68416** allocation errors,  an error message held in memory obtained from
68417** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
68418** returned.  If a memory allocation error occurs, NULL is returned.
68419*/
68420SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
68421  Btree *p,     /* The btree to be checked */
68422  int *aRoot,   /* An array of root pages numbers for individual trees */
68423  int nRoot,    /* Number of entries in aRoot[] */
68424  int mxErr,    /* Stop reporting errors after this many */
68425  int *pnErr    /* Write number of errors seen to this variable */
68426){
68427  Pgno i;
68428  IntegrityCk sCheck;
68429  BtShared *pBt = p->pBt;
68430  int savedDbFlags = pBt->db->flags;
68431  char zErr[100];
68432  VVA_ONLY( int nRef );
68433
68434  sqlite3BtreeEnter(p);
68435  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
68436  VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
68437  assert( nRef>=0 );
68438  sCheck.pBt = pBt;
68439  sCheck.pPager = pBt->pPager;
68440  sCheck.nPage = btreePagecount(sCheck.pBt);
68441  sCheck.mxErr = mxErr;
68442  sCheck.nErr = 0;
68443  sCheck.mallocFailed = 0;
68444  sCheck.zPfx = 0;
68445  sCheck.v1 = 0;
68446  sCheck.v2 = 0;
68447  sCheck.aPgRef = 0;
68448  sCheck.heap = 0;
68449  sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
68450  sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
68451  if( sCheck.nPage==0 ){
68452    goto integrity_ck_cleanup;
68453  }
68454
68455  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
68456  if( !sCheck.aPgRef ){
68457    sCheck.mallocFailed = 1;
68458    goto integrity_ck_cleanup;
68459  }
68460  sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
68461  if( sCheck.heap==0 ){
68462    sCheck.mallocFailed = 1;
68463    goto integrity_ck_cleanup;
68464  }
68465
68466  i = PENDING_BYTE_PAGE(pBt);
68467  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
68468
68469  /* Check the integrity of the freelist
68470  */
68471  sCheck.zPfx = "Main freelist: ";
68472  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
68473            get4byte(&pBt->pPage1->aData[36]));
68474  sCheck.zPfx = 0;
68475
68476  /* Check all the tables.
68477  */
68478  testcase( pBt->db->flags & SQLITE_CellSizeCk );
68479  pBt->db->flags &= ~SQLITE_CellSizeCk;
68480  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
68481    i64 notUsed;
68482    if( aRoot[i]==0 ) continue;
68483#ifndef SQLITE_OMIT_AUTOVACUUM
68484    if( pBt->autoVacuum && aRoot[i]>1 ){
68485      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
68486    }
68487#endif
68488    checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
68489  }
68490  pBt->db->flags = savedDbFlags;
68491
68492  /* Make sure every page in the file is referenced
68493  */
68494  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
68495#ifdef SQLITE_OMIT_AUTOVACUUM
68496    if( getPageReferenced(&sCheck, i)==0 ){
68497      checkAppendMsg(&sCheck, "Page %d is never used", i);
68498    }
68499#else
68500    /* If the database supports auto-vacuum, make sure no tables contain
68501    ** references to pointer-map pages.
68502    */
68503    if( getPageReferenced(&sCheck, i)==0 &&
68504       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
68505      checkAppendMsg(&sCheck, "Page %d is never used", i);
68506    }
68507    if( getPageReferenced(&sCheck, i)!=0 &&
68508       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
68509      checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
68510    }
68511#endif
68512  }
68513
68514  /* Clean  up and report errors.
68515  */
68516integrity_ck_cleanup:
68517  sqlite3PageFree(sCheck.heap);
68518  sqlite3_free(sCheck.aPgRef);
68519  if( sCheck.mallocFailed ){
68520    sqlite3StrAccumReset(&sCheck.errMsg);
68521    sCheck.nErr++;
68522  }
68523  *pnErr = sCheck.nErr;
68524  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
68525  /* Make sure this analysis did not leave any unref() pages. */
68526  assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
68527  sqlite3BtreeLeave(p);
68528  return sqlite3StrAccumFinish(&sCheck.errMsg);
68529}
68530#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
68531
68532/*
68533** Return the full pathname of the underlying database file.  Return
68534** an empty string if the database is in-memory or a TEMP database.
68535**
68536** The pager filename is invariant as long as the pager is
68537** open so it is safe to access without the BtShared mutex.
68538*/
68539SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
68540  assert( p->pBt->pPager!=0 );
68541  return sqlite3PagerFilename(p->pBt->pPager, 1);
68542}
68543
68544/*
68545** Return the pathname of the journal file for this database. The return
68546** value of this routine is the same regardless of whether the journal file
68547** has been created or not.
68548**
68549** The pager journal filename is invariant as long as the pager is
68550** open so it is safe to access without the BtShared mutex.
68551*/
68552SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
68553  assert( p->pBt->pPager!=0 );
68554  return sqlite3PagerJournalname(p->pBt->pPager);
68555}
68556
68557/*
68558** Return non-zero if a transaction is active.
68559*/
68560SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
68561  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
68562  return (p && (p->inTrans==TRANS_WRITE));
68563}
68564
68565#ifndef SQLITE_OMIT_WAL
68566/*
68567** Run a checkpoint on the Btree passed as the first argument.
68568**
68569** Return SQLITE_LOCKED if this or any other connection has an open
68570** transaction on the shared-cache the argument Btree is connected to.
68571**
68572** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
68573*/
68574SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
68575  int rc = SQLITE_OK;
68576  if( p ){
68577    BtShared *pBt = p->pBt;
68578    sqlite3BtreeEnter(p);
68579    if( pBt->inTransaction!=TRANS_NONE ){
68580      rc = SQLITE_LOCKED;
68581    }else{
68582      rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
68583    }
68584    sqlite3BtreeLeave(p);
68585  }
68586  return rc;
68587}
68588#endif
68589
68590/*
68591** Return non-zero if a read (or write) transaction is active.
68592*/
68593SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
68594  assert( p );
68595  assert( sqlite3_mutex_held(p->db->mutex) );
68596  return p->inTrans!=TRANS_NONE;
68597}
68598
68599SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
68600  assert( p );
68601  assert( sqlite3_mutex_held(p->db->mutex) );
68602  return p->nBackup!=0;
68603}
68604
68605/*
68606** This function returns a pointer to a blob of memory associated with
68607** a single shared-btree. The memory is used by client code for its own
68608** purposes (for example, to store a high-level schema associated with
68609** the shared-btree). The btree layer manages reference counting issues.
68610**
68611** The first time this is called on a shared-btree, nBytes bytes of memory
68612** are allocated, zeroed, and returned to the caller. For each subsequent
68613** call the nBytes parameter is ignored and a pointer to the same blob
68614** of memory returned.
68615**
68616** If the nBytes parameter is 0 and the blob of memory has not yet been
68617** allocated, a null pointer is returned. If the blob has already been
68618** allocated, it is returned as normal.
68619**
68620** Just before the shared-btree is closed, the function passed as the
68621** xFree argument when the memory allocation was made is invoked on the
68622** blob of allocated memory. The xFree function should not call sqlite3_free()
68623** on the memory, the btree layer does that.
68624*/
68625SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
68626  BtShared *pBt = p->pBt;
68627  sqlite3BtreeEnter(p);
68628  if( !pBt->pSchema && nBytes ){
68629    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
68630    pBt->xFreeSchema = xFree;
68631  }
68632  sqlite3BtreeLeave(p);
68633  return pBt->pSchema;
68634}
68635
68636/*
68637** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
68638** btree as the argument handle holds an exclusive lock on the
68639** sqlite_master table. Otherwise SQLITE_OK.
68640*/
68641SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
68642  int rc;
68643  assert( sqlite3_mutex_held(p->db->mutex) );
68644  sqlite3BtreeEnter(p);
68645  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
68646  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
68647  sqlite3BtreeLeave(p);
68648  return rc;
68649}
68650
68651
68652#ifndef SQLITE_OMIT_SHARED_CACHE
68653/*
68654** Obtain a lock on the table whose root page is iTab.  The
68655** lock is a write lock if isWritelock is true or a read lock
68656** if it is false.
68657*/
68658SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
68659  int rc = SQLITE_OK;
68660  assert( p->inTrans!=TRANS_NONE );
68661  if( p->sharable ){
68662    u8 lockType = READ_LOCK + isWriteLock;
68663    assert( READ_LOCK+1==WRITE_LOCK );
68664    assert( isWriteLock==0 || isWriteLock==1 );
68665
68666    sqlite3BtreeEnter(p);
68667    rc = querySharedCacheTableLock(p, iTab, lockType);
68668    if( rc==SQLITE_OK ){
68669      rc = setSharedCacheTableLock(p, iTab, lockType);
68670    }
68671    sqlite3BtreeLeave(p);
68672  }
68673  return rc;
68674}
68675#endif
68676
68677#ifndef SQLITE_OMIT_INCRBLOB
68678/*
68679** Argument pCsr must be a cursor opened for writing on an
68680** INTKEY table currently pointing at a valid table entry.
68681** This function modifies the data stored as part of that entry.
68682**
68683** Only the data content may only be modified, it is not possible to
68684** change the length of the data stored. If this function is called with
68685** parameters that attempt to write past the end of the existing data,
68686** no modifications are made and SQLITE_CORRUPT is returned.
68687*/
68688SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
68689  int rc;
68690  assert( cursorOwnsBtShared(pCsr) );
68691  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
68692  assert( pCsr->curFlags & BTCF_Incrblob );
68693
68694  rc = restoreCursorPosition(pCsr);
68695  if( rc!=SQLITE_OK ){
68696    return rc;
68697  }
68698  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
68699  if( pCsr->eState!=CURSOR_VALID ){
68700    return SQLITE_ABORT;
68701  }
68702
68703  /* Save the positions of all other cursors open on this table. This is
68704  ** required in case any of them are holding references to an xFetch
68705  ** version of the b-tree page modified by the accessPayload call below.
68706  **
68707  ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
68708  ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
68709  ** saveAllCursors can only return SQLITE_OK.
68710  */
68711  VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
68712  assert( rc==SQLITE_OK );
68713
68714  /* Check some assumptions:
68715  **   (a) the cursor is open for writing,
68716  **   (b) there is a read/write transaction open,
68717  **   (c) the connection holds a write-lock on the table (if required),
68718  **   (d) there are no conflicting read-locks, and
68719  **   (e) the cursor points at a valid row of an intKey table.
68720  */
68721  if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
68722    return SQLITE_READONLY;
68723  }
68724  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
68725              && pCsr->pBt->inTransaction==TRANS_WRITE );
68726  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
68727  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
68728  assert( pCsr->apPage[pCsr->iPage]->intKey );
68729
68730  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
68731}
68732
68733/*
68734** Mark this cursor as an incremental blob cursor.
68735*/
68736SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
68737  pCur->curFlags |= BTCF_Incrblob;
68738  pCur->pBtree->hasIncrblobCur = 1;
68739}
68740#endif
68741
68742/*
68743** Set both the "read version" (single byte at byte offset 18) and
68744** "write version" (single byte at byte offset 19) fields in the database
68745** header to iVersion.
68746*/
68747SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
68748  BtShared *pBt = pBtree->pBt;
68749  int rc;                         /* Return code */
68750
68751  assert( iVersion==1 || iVersion==2 );
68752
68753  /* If setting the version fields to 1, do not automatically open the
68754  ** WAL connection, even if the version fields are currently set to 2.
68755  */
68756  pBt->btsFlags &= ~BTS_NO_WAL;
68757  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
68758
68759  rc = sqlite3BtreeBeginTrans(pBtree, 0);
68760  if( rc==SQLITE_OK ){
68761    u8 *aData = pBt->pPage1->aData;
68762    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
68763      rc = sqlite3BtreeBeginTrans(pBtree, 2);
68764      if( rc==SQLITE_OK ){
68765        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
68766        if( rc==SQLITE_OK ){
68767          aData[18] = (u8)iVersion;
68768          aData[19] = (u8)iVersion;
68769        }
68770      }
68771    }
68772  }
68773
68774  pBt->btsFlags &= ~BTS_NO_WAL;
68775  return rc;
68776}
68777
68778/*
68779** Return true if the cursor has a hint specified.  This routine is
68780** only used from within assert() statements
68781*/
68782SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
68783  return (pCsr->hints & mask)!=0;
68784}
68785
68786/*
68787** Return true if the given Btree is read-only.
68788*/
68789SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
68790  return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
68791}
68792
68793/*
68794** Return the size of the header added to each page by this module.
68795*/
68796SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
68797
68798#if !defined(SQLITE_OMIT_SHARED_CACHE)
68799/*
68800** Return true if the Btree passed as the only argument is sharable.
68801*/
68802SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
68803  return p->sharable;
68804}
68805
68806/*
68807** Return the number of connections to the BtShared object accessed by
68808** the Btree handle passed as the only argument. For private caches
68809** this is always 1. For shared caches it may be 1 or greater.
68810*/
68811SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
68812  testcase( p->sharable );
68813  return p->pBt->nRef;
68814}
68815#endif
68816
68817/************** End of btree.c ***********************************************/
68818/************** Begin file backup.c ******************************************/
68819/*
68820** 2009 January 28
68821**
68822** The author disclaims copyright to this source code.  In place of
68823** a legal notice, here is a blessing:
68824**
68825**    May you do good and not evil.
68826**    May you find forgiveness for yourself and forgive others.
68827**    May you share freely, never taking more than you give.
68828**
68829*************************************************************************
68830** This file contains the implementation of the sqlite3_backup_XXX()
68831** API functions and the related features.
68832*/
68833/* #include "sqliteInt.h" */
68834/* #include "btreeInt.h" */
68835
68836/*
68837** Structure allocated for each backup operation.
68838*/
68839struct sqlite3_backup {
68840  sqlite3* pDestDb;        /* Destination database handle */
68841  Btree *pDest;            /* Destination b-tree file */
68842  u32 iDestSchema;         /* Original schema cookie in destination */
68843  int bDestLocked;         /* True once a write-transaction is open on pDest */
68844
68845  Pgno iNext;              /* Page number of the next source page to copy */
68846  sqlite3* pSrcDb;         /* Source database handle */
68847  Btree *pSrc;             /* Source b-tree file */
68848
68849  int rc;                  /* Backup process error code */
68850
68851  /* These two variables are set by every call to backup_step(). They are
68852  ** read by calls to backup_remaining() and backup_pagecount().
68853  */
68854  Pgno nRemaining;         /* Number of pages left to copy */
68855  Pgno nPagecount;         /* Total number of pages to copy */
68856
68857  int isAttached;          /* True once backup has been registered with pager */
68858  sqlite3_backup *pNext;   /* Next backup associated with source pager */
68859};
68860
68861/*
68862** THREAD SAFETY NOTES:
68863**
68864**   Once it has been created using backup_init(), a single sqlite3_backup
68865**   structure may be accessed via two groups of thread-safe entry points:
68866**
68867**     * Via the sqlite3_backup_XXX() API function backup_step() and
68868**       backup_finish(). Both these functions obtain the source database
68869**       handle mutex and the mutex associated with the source BtShared
68870**       structure, in that order.
68871**
68872**     * Via the BackupUpdate() and BackupRestart() functions, which are
68873**       invoked by the pager layer to report various state changes in
68874**       the page cache associated with the source database. The mutex
68875**       associated with the source database BtShared structure will always
68876**       be held when either of these functions are invoked.
68877**
68878**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
68879**   backup_pagecount() are not thread-safe functions. If they are called
68880**   while some other thread is calling backup_step() or backup_finish(),
68881**   the values returned may be invalid. There is no way for a call to
68882**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
68883**   or backup_pagecount().
68884**
68885**   Depending on the SQLite configuration, the database handles and/or
68886**   the Btree objects may have their own mutexes that require locking.
68887**   Non-sharable Btrees (in-memory databases for example), do not have
68888**   associated mutexes.
68889*/
68890
68891/*
68892** Return a pointer corresponding to database zDb (i.e. "main", "temp")
68893** in connection handle pDb. If such a database cannot be found, return
68894** a NULL pointer and write an error message to pErrorDb.
68895**
68896** If the "temp" database is requested, it may need to be opened by this
68897** function. If an error occurs while doing so, return 0 and write an
68898** error message to pErrorDb.
68899*/
68900static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
68901  int i = sqlite3FindDbName(pDb, zDb);
68902
68903  if( i==1 ){
68904    Parse sParse;
68905    int rc = 0;
68906    memset(&sParse, 0, sizeof(sParse));
68907    sParse.db = pDb;
68908    if( sqlite3OpenTempDatabase(&sParse) ){
68909      sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
68910      rc = SQLITE_ERROR;
68911    }
68912    sqlite3DbFree(pErrorDb, sParse.zErrMsg);
68913    sqlite3ParserReset(&sParse);
68914    if( rc ){
68915      return 0;
68916    }
68917  }
68918
68919  if( i<0 ){
68920    sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
68921    return 0;
68922  }
68923
68924  return pDb->aDb[i].pBt;
68925}
68926
68927/*
68928** Attempt to set the page size of the destination to match the page size
68929** of the source.
68930*/
68931static int setDestPgsz(sqlite3_backup *p){
68932  int rc;
68933  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
68934  return rc;
68935}
68936
68937/*
68938** Check that there is no open read-transaction on the b-tree passed as the
68939** second argument. If there is not, return SQLITE_OK. Otherwise, if there
68940** is an open read-transaction, return SQLITE_ERROR and leave an error
68941** message in database handle db.
68942*/
68943static int checkReadTransaction(sqlite3 *db, Btree *p){
68944  if( sqlite3BtreeIsInReadTrans(p) ){
68945    sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
68946    return SQLITE_ERROR;
68947  }
68948  return SQLITE_OK;
68949}
68950
68951/*
68952** Create an sqlite3_backup process to copy the contents of zSrcDb from
68953** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
68954** a pointer to the new sqlite3_backup object.
68955**
68956** If an error occurs, NULL is returned and an error code and error message
68957** stored in database handle pDestDb.
68958*/
68959SQLITE_API sqlite3_backup *sqlite3_backup_init(
68960  sqlite3* pDestDb,                     /* Database to write to */
68961  const char *zDestDb,                  /* Name of database within pDestDb */
68962  sqlite3* pSrcDb,                      /* Database connection to read from */
68963  const char *zSrcDb                    /* Name of database within pSrcDb */
68964){
68965  sqlite3_backup *p;                    /* Value to return */
68966
68967#ifdef SQLITE_ENABLE_API_ARMOR
68968  if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
68969    (void)SQLITE_MISUSE_BKPT;
68970    return 0;
68971  }
68972#endif
68973
68974  /* Lock the source database handle. The destination database
68975  ** handle is not locked in this routine, but it is locked in
68976  ** sqlite3_backup_step(). The user is required to ensure that no
68977  ** other thread accesses the destination handle for the duration
68978  ** of the backup operation.  Any attempt to use the destination
68979  ** database connection while a backup is in progress may cause
68980  ** a malfunction or a deadlock.
68981  */
68982  sqlite3_mutex_enter(pSrcDb->mutex);
68983  sqlite3_mutex_enter(pDestDb->mutex);
68984
68985  if( pSrcDb==pDestDb ){
68986    sqlite3ErrorWithMsg(
68987        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
68988    );
68989    p = 0;
68990  }else {
68991    /* Allocate space for a new sqlite3_backup object...
68992    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
68993    ** call to sqlite3_backup_init() and is destroyed by a call to
68994    ** sqlite3_backup_finish(). */
68995    p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
68996    if( !p ){
68997      sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
68998    }
68999  }
69000
69001  /* If the allocation succeeded, populate the new object. */
69002  if( p ){
69003    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
69004    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
69005    p->pDestDb = pDestDb;
69006    p->pSrcDb = pSrcDb;
69007    p->iNext = 1;
69008    p->isAttached = 0;
69009
69010    if( 0==p->pSrc || 0==p->pDest
69011     || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
69012     ){
69013      /* One (or both) of the named databases did not exist or an OOM
69014      ** error was hit. Or there is a transaction open on the destination
69015      ** database. The error has already been written into the pDestDb
69016      ** handle. All that is left to do here is free the sqlite3_backup
69017      ** structure.  */
69018      sqlite3_free(p);
69019      p = 0;
69020    }
69021  }
69022  if( p ){
69023    p->pSrc->nBackup++;
69024  }
69025
69026  sqlite3_mutex_leave(pDestDb->mutex);
69027  sqlite3_mutex_leave(pSrcDb->mutex);
69028  return p;
69029}
69030
69031/*
69032** Argument rc is an SQLite error code. Return true if this error is
69033** considered fatal if encountered during a backup operation. All errors
69034** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
69035*/
69036static int isFatalError(int rc){
69037  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
69038}
69039
69040/*
69041** Parameter zSrcData points to a buffer containing the data for
69042** page iSrcPg from the source database. Copy this data into the
69043** destination database.
69044*/
69045static int backupOnePage(
69046  sqlite3_backup *p,              /* Backup handle */
69047  Pgno iSrcPg,                    /* Source database page to backup */
69048  const u8 *zSrcData,             /* Source database page data */
69049  int bUpdate                     /* True for an update, false otherwise */
69050){
69051  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
69052  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
69053  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
69054  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
69055  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
69056#ifdef SQLITE_HAS_CODEC
69057  /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
69058  ** guaranteed that the shared-mutex is held by this thread, handle
69059  ** p->pSrc may not actually be the owner.  */
69060  int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
69061  int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
69062#endif
69063  int rc = SQLITE_OK;
69064  i64 iOff;
69065
69066  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
69067  assert( p->bDestLocked );
69068  assert( !isFatalError(p->rc) );
69069  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
69070  assert( zSrcData );
69071
69072  /* Catch the case where the destination is an in-memory database and the
69073  ** page sizes of the source and destination differ.
69074  */
69075  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
69076    rc = SQLITE_READONLY;
69077  }
69078
69079#ifdef SQLITE_HAS_CODEC
69080  /* Backup is not possible if the page size of the destination is changing
69081  ** and a codec is in use.
69082  */
69083  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
69084    rc = SQLITE_READONLY;
69085  }
69086
69087  /* Backup is not possible if the number of bytes of reserve space differ
69088  ** between source and destination.  If there is a difference, try to
69089  ** fix the destination to agree with the source.  If that is not possible,
69090  ** then the backup cannot proceed.
69091  */
69092  if( nSrcReserve!=nDestReserve ){
69093    u32 newPgsz = nSrcPgsz;
69094    rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
69095    if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
69096  }
69097#endif
69098
69099  /* This loop runs once for each destination page spanned by the source
69100  ** page. For each iteration, variable iOff is set to the byte offset
69101  ** of the destination page.
69102  */
69103  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
69104    DbPage *pDestPg = 0;
69105    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
69106    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
69107    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
69108     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
69109    ){
69110      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
69111      u8 *zDestData = sqlite3PagerGetData(pDestPg);
69112      u8 *zOut = &zDestData[iOff%nDestPgsz];
69113
69114      /* Copy the data from the source page into the destination page.
69115      ** Then clear the Btree layer MemPage.isInit flag. Both this module
69116      ** and the pager code use this trick (clearing the first byte
69117      ** of the page 'extra' space to invalidate the Btree layers
69118      ** cached parse of the page). MemPage.isInit is marked
69119      ** "MUST BE FIRST" for this purpose.
69120      */
69121      memcpy(zOut, zIn, nCopy);
69122      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
69123      if( iOff==0 && bUpdate==0 ){
69124        sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
69125      }
69126    }
69127    sqlite3PagerUnref(pDestPg);
69128  }
69129
69130  return rc;
69131}
69132
69133/*
69134** If pFile is currently larger than iSize bytes, then truncate it to
69135** exactly iSize bytes. If pFile is not larger than iSize bytes, then
69136** this function is a no-op.
69137**
69138** Return SQLITE_OK if everything is successful, or an SQLite error
69139** code if an error occurs.
69140*/
69141static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
69142  i64 iCurrent;
69143  int rc = sqlite3OsFileSize(pFile, &iCurrent);
69144  if( rc==SQLITE_OK && iCurrent>iSize ){
69145    rc = sqlite3OsTruncate(pFile, iSize);
69146  }
69147  return rc;
69148}
69149
69150/*
69151** Register this backup object with the associated source pager for
69152** callbacks when pages are changed or the cache invalidated.
69153*/
69154static void attachBackupObject(sqlite3_backup *p){
69155  sqlite3_backup **pp;
69156  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
69157  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
69158  p->pNext = *pp;
69159  *pp = p;
69160  p->isAttached = 1;
69161}
69162
69163/*
69164** Copy nPage pages from the source b-tree to the destination.
69165*/
69166SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
69167  int rc;
69168  int destMode;       /* Destination journal mode */
69169  int pgszSrc = 0;    /* Source page size */
69170  int pgszDest = 0;   /* Destination page size */
69171
69172#ifdef SQLITE_ENABLE_API_ARMOR
69173  if( p==0 ) return SQLITE_MISUSE_BKPT;
69174#endif
69175  sqlite3_mutex_enter(p->pSrcDb->mutex);
69176  sqlite3BtreeEnter(p->pSrc);
69177  if( p->pDestDb ){
69178    sqlite3_mutex_enter(p->pDestDb->mutex);
69179  }
69180
69181  rc = p->rc;
69182  if( !isFatalError(rc) ){
69183    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
69184    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
69185    int ii;                            /* Iterator variable */
69186    int nSrcPage = -1;                 /* Size of source db in pages */
69187    int bCloseTrans = 0;               /* True if src db requires unlocking */
69188
69189    /* If the source pager is currently in a write-transaction, return
69190    ** SQLITE_BUSY immediately.
69191    */
69192    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
69193      rc = SQLITE_BUSY;
69194    }else{
69195      rc = SQLITE_OK;
69196    }
69197
69198    /* If there is no open read-transaction on the source database, open
69199    ** one now. If a transaction is opened here, then it will be closed
69200    ** before this function exits.
69201    */
69202    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
69203      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
69204      bCloseTrans = 1;
69205    }
69206
69207    /* If the destination database has not yet been locked (i.e. if this
69208    ** is the first call to backup_step() for the current backup operation),
69209    ** try to set its page size to the same as the source database. This
69210    ** is especially important on ZipVFS systems, as in that case it is
69211    ** not possible to create a database file that uses one page size by
69212    ** writing to it with another.  */
69213    if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
69214      rc = SQLITE_NOMEM;
69215    }
69216
69217    /* Lock the destination database, if it is not locked already. */
69218    if( SQLITE_OK==rc && p->bDestLocked==0
69219     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
69220    ){
69221      p->bDestLocked = 1;
69222      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
69223    }
69224
69225    /* Do not allow backup if the destination database is in WAL mode
69226    ** and the page sizes are different between source and destination */
69227    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
69228    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
69229    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
69230    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
69231      rc = SQLITE_READONLY;
69232    }
69233
69234    /* Now that there is a read-lock on the source database, query the
69235    ** source pager for the number of pages in the database.
69236    */
69237    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
69238    assert( nSrcPage>=0 );
69239    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
69240      const Pgno iSrcPg = p->iNext;                 /* Source page number */
69241      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
69242        DbPage *pSrcPg;                             /* Source page object */
69243        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
69244        if( rc==SQLITE_OK ){
69245          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
69246          sqlite3PagerUnref(pSrcPg);
69247        }
69248      }
69249      p->iNext++;
69250    }
69251    if( rc==SQLITE_OK ){
69252      p->nPagecount = nSrcPage;
69253      p->nRemaining = nSrcPage+1-p->iNext;
69254      if( p->iNext>(Pgno)nSrcPage ){
69255        rc = SQLITE_DONE;
69256      }else if( !p->isAttached ){
69257        attachBackupObject(p);
69258      }
69259    }
69260
69261    /* Update the schema version field in the destination database. This
69262    ** is to make sure that the schema-version really does change in
69263    ** the case where the source and destination databases have the
69264    ** same schema version.
69265    */
69266    if( rc==SQLITE_DONE ){
69267      if( nSrcPage==0 ){
69268        rc = sqlite3BtreeNewDb(p->pDest);
69269        nSrcPage = 1;
69270      }
69271      if( rc==SQLITE_OK || rc==SQLITE_DONE ){
69272        rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
69273      }
69274      if( rc==SQLITE_OK ){
69275        if( p->pDestDb ){
69276          sqlite3ResetAllSchemasOfConnection(p->pDestDb);
69277        }
69278        if( destMode==PAGER_JOURNALMODE_WAL ){
69279          rc = sqlite3BtreeSetVersion(p->pDest, 2);
69280        }
69281      }
69282      if( rc==SQLITE_OK ){
69283        int nDestTruncate;
69284        /* Set nDestTruncate to the final number of pages in the destination
69285        ** database. The complication here is that the destination page
69286        ** size may be different to the source page size.
69287        **
69288        ** If the source page size is smaller than the destination page size,
69289        ** round up. In this case the call to sqlite3OsTruncate() below will
69290        ** fix the size of the file. However it is important to call
69291        ** sqlite3PagerTruncateImage() here so that any pages in the
69292        ** destination file that lie beyond the nDestTruncate page mark are
69293        ** journalled by PagerCommitPhaseOne() before they are destroyed
69294        ** by the file truncation.
69295        */
69296        assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
69297        assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
69298        if( pgszSrc<pgszDest ){
69299          int ratio = pgszDest/pgszSrc;
69300          nDestTruncate = (nSrcPage+ratio-1)/ratio;
69301          if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
69302            nDestTruncate--;
69303          }
69304        }else{
69305          nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
69306        }
69307        assert( nDestTruncate>0 );
69308
69309        if( pgszSrc<pgszDest ){
69310          /* If the source page-size is smaller than the destination page-size,
69311          ** two extra things may need to happen:
69312          **
69313          **   * The destination may need to be truncated, and
69314          **
69315          **   * Data stored on the pages immediately following the
69316          **     pending-byte page in the source database may need to be
69317          **     copied into the destination database.
69318          */
69319          const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
69320          sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
69321          Pgno iPg;
69322          int nDstPage;
69323          i64 iOff;
69324          i64 iEnd;
69325
69326          assert( pFile );
69327          assert( nDestTruncate==0
69328              || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
69329                nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
69330             && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
69331          ));
69332
69333          /* This block ensures that all data required to recreate the original
69334          ** database has been stored in the journal for pDestPager and the
69335          ** journal synced to disk. So at this point we may safely modify
69336          ** the database file in any way, knowing that if a power failure
69337          ** occurs, the original database will be reconstructed from the
69338          ** journal file.  */
69339          sqlite3PagerPagecount(pDestPager, &nDstPage);
69340          for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
69341            if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
69342              DbPage *pPg;
69343              rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
69344              if( rc==SQLITE_OK ){
69345                rc = sqlite3PagerWrite(pPg);
69346                sqlite3PagerUnref(pPg);
69347              }
69348            }
69349          }
69350          if( rc==SQLITE_OK ){
69351            rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
69352          }
69353
69354          /* Write the extra pages and truncate the database file as required */
69355          iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
69356          for(
69357            iOff=PENDING_BYTE+pgszSrc;
69358            rc==SQLITE_OK && iOff<iEnd;
69359            iOff+=pgszSrc
69360          ){
69361            PgHdr *pSrcPg = 0;
69362            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
69363            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
69364            if( rc==SQLITE_OK ){
69365              u8 *zData = sqlite3PagerGetData(pSrcPg);
69366              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
69367            }
69368            sqlite3PagerUnref(pSrcPg);
69369          }
69370          if( rc==SQLITE_OK ){
69371            rc = backupTruncateFile(pFile, iSize);
69372          }
69373
69374          /* Sync the database file to disk. */
69375          if( rc==SQLITE_OK ){
69376            rc = sqlite3PagerSync(pDestPager, 0);
69377          }
69378        }else{
69379          sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
69380          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
69381        }
69382
69383        /* Finish committing the transaction to the destination database. */
69384        if( SQLITE_OK==rc
69385         && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
69386        ){
69387          rc = SQLITE_DONE;
69388        }
69389      }
69390    }
69391
69392    /* If bCloseTrans is true, then this function opened a read transaction
69393    ** on the source database. Close the read transaction here. There is
69394    ** no need to check the return values of the btree methods here, as
69395    ** "committing" a read-only transaction cannot fail.
69396    */
69397    if( bCloseTrans ){
69398      TESTONLY( int rc2 );
69399      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
69400      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
69401      assert( rc2==SQLITE_OK );
69402    }
69403
69404    if( rc==SQLITE_IOERR_NOMEM ){
69405      rc = SQLITE_NOMEM_BKPT;
69406    }
69407    p->rc = rc;
69408  }
69409  if( p->pDestDb ){
69410    sqlite3_mutex_leave(p->pDestDb->mutex);
69411  }
69412  sqlite3BtreeLeave(p->pSrc);
69413  sqlite3_mutex_leave(p->pSrcDb->mutex);
69414  return rc;
69415}
69416
69417/*
69418** Release all resources associated with an sqlite3_backup* handle.
69419*/
69420SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
69421  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
69422  sqlite3 *pSrcDb;                     /* Source database connection */
69423  int rc;                              /* Value to return */
69424
69425  /* Enter the mutexes */
69426  if( p==0 ) return SQLITE_OK;
69427  pSrcDb = p->pSrcDb;
69428  sqlite3_mutex_enter(pSrcDb->mutex);
69429  sqlite3BtreeEnter(p->pSrc);
69430  if( p->pDestDb ){
69431    sqlite3_mutex_enter(p->pDestDb->mutex);
69432  }
69433
69434  /* Detach this backup from the source pager. */
69435  if( p->pDestDb ){
69436    p->pSrc->nBackup--;
69437  }
69438  if( p->isAttached ){
69439    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
69440    while( *pp!=p ){
69441      pp = &(*pp)->pNext;
69442    }
69443    *pp = p->pNext;
69444  }
69445
69446  /* If a transaction is still open on the Btree, roll it back. */
69447  sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
69448
69449  /* Set the error code of the destination database handle. */
69450  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
69451  if( p->pDestDb ){
69452    sqlite3Error(p->pDestDb, rc);
69453
69454    /* Exit the mutexes and free the backup context structure. */
69455    sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
69456  }
69457  sqlite3BtreeLeave(p->pSrc);
69458  if( p->pDestDb ){
69459    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
69460    ** call to sqlite3_backup_init() and is destroyed by a call to
69461    ** sqlite3_backup_finish(). */
69462    sqlite3_free(p);
69463  }
69464  sqlite3LeaveMutexAndCloseZombie(pSrcDb);
69465  return rc;
69466}
69467
69468/*
69469** Return the number of pages still to be backed up as of the most recent
69470** call to sqlite3_backup_step().
69471*/
69472SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
69473#ifdef SQLITE_ENABLE_API_ARMOR
69474  if( p==0 ){
69475    (void)SQLITE_MISUSE_BKPT;
69476    return 0;
69477  }
69478#endif
69479  return p->nRemaining;
69480}
69481
69482/*
69483** Return the total number of pages in the source database as of the most
69484** recent call to sqlite3_backup_step().
69485*/
69486SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
69487#ifdef SQLITE_ENABLE_API_ARMOR
69488  if( p==0 ){
69489    (void)SQLITE_MISUSE_BKPT;
69490    return 0;
69491  }
69492#endif
69493  return p->nPagecount;
69494}
69495
69496/*
69497** This function is called after the contents of page iPage of the
69498** source database have been modified. If page iPage has already been
69499** copied into the destination database, then the data written to the
69500** destination is now invalidated. The destination copy of iPage needs
69501** to be updated with the new data before the backup operation is
69502** complete.
69503**
69504** It is assumed that the mutex associated with the BtShared object
69505** corresponding to the source database is held when this function is
69506** called.
69507*/
69508static SQLITE_NOINLINE void backupUpdate(
69509  sqlite3_backup *p,
69510  Pgno iPage,
69511  const u8 *aData
69512){
69513  assert( p!=0 );
69514  do{
69515    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
69516    if( !isFatalError(p->rc) && iPage<p->iNext ){
69517      /* The backup process p has already copied page iPage. But now it
69518      ** has been modified by a transaction on the source pager. Copy
69519      ** the new data into the backup.
69520      */
69521      int rc;
69522      assert( p->pDestDb );
69523      sqlite3_mutex_enter(p->pDestDb->mutex);
69524      rc = backupOnePage(p, iPage, aData, 1);
69525      sqlite3_mutex_leave(p->pDestDb->mutex);
69526      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
69527      if( rc!=SQLITE_OK ){
69528        p->rc = rc;
69529      }
69530    }
69531  }while( (p = p->pNext)!=0 );
69532}
69533SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
69534  if( pBackup ) backupUpdate(pBackup, iPage, aData);
69535}
69536
69537/*
69538** Restart the backup process. This is called when the pager layer
69539** detects that the database has been modified by an external database
69540** connection. In this case there is no way of knowing which of the
69541** pages that have been copied into the destination database are still
69542** valid and which are not, so the entire process needs to be restarted.
69543**
69544** It is assumed that the mutex associated with the BtShared object
69545** corresponding to the source database is held when this function is
69546** called.
69547*/
69548SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
69549  sqlite3_backup *p;                   /* Iterator variable */
69550  for(p=pBackup; p; p=p->pNext){
69551    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
69552    p->iNext = 1;
69553  }
69554}
69555
69556#ifndef SQLITE_OMIT_VACUUM
69557/*
69558** Copy the complete content of pBtFrom into pBtTo.  A transaction
69559** must be active for both files.
69560**
69561** The size of file pTo may be reduced by this operation. If anything
69562** goes wrong, the transaction on pTo is rolled back. If successful, the
69563** transaction is committed before returning.
69564*/
69565SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
69566  int rc;
69567  sqlite3_file *pFd;              /* File descriptor for database pTo */
69568  sqlite3_backup b;
69569  sqlite3BtreeEnter(pTo);
69570  sqlite3BtreeEnter(pFrom);
69571
69572  assert( sqlite3BtreeIsInTrans(pTo) );
69573  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
69574  if( pFd->pMethods ){
69575    i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
69576    rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
69577    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
69578    if( rc ) goto copy_finished;
69579  }
69580
69581  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
69582  ** to 0. This is used by the implementations of sqlite3_backup_step()
69583  ** and sqlite3_backup_finish() to detect that they are being called
69584  ** from this function, not directly by the user.
69585  */
69586  memset(&b, 0, sizeof(b));
69587  b.pSrcDb = pFrom->db;
69588  b.pSrc = pFrom;
69589  b.pDest = pTo;
69590  b.iNext = 1;
69591
69592#ifdef SQLITE_HAS_CODEC
69593  sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
69594#endif
69595
69596  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
69597  ** file. By passing this as the number of pages to copy to
69598  ** sqlite3_backup_step(), we can guarantee that the copy finishes
69599  ** within a single call (unless an error occurs). The assert() statement
69600  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
69601  ** or an error code.  */
69602  sqlite3_backup_step(&b, 0x7FFFFFFF);
69603  assert( b.rc!=SQLITE_OK );
69604
69605  rc = sqlite3_backup_finish(&b);
69606  if( rc==SQLITE_OK ){
69607    pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
69608  }else{
69609    sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
69610  }
69611
69612  assert( sqlite3BtreeIsInTrans(pTo)==0 );
69613copy_finished:
69614  sqlite3BtreeLeave(pFrom);
69615  sqlite3BtreeLeave(pTo);
69616  return rc;
69617}
69618#endif /* SQLITE_OMIT_VACUUM */
69619
69620/************** End of backup.c **********************************************/
69621/************** Begin file vdbemem.c *****************************************/
69622/*
69623** 2004 May 26
69624**
69625** The author disclaims copyright to this source code.  In place of
69626** a legal notice, here is a blessing:
69627**
69628**    May you do good and not evil.
69629**    May you find forgiveness for yourself and forgive others.
69630**    May you share freely, never taking more than you give.
69631**
69632*************************************************************************
69633**
69634** This file contains code use to manipulate "Mem" structure.  A "Mem"
69635** stores a single value in the VDBE.  Mem is an opaque structure visible
69636** only within the VDBE.  Interface routines refer to a Mem using the
69637** name sqlite_value
69638*/
69639/* #include "sqliteInt.h" */
69640/* #include "vdbeInt.h" */
69641
69642#ifdef SQLITE_DEBUG
69643/*
69644** Check invariants on a Mem object.
69645**
69646** This routine is intended for use inside of assert() statements, like
69647** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
69648*/
69649SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
69650  /* If MEM_Dyn is set then Mem.xDel!=0.
69651  ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
69652  */
69653  assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
69654
69655  /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
69656  ** ensure that if Mem.szMalloc>0 then it is safe to do
69657  ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
69658  ** That saves a few cycles in inner loops. */
69659  assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
69660
69661  /* Cannot be both MEM_Int and MEM_Real at the same time */
69662  assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
69663
69664  /* The szMalloc field holds the correct memory allocation size */
69665  assert( p->szMalloc==0
69666       || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
69667
69668  /* If p holds a string or blob, the Mem.z must point to exactly
69669  ** one of the following:
69670  **
69671  **   (1) Memory in Mem.zMalloc and managed by the Mem object
69672  **   (2) Memory to be freed using Mem.xDel
69673  **   (3) An ephemeral string or blob
69674  **   (4) A static string or blob
69675  */
69676  if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
69677    assert(
69678      ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
69679      ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
69680      ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
69681      ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
69682    );
69683  }
69684  return 1;
69685}
69686#endif
69687
69688
69689/*
69690** If pMem is an object with a valid string representation, this routine
69691** ensures the internal encoding for the string representation is
69692** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
69693**
69694** If pMem is not a string object, or the encoding of the string
69695** representation is already stored using the requested encoding, then this
69696** routine is a no-op.
69697**
69698** SQLITE_OK is returned if the conversion is successful (or not required).
69699** SQLITE_NOMEM may be returned if a malloc() fails during conversion
69700** between formats.
69701*/
69702SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
69703#ifndef SQLITE_OMIT_UTF16
69704  int rc;
69705#endif
69706  assert( (pMem->flags&MEM_RowSet)==0 );
69707  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
69708           || desiredEnc==SQLITE_UTF16BE );
69709  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
69710    return SQLITE_OK;
69711  }
69712  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69713#ifdef SQLITE_OMIT_UTF16
69714  return SQLITE_ERROR;
69715#else
69716
69717  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
69718  ** then the encoding of the value may not have changed.
69719  */
69720  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
69721  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
69722  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
69723  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
69724  return rc;
69725#endif
69726}
69727
69728/*
69729** Make sure pMem->z points to a writable allocation of at least
69730** min(n,32) bytes.
69731**
69732** If the bPreserve argument is true, then copy of the content of
69733** pMem->z into the new allocation.  pMem must be either a string or
69734** blob if bPreserve is true.  If bPreserve is false, any prior content
69735** in pMem->z is discarded.
69736*/
69737SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
69738  assert( sqlite3VdbeCheckMemInvariants(pMem) );
69739  assert( (pMem->flags&MEM_RowSet)==0 );
69740  testcase( pMem->db==0 );
69741
69742  /* If the bPreserve flag is set to true, then the memory cell must already
69743  ** contain a valid string or blob value.  */
69744  assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
69745  testcase( bPreserve && pMem->z==0 );
69746
69747  assert( pMem->szMalloc==0
69748       || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
69749  if( pMem->szMalloc<n ){
69750    if( n<32 ) n = 32;
69751    if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
69752      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
69753      bPreserve = 0;
69754    }else{
69755      if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
69756      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
69757    }
69758    if( pMem->zMalloc==0 ){
69759      sqlite3VdbeMemSetNull(pMem);
69760      pMem->z = 0;
69761      pMem->szMalloc = 0;
69762      return SQLITE_NOMEM_BKPT;
69763    }else{
69764      pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
69765    }
69766  }
69767
69768  if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
69769    memcpy(pMem->zMalloc, pMem->z, pMem->n);
69770  }
69771  if( (pMem->flags&MEM_Dyn)!=0 ){
69772    assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
69773    pMem->xDel((void *)(pMem->z));
69774  }
69775
69776  pMem->z = pMem->zMalloc;
69777  pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
69778  return SQLITE_OK;
69779}
69780
69781/*
69782** Change the pMem->zMalloc allocation to be at least szNew bytes.
69783** If pMem->zMalloc already meets or exceeds the requested size, this
69784** routine is a no-op.
69785**
69786** Any prior string or blob content in the pMem object may be discarded.
69787** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
69788** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
69789** values are preserved.
69790**
69791** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
69792** if unable to complete the resizing.
69793*/
69794SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
69795  assert( szNew>0 );
69796  assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
69797  if( pMem->szMalloc<szNew ){
69798    return sqlite3VdbeMemGrow(pMem, szNew, 0);
69799  }
69800  assert( (pMem->flags & MEM_Dyn)==0 );
69801  pMem->z = pMem->zMalloc;
69802  pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
69803  return SQLITE_OK;
69804}
69805
69806/*
69807** Change pMem so that its MEM_Str or MEM_Blob value is stored in
69808** MEM.zMalloc, where it can be safely written.
69809**
69810** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
69811*/
69812SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
69813  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69814  assert( (pMem->flags&MEM_RowSet)==0 );
69815  if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
69816    if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
69817    if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
69818      if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
69819        return SQLITE_NOMEM_BKPT;
69820      }
69821      pMem->z[pMem->n] = 0;
69822      pMem->z[pMem->n+1] = 0;
69823      pMem->flags |= MEM_Term;
69824    }
69825  }
69826  pMem->flags &= ~MEM_Ephem;
69827#ifdef SQLITE_DEBUG
69828  pMem->pScopyFrom = 0;
69829#endif
69830
69831  return SQLITE_OK;
69832}
69833
69834/*
69835** If the given Mem* has a zero-filled tail, turn it into an ordinary
69836** blob stored in dynamically allocated space.
69837*/
69838#ifndef SQLITE_OMIT_INCRBLOB
69839SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
69840  int nByte;
69841  assert( pMem->flags & MEM_Zero );
69842  assert( pMem->flags&MEM_Blob );
69843  assert( (pMem->flags&MEM_RowSet)==0 );
69844  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69845
69846  /* Set nByte to the number of bytes required to store the expanded blob. */
69847  nByte = pMem->n + pMem->u.nZero;
69848  if( nByte<=0 ){
69849    nByte = 1;
69850  }
69851  if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
69852    return SQLITE_NOMEM_BKPT;
69853  }
69854
69855  memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
69856  pMem->n += pMem->u.nZero;
69857  pMem->flags &= ~(MEM_Zero|MEM_Term);
69858  return SQLITE_OK;
69859}
69860#endif
69861
69862/*
69863** It is already known that pMem contains an unterminated string.
69864** Add the zero terminator.
69865*/
69866static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
69867  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
69868    return SQLITE_NOMEM_BKPT;
69869  }
69870  pMem->z[pMem->n] = 0;
69871  pMem->z[pMem->n+1] = 0;
69872  pMem->flags |= MEM_Term;
69873  return SQLITE_OK;
69874}
69875
69876/*
69877** Make sure the given Mem is \u0000 terminated.
69878*/
69879SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
69880  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69881  testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
69882  testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
69883  if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
69884    return SQLITE_OK;   /* Nothing to do */
69885  }else{
69886    return vdbeMemAddTerminator(pMem);
69887  }
69888}
69889
69890/*
69891** Add MEM_Str to the set of representations for the given Mem.  Numbers
69892** are converted using sqlite3_snprintf().  Converting a BLOB to a string
69893** is a no-op.
69894**
69895** Existing representations MEM_Int and MEM_Real are invalidated if
69896** bForce is true but are retained if bForce is false.
69897**
69898** A MEM_Null value will never be passed to this function. This function is
69899** used for converting values to text for returning to the user (i.e. via
69900** sqlite3_value_text()), or for ensuring that values to be used as btree
69901** keys are strings. In the former case a NULL pointer is returned the
69902** user and the latter is an internal programming error.
69903*/
69904SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
69905  int fg = pMem->flags;
69906  const int nByte = 32;
69907
69908  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69909  assert( !(fg&MEM_Zero) );
69910  assert( !(fg&(MEM_Str|MEM_Blob)) );
69911  assert( fg&(MEM_Int|MEM_Real) );
69912  assert( (pMem->flags&MEM_RowSet)==0 );
69913  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69914
69915
69916  if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
69917    pMem->enc = 0;
69918    return SQLITE_NOMEM_BKPT;
69919  }
69920
69921  /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
69922  ** string representation of the value. Then, if the required encoding
69923  ** is UTF-16le or UTF-16be do a translation.
69924  **
69925  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
69926  */
69927  if( fg & MEM_Int ){
69928    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
69929  }else{
69930    assert( fg & MEM_Real );
69931    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
69932  }
69933  pMem->n = sqlite3Strlen30(pMem->z);
69934  pMem->enc = SQLITE_UTF8;
69935  pMem->flags |= MEM_Str|MEM_Term;
69936  if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
69937  sqlite3VdbeChangeEncoding(pMem, enc);
69938  return SQLITE_OK;
69939}
69940
69941/*
69942** Memory cell pMem contains the context of an aggregate function.
69943** This routine calls the finalize method for that function.  The
69944** result of the aggregate is stored back into pMem.
69945**
69946** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
69947** otherwise.
69948*/
69949SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
69950  int rc = SQLITE_OK;
69951  if( ALWAYS(pFunc && pFunc->xFinalize) ){
69952    sqlite3_context ctx;
69953    Mem t;
69954    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
69955    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69956    memset(&ctx, 0, sizeof(ctx));
69957    memset(&t, 0, sizeof(t));
69958    t.flags = MEM_Null;
69959    t.db = pMem->db;
69960    ctx.pOut = &t;
69961    ctx.pMem = pMem;
69962    ctx.pFunc = pFunc;
69963    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
69964    assert( (pMem->flags & MEM_Dyn)==0 );
69965    if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
69966    memcpy(pMem, &t, sizeof(t));
69967    rc = ctx.isError;
69968  }
69969  return rc;
69970}
69971
69972/*
69973** If the memory cell contains a value that must be freed by
69974** invoking the external callback in Mem.xDel, then this routine
69975** will free that value.  It also sets Mem.flags to MEM_Null.
69976**
69977** This is a helper routine for sqlite3VdbeMemSetNull() and
69978** for sqlite3VdbeMemRelease().  Use those other routines as the
69979** entry point for releasing Mem resources.
69980*/
69981static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
69982  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
69983  assert( VdbeMemDynamic(p) );
69984  if( p->flags&MEM_Agg ){
69985    sqlite3VdbeMemFinalize(p, p->u.pDef);
69986    assert( (p->flags & MEM_Agg)==0 );
69987    testcase( p->flags & MEM_Dyn );
69988  }
69989  if( p->flags&MEM_Dyn ){
69990    assert( (p->flags&MEM_RowSet)==0 );
69991    assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
69992    p->xDel((void *)p->z);
69993  }else if( p->flags&MEM_RowSet ){
69994    sqlite3RowSetClear(p->u.pRowSet);
69995  }else if( p->flags&MEM_Frame ){
69996    VdbeFrame *pFrame = p->u.pFrame;
69997    pFrame->pParent = pFrame->v->pDelFrame;
69998    pFrame->v->pDelFrame = pFrame;
69999  }
70000  p->flags = MEM_Null;
70001}
70002
70003/*
70004** Release memory held by the Mem p, both external memory cleared
70005** by p->xDel and memory in p->zMalloc.
70006**
70007** This is a helper routine invoked by sqlite3VdbeMemRelease() in
70008** the unusual case where there really is memory in p that needs
70009** to be freed.
70010*/
70011static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
70012  if( VdbeMemDynamic(p) ){
70013    vdbeMemClearExternAndSetNull(p);
70014  }
70015  if( p->szMalloc ){
70016    sqlite3DbFree(p->db, p->zMalloc);
70017    p->szMalloc = 0;
70018  }
70019  p->z = 0;
70020}
70021
70022/*
70023** Release any memory resources held by the Mem.  Both the memory that is
70024** free by Mem.xDel and the Mem.zMalloc allocation are freed.
70025**
70026** Use this routine prior to clean up prior to abandoning a Mem, or to
70027** reset a Mem back to its minimum memory utilization.
70028**
70029** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
70030** prior to inserting new content into the Mem.
70031*/
70032SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
70033  assert( sqlite3VdbeCheckMemInvariants(p) );
70034  if( VdbeMemDynamic(p) || p->szMalloc ){
70035    vdbeMemClear(p);
70036  }
70037}
70038
70039/*
70040** Convert a 64-bit IEEE double into a 64-bit signed integer.
70041** If the double is out of range of a 64-bit signed integer then
70042** return the closest available 64-bit signed integer.
70043*/
70044static i64 doubleToInt64(double r){
70045#ifdef SQLITE_OMIT_FLOATING_POINT
70046  /* When floating-point is omitted, double and int64 are the same thing */
70047  return r;
70048#else
70049  /*
70050  ** Many compilers we encounter do not define constants for the
70051  ** minimum and maximum 64-bit integers, or they define them
70052  ** inconsistently.  And many do not understand the "LL" notation.
70053  ** So we define our own static constants here using nothing
70054  ** larger than a 32-bit integer constant.
70055  */
70056  static const i64 maxInt = LARGEST_INT64;
70057  static const i64 minInt = SMALLEST_INT64;
70058
70059  if( r<=(double)minInt ){
70060    return minInt;
70061  }else if( r>=(double)maxInt ){
70062    return maxInt;
70063  }else{
70064    return (i64)r;
70065  }
70066#endif
70067}
70068
70069/*
70070** Return some kind of integer value which is the best we can do
70071** at representing the value that *pMem describes as an integer.
70072** If pMem is an integer, then the value is exact.  If pMem is
70073** a floating-point then the value returned is the integer part.
70074** If pMem is a string or blob, then we make an attempt to convert
70075** it into an integer and return that.  If pMem represents an
70076** an SQL-NULL value, return 0.
70077**
70078** If pMem represents a string value, its encoding might be changed.
70079*/
70080SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
70081  int flags;
70082  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70083  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70084  flags = pMem->flags;
70085  if( flags & MEM_Int ){
70086    return pMem->u.i;
70087  }else if( flags & MEM_Real ){
70088    return doubleToInt64(pMem->u.r);
70089  }else if( flags & (MEM_Str|MEM_Blob) ){
70090    i64 value = 0;
70091    assert( pMem->z || pMem->n==0 );
70092    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
70093    return value;
70094  }else{
70095    return 0;
70096  }
70097}
70098
70099/*
70100** Return the best representation of pMem that we can get into a
70101** double.  If pMem is already a double or an integer, return its
70102** value.  If it is a string or blob, try to convert it to a double.
70103** If it is a NULL, return 0.0.
70104*/
70105SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
70106  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70107  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70108  if( pMem->flags & MEM_Real ){
70109    return pMem->u.r;
70110  }else if( pMem->flags & MEM_Int ){
70111    return (double)pMem->u.i;
70112  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
70113    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
70114    double val = (double)0;
70115    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
70116    return val;
70117  }else{
70118    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
70119    return (double)0;
70120  }
70121}
70122
70123/*
70124** The MEM structure is already a MEM_Real.  Try to also make it a
70125** MEM_Int if we can.
70126*/
70127SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
70128  i64 ix;
70129  assert( pMem->flags & MEM_Real );
70130  assert( (pMem->flags & MEM_RowSet)==0 );
70131  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70132  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70133
70134  ix = doubleToInt64(pMem->u.r);
70135
70136  /* Only mark the value as an integer if
70137  **
70138  **    (1) the round-trip conversion real->int->real is a no-op, and
70139  **    (2) The integer is neither the largest nor the smallest
70140  **        possible integer (ticket #3922)
70141  **
70142  ** The second and third terms in the following conditional enforces
70143  ** the second condition under the assumption that addition overflow causes
70144  ** values to wrap around.
70145  */
70146  if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
70147    pMem->u.i = ix;
70148    MemSetTypeFlag(pMem, MEM_Int);
70149  }
70150}
70151
70152/*
70153** Convert pMem to type integer.  Invalidate any prior representations.
70154*/
70155SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
70156  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70157  assert( (pMem->flags & MEM_RowSet)==0 );
70158  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70159
70160  pMem->u.i = sqlite3VdbeIntValue(pMem);
70161  MemSetTypeFlag(pMem, MEM_Int);
70162  return SQLITE_OK;
70163}
70164
70165/*
70166** Convert pMem so that it is of type MEM_Real.
70167** Invalidate any prior representations.
70168*/
70169SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
70170  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70171  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70172
70173  pMem->u.r = sqlite3VdbeRealValue(pMem);
70174  MemSetTypeFlag(pMem, MEM_Real);
70175  return SQLITE_OK;
70176}
70177
70178/*
70179** Convert pMem so that it has types MEM_Real or MEM_Int or both.
70180** Invalidate any prior representations.
70181**
70182** Every effort is made to force the conversion, even if the input
70183** is a string that does not look completely like a number.  Convert
70184** as much of the string as we can and ignore the rest.
70185*/
70186SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
70187  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
70188    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
70189    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70190    if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
70191      MemSetTypeFlag(pMem, MEM_Int);
70192    }else{
70193      pMem->u.r = sqlite3VdbeRealValue(pMem);
70194      MemSetTypeFlag(pMem, MEM_Real);
70195      sqlite3VdbeIntegerAffinity(pMem);
70196    }
70197  }
70198  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
70199  pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
70200  return SQLITE_OK;
70201}
70202
70203/*
70204** Cast the datatype of the value in pMem according to the affinity
70205** "aff".  Casting is different from applying affinity in that a cast
70206** is forced.  In other words, the value is converted into the desired
70207** affinity even if that results in loss of data.  This routine is
70208** used (for example) to implement the SQL "cast()" operator.
70209*/
70210SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
70211  if( pMem->flags & MEM_Null ) return;
70212  switch( aff ){
70213    case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
70214      if( (pMem->flags & MEM_Blob)==0 ){
70215        sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
70216        assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
70217        if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
70218      }else{
70219        pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
70220      }
70221      break;
70222    }
70223    case SQLITE_AFF_NUMERIC: {
70224      sqlite3VdbeMemNumerify(pMem);
70225      break;
70226    }
70227    case SQLITE_AFF_INTEGER: {
70228      sqlite3VdbeMemIntegerify(pMem);
70229      break;
70230    }
70231    case SQLITE_AFF_REAL: {
70232      sqlite3VdbeMemRealify(pMem);
70233      break;
70234    }
70235    default: {
70236      assert( aff==SQLITE_AFF_TEXT );
70237      assert( MEM_Str==(MEM_Blob>>3) );
70238      pMem->flags |= (pMem->flags&MEM_Blob)>>3;
70239      sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
70240      assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
70241      pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
70242      break;
70243    }
70244  }
70245}
70246
70247/*
70248** Initialize bulk memory to be a consistent Mem object.
70249**
70250** The minimum amount of initialization feasible is performed.
70251*/
70252SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
70253  assert( (flags & ~MEM_TypeMask)==0 );
70254  pMem->flags = flags;
70255  pMem->db = db;
70256  pMem->szMalloc = 0;
70257}
70258
70259
70260/*
70261** Delete any previous value and set the value stored in *pMem to NULL.
70262**
70263** This routine calls the Mem.xDel destructor to dispose of values that
70264** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
70265** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
70266** routine to invoke the destructor and deallocates Mem.zMalloc.
70267**
70268** Use this routine to reset the Mem prior to insert a new value.
70269**
70270** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
70271*/
70272SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
70273  if( VdbeMemDynamic(pMem) ){
70274    vdbeMemClearExternAndSetNull(pMem);
70275  }else{
70276    pMem->flags = MEM_Null;
70277  }
70278}
70279SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
70280  sqlite3VdbeMemSetNull((Mem*)p);
70281}
70282
70283/*
70284** Delete any previous value and set the value to be a BLOB of length
70285** n containing all zeros.
70286*/
70287SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
70288  sqlite3VdbeMemRelease(pMem);
70289  pMem->flags = MEM_Blob|MEM_Zero;
70290  pMem->n = 0;
70291  if( n<0 ) n = 0;
70292  pMem->u.nZero = n;
70293  pMem->enc = SQLITE_UTF8;
70294  pMem->z = 0;
70295}
70296
70297/*
70298** The pMem is known to contain content that needs to be destroyed prior
70299** to a value change.  So invoke the destructor, then set the value to
70300** a 64-bit integer.
70301*/
70302static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
70303  sqlite3VdbeMemSetNull(pMem);
70304  pMem->u.i = val;
70305  pMem->flags = MEM_Int;
70306}
70307
70308/*
70309** Delete any previous value and set the value stored in *pMem to val,
70310** manifest type INTEGER.
70311*/
70312SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
70313  if( VdbeMemDynamic(pMem) ){
70314    vdbeReleaseAndSetInt64(pMem, val);
70315  }else{
70316    pMem->u.i = val;
70317    pMem->flags = MEM_Int;
70318  }
70319}
70320
70321#ifndef SQLITE_OMIT_FLOATING_POINT
70322/*
70323** Delete any previous value and set the value stored in *pMem to val,
70324** manifest type REAL.
70325*/
70326SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
70327  sqlite3VdbeMemSetNull(pMem);
70328  if( !sqlite3IsNaN(val) ){
70329    pMem->u.r = val;
70330    pMem->flags = MEM_Real;
70331  }
70332}
70333#endif
70334
70335/*
70336** Delete any previous value and set the value of pMem to be an
70337** empty boolean index.
70338*/
70339SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
70340  sqlite3 *db = pMem->db;
70341  assert( db!=0 );
70342  assert( (pMem->flags & MEM_RowSet)==0 );
70343  sqlite3VdbeMemRelease(pMem);
70344  pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
70345  if( db->mallocFailed ){
70346    pMem->flags = MEM_Null;
70347    pMem->szMalloc = 0;
70348  }else{
70349    assert( pMem->zMalloc );
70350    pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
70351    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
70352    assert( pMem->u.pRowSet!=0 );
70353    pMem->flags = MEM_RowSet;
70354  }
70355}
70356
70357/*
70358** Return true if the Mem object contains a TEXT or BLOB that is
70359** too large - whose size exceeds SQLITE_MAX_LENGTH.
70360*/
70361SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
70362  assert( p->db!=0 );
70363  if( p->flags & (MEM_Str|MEM_Blob) ){
70364    int n = p->n;
70365    if( p->flags & MEM_Zero ){
70366      n += p->u.nZero;
70367    }
70368    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
70369  }
70370  return 0;
70371}
70372
70373#ifdef SQLITE_DEBUG
70374/*
70375** This routine prepares a memory cell for modification by breaking
70376** its link to a shallow copy and by marking any current shallow
70377** copies of this cell as invalid.
70378**
70379** This is used for testing and debugging only - to make sure shallow
70380** copies are not misused.
70381*/
70382SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
70383  int i;
70384  Mem *pX;
70385  for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
70386    if( pX->pScopyFrom==pMem ){
70387      pX->flags |= MEM_Undefined;
70388      pX->pScopyFrom = 0;
70389    }
70390  }
70391  pMem->pScopyFrom = 0;
70392}
70393#endif /* SQLITE_DEBUG */
70394
70395
70396/*
70397** Make an shallow copy of pFrom into pTo.  Prior contents of
70398** pTo are freed.  The pFrom->z field is not duplicated.  If
70399** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
70400** and flags gets srcType (either MEM_Ephem or MEM_Static).
70401*/
70402static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
70403  vdbeMemClearExternAndSetNull(pTo);
70404  assert( !VdbeMemDynamic(pTo) );
70405  sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
70406}
70407SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
70408  assert( (pFrom->flags & MEM_RowSet)==0 );
70409  assert( pTo->db==pFrom->db );
70410  if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
70411  memcpy(pTo, pFrom, MEMCELLSIZE);
70412  if( (pFrom->flags&MEM_Static)==0 ){
70413    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
70414    assert( srcType==MEM_Ephem || srcType==MEM_Static );
70415    pTo->flags |= srcType;
70416  }
70417}
70418
70419/*
70420** Make a full copy of pFrom into pTo.  Prior contents of pTo are
70421** freed before the copy is made.
70422*/
70423SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
70424  int rc = SQLITE_OK;
70425
70426  assert( (pFrom->flags & MEM_RowSet)==0 );
70427  if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
70428  memcpy(pTo, pFrom, MEMCELLSIZE);
70429  pTo->flags &= ~MEM_Dyn;
70430  if( pTo->flags&(MEM_Str|MEM_Blob) ){
70431    if( 0==(pFrom->flags&MEM_Static) ){
70432      pTo->flags |= MEM_Ephem;
70433      rc = sqlite3VdbeMemMakeWriteable(pTo);
70434    }
70435  }
70436
70437  return rc;
70438}
70439
70440/*
70441** Transfer the contents of pFrom to pTo. Any existing value in pTo is
70442** freed. If pFrom contains ephemeral data, a copy is made.
70443**
70444** pFrom contains an SQL NULL when this routine returns.
70445*/
70446SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
70447  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
70448  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
70449  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
70450
70451  sqlite3VdbeMemRelease(pTo);
70452  memcpy(pTo, pFrom, sizeof(Mem));
70453  pFrom->flags = MEM_Null;
70454  pFrom->szMalloc = 0;
70455}
70456
70457/*
70458** Change the value of a Mem to be a string or a BLOB.
70459**
70460** The memory management strategy depends on the value of the xDel
70461** parameter. If the value passed is SQLITE_TRANSIENT, then the
70462** string is copied into a (possibly existing) buffer managed by the
70463** Mem structure. Otherwise, any existing buffer is freed and the
70464** pointer copied.
70465**
70466** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
70467** size limit) then no memory allocation occurs.  If the string can be
70468** stored without allocating memory, then it is.  If a memory allocation
70469** is required to store the string, then value of pMem is unchanged.  In
70470** either case, SQLITE_TOOBIG is returned.
70471*/
70472SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
70473  Mem *pMem,          /* Memory cell to set to string value */
70474  const char *z,      /* String pointer */
70475  int n,              /* Bytes in string, or negative */
70476  u8 enc,             /* Encoding of z.  0 for BLOBs */
70477  void (*xDel)(void*) /* Destructor function */
70478){
70479  int nByte = n;      /* New value for pMem->n */
70480  int iLimit;         /* Maximum allowed string or blob size */
70481  u16 flags = 0;      /* New value for pMem->flags */
70482
70483  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70484  assert( (pMem->flags & MEM_RowSet)==0 );
70485
70486  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
70487  if( !z ){
70488    sqlite3VdbeMemSetNull(pMem);
70489    return SQLITE_OK;
70490  }
70491
70492  if( pMem->db ){
70493    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
70494  }else{
70495    iLimit = SQLITE_MAX_LENGTH;
70496  }
70497  flags = (enc==0?MEM_Blob:MEM_Str);
70498  if( nByte<0 ){
70499    assert( enc!=0 );
70500    if( enc==SQLITE_UTF8 ){
70501      nByte = sqlite3Strlen30(z);
70502      if( nByte>iLimit ) nByte = iLimit+1;
70503    }else{
70504      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
70505    }
70506    flags |= MEM_Term;
70507  }
70508
70509  /* The following block sets the new values of Mem.z and Mem.xDel. It
70510  ** also sets a flag in local variable "flags" to indicate the memory
70511  ** management (one of MEM_Dyn or MEM_Static).
70512  */
70513  if( xDel==SQLITE_TRANSIENT ){
70514    int nAlloc = nByte;
70515    if( flags&MEM_Term ){
70516      nAlloc += (enc==SQLITE_UTF8?1:2);
70517    }
70518    if( nByte>iLimit ){
70519      return SQLITE_TOOBIG;
70520    }
70521    testcase( nAlloc==0 );
70522    testcase( nAlloc==31 );
70523    testcase( nAlloc==32 );
70524    if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
70525      return SQLITE_NOMEM_BKPT;
70526    }
70527    memcpy(pMem->z, z, nAlloc);
70528  }else if( xDel==SQLITE_DYNAMIC ){
70529    sqlite3VdbeMemRelease(pMem);
70530    pMem->zMalloc = pMem->z = (char *)z;
70531    pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
70532  }else{
70533    sqlite3VdbeMemRelease(pMem);
70534    pMem->z = (char *)z;
70535    pMem->xDel = xDel;
70536    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
70537  }
70538
70539  pMem->n = nByte;
70540  pMem->flags = flags;
70541  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
70542
70543#ifndef SQLITE_OMIT_UTF16
70544  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
70545    return SQLITE_NOMEM_BKPT;
70546  }
70547#endif
70548
70549  if( nByte>iLimit ){
70550    return SQLITE_TOOBIG;
70551  }
70552
70553  return SQLITE_OK;
70554}
70555
70556/*
70557** Move data out of a btree key or data field and into a Mem structure.
70558** The data is payload from the entry that pCur is currently pointing
70559** to.  offset and amt determine what portion of the data or key to retrieve.
70560** The result is written into the pMem element.
70561**
70562** The pMem object must have been initialized.  This routine will use
70563** pMem->zMalloc to hold the content from the btree, if possible.  New
70564** pMem->zMalloc space will be allocated if necessary.  The calling routine
70565** is responsible for making sure that the pMem object is eventually
70566** destroyed.
70567**
70568** If this routine fails for any reason (malloc returns NULL or unable
70569** to read from the disk) then the pMem is left in an inconsistent state.
70570*/
70571static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
70572  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
70573  u32 offset,       /* Offset from the start of data to return bytes from. */
70574  u32 amt,          /* Number of bytes to return. */
70575  Mem *pMem         /* OUT: Return data in this Mem structure. */
70576){
70577  int rc;
70578  pMem->flags = MEM_Null;
70579  if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
70580    rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
70581    if( rc==SQLITE_OK ){
70582      pMem->z[amt] = 0;
70583      pMem->z[amt+1] = 0;
70584      pMem->flags = MEM_Blob|MEM_Term;
70585      pMem->n = (int)amt;
70586    }else{
70587      sqlite3VdbeMemRelease(pMem);
70588    }
70589  }
70590  return rc;
70591}
70592SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
70593  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
70594  u32 offset,       /* Offset from the start of data to return bytes from. */
70595  u32 amt,          /* Number of bytes to return. */
70596  Mem *pMem         /* OUT: Return data in this Mem structure. */
70597){
70598  char *zData;        /* Data from the btree layer */
70599  u32 available = 0;  /* Number of bytes available on the local btree page */
70600  int rc = SQLITE_OK; /* Return code */
70601
70602  assert( sqlite3BtreeCursorIsValid(pCur) );
70603  assert( !VdbeMemDynamic(pMem) );
70604
70605  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
70606  ** that both the BtShared and database handle mutexes are held. */
70607  assert( (pMem->flags & MEM_RowSet)==0 );
70608  zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
70609  assert( zData!=0 );
70610
70611  if( offset+amt<=available ){
70612    pMem->z = &zData[offset];
70613    pMem->flags = MEM_Blob|MEM_Ephem;
70614    pMem->n = (int)amt;
70615  }else{
70616    rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
70617  }
70618
70619  return rc;
70620}
70621
70622/*
70623** The pVal argument is known to be a value other than NULL.
70624** Convert it into a string with encoding enc and return a pointer
70625** to a zero-terminated version of that string.
70626*/
70627static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
70628  assert( pVal!=0 );
70629  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
70630  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
70631  assert( (pVal->flags & MEM_RowSet)==0 );
70632  assert( (pVal->flags & (MEM_Null))==0 );
70633  if( pVal->flags & (MEM_Blob|MEM_Str) ){
70634    if( ExpandBlob(pVal) ) return 0;
70635    pVal->flags |= MEM_Str;
70636    if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
70637      sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
70638    }
70639    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
70640      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
70641      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
70642        return 0;
70643      }
70644    }
70645    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
70646  }else{
70647    sqlite3VdbeMemStringify(pVal, enc, 0);
70648    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
70649  }
70650  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
70651              || pVal->db->mallocFailed );
70652  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
70653    return pVal->z;
70654  }else{
70655    return 0;
70656  }
70657}
70658
70659/* This function is only available internally, it is not part of the
70660** external API. It works in a similar way to sqlite3_value_text(),
70661** except the data returned is in the encoding specified by the second
70662** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
70663** SQLITE_UTF8.
70664**
70665** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
70666** If that is the case, then the result must be aligned on an even byte
70667** boundary.
70668*/
70669SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
70670  if( !pVal ) return 0;
70671  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
70672  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
70673  assert( (pVal->flags & MEM_RowSet)==0 );
70674  if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
70675    return pVal->z;
70676  }
70677  if( pVal->flags&MEM_Null ){
70678    return 0;
70679  }
70680  return valueToText(pVal, enc);
70681}
70682
70683/*
70684** Create a new sqlite3_value object.
70685*/
70686SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
70687  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
70688  if( p ){
70689    p->flags = MEM_Null;
70690    p->db = db;
70691  }
70692  return p;
70693}
70694
70695/*
70696** Context object passed by sqlite3Stat4ProbeSetValue() through to
70697** valueNew(). See comments above valueNew() for details.
70698*/
70699struct ValueNewStat4Ctx {
70700  Parse *pParse;
70701  Index *pIdx;
70702  UnpackedRecord **ppRec;
70703  int iVal;
70704};
70705
70706/*
70707** Allocate and return a pointer to a new sqlite3_value object. If
70708** the second argument to this function is NULL, the object is allocated
70709** by calling sqlite3ValueNew().
70710**
70711** Otherwise, if the second argument is non-zero, then this function is
70712** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
70713** already been allocated, allocate the UnpackedRecord structure that
70714** that function will return to its caller here. Then return a pointer to
70715** an sqlite3_value within the UnpackedRecord.a[] array.
70716*/
70717static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
70718#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70719  if( p ){
70720    UnpackedRecord *pRec = p->ppRec[0];
70721
70722    if( pRec==0 ){
70723      Index *pIdx = p->pIdx;      /* Index being probed */
70724      int nByte;                  /* Bytes of space to allocate */
70725      int i;                      /* Counter variable */
70726      int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
70727
70728      nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
70729      pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
70730      if( pRec ){
70731        pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
70732        if( pRec->pKeyInfo ){
70733          assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
70734          assert( pRec->pKeyInfo->enc==ENC(db) );
70735          pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
70736          for(i=0; i<nCol; i++){
70737            pRec->aMem[i].flags = MEM_Null;
70738            pRec->aMem[i].db = db;
70739          }
70740        }else{
70741          sqlite3DbFree(db, pRec);
70742          pRec = 0;
70743        }
70744      }
70745      if( pRec==0 ) return 0;
70746      p->ppRec[0] = pRec;
70747    }
70748
70749    pRec->nField = p->iVal+1;
70750    return &pRec->aMem[p->iVal];
70751  }
70752#else
70753  UNUSED_PARAMETER(p);
70754#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
70755  return sqlite3ValueNew(db);
70756}
70757
70758/*
70759** The expression object indicated by the second argument is guaranteed
70760** to be a scalar SQL function. If
70761**
70762**   * all function arguments are SQL literals,
70763**   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
70764**   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
70765**
70766** then this routine attempts to invoke the SQL function. Assuming no
70767** error occurs, output parameter (*ppVal) is set to point to a value
70768** object containing the result before returning SQLITE_OK.
70769**
70770** Affinity aff is applied to the result of the function before returning.
70771** If the result is a text value, the sqlite3_value object uses encoding
70772** enc.
70773**
70774** If the conditions above are not met, this function returns SQLITE_OK
70775** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
70776** NULL and an SQLite error code returned.
70777*/
70778#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70779static int valueFromFunction(
70780  sqlite3 *db,                    /* The database connection */
70781  Expr *p,                        /* The expression to evaluate */
70782  u8 enc,                         /* Encoding to use */
70783  u8 aff,                         /* Affinity to use */
70784  sqlite3_value **ppVal,          /* Write the new value here */
70785  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
70786){
70787  sqlite3_context ctx;            /* Context object for function invocation */
70788  sqlite3_value **apVal = 0;      /* Function arguments */
70789  int nVal = 0;                   /* Size of apVal[] array */
70790  FuncDef *pFunc = 0;             /* Function definition */
70791  sqlite3_value *pVal = 0;        /* New value */
70792  int rc = SQLITE_OK;             /* Return code */
70793  ExprList *pList = 0;            /* Function arguments */
70794  int i;                          /* Iterator variable */
70795
70796  assert( pCtx!=0 );
70797  assert( (p->flags & EP_TokenOnly)==0 );
70798  pList = p->x.pList;
70799  if( pList ) nVal = pList->nExpr;
70800  pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
70801  assert( pFunc );
70802  if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
70803   || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
70804  ){
70805    return SQLITE_OK;
70806  }
70807
70808  if( pList ){
70809    apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
70810    if( apVal==0 ){
70811      rc = SQLITE_NOMEM_BKPT;
70812      goto value_from_function_out;
70813    }
70814    for(i=0; i<nVal; i++){
70815      rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
70816      if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
70817    }
70818  }
70819
70820  pVal = valueNew(db, pCtx);
70821  if( pVal==0 ){
70822    rc = SQLITE_NOMEM_BKPT;
70823    goto value_from_function_out;
70824  }
70825
70826  assert( pCtx->pParse->rc==SQLITE_OK );
70827  memset(&ctx, 0, sizeof(ctx));
70828  ctx.pOut = pVal;
70829  ctx.pFunc = pFunc;
70830  pFunc->xSFunc(&ctx, nVal, apVal);
70831  if( ctx.isError ){
70832    rc = ctx.isError;
70833    sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
70834  }else{
70835    sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
70836    assert( rc==SQLITE_OK );
70837    rc = sqlite3VdbeChangeEncoding(pVal, enc);
70838    if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
70839      rc = SQLITE_TOOBIG;
70840      pCtx->pParse->nErr++;
70841    }
70842  }
70843  pCtx->pParse->rc = rc;
70844
70845 value_from_function_out:
70846  if( rc!=SQLITE_OK ){
70847    pVal = 0;
70848  }
70849  if( apVal ){
70850    for(i=0; i<nVal; i++){
70851      sqlite3ValueFree(apVal[i]);
70852    }
70853    sqlite3DbFree(db, apVal);
70854  }
70855
70856  *ppVal = pVal;
70857  return rc;
70858}
70859#else
70860# define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
70861#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
70862
70863/*
70864** Extract a value from the supplied expression in the manner described
70865** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
70866** using valueNew().
70867**
70868** If pCtx is NULL and an error occurs after the sqlite3_value object
70869** has been allocated, it is freed before returning. Or, if pCtx is not
70870** NULL, it is assumed that the caller will free any allocated object
70871** in all cases.
70872*/
70873static int valueFromExpr(
70874  sqlite3 *db,                    /* The database connection */
70875  Expr *pExpr,                    /* The expression to evaluate */
70876  u8 enc,                         /* Encoding to use */
70877  u8 affinity,                    /* Affinity to use */
70878  sqlite3_value **ppVal,          /* Write the new value here */
70879  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
70880){
70881  int op;
70882  char *zVal = 0;
70883  sqlite3_value *pVal = 0;
70884  int negInt = 1;
70885  const char *zNeg = "";
70886  int rc = SQLITE_OK;
70887
70888  assert( pExpr!=0 );
70889  while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
70890  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
70891
70892  /* Compressed expressions only appear when parsing the DEFAULT clause
70893  ** on a table column definition, and hence only when pCtx==0.  This
70894  ** check ensures that an EP_TokenOnly expression is never passed down
70895  ** into valueFromFunction(). */
70896  assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
70897
70898  if( op==TK_CAST ){
70899    u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
70900    rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
70901    testcase( rc!=SQLITE_OK );
70902    if( *ppVal ){
70903      sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
70904      sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
70905    }
70906    return rc;
70907  }
70908
70909  /* Handle negative integers in a single step.  This is needed in the
70910  ** case when the value is -9223372036854775808.
70911  */
70912  if( op==TK_UMINUS
70913   && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
70914    pExpr = pExpr->pLeft;
70915    op = pExpr->op;
70916    negInt = -1;
70917    zNeg = "-";
70918  }
70919
70920  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
70921    pVal = valueNew(db, pCtx);
70922    if( pVal==0 ) goto no_mem;
70923    if( ExprHasProperty(pExpr, EP_IntValue) ){
70924      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
70925    }else{
70926      zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
70927      if( zVal==0 ) goto no_mem;
70928      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
70929    }
70930    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
70931      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
70932    }else{
70933      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
70934    }
70935    if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
70936    if( enc!=SQLITE_UTF8 ){
70937      rc = sqlite3VdbeChangeEncoding(pVal, enc);
70938    }
70939  }else if( op==TK_UMINUS ) {
70940    /* This branch happens for multiple negative signs.  Ex: -(-5) */
70941    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
70942     && pVal!=0
70943    ){
70944      sqlite3VdbeMemNumerify(pVal);
70945      if( pVal->flags & MEM_Real ){
70946        pVal->u.r = -pVal->u.r;
70947      }else if( pVal->u.i==SMALLEST_INT64 ){
70948        pVal->u.r = -(double)SMALLEST_INT64;
70949        MemSetTypeFlag(pVal, MEM_Real);
70950      }else{
70951        pVal->u.i = -pVal->u.i;
70952      }
70953      sqlite3ValueApplyAffinity(pVal, affinity, enc);
70954    }
70955  }else if( op==TK_NULL ){
70956    pVal = valueNew(db, pCtx);
70957    if( pVal==0 ) goto no_mem;
70958    sqlite3VdbeMemNumerify(pVal);
70959  }
70960#ifndef SQLITE_OMIT_BLOB_LITERAL
70961  else if( op==TK_BLOB ){
70962    int nVal;
70963    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
70964    assert( pExpr->u.zToken[1]=='\'' );
70965    pVal = valueNew(db, pCtx);
70966    if( !pVal ) goto no_mem;
70967    zVal = &pExpr->u.zToken[2];
70968    nVal = sqlite3Strlen30(zVal)-1;
70969    assert( zVal[nVal]=='\'' );
70970    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
70971                         0, SQLITE_DYNAMIC);
70972  }
70973#endif
70974
70975#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70976  else if( op==TK_FUNCTION && pCtx!=0 ){
70977    rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
70978  }
70979#endif
70980
70981  *ppVal = pVal;
70982  return rc;
70983
70984no_mem:
70985  sqlite3OomFault(db);
70986  sqlite3DbFree(db, zVal);
70987  assert( *ppVal==0 );
70988#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70989  if( pCtx==0 ) sqlite3ValueFree(pVal);
70990#else
70991  assert( pCtx==0 ); sqlite3ValueFree(pVal);
70992#endif
70993  return SQLITE_NOMEM_BKPT;
70994}
70995
70996/*
70997** Create a new sqlite3_value object, containing the value of pExpr.
70998**
70999** This only works for very simple expressions that consist of one constant
71000** token (i.e. "5", "5.1", "'a string'"). If the expression can
71001** be converted directly into a value, then the value is allocated and
71002** a pointer written to *ppVal. The caller is responsible for deallocating
71003** the value by passing it to sqlite3ValueFree() later on. If the expression
71004** cannot be converted to a value, then *ppVal is set to NULL.
71005*/
71006SQLITE_PRIVATE int sqlite3ValueFromExpr(
71007  sqlite3 *db,              /* The database connection */
71008  Expr *pExpr,              /* The expression to evaluate */
71009  u8 enc,                   /* Encoding to use */
71010  u8 affinity,              /* Affinity to use */
71011  sqlite3_value **ppVal     /* Write the new value here */
71012){
71013  return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
71014}
71015
71016#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
71017/*
71018** The implementation of the sqlite_record() function. This function accepts
71019** a single argument of any type. The return value is a formatted database
71020** record (a blob) containing the argument value.
71021**
71022** This is used to convert the value stored in the 'sample' column of the
71023** sqlite_stat3 table to the record format SQLite uses internally.
71024*/
71025static void recordFunc(
71026  sqlite3_context *context,
71027  int argc,
71028  sqlite3_value **argv
71029){
71030  const int file_format = 1;
71031  u32 iSerial;                    /* Serial type */
71032  int nSerial;                    /* Bytes of space for iSerial as varint */
71033  u32 nVal;                       /* Bytes of space required for argv[0] */
71034  int nRet;
71035  sqlite3 *db;
71036  u8 *aRet;
71037
71038  UNUSED_PARAMETER( argc );
71039  iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
71040  nSerial = sqlite3VarintLen(iSerial);
71041  db = sqlite3_context_db_handle(context);
71042
71043  nRet = 1 + nSerial + nVal;
71044  aRet = sqlite3DbMallocRawNN(db, nRet);
71045  if( aRet==0 ){
71046    sqlite3_result_error_nomem(context);
71047  }else{
71048    aRet[0] = nSerial+1;
71049    putVarint32(&aRet[1], iSerial);
71050    sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
71051    sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
71052    sqlite3DbFree(db, aRet);
71053  }
71054}
71055
71056/*
71057** Register built-in functions used to help read ANALYZE data.
71058*/
71059SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
71060  static FuncDef aAnalyzeTableFuncs[] = {
71061    FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
71062  };
71063  sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
71064}
71065
71066/*
71067** Attempt to extract a value from pExpr and use it to construct *ppVal.
71068**
71069** If pAlloc is not NULL, then an UnpackedRecord object is created for
71070** pAlloc if one does not exist and the new value is added to the
71071** UnpackedRecord object.
71072**
71073** A value is extracted in the following cases:
71074**
71075**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
71076**
71077**  * The expression is a bound variable, and this is a reprepare, or
71078**
71079**  * The expression is a literal value.
71080**
71081** On success, *ppVal is made to point to the extracted value.  The caller
71082** is responsible for ensuring that the value is eventually freed.
71083*/
71084static int stat4ValueFromExpr(
71085  Parse *pParse,                  /* Parse context */
71086  Expr *pExpr,                    /* The expression to extract a value from */
71087  u8 affinity,                    /* Affinity to use */
71088  struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
71089  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
71090){
71091  int rc = SQLITE_OK;
71092  sqlite3_value *pVal = 0;
71093  sqlite3 *db = pParse->db;
71094
71095  /* Skip over any TK_COLLATE nodes */
71096  pExpr = sqlite3ExprSkipCollate(pExpr);
71097
71098  if( !pExpr ){
71099    pVal = valueNew(db, pAlloc);
71100    if( pVal ){
71101      sqlite3VdbeMemSetNull((Mem*)pVal);
71102    }
71103  }else if( pExpr->op==TK_VARIABLE
71104        || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
71105  ){
71106    Vdbe *v;
71107    int iBindVar = pExpr->iColumn;
71108    sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
71109    if( (v = pParse->pReprepare)!=0 ){
71110      pVal = valueNew(db, pAlloc);
71111      if( pVal ){
71112        rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
71113        if( rc==SQLITE_OK ){
71114          sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
71115        }
71116        pVal->db = pParse->db;
71117      }
71118    }
71119  }else{
71120    rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
71121  }
71122
71123  assert( pVal==0 || pVal->db==db );
71124  *ppVal = pVal;
71125  return rc;
71126}
71127
71128/*
71129** This function is used to allocate and populate UnpackedRecord
71130** structures intended to be compared against sample index keys stored
71131** in the sqlite_stat4 table.
71132**
71133** A single call to this function populates zero or more fields of the
71134** record starting with field iVal (fields are numbered from left to
71135** right starting with 0). A single field is populated if:
71136**
71137**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
71138**
71139**  * The expression is a bound variable, and this is a reprepare, or
71140**
71141**  * The sqlite3ValueFromExpr() function is able to extract a value
71142**    from the expression (i.e. the expression is a literal value).
71143**
71144** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
71145** vector components that match either of the two latter criteria listed
71146** above.
71147**
71148** Before any value is appended to the record, the affinity of the
71149** corresponding column within index pIdx is applied to it. Before
71150** this function returns, output parameter *pnExtract is set to the
71151** number of values appended to the record.
71152**
71153** When this function is called, *ppRec must either point to an object
71154** allocated by an earlier call to this function, or must be NULL. If it
71155** is NULL and a value can be successfully extracted, a new UnpackedRecord
71156** is allocated (and *ppRec set to point to it) before returning.
71157**
71158** Unless an error is encountered, SQLITE_OK is returned. It is not an
71159** error if a value cannot be extracted from pExpr. If an error does
71160** occur, an SQLite error code is returned.
71161*/
71162SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
71163  Parse *pParse,                  /* Parse context */
71164  Index *pIdx,                    /* Index being probed */
71165  UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
71166  Expr *pExpr,                    /* The expression to extract a value from */
71167  int nElem,                      /* Maximum number of values to append */
71168  int iVal,                       /* Array element to populate */
71169  int *pnExtract                  /* OUT: Values appended to the record */
71170){
71171  int rc = SQLITE_OK;
71172  int nExtract = 0;
71173
71174  if( pExpr==0 || pExpr->op!=TK_SELECT ){
71175    int i;
71176    struct ValueNewStat4Ctx alloc;
71177
71178    alloc.pParse = pParse;
71179    alloc.pIdx = pIdx;
71180    alloc.ppRec = ppRec;
71181
71182    for(i=0; i<nElem; i++){
71183      sqlite3_value *pVal = 0;
71184      Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
71185      u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
71186      alloc.iVal = iVal+i;
71187      rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
71188      if( !pVal ) break;
71189      nExtract++;
71190    }
71191  }
71192
71193  *pnExtract = nExtract;
71194  return rc;
71195}
71196
71197/*
71198** Attempt to extract a value from expression pExpr using the methods
71199** as described for sqlite3Stat4ProbeSetValue() above.
71200**
71201** If successful, set *ppVal to point to a new value object and return
71202** SQLITE_OK. If no value can be extracted, but no other error occurs
71203** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
71204** does occur, return an SQLite error code. The final value of *ppVal
71205** is undefined in this case.
71206*/
71207SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
71208  Parse *pParse,                  /* Parse context */
71209  Expr *pExpr,                    /* The expression to extract a value from */
71210  u8 affinity,                    /* Affinity to use */
71211  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
71212){
71213  return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
71214}
71215
71216/*
71217** Extract the iCol-th column from the nRec-byte record in pRec.  Write
71218** the column value into *ppVal.  If *ppVal is initially NULL then a new
71219** sqlite3_value object is allocated.
71220**
71221** If *ppVal is initially NULL then the caller is responsible for
71222** ensuring that the value written into *ppVal is eventually freed.
71223*/
71224SQLITE_PRIVATE int sqlite3Stat4Column(
71225  sqlite3 *db,                    /* Database handle */
71226  const void *pRec,               /* Pointer to buffer containing record */
71227  int nRec,                       /* Size of buffer pRec in bytes */
71228  int iCol,                       /* Column to extract */
71229  sqlite3_value **ppVal           /* OUT: Extracted value */
71230){
71231  u32 t;                          /* a column type code */
71232  int nHdr;                       /* Size of the header in the record */
71233  int iHdr;                       /* Next unread header byte */
71234  int iField;                     /* Next unread data byte */
71235  int szField;                    /* Size of the current data field */
71236  int i;                          /* Column index */
71237  u8 *a = (u8*)pRec;              /* Typecast byte array */
71238  Mem *pMem = *ppVal;             /* Write result into this Mem object */
71239
71240  assert( iCol>0 );
71241  iHdr = getVarint32(a, nHdr);
71242  if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
71243  iField = nHdr;
71244  for(i=0; i<=iCol; i++){
71245    iHdr += getVarint32(&a[iHdr], t);
71246    testcase( iHdr==nHdr );
71247    testcase( iHdr==nHdr+1 );
71248    if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
71249    szField = sqlite3VdbeSerialTypeLen(t);
71250    iField += szField;
71251  }
71252  testcase( iField==nRec );
71253  testcase( iField==nRec+1 );
71254  if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
71255  if( pMem==0 ){
71256    pMem = *ppVal = sqlite3ValueNew(db);
71257    if( pMem==0 ) return SQLITE_NOMEM_BKPT;
71258  }
71259  sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
71260  pMem->enc = ENC(db);
71261  return SQLITE_OK;
71262}
71263
71264/*
71265** Unless it is NULL, the argument must be an UnpackedRecord object returned
71266** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
71267** the object.
71268*/
71269SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
71270  if( pRec ){
71271    int i;
71272    int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
71273    Mem *aMem = pRec->aMem;
71274    sqlite3 *db = aMem[0].db;
71275    for(i=0; i<nCol; i++){
71276      sqlite3VdbeMemRelease(&aMem[i]);
71277    }
71278    sqlite3KeyInfoUnref(pRec->pKeyInfo);
71279    sqlite3DbFree(db, pRec);
71280  }
71281}
71282#endif /* ifdef SQLITE_ENABLE_STAT4 */
71283
71284/*
71285** Change the string value of an sqlite3_value object
71286*/
71287SQLITE_PRIVATE void sqlite3ValueSetStr(
71288  sqlite3_value *v,     /* Value to be set */
71289  int n,                /* Length of string z */
71290  const void *z,        /* Text of the new string */
71291  u8 enc,               /* Encoding to use */
71292  void (*xDel)(void*)   /* Destructor for the string */
71293){
71294  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
71295}
71296
71297/*
71298** Free an sqlite3_value object
71299*/
71300SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
71301  if( !v ) return;
71302  sqlite3VdbeMemRelease((Mem *)v);
71303  sqlite3DbFree(((Mem*)v)->db, v);
71304}
71305
71306/*
71307** The sqlite3ValueBytes() routine returns the number of bytes in the
71308** sqlite3_value object assuming that it uses the encoding "enc".
71309** The valueBytes() routine is a helper function.
71310*/
71311static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
71312  return valueToText(pVal, enc)!=0 ? pVal->n : 0;
71313}
71314SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
71315  Mem *p = (Mem*)pVal;
71316  assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
71317  if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
71318    return p->n;
71319  }
71320  if( (p->flags & MEM_Blob)!=0 ){
71321    if( p->flags & MEM_Zero ){
71322      return p->n + p->u.nZero;
71323    }else{
71324      return p->n;
71325    }
71326  }
71327  if( p->flags & MEM_Null ) return 0;
71328  return valueBytes(pVal, enc);
71329}
71330
71331/************** End of vdbemem.c *********************************************/
71332/************** Begin file vdbeaux.c *****************************************/
71333/*
71334** 2003 September 6
71335**
71336** The author disclaims copyright to this source code.  In place of
71337** a legal notice, here is a blessing:
71338**
71339**    May you do good and not evil.
71340**    May you find forgiveness for yourself and forgive others.
71341**    May you share freely, never taking more than you give.
71342**
71343*************************************************************************
71344** This file contains code used for creating, destroying, and populating
71345** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
71346*/
71347/* #include "sqliteInt.h" */
71348/* #include "vdbeInt.h" */
71349
71350/*
71351** Create a new virtual database engine.
71352*/
71353SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
71354  sqlite3 *db = pParse->db;
71355  Vdbe *p;
71356  p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
71357  if( p==0 ) return 0;
71358  memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
71359  p->db = db;
71360  if( db->pVdbe ){
71361    db->pVdbe->pPrev = p;
71362  }
71363  p->pNext = db->pVdbe;
71364  p->pPrev = 0;
71365  db->pVdbe = p;
71366  p->magic = VDBE_MAGIC_INIT;
71367  p->pParse = pParse;
71368  assert( pParse->aLabel==0 );
71369  assert( pParse->nLabel==0 );
71370  assert( pParse->nOpAlloc==0 );
71371  assert( pParse->szOpAlloc==0 );
71372  return p;
71373}
71374
71375/*
71376** Change the error string stored in Vdbe.zErrMsg
71377*/
71378SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
71379  va_list ap;
71380  sqlite3DbFree(p->db, p->zErrMsg);
71381  va_start(ap, zFormat);
71382  p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
71383  va_end(ap);
71384}
71385
71386/*
71387** Remember the SQL string for a prepared statement.
71388*/
71389SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
71390  assert( isPrepareV2==1 || isPrepareV2==0 );
71391  if( p==0 ) return;
71392  if( !isPrepareV2 ) p->expmask = 0;
71393#if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
71394  if( !isPrepareV2 ) return;
71395#endif
71396  assert( p->zSql==0 );
71397  p->zSql = sqlite3DbStrNDup(p->db, z, n);
71398  p->isPrepareV2 = (u8)isPrepareV2;
71399}
71400
71401/*
71402** Swap all content between two VDBE structures.
71403*/
71404SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
71405  Vdbe tmp, *pTmp;
71406  char *zTmp;
71407  assert( pA->db==pB->db );
71408  tmp = *pA;
71409  *pA = *pB;
71410  *pB = tmp;
71411  pTmp = pA->pNext;
71412  pA->pNext = pB->pNext;
71413  pB->pNext = pTmp;
71414  pTmp = pA->pPrev;
71415  pA->pPrev = pB->pPrev;
71416  pB->pPrev = pTmp;
71417  zTmp = pA->zSql;
71418  pA->zSql = pB->zSql;
71419  pB->zSql = zTmp;
71420  pB->isPrepareV2 = pA->isPrepareV2;
71421  pB->expmask = pA->expmask;
71422}
71423
71424/*
71425** Resize the Vdbe.aOp array so that it is at least nOp elements larger
71426** than its current size. nOp is guaranteed to be less than or equal
71427** to 1024/sizeof(Op).
71428**
71429** If an out-of-memory error occurs while resizing the array, return
71430** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
71431** unchanged (this is so that any opcodes already allocated can be
71432** correctly deallocated along with the rest of the Vdbe).
71433*/
71434static int growOpArray(Vdbe *v, int nOp){
71435  VdbeOp *pNew;
71436  Parse *p = v->pParse;
71437
71438  /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
71439  ** more frequent reallocs and hence provide more opportunities for
71440  ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
71441  ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
71442  ** by the minimum* amount required until the size reaches 512.  Normal
71443  ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
71444  ** size of the op array or add 1KB of space, whichever is smaller. */
71445#ifdef SQLITE_TEST_REALLOC_STRESS
71446  int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
71447#else
71448  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
71449  UNUSED_PARAMETER(nOp);
71450#endif
71451
71452  /* Ensure that the size of a VDBE does not grow too large */
71453  if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
71454    sqlite3OomFault(p->db);
71455    return SQLITE_NOMEM;
71456  }
71457
71458  assert( nOp<=(1024/sizeof(Op)) );
71459  assert( nNew>=(p->nOpAlloc+nOp) );
71460  pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
71461  if( pNew ){
71462    p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
71463    p->nOpAlloc = p->szOpAlloc/sizeof(Op);
71464    v->aOp = pNew;
71465  }
71466  return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
71467}
71468
71469#ifdef SQLITE_DEBUG
71470/* This routine is just a convenient place to set a breakpoint that will
71471** fire after each opcode is inserted and displayed using
71472** "PRAGMA vdbe_addoptrace=on".
71473*/
71474static void test_addop_breakpoint(void){
71475  static int n = 0;
71476  n++;
71477}
71478#endif
71479
71480/*
71481** Add a new instruction to the list of instructions current in the
71482** VDBE.  Return the address of the new instruction.
71483**
71484** Parameters:
71485**
71486**    p               Pointer to the VDBE
71487**
71488**    op              The opcode for this instruction
71489**
71490**    p1, p2, p3      Operands
71491**
71492** Use the sqlite3VdbeResolveLabel() function to fix an address and
71493** the sqlite3VdbeChangeP4() function to change the value of the P4
71494** operand.
71495*/
71496static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
71497  assert( p->pParse->nOpAlloc<=p->nOp );
71498  if( growOpArray(p, 1) ) return 1;
71499  assert( p->pParse->nOpAlloc>p->nOp );
71500  return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
71501}
71502SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
71503  int i;
71504  VdbeOp *pOp;
71505
71506  i = p->nOp;
71507  assert( p->magic==VDBE_MAGIC_INIT );
71508  assert( op>=0 && op<0xff );
71509  if( p->pParse->nOpAlloc<=i ){
71510    return growOp3(p, op, p1, p2, p3);
71511  }
71512  p->nOp++;
71513  pOp = &p->aOp[i];
71514  pOp->opcode = (u8)op;
71515  pOp->p5 = 0;
71516  pOp->p1 = p1;
71517  pOp->p2 = p2;
71518  pOp->p3 = p3;
71519  pOp->p4.p = 0;
71520  pOp->p4type = P4_NOTUSED;
71521#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71522  pOp->zComment = 0;
71523#endif
71524#ifdef SQLITE_DEBUG
71525  if( p->db->flags & SQLITE_VdbeAddopTrace ){
71526    int jj, kk;
71527    Parse *pParse = p->pParse;
71528    for(jj=kk=0; jj<pParse->nColCache; jj++){
71529      struct yColCache *x = pParse->aColCache + jj;
71530      printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
71531      kk++;
71532    }
71533    if( kk ) printf("\n");
71534    sqlite3VdbePrintOp(0, i, &p->aOp[i]);
71535    test_addop_breakpoint();
71536  }
71537#endif
71538#ifdef VDBE_PROFILE
71539  pOp->cycles = 0;
71540  pOp->cnt = 0;
71541#endif
71542#ifdef SQLITE_VDBE_COVERAGE
71543  pOp->iSrcLine = 0;
71544#endif
71545  return i;
71546}
71547SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
71548  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
71549}
71550SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
71551  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
71552}
71553SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
71554  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
71555}
71556
71557/* Generate code for an unconditional jump to instruction iDest
71558*/
71559SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
71560  return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
71561}
71562
71563/* Generate code to cause the string zStr to be loaded into
71564** register iDest
71565*/
71566SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
71567  return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
71568}
71569
71570/*
71571** Generate code that initializes multiple registers to string or integer
71572** constants.  The registers begin with iDest and increase consecutively.
71573** One register is initialized for each characgter in zTypes[].  For each
71574** "s" character in zTypes[], the register is a string if the argument is
71575** not NULL, or OP_Null if the value is a null pointer.  For each "i" character
71576** in zTypes[], the register is initialized to an integer.
71577*/
71578SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
71579  va_list ap;
71580  int i;
71581  char c;
71582  va_start(ap, zTypes);
71583  for(i=0; (c = zTypes[i])!=0; i++){
71584    if( c=='s' ){
71585      const char *z = va_arg(ap, const char*);
71586      sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest++, 0, z, 0);
71587    }else{
71588      assert( c=='i' );
71589      sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
71590    }
71591  }
71592  va_end(ap);
71593}
71594
71595/*
71596** Add an opcode that includes the p4 value as a pointer.
71597*/
71598SQLITE_PRIVATE int sqlite3VdbeAddOp4(
71599  Vdbe *p,            /* Add the opcode to this VM */
71600  int op,             /* The new opcode */
71601  int p1,             /* The P1 operand */
71602  int p2,             /* The P2 operand */
71603  int p3,             /* The P3 operand */
71604  const char *zP4,    /* The P4 operand */
71605  int p4type          /* P4 operand type */
71606){
71607  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
71608  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
71609  return addr;
71610}
71611
71612/*
71613** Add an opcode that includes the p4 value with a P4_INT64 or
71614** P4_REAL type.
71615*/
71616SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
71617  Vdbe *p,            /* Add the opcode to this VM */
71618  int op,             /* The new opcode */
71619  int p1,             /* The P1 operand */
71620  int p2,             /* The P2 operand */
71621  int p3,             /* The P3 operand */
71622  const u8 *zP4,      /* The P4 operand */
71623  int p4type          /* P4 operand type */
71624){
71625  char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
71626  if( p4copy ) memcpy(p4copy, zP4, 8);
71627  return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
71628}
71629
71630/*
71631** Add an OP_ParseSchema opcode.  This routine is broken out from
71632** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
71633** as having been used.
71634**
71635** The zWhere string must have been obtained from sqlite3_malloc().
71636** This routine will take ownership of the allocated memory.
71637*/
71638SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
71639  int j;
71640  sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
71641  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
71642}
71643
71644/*
71645** Add an opcode that includes the p4 value as an integer.
71646*/
71647SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
71648  Vdbe *p,            /* Add the opcode to this VM */
71649  int op,             /* The new opcode */
71650  int p1,             /* The P1 operand */
71651  int p2,             /* The P2 operand */
71652  int p3,             /* The P3 operand */
71653  int p4              /* The P4 operand as an integer */
71654){
71655  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
71656  if( p->db->mallocFailed==0 ){
71657    VdbeOp *pOp = &p->aOp[addr];
71658    pOp->p4type = P4_INT32;
71659    pOp->p4.i = p4;
71660  }
71661  return addr;
71662}
71663
71664/* Insert the end of a co-routine
71665*/
71666SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
71667  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
71668
71669  /* Clear the temporary register cache, thereby ensuring that each
71670  ** co-routine has its own independent set of registers, because co-routines
71671  ** might expect their registers to be preserved across an OP_Yield, and
71672  ** that could cause problems if two or more co-routines are using the same
71673  ** temporary register.
71674  */
71675  v->pParse->nTempReg = 0;
71676  v->pParse->nRangeReg = 0;
71677}
71678
71679/*
71680** Create a new symbolic label for an instruction that has yet to be
71681** coded.  The symbolic label is really just a negative number.  The
71682** label can be used as the P2 value of an operation.  Later, when
71683** the label is resolved to a specific address, the VDBE will scan
71684** through its operation list and change all values of P2 which match
71685** the label into the resolved address.
71686**
71687** The VDBE knows that a P2 value is a label because labels are
71688** always negative and P2 values are suppose to be non-negative.
71689** Hence, a negative P2 value is a label that has yet to be resolved.
71690**
71691** Zero is returned if a malloc() fails.
71692*/
71693SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
71694  Parse *p = v->pParse;
71695  int i = p->nLabel++;
71696  assert( v->magic==VDBE_MAGIC_INIT );
71697  if( (i & (i-1))==0 ){
71698    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
71699                                       (i*2+1)*sizeof(p->aLabel[0]));
71700  }
71701  if( p->aLabel ){
71702    p->aLabel[i] = -1;
71703  }
71704  return ADDR(i);
71705}
71706
71707/*
71708** Resolve label "x" to be the address of the next instruction to
71709** be inserted.  The parameter "x" must have been obtained from
71710** a prior call to sqlite3VdbeMakeLabel().
71711*/
71712SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
71713  Parse *p = v->pParse;
71714  int j = ADDR(x);
71715  assert( v->magic==VDBE_MAGIC_INIT );
71716  assert( j<p->nLabel );
71717  assert( j>=0 );
71718  if( p->aLabel ){
71719    p->aLabel[j] = v->nOp;
71720  }
71721}
71722
71723/*
71724** Mark the VDBE as one that can only be run one time.
71725*/
71726SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
71727  p->runOnlyOnce = 1;
71728}
71729
71730/*
71731** Mark the VDBE as one that can only be run multiple times.
71732*/
71733SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
71734  p->runOnlyOnce = 0;
71735}
71736
71737#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
71738
71739/*
71740** The following type and function are used to iterate through all opcodes
71741** in a Vdbe main program and each of the sub-programs (triggers) it may
71742** invoke directly or indirectly. It should be used as follows:
71743**
71744**   Op *pOp;
71745**   VdbeOpIter sIter;
71746**
71747**   memset(&sIter, 0, sizeof(sIter));
71748**   sIter.v = v;                            // v is of type Vdbe*
71749**   while( (pOp = opIterNext(&sIter)) ){
71750**     // Do something with pOp
71751**   }
71752**   sqlite3DbFree(v->db, sIter.apSub);
71753**
71754*/
71755typedef struct VdbeOpIter VdbeOpIter;
71756struct VdbeOpIter {
71757  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
71758  SubProgram **apSub;        /* Array of subprograms */
71759  int nSub;                  /* Number of entries in apSub */
71760  int iAddr;                 /* Address of next instruction to return */
71761  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
71762};
71763static Op *opIterNext(VdbeOpIter *p){
71764  Vdbe *v = p->v;
71765  Op *pRet = 0;
71766  Op *aOp;
71767  int nOp;
71768
71769  if( p->iSub<=p->nSub ){
71770
71771    if( p->iSub==0 ){
71772      aOp = v->aOp;
71773      nOp = v->nOp;
71774    }else{
71775      aOp = p->apSub[p->iSub-1]->aOp;
71776      nOp = p->apSub[p->iSub-1]->nOp;
71777    }
71778    assert( p->iAddr<nOp );
71779
71780    pRet = &aOp[p->iAddr];
71781    p->iAddr++;
71782    if( p->iAddr==nOp ){
71783      p->iSub++;
71784      p->iAddr = 0;
71785    }
71786
71787    if( pRet->p4type==P4_SUBPROGRAM ){
71788      int nByte = (p->nSub+1)*sizeof(SubProgram*);
71789      int j;
71790      for(j=0; j<p->nSub; j++){
71791        if( p->apSub[j]==pRet->p4.pProgram ) break;
71792      }
71793      if( j==p->nSub ){
71794        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
71795        if( !p->apSub ){
71796          pRet = 0;
71797        }else{
71798          p->apSub[p->nSub++] = pRet->p4.pProgram;
71799        }
71800      }
71801    }
71802  }
71803
71804  return pRet;
71805}
71806
71807/*
71808** Check if the program stored in the VM associated with pParse may
71809** throw an ABORT exception (causing the statement, but not entire transaction
71810** to be rolled back). This condition is true if the main program or any
71811** sub-programs contains any of the following:
71812**
71813**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
71814**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
71815**   *  OP_Destroy
71816**   *  OP_VUpdate
71817**   *  OP_VRename
71818**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
71819**   *  OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
71820**
71821** Then check that the value of Parse.mayAbort is true if an
71822** ABORT may be thrown, or false otherwise. Return true if it does
71823** match, or false otherwise. This function is intended to be used as
71824** part of an assert statement in the compiler. Similar to:
71825**
71826**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
71827*/
71828SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
71829  int hasAbort = 0;
71830  int hasFkCounter = 0;
71831  int hasCreateTable = 0;
71832  int hasInitCoroutine = 0;
71833  Op *pOp;
71834  VdbeOpIter sIter;
71835  memset(&sIter, 0, sizeof(sIter));
71836  sIter.v = v;
71837
71838  while( (pOp = opIterNext(&sIter))!=0 ){
71839    int opcode = pOp->opcode;
71840    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
71841     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
71842      && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
71843    ){
71844      hasAbort = 1;
71845      break;
71846    }
71847    if( opcode==OP_CreateTable ) hasCreateTable = 1;
71848    if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
71849#ifndef SQLITE_OMIT_FOREIGN_KEY
71850    if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
71851      hasFkCounter = 1;
71852    }
71853#endif
71854  }
71855  sqlite3DbFree(v->db, sIter.apSub);
71856
71857  /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
71858  ** If malloc failed, then the while() loop above may not have iterated
71859  ** through all opcodes and hasAbort may be set incorrectly. Return
71860  ** true for this case to prevent the assert() in the callers frame
71861  ** from failing.  */
71862  return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
71863              || (hasCreateTable && hasInitCoroutine) );
71864}
71865#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
71866
71867/*
71868** This routine is called after all opcodes have been inserted.  It loops
71869** through all the opcodes and fixes up some details.
71870**
71871** (1) For each jump instruction with a negative P2 value (a label)
71872**     resolve the P2 value to an actual address.
71873**
71874** (2) Compute the maximum number of arguments used by any SQL function
71875**     and store that value in *pMaxFuncArgs.
71876**
71877** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
71878**     indicate what the prepared statement actually does.
71879**
71880** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
71881**
71882** (5) Reclaim the memory allocated for storing labels.
71883**
71884** This routine will only function correctly if the mkopcodeh.tcl generator
71885** script numbers the opcodes correctly.  Changes to this routine must be
71886** coordinated with changes to mkopcodeh.tcl.
71887*/
71888static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
71889  int nMaxArgs = *pMaxFuncArgs;
71890  Op *pOp;
71891  Parse *pParse = p->pParse;
71892  int *aLabel = pParse->aLabel;
71893  p->readOnly = 1;
71894  p->bIsReader = 0;
71895  pOp = &p->aOp[p->nOp-1];
71896  while(1){
71897
71898    /* Only JUMP opcodes and the short list of special opcodes in the switch
71899    ** below need to be considered.  The mkopcodeh.tcl generator script groups
71900    ** all these opcodes together near the front of the opcode list.  Skip
71901    ** any opcode that does not need processing by virtual of the fact that
71902    ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
71903    */
71904    if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
71905      /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
71906      ** cases from this switch! */
71907      switch( pOp->opcode ){
71908        case OP_Transaction: {
71909          if( pOp->p2!=0 ) p->readOnly = 0;
71910          /* fall thru */
71911        }
71912        case OP_AutoCommit:
71913        case OP_Savepoint: {
71914          p->bIsReader = 1;
71915          break;
71916        }
71917#ifndef SQLITE_OMIT_WAL
71918        case OP_Checkpoint:
71919#endif
71920        case OP_Vacuum:
71921        case OP_JournalMode: {
71922          p->readOnly = 0;
71923          p->bIsReader = 1;
71924          break;
71925        }
71926#ifndef SQLITE_OMIT_VIRTUALTABLE
71927        case OP_VUpdate: {
71928          if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
71929          break;
71930        }
71931        case OP_VFilter: {
71932          int n;
71933          assert( (pOp - p->aOp) >= 3 );
71934          assert( pOp[-1].opcode==OP_Integer );
71935          n = pOp[-1].p1;
71936          if( n>nMaxArgs ) nMaxArgs = n;
71937          break;
71938        }
71939#endif
71940        case OP_Next:
71941        case OP_NextIfOpen:
71942        case OP_SorterNext: {
71943          pOp->p4.xAdvance = sqlite3BtreeNext;
71944          pOp->p4type = P4_ADVANCE;
71945          break;
71946        }
71947        case OP_Prev:
71948        case OP_PrevIfOpen: {
71949          pOp->p4.xAdvance = sqlite3BtreePrevious;
71950          pOp->p4type = P4_ADVANCE;
71951          break;
71952        }
71953      }
71954      if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){
71955        assert( ADDR(pOp->p2)<pParse->nLabel );
71956        pOp->p2 = aLabel[ADDR(pOp->p2)];
71957      }
71958    }
71959    if( pOp==p->aOp ) break;
71960    pOp--;
71961  }
71962  sqlite3DbFree(p->db, pParse->aLabel);
71963  pParse->aLabel = 0;
71964  pParse->nLabel = 0;
71965  *pMaxFuncArgs = nMaxArgs;
71966  assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
71967}
71968
71969/*
71970** Return the address of the next instruction to be inserted.
71971*/
71972SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
71973  assert( p->magic==VDBE_MAGIC_INIT );
71974  return p->nOp;
71975}
71976
71977/*
71978** Verify that at least N opcode slots are available in p without
71979** having to malloc for more space (except when compiled using
71980** SQLITE_TEST_REALLOC_STRESS).  This interface is used during testing
71981** to verify that certain calls to sqlite3VdbeAddOpList() can never
71982** fail due to a OOM fault and hence that the return value from
71983** sqlite3VdbeAddOpList() will always be non-NULL.
71984*/
71985#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
71986SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
71987  assert( p->nOp + N <= p->pParse->nOpAlloc );
71988}
71989#endif
71990
71991/*
71992** Verify that the VM passed as the only argument does not contain
71993** an OP_ResultRow opcode. Fail an assert() if it does. This is used
71994** by code in pragma.c to ensure that the implementation of certain
71995** pragmas comports with the flags specified in the mkpragmatab.tcl
71996** script.
71997*/
71998#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
71999SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
72000  int i;
72001  for(i=0; i<p->nOp; i++){
72002    assert( p->aOp[i].opcode!=OP_ResultRow );
72003  }
72004}
72005#endif
72006
72007/*
72008** This function returns a pointer to the array of opcodes associated with
72009** the Vdbe passed as the first argument. It is the callers responsibility
72010** to arrange for the returned array to be eventually freed using the
72011** vdbeFreeOpArray() function.
72012**
72013** Before returning, *pnOp is set to the number of entries in the returned
72014** array. Also, *pnMaxArg is set to the larger of its current value and
72015** the number of entries in the Vdbe.apArg[] array required to execute the
72016** returned program.
72017*/
72018SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
72019  VdbeOp *aOp = p->aOp;
72020  assert( aOp && !p->db->mallocFailed );
72021
72022  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
72023  assert( DbMaskAllZero(p->btreeMask) );
72024
72025  resolveP2Values(p, pnMaxArg);
72026  *pnOp = p->nOp;
72027  p->aOp = 0;
72028  return aOp;
72029}
72030
72031/*
72032** Add a whole list of operations to the operation stack.  Return a
72033** pointer to the first operation inserted.
72034**
72035** Non-zero P2 arguments to jump instructions are automatically adjusted
72036** so that the jump target is relative to the first operation inserted.
72037*/
72038SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
72039  Vdbe *p,                     /* Add opcodes to the prepared statement */
72040  int nOp,                     /* Number of opcodes to add */
72041  VdbeOpList const *aOp,       /* The opcodes to be added */
72042  int iLineno                  /* Source-file line number of first opcode */
72043){
72044  int i;
72045  VdbeOp *pOut, *pFirst;
72046  assert( nOp>0 );
72047  assert( p->magic==VDBE_MAGIC_INIT );
72048  if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
72049    return 0;
72050  }
72051  pFirst = pOut = &p->aOp[p->nOp];
72052  for(i=0; i<nOp; i++, aOp++, pOut++){
72053    pOut->opcode = aOp->opcode;
72054    pOut->p1 = aOp->p1;
72055    pOut->p2 = aOp->p2;
72056    assert( aOp->p2>=0 );
72057    if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
72058      pOut->p2 += p->nOp;
72059    }
72060    pOut->p3 = aOp->p3;
72061    pOut->p4type = P4_NOTUSED;
72062    pOut->p4.p = 0;
72063    pOut->p5 = 0;
72064#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
72065    pOut->zComment = 0;
72066#endif
72067#ifdef SQLITE_VDBE_COVERAGE
72068    pOut->iSrcLine = iLineno+i;
72069#else
72070    (void)iLineno;
72071#endif
72072#ifdef SQLITE_DEBUG
72073    if( p->db->flags & SQLITE_VdbeAddopTrace ){
72074      sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
72075    }
72076#endif
72077  }
72078  p->nOp += nOp;
72079  return pFirst;
72080}
72081
72082#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
72083/*
72084** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
72085*/
72086SQLITE_PRIVATE void sqlite3VdbeScanStatus(
72087  Vdbe *p,                        /* VM to add scanstatus() to */
72088  int addrExplain,                /* Address of OP_Explain (or 0) */
72089  int addrLoop,                   /* Address of loop counter */
72090  int addrVisit,                  /* Address of rows visited counter */
72091  LogEst nEst,                    /* Estimated number of output rows */
72092  const char *zName               /* Name of table or index being scanned */
72093){
72094  int nByte = (p->nScan+1) * sizeof(ScanStatus);
72095  ScanStatus *aNew;
72096  aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
72097  if( aNew ){
72098    ScanStatus *pNew = &aNew[p->nScan++];
72099    pNew->addrExplain = addrExplain;
72100    pNew->addrLoop = addrLoop;
72101    pNew->addrVisit = addrVisit;
72102    pNew->nEst = nEst;
72103    pNew->zName = sqlite3DbStrDup(p->db, zName);
72104    p->aScan = aNew;
72105  }
72106}
72107#endif
72108
72109
72110/*
72111** Change the value of the opcode, or P1, P2, P3, or P5 operands
72112** for a specific instruction.
72113*/
72114SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
72115  sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
72116}
72117SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
72118  sqlite3VdbeGetOp(p,addr)->p1 = val;
72119}
72120SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
72121  sqlite3VdbeGetOp(p,addr)->p2 = val;
72122}
72123SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
72124  sqlite3VdbeGetOp(p,addr)->p3 = val;
72125}
72126SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
72127  assert( p->nOp>0 || p->db->mallocFailed );
72128  if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
72129}
72130
72131/*
72132** Change the P2 operand of instruction addr so that it points to
72133** the address of the next instruction to be coded.
72134*/
72135SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
72136  sqlite3VdbeChangeP2(p, addr, p->nOp);
72137}
72138
72139
72140/*
72141** If the input FuncDef structure is ephemeral, then free it.  If
72142** the FuncDef is not ephermal, then do nothing.
72143*/
72144static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
72145  if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
72146    sqlite3DbFree(db, pDef);
72147  }
72148}
72149
72150static void vdbeFreeOpArray(sqlite3 *, Op *, int);
72151
72152/*
72153** Delete a P4 value if necessary.
72154*/
72155static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
72156  if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
72157  sqlite3DbFree(db, p);
72158}
72159static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
72160  freeEphemeralFunction(db, p->pFunc);
72161  sqlite3DbFree(db, p);
72162}
72163static void freeP4(sqlite3 *db, int p4type, void *p4){
72164  assert( db );
72165  switch( p4type ){
72166    case P4_FUNCCTX: {
72167      freeP4FuncCtx(db, (sqlite3_context*)p4);
72168      break;
72169    }
72170    case P4_REAL:
72171    case P4_INT64:
72172    case P4_DYNAMIC:
72173    case P4_INTARRAY: {
72174      sqlite3DbFree(db, p4);
72175      break;
72176    }
72177    case P4_KEYINFO: {
72178      if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
72179      break;
72180    }
72181#ifdef SQLITE_ENABLE_CURSOR_HINTS
72182    case P4_EXPR: {
72183      sqlite3ExprDelete(db, (Expr*)p4);
72184      break;
72185    }
72186#endif
72187    case P4_FUNCDEF: {
72188      freeEphemeralFunction(db, (FuncDef*)p4);
72189      break;
72190    }
72191    case P4_MEM: {
72192      if( db->pnBytesFreed==0 ){
72193        sqlite3ValueFree((sqlite3_value*)p4);
72194      }else{
72195        freeP4Mem(db, (Mem*)p4);
72196      }
72197      break;
72198    }
72199    case P4_VTAB : {
72200      if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
72201      break;
72202    }
72203  }
72204}
72205
72206/*
72207** Free the space allocated for aOp and any p4 values allocated for the
72208** opcodes contained within. If aOp is not NULL it is assumed to contain
72209** nOp entries.
72210*/
72211static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
72212  if( aOp ){
72213    Op *pOp;
72214    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
72215      if( pOp->p4type ) freeP4(db, pOp->p4type, pOp->p4.p);
72216#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
72217      sqlite3DbFree(db, pOp->zComment);
72218#endif
72219    }
72220  }
72221  sqlite3DbFree(db, aOp);
72222}
72223
72224/*
72225** Link the SubProgram object passed as the second argument into the linked
72226** list at Vdbe.pSubProgram. This list is used to delete all sub-program
72227** objects when the VM is no longer required.
72228*/
72229SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
72230  p->pNext = pVdbe->pProgram;
72231  pVdbe->pProgram = p;
72232}
72233
72234/*
72235** Change the opcode at addr into OP_Noop
72236*/
72237SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
72238  VdbeOp *pOp;
72239  if( p->db->mallocFailed ) return 0;
72240  assert( addr>=0 && addr<p->nOp );
72241  pOp = &p->aOp[addr];
72242  freeP4(p->db, pOp->p4type, pOp->p4.p);
72243  pOp->p4type = P4_NOTUSED;
72244  pOp->p4.z = 0;
72245  pOp->opcode = OP_Noop;
72246  return 1;
72247}
72248
72249/*
72250** If the last opcode is "op" and it is not a jump destination,
72251** then remove it.  Return true if and only if an opcode was removed.
72252*/
72253SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
72254  if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
72255    return sqlite3VdbeChangeToNoop(p, p->nOp-1);
72256  }else{
72257    return 0;
72258  }
72259}
72260
72261/*
72262** Change the value of the P4 operand for a specific instruction.
72263** This routine is useful when a large program is loaded from a
72264** static array using sqlite3VdbeAddOpList but we want to make a
72265** few minor changes to the program.
72266**
72267** If n>=0 then the P4 operand is dynamic, meaning that a copy of
72268** the string is made into memory obtained from sqlite3_malloc().
72269** A value of n==0 means copy bytes of zP4 up to and including the
72270** first null byte.  If n>0 then copy n+1 bytes of zP4.
72271**
72272** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
72273** to a string or structure that is guaranteed to exist for the lifetime of
72274** the Vdbe. In these cases we can just copy the pointer.
72275**
72276** If addr<0 then change P4 on the most recently inserted instruction.
72277*/
72278static void SQLITE_NOINLINE vdbeChangeP4Full(
72279  Vdbe *p,
72280  Op *pOp,
72281  const char *zP4,
72282  int n
72283){
72284  if( pOp->p4type ){
72285    freeP4(p->db, pOp->p4type, pOp->p4.p);
72286    pOp->p4type = 0;
72287    pOp->p4.p = 0;
72288  }
72289  if( n<0 ){
72290    sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
72291  }else{
72292    if( n==0 ) n = sqlite3Strlen30(zP4);
72293    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
72294    pOp->p4type = P4_DYNAMIC;
72295  }
72296}
72297SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
72298  Op *pOp;
72299  sqlite3 *db;
72300  assert( p!=0 );
72301  db = p->db;
72302  assert( p->magic==VDBE_MAGIC_INIT );
72303  assert( p->aOp!=0 || db->mallocFailed );
72304  if( db->mallocFailed ){
72305    if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
72306    return;
72307  }
72308  assert( p->nOp>0 );
72309  assert( addr<p->nOp );
72310  if( addr<0 ){
72311    addr = p->nOp - 1;
72312  }
72313  pOp = &p->aOp[addr];
72314  if( n>=0 || pOp->p4type ){
72315    vdbeChangeP4Full(p, pOp, zP4, n);
72316    return;
72317  }
72318  if( n==P4_INT32 ){
72319    /* Note: this cast is safe, because the origin data point was an int
72320    ** that was cast to a (const char *). */
72321    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
72322    pOp->p4type = P4_INT32;
72323  }else if( zP4!=0 ){
72324    assert( n<0 );
72325    pOp->p4.p = (void*)zP4;
72326    pOp->p4type = (signed char)n;
72327    if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
72328  }
72329}
72330
72331/*
72332** Change the P4 operand of the most recently coded instruction
72333** to the value defined by the arguments.  This is a high-speed
72334** version of sqlite3VdbeChangeP4().
72335**
72336** The P4 operand must not have been previously defined.  And the new
72337** P4 must not be P4_INT32.  Use sqlite3VdbeChangeP4() in either of
72338** those cases.
72339*/
72340SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
72341  VdbeOp *pOp;
72342  assert( n!=P4_INT32 && n!=P4_VTAB );
72343  assert( n<=0 );
72344  if( p->db->mallocFailed ){
72345    freeP4(p->db, n, pP4);
72346  }else{
72347    assert( pP4!=0 );
72348    assert( p->nOp>0 );
72349    pOp = &p->aOp[p->nOp-1];
72350    assert( pOp->p4type==P4_NOTUSED );
72351    pOp->p4type = n;
72352    pOp->p4.p = pP4;
72353  }
72354}
72355
72356/*
72357** Set the P4 on the most recently added opcode to the KeyInfo for the
72358** index given.
72359*/
72360SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
72361  Vdbe *v = pParse->pVdbe;
72362  KeyInfo *pKeyInfo;
72363  assert( v!=0 );
72364  assert( pIdx!=0 );
72365  pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
72366  if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
72367}
72368
72369#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
72370/*
72371** Change the comment on the most recently coded instruction.  Or
72372** insert a No-op and add the comment to that new instruction.  This
72373** makes the code easier to read during debugging.  None of this happens
72374** in a production build.
72375*/
72376static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
72377  assert( p->nOp>0 || p->aOp==0 );
72378  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
72379  if( p->nOp ){
72380    assert( p->aOp );
72381    sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
72382    p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
72383  }
72384}
72385SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
72386  va_list ap;
72387  if( p ){
72388    va_start(ap, zFormat);
72389    vdbeVComment(p, zFormat, ap);
72390    va_end(ap);
72391  }
72392}
72393SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
72394  va_list ap;
72395  if( p ){
72396    sqlite3VdbeAddOp0(p, OP_Noop);
72397    va_start(ap, zFormat);
72398    vdbeVComment(p, zFormat, ap);
72399    va_end(ap);
72400  }
72401}
72402#endif  /* NDEBUG */
72403
72404#ifdef SQLITE_VDBE_COVERAGE
72405/*
72406** Set the value if the iSrcLine field for the previously coded instruction.
72407*/
72408SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
72409  sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
72410}
72411#endif /* SQLITE_VDBE_COVERAGE */
72412
72413/*
72414** Return the opcode for a given address.  If the address is -1, then
72415** return the most recently inserted opcode.
72416**
72417** If a memory allocation error has occurred prior to the calling of this
72418** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
72419** is readable but not writable, though it is cast to a writable value.
72420** The return of a dummy opcode allows the call to continue functioning
72421** after an OOM fault without having to check to see if the return from
72422** this routine is a valid pointer.  But because the dummy.opcode is 0,
72423** dummy will never be written to.  This is verified by code inspection and
72424** by running with Valgrind.
72425*/
72426SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
72427  /* C89 specifies that the constant "dummy" will be initialized to all
72428  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
72429  static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
72430  assert( p->magic==VDBE_MAGIC_INIT );
72431  if( addr<0 ){
72432    addr = p->nOp - 1;
72433  }
72434  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
72435  if( p->db->mallocFailed ){
72436    return (VdbeOp*)&dummy;
72437  }else{
72438    return &p->aOp[addr];
72439  }
72440}
72441
72442#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
72443/*
72444** Return an integer value for one of the parameters to the opcode pOp
72445** determined by character c.
72446*/
72447static int translateP(char c, const Op *pOp){
72448  if( c=='1' ) return pOp->p1;
72449  if( c=='2' ) return pOp->p2;
72450  if( c=='3' ) return pOp->p3;
72451  if( c=='4' ) return pOp->p4.i;
72452  return pOp->p5;
72453}
72454
72455/*
72456** Compute a string for the "comment" field of a VDBE opcode listing.
72457**
72458** The Synopsis: field in comments in the vdbe.c source file gets converted
72459** to an extra string that is appended to the sqlite3OpcodeName().  In the
72460** absence of other comments, this synopsis becomes the comment on the opcode.
72461** Some translation occurs:
72462**
72463**       "PX"      ->  "r[X]"
72464**       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
72465**       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
72466**       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
72467*/
72468static int displayComment(
72469  const Op *pOp,     /* The opcode to be commented */
72470  const char *zP4,   /* Previously obtained value for P4 */
72471  char *zTemp,       /* Write result here */
72472  int nTemp          /* Space available in zTemp[] */
72473){
72474  const char *zOpName;
72475  const char *zSynopsis;
72476  int nOpName;
72477  int ii, jj;
72478  char zAlt[50];
72479  zOpName = sqlite3OpcodeName(pOp->opcode);
72480  nOpName = sqlite3Strlen30(zOpName);
72481  if( zOpName[nOpName+1] ){
72482    int seenCom = 0;
72483    char c;
72484    zSynopsis = zOpName += nOpName + 1;
72485    if( strncmp(zSynopsis,"IF ",3)==0 ){
72486      if( pOp->p5 & SQLITE_STOREP2 ){
72487        sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
72488      }else{
72489        sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
72490      }
72491      zSynopsis = zAlt;
72492    }
72493    for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
72494      if( c=='P' ){
72495        c = zSynopsis[++ii];
72496        if( c=='4' ){
72497          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
72498        }else if( c=='X' ){
72499          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
72500          seenCom = 1;
72501        }else{
72502          int v1 = translateP(c, pOp);
72503          int v2;
72504          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
72505          if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
72506            ii += 3;
72507            jj += sqlite3Strlen30(zTemp+jj);
72508            v2 = translateP(zSynopsis[ii], pOp);
72509            if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
72510              ii += 2;
72511              v2++;
72512            }
72513            if( v2>1 ){
72514              sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
72515            }
72516          }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
72517            ii += 4;
72518          }
72519        }
72520        jj += sqlite3Strlen30(zTemp+jj);
72521      }else{
72522        zTemp[jj++] = c;
72523      }
72524    }
72525    if( !seenCom && jj<nTemp-5 && pOp->zComment ){
72526      sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
72527      jj += sqlite3Strlen30(zTemp+jj);
72528    }
72529    if( jj<nTemp ) zTemp[jj] = 0;
72530  }else if( pOp->zComment ){
72531    sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
72532    jj = sqlite3Strlen30(zTemp);
72533  }else{
72534    zTemp[0] = 0;
72535    jj = 0;
72536  }
72537  return jj;
72538}
72539#endif /* SQLITE_DEBUG */
72540
72541#if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
72542/*
72543** Translate the P4.pExpr value for an OP_CursorHint opcode into text
72544** that can be displayed in the P4 column of EXPLAIN output.
72545*/
72546static void displayP4Expr(StrAccum *p, Expr *pExpr){
72547  const char *zOp = 0;
72548  switch( pExpr->op ){
72549    case TK_STRING:
72550      sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
72551      break;
72552    case TK_INTEGER:
72553      sqlite3XPrintf(p, "%d", pExpr->u.iValue);
72554      break;
72555    case TK_NULL:
72556      sqlite3XPrintf(p, "NULL");
72557      break;
72558    case TK_REGISTER: {
72559      sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
72560      break;
72561    }
72562    case TK_COLUMN: {
72563      if( pExpr->iColumn<0 ){
72564        sqlite3XPrintf(p, "rowid");
72565      }else{
72566        sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
72567      }
72568      break;
72569    }
72570    case TK_LT:      zOp = "LT";      break;
72571    case TK_LE:      zOp = "LE";      break;
72572    case TK_GT:      zOp = "GT";      break;
72573    case TK_GE:      zOp = "GE";      break;
72574    case TK_NE:      zOp = "NE";      break;
72575    case TK_EQ:      zOp = "EQ";      break;
72576    case TK_IS:      zOp = "IS";      break;
72577    case TK_ISNOT:   zOp = "ISNOT";   break;
72578    case TK_AND:     zOp = "AND";     break;
72579    case TK_OR:      zOp = "OR";      break;
72580    case TK_PLUS:    zOp = "ADD";     break;
72581    case TK_STAR:    zOp = "MUL";     break;
72582    case TK_MINUS:   zOp = "SUB";     break;
72583    case TK_REM:     zOp = "REM";     break;
72584    case TK_BITAND:  zOp = "BITAND";  break;
72585    case TK_BITOR:   zOp = "BITOR";   break;
72586    case TK_SLASH:   zOp = "DIV";     break;
72587    case TK_LSHIFT:  zOp = "LSHIFT";  break;
72588    case TK_RSHIFT:  zOp = "RSHIFT";  break;
72589    case TK_CONCAT:  zOp = "CONCAT";  break;
72590    case TK_UMINUS:  zOp = "MINUS";   break;
72591    case TK_UPLUS:   zOp = "PLUS";    break;
72592    case TK_BITNOT:  zOp = "BITNOT";  break;
72593    case TK_NOT:     zOp = "NOT";     break;
72594    case TK_ISNULL:  zOp = "ISNULL";  break;
72595    case TK_NOTNULL: zOp = "NOTNULL"; break;
72596
72597    default:
72598      sqlite3XPrintf(p, "%s", "expr");
72599      break;
72600  }
72601
72602  if( zOp ){
72603    sqlite3XPrintf(p, "%s(", zOp);
72604    displayP4Expr(p, pExpr->pLeft);
72605    if( pExpr->pRight ){
72606      sqlite3StrAccumAppend(p, ",", 1);
72607      displayP4Expr(p, pExpr->pRight);
72608    }
72609    sqlite3StrAccumAppend(p, ")", 1);
72610  }
72611}
72612#endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
72613
72614
72615#if VDBE_DISPLAY_P4
72616/*
72617** Compute a string that describes the P4 parameter for an opcode.
72618** Use zTemp for any required temporary buffer space.
72619*/
72620static char *displayP4(Op *pOp, char *zTemp, int nTemp){
72621  char *zP4 = zTemp;
72622  StrAccum x;
72623  assert( nTemp>=20 );
72624  sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
72625  switch( pOp->p4type ){
72626    case P4_KEYINFO: {
72627      int j;
72628      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
72629      assert( pKeyInfo->aSortOrder!=0 );
72630      sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField);
72631      for(j=0; j<pKeyInfo->nField; j++){
72632        CollSeq *pColl = pKeyInfo->aColl[j];
72633        const char *zColl = pColl ? pColl->zName : "";
72634        if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
72635        sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
72636      }
72637      sqlite3StrAccumAppend(&x, ")", 1);
72638      break;
72639    }
72640#ifdef SQLITE_ENABLE_CURSOR_HINTS
72641    case P4_EXPR: {
72642      displayP4Expr(&x, pOp->p4.pExpr);
72643      break;
72644    }
72645#endif
72646    case P4_COLLSEQ: {
72647      CollSeq *pColl = pOp->p4.pColl;
72648      sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
72649      break;
72650    }
72651    case P4_FUNCDEF: {
72652      FuncDef *pDef = pOp->p4.pFunc;
72653      sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
72654      break;
72655    }
72656#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
72657    case P4_FUNCCTX: {
72658      FuncDef *pDef = pOp->p4.pCtx->pFunc;
72659      sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
72660      break;
72661    }
72662#endif
72663    case P4_INT64: {
72664      sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
72665      break;
72666    }
72667    case P4_INT32: {
72668      sqlite3XPrintf(&x, "%d", pOp->p4.i);
72669      break;
72670    }
72671    case P4_REAL: {
72672      sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
72673      break;
72674    }
72675    case P4_MEM: {
72676      Mem *pMem = pOp->p4.pMem;
72677      if( pMem->flags & MEM_Str ){
72678        zP4 = pMem->z;
72679      }else if( pMem->flags & MEM_Int ){
72680        sqlite3XPrintf(&x, "%lld", pMem->u.i);
72681      }else if( pMem->flags & MEM_Real ){
72682        sqlite3XPrintf(&x, "%.16g", pMem->u.r);
72683      }else if( pMem->flags & MEM_Null ){
72684        zP4 = "NULL";
72685      }else{
72686        assert( pMem->flags & MEM_Blob );
72687        zP4 = "(blob)";
72688      }
72689      break;
72690    }
72691#ifndef SQLITE_OMIT_VIRTUALTABLE
72692    case P4_VTAB: {
72693      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
72694      sqlite3XPrintf(&x, "vtab:%p", pVtab);
72695      break;
72696    }
72697#endif
72698    case P4_INTARRAY: {
72699      int i;
72700      int *ai = pOp->p4.ai;
72701      int n = ai[0];   /* The first element of an INTARRAY is always the
72702                       ** count of the number of elements to follow */
72703      for(i=1; i<n; i++){
72704        sqlite3XPrintf(&x, ",%d", ai[i]);
72705      }
72706      zTemp[0] = '[';
72707      sqlite3StrAccumAppend(&x, "]", 1);
72708      break;
72709    }
72710    case P4_SUBPROGRAM: {
72711      sqlite3XPrintf(&x, "program");
72712      break;
72713    }
72714    case P4_ADVANCE: {
72715      zTemp[0] = 0;
72716      break;
72717    }
72718    case P4_TABLE: {
72719      sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
72720      break;
72721    }
72722    default: {
72723      zP4 = pOp->p4.z;
72724      if( zP4==0 ){
72725        zP4 = zTemp;
72726        zTemp[0] = 0;
72727      }
72728    }
72729  }
72730  sqlite3StrAccumFinish(&x);
72731  assert( zP4!=0 );
72732  return zP4;
72733}
72734#endif /* VDBE_DISPLAY_P4 */
72735
72736/*
72737** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
72738**
72739** The prepared statements need to know in advance the complete set of
72740** attached databases that will be use.  A mask of these databases
72741** is maintained in p->btreeMask.  The p->lockMask value is the subset of
72742** p->btreeMask of databases that will require a lock.
72743*/
72744SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
72745  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
72746  assert( i<(int)sizeof(p->btreeMask)*8 );
72747  DbMaskSet(p->btreeMask, i);
72748  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
72749    DbMaskSet(p->lockMask, i);
72750  }
72751}
72752
72753#if !defined(SQLITE_OMIT_SHARED_CACHE)
72754/*
72755** If SQLite is compiled to support shared-cache mode and to be threadsafe,
72756** this routine obtains the mutex associated with each BtShared structure
72757** that may be accessed by the VM passed as an argument. In doing so it also
72758** sets the BtShared.db member of each of the BtShared structures, ensuring
72759** that the correct busy-handler callback is invoked if required.
72760**
72761** If SQLite is not threadsafe but does support shared-cache mode, then
72762** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
72763** of all of BtShared structures accessible via the database handle
72764** associated with the VM.
72765**
72766** If SQLite is not threadsafe and does not support shared-cache mode, this
72767** function is a no-op.
72768**
72769** The p->btreeMask field is a bitmask of all btrees that the prepared
72770** statement p will ever use.  Let N be the number of bits in p->btreeMask
72771** corresponding to btrees that use shared cache.  Then the runtime of
72772** this routine is N*N.  But as N is rarely more than 1, this should not
72773** be a problem.
72774*/
72775SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
72776  int i;
72777  sqlite3 *db;
72778  Db *aDb;
72779  int nDb;
72780  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
72781  db = p->db;
72782  aDb = db->aDb;
72783  nDb = db->nDb;
72784  for(i=0; i<nDb; i++){
72785    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
72786      sqlite3BtreeEnter(aDb[i].pBt);
72787    }
72788  }
72789}
72790#endif
72791
72792#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
72793/*
72794** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
72795*/
72796static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
72797  int i;
72798  sqlite3 *db;
72799  Db *aDb;
72800  int nDb;
72801  db = p->db;
72802  aDb = db->aDb;
72803  nDb = db->nDb;
72804  for(i=0; i<nDb; i++){
72805    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
72806      sqlite3BtreeLeave(aDb[i].pBt);
72807    }
72808  }
72809}
72810SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
72811  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
72812  vdbeLeave(p);
72813}
72814#endif
72815
72816#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
72817/*
72818** Print a single opcode.  This routine is used for debugging only.
72819*/
72820SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
72821  char *zP4;
72822  char zPtr[50];
72823  char zCom[100];
72824  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
72825  if( pOut==0 ) pOut = stdout;
72826  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
72827#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
72828  displayComment(pOp, zP4, zCom, sizeof(zCom));
72829#else
72830  zCom[0] = 0;
72831#endif
72832  /* NB:  The sqlite3OpcodeName() function is implemented by code created
72833  ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
72834  ** information from the vdbe.c source text */
72835  fprintf(pOut, zFormat1, pc,
72836      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
72837      zCom
72838  );
72839  fflush(pOut);
72840}
72841#endif
72842
72843/*
72844** Initialize an array of N Mem element.
72845*/
72846static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
72847  while( (N--)>0 ){
72848    p->db = db;
72849    p->flags = flags;
72850    p->szMalloc = 0;
72851#ifdef SQLITE_DEBUG
72852    p->pScopyFrom = 0;
72853#endif
72854    p++;
72855  }
72856}
72857
72858/*
72859** Release an array of N Mem elements
72860*/
72861static void releaseMemArray(Mem *p, int N){
72862  if( p && N ){
72863    Mem *pEnd = &p[N];
72864    sqlite3 *db = p->db;
72865    if( db->pnBytesFreed ){
72866      do{
72867        if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
72868      }while( (++p)<pEnd );
72869      return;
72870    }
72871    do{
72872      assert( (&p[1])==pEnd || p[0].db==p[1].db );
72873      assert( sqlite3VdbeCheckMemInvariants(p) );
72874
72875      /* This block is really an inlined version of sqlite3VdbeMemRelease()
72876      ** that takes advantage of the fact that the memory cell value is
72877      ** being set to NULL after releasing any dynamic resources.
72878      **
72879      ** The justification for duplicating code is that according to
72880      ** callgrind, this causes a certain test case to hit the CPU 4.7
72881      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
72882      ** sqlite3MemRelease() were called from here. With -O2, this jumps
72883      ** to 6.6 percent. The test case is inserting 1000 rows into a table
72884      ** with no indexes using a single prepared INSERT statement, bind()
72885      ** and reset(). Inserts are grouped into a transaction.
72886      */
72887      testcase( p->flags & MEM_Agg );
72888      testcase( p->flags & MEM_Dyn );
72889      testcase( p->flags & MEM_Frame );
72890      testcase( p->flags & MEM_RowSet );
72891      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
72892        sqlite3VdbeMemRelease(p);
72893      }else if( p->szMalloc ){
72894        sqlite3DbFree(db, p->zMalloc);
72895        p->szMalloc = 0;
72896      }
72897
72898      p->flags = MEM_Undefined;
72899    }while( (++p)<pEnd );
72900  }
72901}
72902
72903/*
72904** Delete a VdbeFrame object and its contents. VdbeFrame objects are
72905** allocated by the OP_Program opcode in sqlite3VdbeExec().
72906*/
72907SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
72908  int i;
72909  Mem *aMem = VdbeFrameMem(p);
72910  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
72911  for(i=0; i<p->nChildCsr; i++){
72912    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
72913  }
72914  releaseMemArray(aMem, p->nChildMem);
72915  sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
72916  sqlite3DbFree(p->v->db, p);
72917}
72918
72919#ifndef SQLITE_OMIT_EXPLAIN
72920/*
72921** Give a listing of the program in the virtual machine.
72922**
72923** The interface is the same as sqlite3VdbeExec().  But instead of
72924** running the code, it invokes the callback once for each instruction.
72925** This feature is used to implement "EXPLAIN".
72926**
72927** When p->explain==1, each instruction is listed.  When
72928** p->explain==2, only OP_Explain instructions are listed and these
72929** are shown in a different format.  p->explain==2 is used to implement
72930** EXPLAIN QUERY PLAN.
72931**
72932** When p->explain==1, first the main program is listed, then each of
72933** the trigger subprograms are listed one by one.
72934*/
72935SQLITE_PRIVATE int sqlite3VdbeList(
72936  Vdbe *p                   /* The VDBE */
72937){
72938  int nRow;                            /* Stop when row count reaches this */
72939  int nSub = 0;                        /* Number of sub-vdbes seen so far */
72940  SubProgram **apSub = 0;              /* Array of sub-vdbes */
72941  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
72942  sqlite3 *db = p->db;                 /* The database connection */
72943  int i;                               /* Loop counter */
72944  int rc = SQLITE_OK;                  /* Return code */
72945  Mem *pMem = &p->aMem[1];             /* First Mem of result set */
72946
72947  assert( p->explain );
72948  assert( p->magic==VDBE_MAGIC_RUN );
72949  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
72950
72951  /* Even though this opcode does not use dynamic strings for
72952  ** the result, result columns may become dynamic if the user calls
72953  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
72954  */
72955  releaseMemArray(pMem, 8);
72956  p->pResultSet = 0;
72957
72958  if( p->rc==SQLITE_NOMEM_BKPT ){
72959    /* This happens if a malloc() inside a call to sqlite3_column_text() or
72960    ** sqlite3_column_text16() failed.  */
72961    sqlite3OomFault(db);
72962    return SQLITE_ERROR;
72963  }
72964
72965  /* When the number of output rows reaches nRow, that means the
72966  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
72967  ** nRow is the sum of the number of rows in the main program, plus
72968  ** the sum of the number of rows in all trigger subprograms encountered
72969  ** so far.  The nRow value will increase as new trigger subprograms are
72970  ** encountered, but p->pc will eventually catch up to nRow.
72971  */
72972  nRow = p->nOp;
72973  if( p->explain==1 ){
72974    /* The first 8 memory cells are used for the result set.  So we will
72975    ** commandeer the 9th cell to use as storage for an array of pointers
72976    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
72977    ** cells.  */
72978    assert( p->nMem>9 );
72979    pSub = &p->aMem[9];
72980    if( pSub->flags&MEM_Blob ){
72981      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
72982      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
72983      nSub = pSub->n/sizeof(Vdbe*);
72984      apSub = (SubProgram **)pSub->z;
72985    }
72986    for(i=0; i<nSub; i++){
72987      nRow += apSub[i]->nOp;
72988    }
72989  }
72990
72991  do{
72992    i = p->pc++;
72993  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
72994  if( i>=nRow ){
72995    p->rc = SQLITE_OK;
72996    rc = SQLITE_DONE;
72997  }else if( db->u1.isInterrupted ){
72998    p->rc = SQLITE_INTERRUPT;
72999    rc = SQLITE_ERROR;
73000    sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
73001  }else{
73002    char *zP4;
73003    Op *pOp;
73004    if( i<p->nOp ){
73005      /* The output line number is small enough that we are still in the
73006      ** main program. */
73007      pOp = &p->aOp[i];
73008    }else{
73009      /* We are currently listing subprograms.  Figure out which one and
73010      ** pick up the appropriate opcode. */
73011      int j;
73012      i -= p->nOp;
73013      for(j=0; i>=apSub[j]->nOp; j++){
73014        i -= apSub[j]->nOp;
73015      }
73016      pOp = &apSub[j]->aOp[i];
73017    }
73018    if( p->explain==1 ){
73019      pMem->flags = MEM_Int;
73020      pMem->u.i = i;                                /* Program counter */
73021      pMem++;
73022
73023      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
73024      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
73025      assert( pMem->z!=0 );
73026      pMem->n = sqlite3Strlen30(pMem->z);
73027      pMem->enc = SQLITE_UTF8;
73028      pMem++;
73029
73030      /* When an OP_Program opcode is encounter (the only opcode that has
73031      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
73032      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
73033      ** has not already been seen.
73034      */
73035      if( pOp->p4type==P4_SUBPROGRAM ){
73036        int nByte = (nSub+1)*sizeof(SubProgram*);
73037        int j;
73038        for(j=0; j<nSub; j++){
73039          if( apSub[j]==pOp->p4.pProgram ) break;
73040        }
73041        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
73042          apSub = (SubProgram **)pSub->z;
73043          apSub[nSub++] = pOp->p4.pProgram;
73044          pSub->flags |= MEM_Blob;
73045          pSub->n = nSub*sizeof(SubProgram*);
73046        }
73047      }
73048    }
73049
73050    pMem->flags = MEM_Int;
73051    pMem->u.i = pOp->p1;                          /* P1 */
73052    pMem++;
73053
73054    pMem->flags = MEM_Int;
73055    pMem->u.i = pOp->p2;                          /* P2 */
73056    pMem++;
73057
73058    pMem->flags = MEM_Int;
73059    pMem->u.i = pOp->p3;                          /* P3 */
73060    pMem++;
73061
73062    if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
73063      assert( p->db->mallocFailed );
73064      return SQLITE_ERROR;
73065    }
73066    pMem->flags = MEM_Str|MEM_Term;
73067    zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
73068    if( zP4!=pMem->z ){
73069      pMem->n = 0;
73070      sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
73071    }else{
73072      assert( pMem->z!=0 );
73073      pMem->n = sqlite3Strlen30(pMem->z);
73074      pMem->enc = SQLITE_UTF8;
73075    }
73076    pMem++;
73077
73078    if( p->explain==1 ){
73079      if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
73080        assert( p->db->mallocFailed );
73081        return SQLITE_ERROR;
73082      }
73083      pMem->flags = MEM_Str|MEM_Term;
73084      pMem->n = 2;
73085      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
73086      pMem->enc = SQLITE_UTF8;
73087      pMem++;
73088
73089#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
73090      if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
73091        assert( p->db->mallocFailed );
73092        return SQLITE_ERROR;
73093      }
73094      pMem->flags = MEM_Str|MEM_Term;
73095      pMem->n = displayComment(pOp, zP4, pMem->z, 500);
73096      pMem->enc = SQLITE_UTF8;
73097#else
73098      pMem->flags = MEM_Null;                       /* Comment */
73099#endif
73100    }
73101
73102    p->nResColumn = 8 - 4*(p->explain-1);
73103    p->pResultSet = &p->aMem[1];
73104    p->rc = SQLITE_OK;
73105    rc = SQLITE_ROW;
73106  }
73107  return rc;
73108}
73109#endif /* SQLITE_OMIT_EXPLAIN */
73110
73111#ifdef SQLITE_DEBUG
73112/*
73113** Print the SQL that was used to generate a VDBE program.
73114*/
73115SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
73116  const char *z = 0;
73117  if( p->zSql ){
73118    z = p->zSql;
73119  }else if( p->nOp>=1 ){
73120    const VdbeOp *pOp = &p->aOp[0];
73121    if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
73122      z = pOp->p4.z;
73123      while( sqlite3Isspace(*z) ) z++;
73124    }
73125  }
73126  if( z ) printf("SQL: [%s]\n", z);
73127}
73128#endif
73129
73130#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
73131/*
73132** Print an IOTRACE message showing SQL content.
73133*/
73134SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
73135  int nOp = p->nOp;
73136  VdbeOp *pOp;
73137  if( sqlite3IoTrace==0 ) return;
73138  if( nOp<1 ) return;
73139  pOp = &p->aOp[0];
73140  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
73141    int i, j;
73142    char z[1000];
73143    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
73144    for(i=0; sqlite3Isspace(z[i]); i++){}
73145    for(j=0; z[i]; i++){
73146      if( sqlite3Isspace(z[i]) ){
73147        if( z[i-1]!=' ' ){
73148          z[j++] = ' ';
73149        }
73150      }else{
73151        z[j++] = z[i];
73152      }
73153    }
73154    z[j] = 0;
73155    sqlite3IoTrace("SQL %s\n", z);
73156  }
73157}
73158#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
73159
73160/* An instance of this object describes bulk memory available for use
73161** by subcomponents of a prepared statement.  Space is allocated out
73162** of a ReusableSpace object by the allocSpace() routine below.
73163*/
73164struct ReusableSpace {
73165  u8 *pSpace;          /* Available memory */
73166  int nFree;           /* Bytes of available memory */
73167  int nNeeded;         /* Total bytes that could not be allocated */
73168};
73169
73170/* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
73171** from the ReusableSpace object.  Return a pointer to the allocated
73172** memory on success.  If insufficient memory is available in the
73173** ReusableSpace object, increase the ReusableSpace.nNeeded
73174** value by the amount needed and return NULL.
73175**
73176** If pBuf is not initially NULL, that means that the memory has already
73177** been allocated by a prior call to this routine, so just return a copy
73178** of pBuf and leave ReusableSpace unchanged.
73179**
73180** This allocator is employed to repurpose unused slots at the end of the
73181** opcode array of prepared state for other memory needs of the prepared
73182** statement.
73183*/
73184static void *allocSpace(
73185  struct ReusableSpace *p,  /* Bulk memory available for allocation */
73186  void *pBuf,               /* Pointer to a prior allocation */
73187  int nByte                 /* Bytes of memory needed */
73188){
73189  assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
73190  if( pBuf==0 ){
73191    nByte = ROUND8(nByte);
73192    if( nByte <= p->nFree ){
73193      p->nFree -= nByte;
73194      pBuf = &p->pSpace[p->nFree];
73195    }else{
73196      p->nNeeded += nByte;
73197    }
73198  }
73199  assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
73200  return pBuf;
73201}
73202
73203/*
73204** Rewind the VDBE back to the beginning in preparation for
73205** running it.
73206*/
73207SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
73208#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
73209  int i;
73210#endif
73211  assert( p!=0 );
73212  assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
73213
73214  /* There should be at least one opcode.
73215  */
73216  assert( p->nOp>0 );
73217
73218  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
73219  p->magic = VDBE_MAGIC_RUN;
73220
73221#ifdef SQLITE_DEBUG
73222  for(i=0; i<p->nMem; i++){
73223    assert( p->aMem[i].db==p->db );
73224  }
73225#endif
73226  p->pc = -1;
73227  p->rc = SQLITE_OK;
73228  p->errorAction = OE_Abort;
73229  p->nChange = 0;
73230  p->cacheCtr = 1;
73231  p->minWriteFileFormat = 255;
73232  p->iStatement = 0;
73233  p->nFkConstraint = 0;
73234#ifdef VDBE_PROFILE
73235  for(i=0; i<p->nOp; i++){
73236    p->aOp[i].cnt = 0;
73237    p->aOp[i].cycles = 0;
73238  }
73239#endif
73240}
73241
73242/*
73243** Prepare a virtual machine for execution for the first time after
73244** creating the virtual machine.  This involves things such
73245** as allocating registers and initializing the program counter.
73246** After the VDBE has be prepped, it can be executed by one or more
73247** calls to sqlite3VdbeExec().
73248**
73249** This function may be called exactly once on each virtual machine.
73250** After this routine is called the VM has been "packaged" and is ready
73251** to run.  After this routine is called, further calls to
73252** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
73253** the Vdbe from the Parse object that helped generate it so that the
73254** the Vdbe becomes an independent entity and the Parse object can be
73255** destroyed.
73256**
73257** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
73258** to its initial state after it has been run.
73259*/
73260SQLITE_PRIVATE void sqlite3VdbeMakeReady(
73261  Vdbe *p,                       /* The VDBE */
73262  Parse *pParse                  /* Parsing context */
73263){
73264  sqlite3 *db;                   /* The database connection */
73265  int nVar;                      /* Number of parameters */
73266  int nMem;                      /* Number of VM memory registers */
73267  int nCursor;                   /* Number of cursors required */
73268  int nArg;                      /* Number of arguments in subprograms */
73269  int n;                         /* Loop counter */
73270  struct ReusableSpace x;        /* Reusable bulk memory */
73271
73272  assert( p!=0 );
73273  assert( p->nOp>0 );
73274  assert( pParse!=0 );
73275  assert( p->magic==VDBE_MAGIC_INIT );
73276  assert( pParse==p->pParse );
73277  db = p->db;
73278  assert( db->mallocFailed==0 );
73279  nVar = pParse->nVar;
73280  nMem = pParse->nMem;
73281  nCursor = pParse->nTab;
73282  nArg = pParse->nMaxArg;
73283
73284  /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
73285  ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
73286  ** space at the end of aMem[] for cursors 1 and greater.
73287  ** See also: allocateCursor().
73288  */
73289  nMem += nCursor;
73290  if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */
73291
73292  /* Figure out how much reusable memory is available at the end of the
73293  ** opcode array.  This extra memory will be reallocated for other elements
73294  ** of the prepared statement.
73295  */
73296  n = ROUND8(sizeof(Op)*p->nOp);              /* Bytes of opcode memory used */
73297  x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */
73298  assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
73299  x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n);  /* Bytes of unused memory */
73300  assert( x.nFree>=0 );
73301  assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
73302
73303  resolveP2Values(p, &nArg);
73304  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
73305  if( pParse->explain && nMem<10 ){
73306    nMem = 10;
73307  }
73308  p->expired = 0;
73309
73310  /* Memory for registers, parameters, cursor, etc, is allocated in one or two
73311  ** passes.  On the first pass, we try to reuse unused memory at the
73312  ** end of the opcode array.  If we are unable to satisfy all memory
73313  ** requirements by reusing the opcode array tail, then the second
73314  ** pass will fill in the remainder using a fresh memory allocation.
73315  **
73316  ** This two-pass approach that reuses as much memory as possible from
73317  ** the leftover memory at the end of the opcode array.  This can significantly
73318  ** reduce the amount of memory held by a prepared statement.
73319  */
73320  do {
73321    x.nNeeded = 0;
73322    p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
73323    p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
73324    p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
73325    p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
73326#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
73327    p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
73328#endif
73329    if( x.nNeeded==0 ) break;
73330    x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
73331    x.nFree = x.nNeeded;
73332  }while( !db->mallocFailed );
73333
73334  p->pVList = pParse->pVList;
73335  pParse->pVList =  0;
73336  p->explain = pParse->explain;
73337  if( db->mallocFailed ){
73338    p->nVar = 0;
73339    p->nCursor = 0;
73340    p->nMem = 0;
73341  }else{
73342    p->nCursor = nCursor;
73343    p->nVar = (ynVar)nVar;
73344    initMemArray(p->aVar, nVar, db, MEM_Null);
73345    p->nMem = nMem;
73346    initMemArray(p->aMem, nMem, db, MEM_Undefined);
73347    memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
73348#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
73349    memset(p->anExec, 0, p->nOp*sizeof(i64));
73350#endif
73351  }
73352  sqlite3VdbeRewind(p);
73353}
73354
73355/*
73356** Close a VDBE cursor and release all the resources that cursor
73357** happens to hold.
73358*/
73359SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
73360  if( pCx==0 ){
73361    return;
73362  }
73363  assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
73364  switch( pCx->eCurType ){
73365    case CURTYPE_SORTER: {
73366      sqlite3VdbeSorterClose(p->db, pCx);
73367      break;
73368    }
73369    case CURTYPE_BTREE: {
73370      if( pCx->pBtx ){
73371        sqlite3BtreeClose(pCx->pBtx);
73372        /* The pCx->pCursor will be close automatically, if it exists, by
73373        ** the call above. */
73374      }else{
73375        assert( pCx->uc.pCursor!=0 );
73376        sqlite3BtreeCloseCursor(pCx->uc.pCursor);
73377      }
73378      break;
73379    }
73380#ifndef SQLITE_OMIT_VIRTUALTABLE
73381    case CURTYPE_VTAB: {
73382      sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
73383      const sqlite3_module *pModule = pVCur->pVtab->pModule;
73384      assert( pVCur->pVtab->nRef>0 );
73385      pVCur->pVtab->nRef--;
73386      pModule->xClose(pVCur);
73387      break;
73388    }
73389#endif
73390  }
73391}
73392
73393/*
73394** Close all cursors in the current frame.
73395*/
73396static void closeCursorsInFrame(Vdbe *p){
73397  if( p->apCsr ){
73398    int i;
73399    for(i=0; i<p->nCursor; i++){
73400      VdbeCursor *pC = p->apCsr[i];
73401      if( pC ){
73402        sqlite3VdbeFreeCursor(p, pC);
73403        p->apCsr[i] = 0;
73404      }
73405    }
73406  }
73407}
73408
73409/*
73410** Copy the values stored in the VdbeFrame structure to its Vdbe. This
73411** is used, for example, when a trigger sub-program is halted to restore
73412** control to the main program.
73413*/
73414SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
73415  Vdbe *v = pFrame->v;
73416  closeCursorsInFrame(v);
73417#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
73418  v->anExec = pFrame->anExec;
73419#endif
73420  v->aOp = pFrame->aOp;
73421  v->nOp = pFrame->nOp;
73422  v->aMem = pFrame->aMem;
73423  v->nMem = pFrame->nMem;
73424  v->apCsr = pFrame->apCsr;
73425  v->nCursor = pFrame->nCursor;
73426  v->db->lastRowid = pFrame->lastRowid;
73427  v->nChange = pFrame->nChange;
73428  v->db->nChange = pFrame->nDbChange;
73429  sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
73430  v->pAuxData = pFrame->pAuxData;
73431  pFrame->pAuxData = 0;
73432  return pFrame->pc;
73433}
73434
73435/*
73436** Close all cursors.
73437**
73438** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
73439** cell array. This is necessary as the memory cell array may contain
73440** pointers to VdbeFrame objects, which may in turn contain pointers to
73441** open cursors.
73442*/
73443static void closeAllCursors(Vdbe *p){
73444  if( p->pFrame ){
73445    VdbeFrame *pFrame;
73446    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
73447    sqlite3VdbeFrameRestore(pFrame);
73448    p->pFrame = 0;
73449    p->nFrame = 0;
73450  }
73451  assert( p->nFrame==0 );
73452  closeCursorsInFrame(p);
73453  if( p->aMem ){
73454    releaseMemArray(p->aMem, p->nMem);
73455  }
73456  while( p->pDelFrame ){
73457    VdbeFrame *pDel = p->pDelFrame;
73458    p->pDelFrame = pDel->pParent;
73459    sqlite3VdbeFrameDelete(pDel);
73460  }
73461
73462  /* Delete any auxdata allocations made by the VM */
73463  if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
73464  assert( p->pAuxData==0 );
73465}
73466
73467/*
73468** Clean up the VM after a single run.
73469*/
73470static void Cleanup(Vdbe *p){
73471  sqlite3 *db = p->db;
73472
73473#ifdef SQLITE_DEBUG
73474  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
73475  ** Vdbe.aMem[] arrays have already been cleaned up.  */
73476  int i;
73477  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
73478  if( p->aMem ){
73479    for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
73480  }
73481#endif
73482
73483  sqlite3DbFree(db, p->zErrMsg);
73484  p->zErrMsg = 0;
73485  p->pResultSet = 0;
73486}
73487
73488/*
73489** Set the number of result columns that will be returned by this SQL
73490** statement. This is now set at compile time, rather than during
73491** execution of the vdbe program so that sqlite3_column_count() can
73492** be called on an SQL statement before sqlite3_step().
73493*/
73494SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
73495  Mem *pColName;
73496  int n;
73497  sqlite3 *db = p->db;
73498
73499  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
73500  sqlite3DbFree(db, p->aColName);
73501  n = nResColumn*COLNAME_N;
73502  p->nResColumn = (u16)nResColumn;
73503  p->aColName = pColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
73504  if( p->aColName==0 ) return;
73505  initMemArray(p->aColName, n, p->db, MEM_Null);
73506}
73507
73508/*
73509** Set the name of the idx'th column to be returned by the SQL statement.
73510** zName must be a pointer to a nul terminated string.
73511**
73512** This call must be made after a call to sqlite3VdbeSetNumCols().
73513**
73514** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
73515** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
73516** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
73517*/
73518SQLITE_PRIVATE int sqlite3VdbeSetColName(
73519  Vdbe *p,                         /* Vdbe being configured */
73520  int idx,                         /* Index of column zName applies to */
73521  int var,                         /* One of the COLNAME_* constants */
73522  const char *zName,               /* Pointer to buffer containing name */
73523  void (*xDel)(void*)              /* Memory management strategy for zName */
73524){
73525  int rc;
73526  Mem *pColName;
73527  assert( idx<p->nResColumn );
73528  assert( var<COLNAME_N );
73529  if( p->db->mallocFailed ){
73530    assert( !zName || xDel!=SQLITE_DYNAMIC );
73531    return SQLITE_NOMEM_BKPT;
73532  }
73533  assert( p->aColName!=0 );
73534  pColName = &(p->aColName[idx+var*p->nResColumn]);
73535  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
73536  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
73537  return rc;
73538}
73539
73540/*
73541** A read or write transaction may or may not be active on database handle
73542** db. If a transaction is active, commit it. If there is a
73543** write-transaction spanning more than one database file, this routine
73544** takes care of the master journal trickery.
73545*/
73546static int vdbeCommit(sqlite3 *db, Vdbe *p){
73547  int i;
73548  int nTrans = 0;  /* Number of databases with an active write-transaction
73549                   ** that are candidates for a two-phase commit using a
73550                   ** master-journal */
73551  int rc = SQLITE_OK;
73552  int needXcommit = 0;
73553
73554#ifdef SQLITE_OMIT_VIRTUALTABLE
73555  /* With this option, sqlite3VtabSync() is defined to be simply
73556  ** SQLITE_OK so p is not used.
73557  */
73558  UNUSED_PARAMETER(p);
73559#endif
73560
73561  /* Before doing anything else, call the xSync() callback for any
73562  ** virtual module tables written in this transaction. This has to
73563  ** be done before determining whether a master journal file is
73564  ** required, as an xSync() callback may add an attached database
73565  ** to the transaction.
73566  */
73567  rc = sqlite3VtabSync(db, p);
73568
73569  /* This loop determines (a) if the commit hook should be invoked and
73570  ** (b) how many database files have open write transactions, not
73571  ** including the temp database. (b) is important because if more than
73572  ** one database file has an open write transaction, a master journal
73573  ** file is required for an atomic commit.
73574  */
73575  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
73576    Btree *pBt = db->aDb[i].pBt;
73577    if( sqlite3BtreeIsInTrans(pBt) ){
73578      /* Whether or not a database might need a master journal depends upon
73579      ** its journal mode (among other things).  This matrix determines which
73580      ** journal modes use a master journal and which do not */
73581      static const u8 aMJNeeded[] = {
73582        /* DELETE   */  1,
73583        /* PERSIST   */ 1,
73584        /* OFF       */ 0,
73585        /* TRUNCATE  */ 1,
73586        /* MEMORY    */ 0,
73587        /* WAL       */ 0
73588      };
73589      Pager *pPager;   /* Pager associated with pBt */
73590      needXcommit = 1;
73591      sqlite3BtreeEnter(pBt);
73592      pPager = sqlite3BtreePager(pBt);
73593      if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
73594       && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
73595      ){
73596        assert( i!=1 );
73597        nTrans++;
73598      }
73599      rc = sqlite3PagerExclusiveLock(pPager);
73600      sqlite3BtreeLeave(pBt);
73601    }
73602  }
73603  if( rc!=SQLITE_OK ){
73604    return rc;
73605  }
73606
73607  /* If there are any write-transactions at all, invoke the commit hook */
73608  if( needXcommit && db->xCommitCallback ){
73609    rc = db->xCommitCallback(db->pCommitArg);
73610    if( rc ){
73611      return SQLITE_CONSTRAINT_COMMITHOOK;
73612    }
73613  }
73614
73615  /* The simple case - no more than one database file (not counting the
73616  ** TEMP database) has a transaction active.   There is no need for the
73617  ** master-journal.
73618  **
73619  ** If the return value of sqlite3BtreeGetFilename() is a zero length
73620  ** string, it means the main database is :memory: or a temp file.  In
73621  ** that case we do not support atomic multi-file commits, so use the
73622  ** simple case then too.
73623  */
73624  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
73625   || nTrans<=1
73626  ){
73627    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
73628      Btree *pBt = db->aDb[i].pBt;
73629      if( pBt ){
73630        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
73631      }
73632    }
73633
73634    /* Do the commit only if all databases successfully complete phase 1.
73635    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
73636    ** IO error while deleting or truncating a journal file. It is unlikely,
73637    ** but could happen. In this case abandon processing and return the error.
73638    */
73639    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
73640      Btree *pBt = db->aDb[i].pBt;
73641      if( pBt ){
73642        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
73643      }
73644    }
73645    if( rc==SQLITE_OK ){
73646      sqlite3VtabCommit(db);
73647    }
73648  }
73649
73650  /* The complex case - There is a multi-file write-transaction active.
73651  ** This requires a master journal file to ensure the transaction is
73652  ** committed atomically.
73653  */
73654#ifndef SQLITE_OMIT_DISKIO
73655  else{
73656    sqlite3_vfs *pVfs = db->pVfs;
73657    char *zMaster = 0;   /* File-name for the master journal */
73658    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
73659    sqlite3_file *pMaster = 0;
73660    i64 offset = 0;
73661    int res;
73662    int retryCount = 0;
73663    int nMainFile;
73664
73665    /* Select a master journal file name */
73666    nMainFile = sqlite3Strlen30(zMainFile);
73667    zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
73668    if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
73669    do {
73670      u32 iRandom;
73671      if( retryCount ){
73672        if( retryCount>100 ){
73673          sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
73674          sqlite3OsDelete(pVfs, zMaster, 0);
73675          break;
73676        }else if( retryCount==1 ){
73677          sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
73678        }
73679      }
73680      retryCount++;
73681      sqlite3_randomness(sizeof(iRandom), &iRandom);
73682      sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
73683                               (iRandom>>8)&0xffffff, iRandom&0xff);
73684      /* The antipenultimate character of the master journal name must
73685      ** be "9" to avoid name collisions when using 8+3 filenames. */
73686      assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
73687      sqlite3FileSuffix3(zMainFile, zMaster);
73688      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
73689    }while( rc==SQLITE_OK && res );
73690    if( rc==SQLITE_OK ){
73691      /* Open the master journal. */
73692      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
73693          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
73694          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
73695      );
73696    }
73697    if( rc!=SQLITE_OK ){
73698      sqlite3DbFree(db, zMaster);
73699      return rc;
73700    }
73701
73702    /* Write the name of each database file in the transaction into the new
73703    ** master journal file. If an error occurs at this point close
73704    ** and delete the master journal file. All the individual journal files
73705    ** still have 'null' as the master journal pointer, so they will roll
73706    ** back independently if a failure occurs.
73707    */
73708    for(i=0; i<db->nDb; i++){
73709      Btree *pBt = db->aDb[i].pBt;
73710      if( sqlite3BtreeIsInTrans(pBt) ){
73711        char const *zFile = sqlite3BtreeGetJournalname(pBt);
73712        if( zFile==0 ){
73713          continue;  /* Ignore TEMP and :memory: databases */
73714        }
73715        assert( zFile[0]!=0 );
73716        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
73717        offset += sqlite3Strlen30(zFile)+1;
73718        if( rc!=SQLITE_OK ){
73719          sqlite3OsCloseFree(pMaster);
73720          sqlite3OsDelete(pVfs, zMaster, 0);
73721          sqlite3DbFree(db, zMaster);
73722          return rc;
73723        }
73724      }
73725    }
73726
73727    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
73728    ** flag is set this is not required.
73729    */
73730    if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
73731     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
73732    ){
73733      sqlite3OsCloseFree(pMaster);
73734      sqlite3OsDelete(pVfs, zMaster, 0);
73735      sqlite3DbFree(db, zMaster);
73736      return rc;
73737    }
73738
73739    /* Sync all the db files involved in the transaction. The same call
73740    ** sets the master journal pointer in each individual journal. If
73741    ** an error occurs here, do not delete the master journal file.
73742    **
73743    ** If the error occurs during the first call to
73744    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
73745    ** master journal file will be orphaned. But we cannot delete it,
73746    ** in case the master journal file name was written into the journal
73747    ** file before the failure occurred.
73748    */
73749    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
73750      Btree *pBt = db->aDb[i].pBt;
73751      if( pBt ){
73752        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
73753      }
73754    }
73755    sqlite3OsCloseFree(pMaster);
73756    assert( rc!=SQLITE_BUSY );
73757    if( rc!=SQLITE_OK ){
73758      sqlite3DbFree(db, zMaster);
73759      return rc;
73760    }
73761
73762    /* Delete the master journal file. This commits the transaction. After
73763    ** doing this the directory is synced again before any individual
73764    ** transaction files are deleted.
73765    */
73766    rc = sqlite3OsDelete(pVfs, zMaster, 1);
73767    sqlite3DbFree(db, zMaster);
73768    zMaster = 0;
73769    if( rc ){
73770      return rc;
73771    }
73772
73773    /* All files and directories have already been synced, so the following
73774    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
73775    ** deleting or truncating journals. If something goes wrong while
73776    ** this is happening we don't really care. The integrity of the
73777    ** transaction is already guaranteed, but some stray 'cold' journals
73778    ** may be lying around. Returning an error code won't help matters.
73779    */
73780    disable_simulated_io_errors();
73781    sqlite3BeginBenignMalloc();
73782    for(i=0; i<db->nDb; i++){
73783      Btree *pBt = db->aDb[i].pBt;
73784      if( pBt ){
73785        sqlite3BtreeCommitPhaseTwo(pBt, 1);
73786      }
73787    }
73788    sqlite3EndBenignMalloc();
73789    enable_simulated_io_errors();
73790
73791    sqlite3VtabCommit(db);
73792  }
73793#endif
73794
73795  return rc;
73796}
73797
73798/*
73799** This routine checks that the sqlite3.nVdbeActive count variable
73800** matches the number of vdbe's in the list sqlite3.pVdbe that are
73801** currently active. An assertion fails if the two counts do not match.
73802** This is an internal self-check only - it is not an essential processing
73803** step.
73804**
73805** This is a no-op if NDEBUG is defined.
73806*/
73807#ifndef NDEBUG
73808static void checkActiveVdbeCnt(sqlite3 *db){
73809  Vdbe *p;
73810  int cnt = 0;
73811  int nWrite = 0;
73812  int nRead = 0;
73813  p = db->pVdbe;
73814  while( p ){
73815    if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
73816      cnt++;
73817      if( p->readOnly==0 ) nWrite++;
73818      if( p->bIsReader ) nRead++;
73819    }
73820    p = p->pNext;
73821  }
73822  assert( cnt==db->nVdbeActive );
73823  assert( nWrite==db->nVdbeWrite );
73824  assert( nRead==db->nVdbeRead );
73825}
73826#else
73827#define checkActiveVdbeCnt(x)
73828#endif
73829
73830/*
73831** If the Vdbe passed as the first argument opened a statement-transaction,
73832** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
73833** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
73834** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
73835** statement transaction is committed.
73836**
73837** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
73838** Otherwise SQLITE_OK.
73839*/
73840static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
73841  sqlite3 *const db = p->db;
73842  int rc = SQLITE_OK;
73843  int i;
73844  const int iSavepoint = p->iStatement-1;
73845
73846  assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
73847  assert( db->nStatement>0 );
73848  assert( p->iStatement==(db->nStatement+db->nSavepoint) );
73849
73850  for(i=0; i<db->nDb; i++){
73851    int rc2 = SQLITE_OK;
73852    Btree *pBt = db->aDb[i].pBt;
73853    if( pBt ){
73854      if( eOp==SAVEPOINT_ROLLBACK ){
73855        rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
73856      }
73857      if( rc2==SQLITE_OK ){
73858        rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
73859      }
73860      if( rc==SQLITE_OK ){
73861        rc = rc2;
73862      }
73863    }
73864  }
73865  db->nStatement--;
73866  p->iStatement = 0;
73867
73868  if( rc==SQLITE_OK ){
73869    if( eOp==SAVEPOINT_ROLLBACK ){
73870      rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
73871    }
73872    if( rc==SQLITE_OK ){
73873      rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
73874    }
73875  }
73876
73877  /* If the statement transaction is being rolled back, also restore the
73878  ** database handles deferred constraint counter to the value it had when
73879  ** the statement transaction was opened.  */
73880  if( eOp==SAVEPOINT_ROLLBACK ){
73881    db->nDeferredCons = p->nStmtDefCons;
73882    db->nDeferredImmCons = p->nStmtDefImmCons;
73883  }
73884  return rc;
73885}
73886SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
73887  if( p->db->nStatement && p->iStatement ){
73888    return vdbeCloseStatement(p, eOp);
73889  }
73890  return SQLITE_OK;
73891}
73892
73893
73894/*
73895** This function is called when a transaction opened by the database
73896** handle associated with the VM passed as an argument is about to be
73897** committed. If there are outstanding deferred foreign key constraint
73898** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
73899**
73900** If there are outstanding FK violations and this function returns
73901** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
73902** and write an error message to it. Then return SQLITE_ERROR.
73903*/
73904#ifndef SQLITE_OMIT_FOREIGN_KEY
73905SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
73906  sqlite3 *db = p->db;
73907  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
73908   || (!deferred && p->nFkConstraint>0)
73909  ){
73910    p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
73911    p->errorAction = OE_Abort;
73912    sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
73913    return SQLITE_ERROR;
73914  }
73915  return SQLITE_OK;
73916}
73917#endif
73918
73919/*
73920** This routine is called the when a VDBE tries to halt.  If the VDBE
73921** has made changes and is in autocommit mode, then commit those
73922** changes.  If a rollback is needed, then do the rollback.
73923**
73924** This routine is the only way to move the state of a VM from
73925** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
73926** call this on a VM that is in the SQLITE_MAGIC_HALT state.
73927**
73928** Return an error code.  If the commit could not complete because of
73929** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
73930** means the close did not happen and needs to be repeated.
73931*/
73932SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
73933  int rc;                         /* Used to store transient return codes */
73934  sqlite3 *db = p->db;
73935
73936  /* This function contains the logic that determines if a statement or
73937  ** transaction will be committed or rolled back as a result of the
73938  ** execution of this virtual machine.
73939  **
73940  ** If any of the following errors occur:
73941  **
73942  **     SQLITE_NOMEM
73943  **     SQLITE_IOERR
73944  **     SQLITE_FULL
73945  **     SQLITE_INTERRUPT
73946  **
73947  ** Then the internal cache might have been left in an inconsistent
73948  ** state.  We need to rollback the statement transaction, if there is
73949  ** one, or the complete transaction if there is no statement transaction.
73950  */
73951
73952  if( p->magic!=VDBE_MAGIC_RUN ){
73953    return SQLITE_OK;
73954  }
73955  if( db->mallocFailed ){
73956    p->rc = SQLITE_NOMEM_BKPT;
73957  }
73958  closeAllCursors(p);
73959  checkActiveVdbeCnt(db);
73960
73961  /* No commit or rollback needed if the program never started or if the
73962  ** SQL statement does not read or write a database file.  */
73963  if( p->pc>=0 && p->bIsReader ){
73964    int mrc;   /* Primary error code from p->rc */
73965    int eStatementOp = 0;
73966    int isSpecialError;            /* Set to true if a 'special' error */
73967
73968    /* Lock all btrees used by the statement */
73969    sqlite3VdbeEnter(p);
73970
73971    /* Check for one of the special errors */
73972    mrc = p->rc & 0xff;
73973    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
73974                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
73975    if( isSpecialError ){
73976      /* If the query was read-only and the error code is SQLITE_INTERRUPT,
73977      ** no rollback is necessary. Otherwise, at least a savepoint
73978      ** transaction must be rolled back to restore the database to a
73979      ** consistent state.
73980      **
73981      ** Even if the statement is read-only, it is important to perform
73982      ** a statement or transaction rollback operation. If the error
73983      ** occurred while writing to the journal, sub-journal or database
73984      ** file as part of an effort to free up cache space (see function
73985      ** pagerStress() in pager.c), the rollback is required to restore
73986      ** the pager to a consistent state.
73987      */
73988      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
73989        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
73990          eStatementOp = SAVEPOINT_ROLLBACK;
73991        }else{
73992          /* We are forced to roll back the active transaction. Before doing
73993          ** so, abort any other statements this handle currently has active.
73994          */
73995          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
73996          sqlite3CloseSavepoints(db);
73997          db->autoCommit = 1;
73998          p->nChange = 0;
73999        }
74000      }
74001    }
74002
74003    /* Check for immediate foreign key violations. */
74004    if( p->rc==SQLITE_OK ){
74005      sqlite3VdbeCheckFk(p, 0);
74006    }
74007
74008    /* If the auto-commit flag is set and this is the only active writer
74009    ** VM, then we do either a commit or rollback of the current transaction.
74010    **
74011    ** Note: This block also runs if one of the special errors handled
74012    ** above has occurred.
74013    */
74014    if( !sqlite3VtabInSync(db)
74015     && db->autoCommit
74016     && db->nVdbeWrite==(p->readOnly==0)
74017    ){
74018      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
74019        rc = sqlite3VdbeCheckFk(p, 1);
74020        if( rc!=SQLITE_OK ){
74021          if( NEVER(p->readOnly) ){
74022            sqlite3VdbeLeave(p);
74023            return SQLITE_ERROR;
74024          }
74025          rc = SQLITE_CONSTRAINT_FOREIGNKEY;
74026        }else{
74027          /* The auto-commit flag is true, the vdbe program was successful
74028          ** or hit an 'OR FAIL' constraint and there are no deferred foreign
74029          ** key constraints to hold up the transaction. This means a commit
74030          ** is required. */
74031          rc = vdbeCommit(db, p);
74032        }
74033        if( rc==SQLITE_BUSY && p->readOnly ){
74034          sqlite3VdbeLeave(p);
74035          return SQLITE_BUSY;
74036        }else if( rc!=SQLITE_OK ){
74037          p->rc = rc;
74038          sqlite3RollbackAll(db, SQLITE_OK);
74039          p->nChange = 0;
74040        }else{
74041          db->nDeferredCons = 0;
74042          db->nDeferredImmCons = 0;
74043          db->flags &= ~SQLITE_DeferFKs;
74044          sqlite3CommitInternalChanges(db);
74045        }
74046      }else{
74047        sqlite3RollbackAll(db, SQLITE_OK);
74048        p->nChange = 0;
74049      }
74050      db->nStatement = 0;
74051    }else if( eStatementOp==0 ){
74052      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
74053        eStatementOp = SAVEPOINT_RELEASE;
74054      }else if( p->errorAction==OE_Abort ){
74055        eStatementOp = SAVEPOINT_ROLLBACK;
74056      }else{
74057        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
74058        sqlite3CloseSavepoints(db);
74059        db->autoCommit = 1;
74060        p->nChange = 0;
74061      }
74062    }
74063
74064    /* If eStatementOp is non-zero, then a statement transaction needs to
74065    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
74066    ** do so. If this operation returns an error, and the current statement
74067    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
74068    ** current statement error code.
74069    */
74070    if( eStatementOp ){
74071      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
74072      if( rc ){
74073        if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
74074          p->rc = rc;
74075          sqlite3DbFree(db, p->zErrMsg);
74076          p->zErrMsg = 0;
74077        }
74078        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
74079        sqlite3CloseSavepoints(db);
74080        db->autoCommit = 1;
74081        p->nChange = 0;
74082      }
74083    }
74084
74085    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
74086    ** has been rolled back, update the database connection change-counter.
74087    */
74088    if( p->changeCntOn ){
74089      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
74090        sqlite3VdbeSetChanges(db, p->nChange);
74091      }else{
74092        sqlite3VdbeSetChanges(db, 0);
74093      }
74094      p->nChange = 0;
74095    }
74096
74097    /* Release the locks */
74098    sqlite3VdbeLeave(p);
74099  }
74100
74101  /* We have successfully halted and closed the VM.  Record this fact. */
74102  if( p->pc>=0 ){
74103    db->nVdbeActive--;
74104    if( !p->readOnly ) db->nVdbeWrite--;
74105    if( p->bIsReader ) db->nVdbeRead--;
74106    assert( db->nVdbeActive>=db->nVdbeRead );
74107    assert( db->nVdbeRead>=db->nVdbeWrite );
74108    assert( db->nVdbeWrite>=0 );
74109  }
74110  p->magic = VDBE_MAGIC_HALT;
74111  checkActiveVdbeCnt(db);
74112  if( db->mallocFailed ){
74113    p->rc = SQLITE_NOMEM_BKPT;
74114  }
74115
74116  /* If the auto-commit flag is set to true, then any locks that were held
74117  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
74118  ** to invoke any required unlock-notify callbacks.
74119  */
74120  if( db->autoCommit ){
74121    sqlite3ConnectionUnlocked(db);
74122  }
74123
74124  assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
74125  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
74126}
74127
74128
74129/*
74130** Each VDBE holds the result of the most recent sqlite3_step() call
74131** in p->rc.  This routine sets that result back to SQLITE_OK.
74132*/
74133SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
74134  p->rc = SQLITE_OK;
74135}
74136
74137/*
74138** Copy the error code and error message belonging to the VDBE passed
74139** as the first argument to its database handle (so that they will be
74140** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
74141**
74142** This function does not clear the VDBE error code or message, just
74143** copies them to the database handle.
74144*/
74145SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
74146  sqlite3 *db = p->db;
74147  int rc = p->rc;
74148  if( p->zErrMsg ){
74149    db->bBenignMalloc++;
74150    sqlite3BeginBenignMalloc();
74151    if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
74152    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
74153    sqlite3EndBenignMalloc();
74154    db->bBenignMalloc--;
74155    db->errCode = rc;
74156  }else{
74157    sqlite3Error(db, rc);
74158  }
74159  return rc;
74160}
74161
74162#ifdef SQLITE_ENABLE_SQLLOG
74163/*
74164** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
74165** invoke it.
74166*/
74167static void vdbeInvokeSqllog(Vdbe *v){
74168  if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
74169    char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
74170    assert( v->db->init.busy==0 );
74171    if( zExpanded ){
74172      sqlite3GlobalConfig.xSqllog(
74173          sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
74174      );
74175      sqlite3DbFree(v->db, zExpanded);
74176    }
74177  }
74178}
74179#else
74180# define vdbeInvokeSqllog(x)
74181#endif
74182
74183/*
74184** Clean up a VDBE after execution but do not delete the VDBE just yet.
74185** Write any error messages into *pzErrMsg.  Return the result code.
74186**
74187** After this routine is run, the VDBE should be ready to be executed
74188** again.
74189**
74190** To look at it another way, this routine resets the state of the
74191** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
74192** VDBE_MAGIC_INIT.
74193*/
74194SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
74195  sqlite3 *db;
74196  db = p->db;
74197
74198  /* If the VM did not run to completion or if it encountered an
74199  ** error, then it might not have been halted properly.  So halt
74200  ** it now.
74201  */
74202  sqlite3VdbeHalt(p);
74203
74204  /* If the VDBE has be run even partially, then transfer the error code
74205  ** and error message from the VDBE into the main database structure.  But
74206  ** if the VDBE has just been set to run but has not actually executed any
74207  ** instructions yet, leave the main database error information unchanged.
74208  */
74209  if( p->pc>=0 ){
74210    vdbeInvokeSqllog(p);
74211    sqlite3VdbeTransferError(p);
74212    sqlite3DbFree(db, p->zErrMsg);
74213    p->zErrMsg = 0;
74214    if( p->runOnlyOnce ) p->expired = 1;
74215  }else if( p->rc && p->expired ){
74216    /* The expired flag was set on the VDBE before the first call
74217    ** to sqlite3_step(). For consistency (since sqlite3_step() was
74218    ** called), set the database error in this case as well.
74219    */
74220    sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
74221    sqlite3DbFree(db, p->zErrMsg);
74222    p->zErrMsg = 0;
74223  }
74224
74225  /* Reclaim all memory used by the VDBE
74226  */
74227  Cleanup(p);
74228
74229  /* Save profiling information from this VDBE run.
74230  */
74231#ifdef VDBE_PROFILE
74232  {
74233    FILE *out = fopen("vdbe_profile.out", "a");
74234    if( out ){
74235      int i;
74236      fprintf(out, "---- ");
74237      for(i=0; i<p->nOp; i++){
74238        fprintf(out, "%02x", p->aOp[i].opcode);
74239      }
74240      fprintf(out, "\n");
74241      if( p->zSql ){
74242        char c, pc = 0;
74243        fprintf(out, "-- ");
74244        for(i=0; (c = p->zSql[i])!=0; i++){
74245          if( pc=='\n' ) fprintf(out, "-- ");
74246          putc(c, out);
74247          pc = c;
74248        }
74249        if( pc!='\n' ) fprintf(out, "\n");
74250      }
74251      for(i=0; i<p->nOp; i++){
74252        char zHdr[100];
74253        sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
74254           p->aOp[i].cnt,
74255           p->aOp[i].cycles,
74256           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
74257        );
74258        fprintf(out, "%s", zHdr);
74259        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
74260      }
74261      fclose(out);
74262    }
74263  }
74264#endif
74265  p->iCurrentTime = 0;
74266  p->magic = VDBE_MAGIC_RESET;
74267  return p->rc & db->errMask;
74268}
74269
74270/*
74271** Clean up and delete a VDBE after execution.  Return an integer which is
74272** the result code.  Write any error message text into *pzErrMsg.
74273*/
74274SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
74275  int rc = SQLITE_OK;
74276  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
74277    rc = sqlite3VdbeReset(p);
74278    assert( (rc & p->db->errMask)==rc );
74279  }
74280  sqlite3VdbeDelete(p);
74281  return rc;
74282}
74283
74284/*
74285** If parameter iOp is less than zero, then invoke the destructor for
74286** all auxiliary data pointers currently cached by the VM passed as
74287** the first argument.
74288**
74289** Or, if iOp is greater than or equal to zero, then the destructor is
74290** only invoked for those auxiliary data pointers created by the user
74291** function invoked by the OP_Function opcode at instruction iOp of
74292** VM pVdbe, and only then if:
74293**
74294**    * the associated function parameter is the 32nd or later (counting
74295**      from left to right), or
74296**
74297**    * the corresponding bit in argument mask is clear (where the first
74298**      function parameter corresponds to bit 0 etc.).
74299*/
74300SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
74301  while( *pp ){
74302    AuxData *pAux = *pp;
74303    if( (iOp<0)
74304     || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
74305    ){
74306      testcase( pAux->iArg==31 );
74307      if( pAux->xDelete ){
74308        pAux->xDelete(pAux->pAux);
74309      }
74310      *pp = pAux->pNext;
74311      sqlite3DbFree(db, pAux);
74312    }else{
74313      pp= &pAux->pNext;
74314    }
74315  }
74316}
74317
74318/*
74319** Free all memory associated with the Vdbe passed as the second argument,
74320** except for object itself, which is preserved.
74321**
74322** The difference between this function and sqlite3VdbeDelete() is that
74323** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
74324** the database connection and frees the object itself.
74325*/
74326SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
74327  SubProgram *pSub, *pNext;
74328  assert( p->db==0 || p->db==db );
74329  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
74330  for(pSub=p->pProgram; pSub; pSub=pNext){
74331    pNext = pSub->pNext;
74332    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
74333    sqlite3DbFree(db, pSub);
74334  }
74335  if( p->magic!=VDBE_MAGIC_INIT ){
74336    releaseMemArray(p->aVar, p->nVar);
74337    sqlite3DbFree(db, p->pVList);
74338    sqlite3DbFree(db, p->pFree);
74339  }
74340  vdbeFreeOpArray(db, p->aOp, p->nOp);
74341  sqlite3DbFree(db, p->aColName);
74342  sqlite3DbFree(db, p->zSql);
74343#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
74344  {
74345    int i;
74346    for(i=0; i<p->nScan; i++){
74347      sqlite3DbFree(db, p->aScan[i].zName);
74348    }
74349    sqlite3DbFree(db, p->aScan);
74350  }
74351#endif
74352}
74353
74354/*
74355** Delete an entire VDBE.
74356*/
74357SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
74358  sqlite3 *db;
74359
74360  if( NEVER(p==0) ) return;
74361  db = p->db;
74362  assert( sqlite3_mutex_held(db->mutex) );
74363  sqlite3VdbeClearObject(db, p);
74364  if( p->pPrev ){
74365    p->pPrev->pNext = p->pNext;
74366  }else{
74367    assert( db->pVdbe==p );
74368    db->pVdbe = p->pNext;
74369  }
74370  if( p->pNext ){
74371    p->pNext->pPrev = p->pPrev;
74372  }
74373  p->magic = VDBE_MAGIC_DEAD;
74374  p->db = 0;
74375  sqlite3DbFree(db, p);
74376}
74377
74378/*
74379** The cursor "p" has a pending seek operation that has not yet been
74380** carried out.  Seek the cursor now.  If an error occurs, return
74381** the appropriate error code.
74382*/
74383static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
74384  int res, rc;
74385#ifdef SQLITE_TEST
74386  extern int sqlite3_search_count;
74387#endif
74388  assert( p->deferredMoveto );
74389  assert( p->isTable );
74390  assert( p->eCurType==CURTYPE_BTREE );
74391  rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
74392  if( rc ) return rc;
74393  if( res!=0 ) return SQLITE_CORRUPT_BKPT;
74394#ifdef SQLITE_TEST
74395  sqlite3_search_count++;
74396#endif
74397  p->deferredMoveto = 0;
74398  p->cacheStatus = CACHE_STALE;
74399  return SQLITE_OK;
74400}
74401
74402/*
74403** Something has moved cursor "p" out of place.  Maybe the row it was
74404** pointed to was deleted out from under it.  Or maybe the btree was
74405** rebalanced.  Whatever the cause, try to restore "p" to the place it
74406** is supposed to be pointing.  If the row was deleted out from under the
74407** cursor, set the cursor to point to a NULL row.
74408*/
74409static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
74410  int isDifferentRow, rc;
74411  assert( p->eCurType==CURTYPE_BTREE );
74412  assert( p->uc.pCursor!=0 );
74413  assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
74414  rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
74415  p->cacheStatus = CACHE_STALE;
74416  if( isDifferentRow ) p->nullRow = 1;
74417  return rc;
74418}
74419
74420/*
74421** Check to ensure that the cursor is valid.  Restore the cursor
74422** if need be.  Return any I/O error from the restore operation.
74423*/
74424SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
74425  assert( p->eCurType==CURTYPE_BTREE );
74426  if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
74427    return handleMovedCursor(p);
74428  }
74429  return SQLITE_OK;
74430}
74431
74432/*
74433** Make sure the cursor p is ready to read or write the row to which it
74434** was last positioned.  Return an error code if an OOM fault or I/O error
74435** prevents us from positioning the cursor to its correct position.
74436**
74437** If a MoveTo operation is pending on the given cursor, then do that
74438** MoveTo now.  If no move is pending, check to see if the row has been
74439** deleted out from under the cursor and if it has, mark the row as
74440** a NULL row.
74441**
74442** If the cursor is already pointing to the correct row and that row has
74443** not been deleted out from under the cursor, then this routine is a no-op.
74444*/
74445SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
74446  VdbeCursor *p = *pp;
74447  if( p->eCurType==CURTYPE_BTREE ){
74448    if( p->deferredMoveto ){
74449      int iMap;
74450      if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
74451        *pp = p->pAltCursor;
74452        *piCol = iMap - 1;
74453        return SQLITE_OK;
74454      }
74455      return handleDeferredMoveto(p);
74456    }
74457    if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
74458      return handleMovedCursor(p);
74459    }
74460  }
74461  return SQLITE_OK;
74462}
74463
74464/*
74465** The following functions:
74466**
74467** sqlite3VdbeSerialType()
74468** sqlite3VdbeSerialTypeLen()
74469** sqlite3VdbeSerialLen()
74470** sqlite3VdbeSerialPut()
74471** sqlite3VdbeSerialGet()
74472**
74473** encapsulate the code that serializes values for storage in SQLite
74474** data and index records. Each serialized value consists of a
74475** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
74476** integer, stored as a varint.
74477**
74478** In an SQLite index record, the serial type is stored directly before
74479** the blob of data that it corresponds to. In a table record, all serial
74480** types are stored at the start of the record, and the blobs of data at
74481** the end. Hence these functions allow the caller to handle the
74482** serial-type and data blob separately.
74483**
74484** The following table describes the various storage classes for data:
74485**
74486**   serial type        bytes of data      type
74487**   --------------     ---------------    ---------------
74488**      0                     0            NULL
74489**      1                     1            signed integer
74490**      2                     2            signed integer
74491**      3                     3            signed integer
74492**      4                     4            signed integer
74493**      5                     6            signed integer
74494**      6                     8            signed integer
74495**      7                     8            IEEE float
74496**      8                     0            Integer constant 0
74497**      9                     0            Integer constant 1
74498**     10,11                               reserved for expansion
74499**    N>=12 and even       (N-12)/2        BLOB
74500**    N>=13 and odd        (N-13)/2        text
74501**
74502** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
74503** of SQLite will not understand those serial types.
74504*/
74505
74506/*
74507** Return the serial-type for the value stored in pMem.
74508*/
74509SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
74510  int flags = pMem->flags;
74511  u32 n;
74512
74513  assert( pLen!=0 );
74514  if( flags&MEM_Null ){
74515    *pLen = 0;
74516    return 0;
74517  }
74518  if( flags&MEM_Int ){
74519    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
74520#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
74521    i64 i = pMem->u.i;
74522    u64 u;
74523    if( i<0 ){
74524      u = ~i;
74525    }else{
74526      u = i;
74527    }
74528    if( u<=127 ){
74529      if( (i&1)==i && file_format>=4 ){
74530        *pLen = 0;
74531        return 8+(u32)u;
74532      }else{
74533        *pLen = 1;
74534        return 1;
74535      }
74536    }
74537    if( u<=32767 ){ *pLen = 2; return 2; }
74538    if( u<=8388607 ){ *pLen = 3; return 3; }
74539    if( u<=2147483647 ){ *pLen = 4; return 4; }
74540    if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
74541    *pLen = 8;
74542    return 6;
74543  }
74544  if( flags&MEM_Real ){
74545    *pLen = 8;
74546    return 7;
74547  }
74548  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
74549  assert( pMem->n>=0 );
74550  n = (u32)pMem->n;
74551  if( flags & MEM_Zero ){
74552    n += pMem->u.nZero;
74553  }
74554  *pLen = n;
74555  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
74556}
74557
74558/*
74559** The sizes for serial types less than 128
74560*/
74561static const u8 sqlite3SmallTypeSizes[] = {
74562        /*  0   1   2   3   4   5   6   7   8   9 */
74563/*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
74564/*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
74565/*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
74566/*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
74567/*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
74568/*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
74569/*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
74570/*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
74571/*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
74572/*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
74573/* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
74574/* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
74575/* 120 */  54, 54, 55, 55, 56, 56, 57, 57
74576};
74577
74578/*
74579** Return the length of the data corresponding to the supplied serial-type.
74580*/
74581SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
74582  if( serial_type>=128 ){
74583    return (serial_type-12)/2;
74584  }else{
74585    assert( serial_type<12
74586            || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
74587    return sqlite3SmallTypeSizes[serial_type];
74588  }
74589}
74590SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
74591  assert( serial_type<128 );
74592  return sqlite3SmallTypeSizes[serial_type];
74593}
74594
74595/*
74596** If we are on an architecture with mixed-endian floating
74597** points (ex: ARM7) then swap the lower 4 bytes with the
74598** upper 4 bytes.  Return the result.
74599**
74600** For most architectures, this is a no-op.
74601**
74602** (later):  It is reported to me that the mixed-endian problem
74603** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
74604** that early versions of GCC stored the two words of a 64-bit
74605** float in the wrong order.  And that error has been propagated
74606** ever since.  The blame is not necessarily with GCC, though.
74607** GCC might have just copying the problem from a prior compiler.
74608** I am also told that newer versions of GCC that follow a different
74609** ABI get the byte order right.
74610**
74611** Developers using SQLite on an ARM7 should compile and run their
74612** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
74613** enabled, some asserts below will ensure that the byte order of
74614** floating point values is correct.
74615**
74616** (2007-08-30)  Frank van Vugt has studied this problem closely
74617** and has send his findings to the SQLite developers.  Frank
74618** writes that some Linux kernels offer floating point hardware
74619** emulation that uses only 32-bit mantissas instead of a full
74620** 48-bits as required by the IEEE standard.  (This is the
74621** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
74622** byte swapping becomes very complicated.  To avoid problems,
74623** the necessary byte swapping is carried out using a 64-bit integer
74624** rather than a 64-bit float.  Frank assures us that the code here
74625** works for him.  We, the developers, have no way to independently
74626** verify this, but Frank seems to know what he is talking about
74627** so we trust him.
74628*/
74629#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
74630static u64 floatSwap(u64 in){
74631  union {
74632    u64 r;
74633    u32 i[2];
74634  } u;
74635  u32 t;
74636
74637  u.r = in;
74638  t = u.i[0];
74639  u.i[0] = u.i[1];
74640  u.i[1] = t;
74641  return u.r;
74642}
74643# define swapMixedEndianFloat(X)  X = floatSwap(X)
74644#else
74645# define swapMixedEndianFloat(X)
74646#endif
74647
74648/*
74649** Write the serialized data blob for the value stored in pMem into
74650** buf. It is assumed that the caller has allocated sufficient space.
74651** Return the number of bytes written.
74652**
74653** nBuf is the amount of space left in buf[].  The caller is responsible
74654** for allocating enough space to buf[] to hold the entire field, exclusive
74655** of the pMem->u.nZero bytes for a MEM_Zero value.
74656**
74657** Return the number of bytes actually written into buf[].  The number
74658** of bytes in the zero-filled tail is included in the return value only
74659** if those bytes were zeroed in buf[].
74660*/
74661SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
74662  u32 len;
74663
74664  /* Integer and Real */
74665  if( serial_type<=7 && serial_type>0 ){
74666    u64 v;
74667    u32 i;
74668    if( serial_type==7 ){
74669      assert( sizeof(v)==sizeof(pMem->u.r) );
74670      memcpy(&v, &pMem->u.r, sizeof(v));
74671      swapMixedEndianFloat(v);
74672    }else{
74673      v = pMem->u.i;
74674    }
74675    len = i = sqlite3SmallTypeSizes[serial_type];
74676    assert( i>0 );
74677    do{
74678      buf[--i] = (u8)(v&0xFF);
74679      v >>= 8;
74680    }while( i );
74681    return len;
74682  }
74683
74684  /* String or blob */
74685  if( serial_type>=12 ){
74686    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
74687             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
74688    len = pMem->n;
74689    if( len>0 ) memcpy(buf, pMem->z, len);
74690    return len;
74691  }
74692
74693  /* NULL or constants 0 or 1 */
74694  return 0;
74695}
74696
74697/* Input "x" is a sequence of unsigned characters that represent a
74698** big-endian integer.  Return the equivalent native integer
74699*/
74700#define ONE_BYTE_INT(x)    ((i8)(x)[0])
74701#define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
74702#define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
74703#define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
74704#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
74705
74706/*
74707** Deserialize the data blob pointed to by buf as serial type serial_type
74708** and store the result in pMem.  Return the number of bytes read.
74709**
74710** This function is implemented as two separate routines for performance.
74711** The few cases that require local variables are broken out into a separate
74712** routine so that in most cases the overhead of moving the stack pointer
74713** is avoided.
74714*/
74715static u32 SQLITE_NOINLINE serialGet(
74716  const unsigned char *buf,     /* Buffer to deserialize from */
74717  u32 serial_type,              /* Serial type to deserialize */
74718  Mem *pMem                     /* Memory cell to write value into */
74719){
74720  u64 x = FOUR_BYTE_UINT(buf);
74721  u32 y = FOUR_BYTE_UINT(buf+4);
74722  x = (x<<32) + y;
74723  if( serial_type==6 ){
74724    /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
74725    ** twos-complement integer. */
74726    pMem->u.i = *(i64*)&x;
74727    pMem->flags = MEM_Int;
74728    testcase( pMem->u.i<0 );
74729  }else{
74730    /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
74731    ** floating point number. */
74732#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
74733    /* Verify that integers and floating point values use the same
74734    ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
74735    ** defined that 64-bit floating point values really are mixed
74736    ** endian.
74737    */
74738    static const u64 t1 = ((u64)0x3ff00000)<<32;
74739    static const double r1 = 1.0;
74740    u64 t2 = t1;
74741    swapMixedEndianFloat(t2);
74742    assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
74743#endif
74744    assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
74745    swapMixedEndianFloat(x);
74746    memcpy(&pMem->u.r, &x, sizeof(x));
74747    pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
74748  }
74749  return 8;
74750}
74751SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
74752  const unsigned char *buf,     /* Buffer to deserialize from */
74753  u32 serial_type,              /* Serial type to deserialize */
74754  Mem *pMem                     /* Memory cell to write value into */
74755){
74756  switch( serial_type ){
74757    case 10:   /* Reserved for future use */
74758    case 11:   /* Reserved for future use */
74759    case 0: {  /* Null */
74760      /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
74761      pMem->flags = MEM_Null;
74762      break;
74763    }
74764    case 1: {
74765      /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
74766      ** integer. */
74767      pMem->u.i = ONE_BYTE_INT(buf);
74768      pMem->flags = MEM_Int;
74769      testcase( pMem->u.i<0 );
74770      return 1;
74771    }
74772    case 2: { /* 2-byte signed integer */
74773      /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
74774      ** twos-complement integer. */
74775      pMem->u.i = TWO_BYTE_INT(buf);
74776      pMem->flags = MEM_Int;
74777      testcase( pMem->u.i<0 );
74778      return 2;
74779    }
74780    case 3: { /* 3-byte signed integer */
74781      /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
74782      ** twos-complement integer. */
74783      pMem->u.i = THREE_BYTE_INT(buf);
74784      pMem->flags = MEM_Int;
74785      testcase( pMem->u.i<0 );
74786      return 3;
74787    }
74788    case 4: { /* 4-byte signed integer */
74789      /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
74790      ** twos-complement integer. */
74791      pMem->u.i = FOUR_BYTE_INT(buf);
74792#ifdef __HP_cc
74793      /* Work around a sign-extension bug in the HP compiler for HP/UX */
74794      if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
74795#endif
74796      pMem->flags = MEM_Int;
74797      testcase( pMem->u.i<0 );
74798      return 4;
74799    }
74800    case 5: { /* 6-byte signed integer */
74801      /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
74802      ** twos-complement integer. */
74803      pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
74804      pMem->flags = MEM_Int;
74805      testcase( pMem->u.i<0 );
74806      return 6;
74807    }
74808    case 6:   /* 8-byte signed integer */
74809    case 7: { /* IEEE floating point */
74810      /* These use local variables, so do them in a separate routine
74811      ** to avoid having to move the frame pointer in the common case */
74812      return serialGet(buf,serial_type,pMem);
74813    }
74814    case 8:    /* Integer 0 */
74815    case 9: {  /* Integer 1 */
74816      /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
74817      /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
74818      pMem->u.i = serial_type-8;
74819      pMem->flags = MEM_Int;
74820      return 0;
74821    }
74822    default: {
74823      /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
74824      ** length.
74825      ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
74826      ** (N-13)/2 bytes in length. */
74827      static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
74828      pMem->z = (char *)buf;
74829      pMem->n = (serial_type-12)/2;
74830      pMem->flags = aFlag[serial_type&1];
74831      return pMem->n;
74832    }
74833  }
74834  return 0;
74835}
74836/*
74837** This routine is used to allocate sufficient space for an UnpackedRecord
74838** structure large enough to be used with sqlite3VdbeRecordUnpack() if
74839** the first argument is a pointer to KeyInfo structure pKeyInfo.
74840**
74841** The space is either allocated using sqlite3DbMallocRaw() or from within
74842** the unaligned buffer passed via the second and third arguments (presumably
74843** stack space). If the former, then *ppFree is set to a pointer that should
74844** be eventually freed by the caller using sqlite3DbFree(). Or, if the
74845** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
74846** before returning.
74847**
74848** If an OOM error occurs, NULL is returned.
74849*/
74850SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
74851  KeyInfo *pKeyInfo               /* Description of the record */
74852){
74853  UnpackedRecord *p;              /* Unpacked record to return */
74854  int nByte;                      /* Number of bytes required for *p */
74855  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
74856  p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
74857  if( !p ) return 0;
74858  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
74859  assert( pKeyInfo->aSortOrder!=0 );
74860  p->pKeyInfo = pKeyInfo;
74861  p->nField = pKeyInfo->nField + 1;
74862  return p;
74863}
74864
74865/*
74866** Given the nKey-byte encoding of a record in pKey[], populate the
74867** UnpackedRecord structure indicated by the fourth argument with the
74868** contents of the decoded record.
74869*/
74870SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
74871  KeyInfo *pKeyInfo,     /* Information about the record format */
74872  int nKey,              /* Size of the binary record */
74873  const void *pKey,      /* The binary record */
74874  UnpackedRecord *p      /* Populate this structure before returning. */
74875){
74876  const unsigned char *aKey = (const unsigned char *)pKey;
74877  int d;
74878  u32 idx;                        /* Offset in aKey[] to read from */
74879  u16 u;                          /* Unsigned loop counter */
74880  u32 szHdr;
74881  Mem *pMem = p->aMem;
74882
74883  p->default_rc = 0;
74884  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
74885  idx = getVarint32(aKey, szHdr);
74886  d = szHdr;
74887  u = 0;
74888  while( idx<szHdr && d<=nKey ){
74889    u32 serial_type;
74890
74891    idx += getVarint32(&aKey[idx], serial_type);
74892    pMem->enc = pKeyInfo->enc;
74893    pMem->db = pKeyInfo->db;
74894    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
74895    pMem->szMalloc = 0;
74896    pMem->z = 0;
74897    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
74898    pMem++;
74899    if( (++u)>=p->nField ) break;
74900  }
74901  assert( u<=pKeyInfo->nField + 1 );
74902  p->nField = u;
74903}
74904
74905#ifdef SQLITE_DEBUG
74906/*
74907** This function compares two index or table record keys in the same way
74908** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
74909** this function deserializes and compares values using the
74910** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
74911** in assert() statements to ensure that the optimized code in
74912** sqlite3VdbeRecordCompare() returns results with these two primitives.
74913**
74914** Return true if the result of comparison is equivalent to desiredResult.
74915** Return false if there is a disagreement.
74916*/
74917static int vdbeRecordCompareDebug(
74918  int nKey1, const void *pKey1, /* Left key */
74919  const UnpackedRecord *pPKey2, /* Right key */
74920  int desiredResult             /* Correct answer */
74921){
74922  u32 d1;            /* Offset into aKey[] of next data element */
74923  u32 idx1;          /* Offset into aKey[] of next header element */
74924  u32 szHdr1;        /* Number of bytes in header */
74925  int i = 0;
74926  int rc = 0;
74927  const unsigned char *aKey1 = (const unsigned char *)pKey1;
74928  KeyInfo *pKeyInfo;
74929  Mem mem1;
74930
74931  pKeyInfo = pPKey2->pKeyInfo;
74932  if( pKeyInfo->db==0 ) return 1;
74933  mem1.enc = pKeyInfo->enc;
74934  mem1.db = pKeyInfo->db;
74935  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
74936  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
74937
74938  /* Compilers may complain that mem1.u.i is potentially uninitialized.
74939  ** We could initialize it, as shown here, to silence those complaints.
74940  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
74941  ** the unnecessary initialization has a measurable negative performance
74942  ** impact, since this routine is a very high runner.  And so, we choose
74943  ** to ignore the compiler warnings and leave this variable uninitialized.
74944  */
74945  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
74946
74947  idx1 = getVarint32(aKey1, szHdr1);
74948  if( szHdr1>98307 ) return SQLITE_CORRUPT;
74949  d1 = szHdr1;
74950  assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
74951  assert( pKeyInfo->aSortOrder!=0 );
74952  assert( pKeyInfo->nField>0 );
74953  assert( idx1<=szHdr1 || CORRUPT_DB );
74954  do{
74955    u32 serial_type1;
74956
74957    /* Read the serial types for the next element in each key. */
74958    idx1 += getVarint32( aKey1+idx1, serial_type1 );
74959
74960    /* Verify that there is enough key space remaining to avoid
74961    ** a buffer overread.  The "d1+serial_type1+2" subexpression will
74962    ** always be greater than or equal to the amount of required key space.
74963    ** Use that approximation to avoid the more expensive call to
74964    ** sqlite3VdbeSerialTypeLen() in the common case.
74965    */
74966    if( d1+serial_type1+2>(u32)nKey1
74967     && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
74968    ){
74969      break;
74970    }
74971
74972    /* Extract the values to be compared.
74973    */
74974    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
74975
74976    /* Do the comparison
74977    */
74978    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
74979    if( rc!=0 ){
74980      assert( mem1.szMalloc==0 );  /* See comment below */
74981      if( pKeyInfo->aSortOrder[i] ){
74982        rc = -rc;  /* Invert the result for DESC sort order. */
74983      }
74984      goto debugCompareEnd;
74985    }
74986    i++;
74987  }while( idx1<szHdr1 && i<pPKey2->nField );
74988
74989  /* No memory allocation is ever used on mem1.  Prove this using
74990  ** the following assert().  If the assert() fails, it indicates a
74991  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
74992  */
74993  assert( mem1.szMalloc==0 );
74994
74995  /* rc==0 here means that one of the keys ran out of fields and
74996  ** all the fields up to that point were equal. Return the default_rc
74997  ** value.  */
74998  rc = pPKey2->default_rc;
74999
75000debugCompareEnd:
75001  if( desiredResult==0 && rc==0 ) return 1;
75002  if( desiredResult<0 && rc<0 ) return 1;
75003  if( desiredResult>0 && rc>0 ) return 1;
75004  if( CORRUPT_DB ) return 1;
75005  if( pKeyInfo->db->mallocFailed ) return 1;
75006  return 0;
75007}
75008#endif
75009
75010#ifdef SQLITE_DEBUG
75011/*
75012** Count the number of fields (a.k.a. columns) in the record given by
75013** pKey,nKey.  The verify that this count is less than or equal to the
75014** limit given by pKeyInfo->nField + pKeyInfo->nXField.
75015**
75016** If this constraint is not satisfied, it means that the high-speed
75017** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
75018** not work correctly.  If this assert() ever fires, it probably means
75019** that the KeyInfo.nField or KeyInfo.nXField values were computed
75020** incorrectly.
75021*/
75022static void vdbeAssertFieldCountWithinLimits(
75023  int nKey, const void *pKey,   /* The record to verify */
75024  const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
75025){
75026  int nField = 0;
75027  u32 szHdr;
75028  u32 idx;
75029  u32 notUsed;
75030  const unsigned char *aKey = (const unsigned char*)pKey;
75031
75032  if( CORRUPT_DB ) return;
75033  idx = getVarint32(aKey, szHdr);
75034  assert( nKey>=0 );
75035  assert( szHdr<=(u32)nKey );
75036  while( idx<szHdr ){
75037    idx += getVarint32(aKey+idx, notUsed);
75038    nField++;
75039  }
75040  assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
75041}
75042#else
75043# define vdbeAssertFieldCountWithinLimits(A,B,C)
75044#endif
75045
75046/*
75047** Both *pMem1 and *pMem2 contain string values. Compare the two values
75048** using the collation sequence pColl. As usual, return a negative , zero
75049** or positive value if *pMem1 is less than, equal to or greater than
75050** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
75051*/
75052static int vdbeCompareMemString(
75053  const Mem *pMem1,
75054  const Mem *pMem2,
75055  const CollSeq *pColl,
75056  u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
75057){
75058  if( pMem1->enc==pColl->enc ){
75059    /* The strings are already in the correct encoding.  Call the
75060     ** comparison function directly */
75061    return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
75062  }else{
75063    int rc;
75064    const void *v1, *v2;
75065    int n1, n2;
75066    Mem c1;
75067    Mem c2;
75068    sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
75069    sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
75070    sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
75071    sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
75072    v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
75073    n1 = v1==0 ? 0 : c1.n;
75074    v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
75075    n2 = v2==0 ? 0 : c2.n;
75076    rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
75077    if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
75078    sqlite3VdbeMemRelease(&c1);
75079    sqlite3VdbeMemRelease(&c2);
75080    return rc;
75081  }
75082}
75083
75084/*
75085** The input pBlob is guaranteed to be a Blob that is not marked
75086** with MEM_Zero.  Return true if it could be a zero-blob.
75087*/
75088static int isAllZero(const char *z, int n){
75089  int i;
75090  for(i=0; i<n; i++){
75091    if( z[i] ) return 0;
75092  }
75093  return 1;
75094}
75095
75096/*
75097** Compare two blobs.  Return negative, zero, or positive if the first
75098** is less than, equal to, or greater than the second, respectively.
75099** If one blob is a prefix of the other, then the shorter is the lessor.
75100*/
75101static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
75102  int c;
75103  int n1 = pB1->n;
75104  int n2 = pB2->n;
75105
75106  /* It is possible to have a Blob value that has some non-zero content
75107  ** followed by zero content.  But that only comes up for Blobs formed
75108  ** by the OP_MakeRecord opcode, and such Blobs never get passed into
75109  ** sqlite3MemCompare(). */
75110  assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
75111  assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
75112
75113  if( (pB1->flags|pB2->flags) & MEM_Zero ){
75114    if( pB1->flags & pB2->flags & MEM_Zero ){
75115      return pB1->u.nZero - pB2->u.nZero;
75116    }else if( pB1->flags & MEM_Zero ){
75117      if( !isAllZero(pB2->z, pB2->n) ) return -1;
75118      return pB1->u.nZero - n2;
75119    }else{
75120      if( !isAllZero(pB1->z, pB1->n) ) return +1;
75121      return n1 - pB2->u.nZero;
75122    }
75123  }
75124  c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
75125  if( c ) return c;
75126  return n1 - n2;
75127}
75128
75129/*
75130** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
75131** number.  Return negative, zero, or positive if the first (i64) is less than,
75132** equal to, or greater than the second (double).
75133*/
75134static int sqlite3IntFloatCompare(i64 i, double r){
75135  if( sizeof(LONGDOUBLE_TYPE)>8 ){
75136    LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
75137    if( x<r ) return -1;
75138    if( x>r ) return +1;
75139    return 0;
75140  }else{
75141    i64 y;
75142    double s;
75143    if( r<-9223372036854775808.0 ) return +1;
75144    if( r>9223372036854775807.0 ) return -1;
75145    y = (i64)r;
75146    if( i<y ) return -1;
75147    if( i>y ){
75148      if( y==SMALLEST_INT64 && r>0.0 ) return -1;
75149      return +1;
75150    }
75151    s = (double)i;
75152    if( s<r ) return -1;
75153    if( s>r ) return +1;
75154    return 0;
75155  }
75156}
75157
75158/*
75159** Compare the values contained by the two memory cells, returning
75160** negative, zero or positive if pMem1 is less than, equal to, or greater
75161** than pMem2. Sorting order is NULL's first, followed by numbers (integers
75162** and reals) sorted numerically, followed by text ordered by the collating
75163** sequence pColl and finally blob's ordered by memcmp().
75164**
75165** Two NULL values are considered equal by this function.
75166*/
75167SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
75168  int f1, f2;
75169  int combined_flags;
75170
75171  f1 = pMem1->flags;
75172  f2 = pMem2->flags;
75173  combined_flags = f1|f2;
75174  assert( (combined_flags & MEM_RowSet)==0 );
75175
75176  /* If one value is NULL, it is less than the other. If both values
75177  ** are NULL, return 0.
75178  */
75179  if( combined_flags&MEM_Null ){
75180    return (f2&MEM_Null) - (f1&MEM_Null);
75181  }
75182
75183  /* At least one of the two values is a number
75184  */
75185  if( combined_flags&(MEM_Int|MEM_Real) ){
75186    if( (f1 & f2 & MEM_Int)!=0 ){
75187      if( pMem1->u.i < pMem2->u.i ) return -1;
75188      if( pMem1->u.i > pMem2->u.i ) return +1;
75189      return 0;
75190    }
75191    if( (f1 & f2 & MEM_Real)!=0 ){
75192      if( pMem1->u.r < pMem2->u.r ) return -1;
75193      if( pMem1->u.r > pMem2->u.r ) return +1;
75194      return 0;
75195    }
75196    if( (f1&MEM_Int)!=0 ){
75197      if( (f2&MEM_Real)!=0 ){
75198        return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
75199      }else{
75200        return -1;
75201      }
75202    }
75203    if( (f1&MEM_Real)!=0 ){
75204      if( (f2&MEM_Int)!=0 ){
75205        return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
75206      }else{
75207        return -1;
75208      }
75209    }
75210    return +1;
75211  }
75212
75213  /* If one value is a string and the other is a blob, the string is less.
75214  ** If both are strings, compare using the collating functions.
75215  */
75216  if( combined_flags&MEM_Str ){
75217    if( (f1 & MEM_Str)==0 ){
75218      return 1;
75219    }
75220    if( (f2 & MEM_Str)==0 ){
75221      return -1;
75222    }
75223
75224    assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
75225    assert( pMem1->enc==SQLITE_UTF8 ||
75226            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
75227
75228    /* The collation sequence must be defined at this point, even if
75229    ** the user deletes the collation sequence after the vdbe program is
75230    ** compiled (this was not always the case).
75231    */
75232    assert( !pColl || pColl->xCmp );
75233
75234    if( pColl ){
75235      return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
75236    }
75237    /* If a NULL pointer was passed as the collate function, fall through
75238    ** to the blob case and use memcmp().  */
75239  }
75240
75241  /* Both values must be blobs.  Compare using memcmp().  */
75242  return sqlite3BlobCompare(pMem1, pMem2);
75243}
75244
75245
75246/*
75247** The first argument passed to this function is a serial-type that
75248** corresponds to an integer - all values between 1 and 9 inclusive
75249** except 7. The second points to a buffer containing an integer value
75250** serialized according to serial_type. This function deserializes
75251** and returns the value.
75252*/
75253static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
75254  u32 y;
75255  assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
75256  switch( serial_type ){
75257    case 0:
75258    case 1:
75259      testcase( aKey[0]&0x80 );
75260      return ONE_BYTE_INT(aKey);
75261    case 2:
75262      testcase( aKey[0]&0x80 );
75263      return TWO_BYTE_INT(aKey);
75264    case 3:
75265      testcase( aKey[0]&0x80 );
75266      return THREE_BYTE_INT(aKey);
75267    case 4: {
75268      testcase( aKey[0]&0x80 );
75269      y = FOUR_BYTE_UINT(aKey);
75270      return (i64)*(int*)&y;
75271    }
75272    case 5: {
75273      testcase( aKey[0]&0x80 );
75274      return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
75275    }
75276    case 6: {
75277      u64 x = FOUR_BYTE_UINT(aKey);
75278      testcase( aKey[0]&0x80 );
75279      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
75280      return (i64)*(i64*)&x;
75281    }
75282  }
75283
75284  return (serial_type - 8);
75285}
75286
75287/*
75288** This function compares the two table rows or index records
75289** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
75290** or positive integer if key1 is less than, equal to or
75291** greater than key2.  The {nKey1, pKey1} key must be a blob
75292** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
75293** key must be a parsed key such as obtained from
75294** sqlite3VdbeParseRecord.
75295**
75296** If argument bSkip is non-zero, it is assumed that the caller has already
75297** determined that the first fields of the keys are equal.
75298**
75299** Key1 and Key2 do not have to contain the same number of fields. If all
75300** fields that appear in both keys are equal, then pPKey2->default_rc is
75301** returned.
75302**
75303** If database corruption is discovered, set pPKey2->errCode to
75304** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
75305** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
75306** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
75307*/
75308SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
75309  int nKey1, const void *pKey1,   /* Left key */
75310  UnpackedRecord *pPKey2,         /* Right key */
75311  int bSkip                       /* If true, skip the first field */
75312){
75313  u32 d1;                         /* Offset into aKey[] of next data element */
75314  int i;                          /* Index of next field to compare */
75315  u32 szHdr1;                     /* Size of record header in bytes */
75316  u32 idx1;                       /* Offset of first type in header */
75317  int rc = 0;                     /* Return value */
75318  Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
75319  KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
75320  const unsigned char *aKey1 = (const unsigned char *)pKey1;
75321  Mem mem1;
75322
75323  /* If bSkip is true, then the caller has already determined that the first
75324  ** two elements in the keys are equal. Fix the various stack variables so
75325  ** that this routine begins comparing at the second field. */
75326  if( bSkip ){
75327    u32 s1;
75328    idx1 = 1 + getVarint32(&aKey1[1], s1);
75329    szHdr1 = aKey1[0];
75330    d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
75331    i = 1;
75332    pRhs++;
75333  }else{
75334    idx1 = getVarint32(aKey1, szHdr1);
75335    d1 = szHdr1;
75336    if( d1>(unsigned)nKey1 ){
75337      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
75338      return 0;  /* Corruption */
75339    }
75340    i = 0;
75341  }
75342
75343  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
75344  assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
75345       || CORRUPT_DB );
75346  assert( pPKey2->pKeyInfo->aSortOrder!=0 );
75347  assert( pPKey2->pKeyInfo->nField>0 );
75348  assert( idx1<=szHdr1 || CORRUPT_DB );
75349  do{
75350    u32 serial_type;
75351
75352    /* RHS is an integer */
75353    if( pRhs->flags & MEM_Int ){
75354      serial_type = aKey1[idx1];
75355      testcase( serial_type==12 );
75356      if( serial_type>=10 ){
75357        rc = +1;
75358      }else if( serial_type==0 ){
75359        rc = -1;
75360      }else if( serial_type==7 ){
75361        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
75362        rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
75363      }else{
75364        i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
75365        i64 rhs = pRhs->u.i;
75366        if( lhs<rhs ){
75367          rc = -1;
75368        }else if( lhs>rhs ){
75369          rc = +1;
75370        }
75371      }
75372    }
75373
75374    /* RHS is real */
75375    else if( pRhs->flags & MEM_Real ){
75376      serial_type = aKey1[idx1];
75377      if( serial_type>=10 ){
75378        /* Serial types 12 or greater are strings and blobs (greater than
75379        ** numbers). Types 10 and 11 are currently "reserved for future
75380        ** use", so it doesn't really matter what the results of comparing
75381        ** them to numberic values are.  */
75382        rc = +1;
75383      }else if( serial_type==0 ){
75384        rc = -1;
75385      }else{
75386        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
75387        if( serial_type==7 ){
75388          if( mem1.u.r<pRhs->u.r ){
75389            rc = -1;
75390          }else if( mem1.u.r>pRhs->u.r ){
75391            rc = +1;
75392          }
75393        }else{
75394          rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
75395        }
75396      }
75397    }
75398
75399    /* RHS is a string */
75400    else if( pRhs->flags & MEM_Str ){
75401      getVarint32(&aKey1[idx1], serial_type);
75402      testcase( serial_type==12 );
75403      if( serial_type<12 ){
75404        rc = -1;
75405      }else if( !(serial_type & 0x01) ){
75406        rc = +1;
75407      }else{
75408        mem1.n = (serial_type - 12) / 2;
75409        testcase( (d1+mem1.n)==(unsigned)nKey1 );
75410        testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
75411        if( (d1+mem1.n) > (unsigned)nKey1 ){
75412          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
75413          return 0;                /* Corruption */
75414        }else if( pKeyInfo->aColl[i] ){
75415          mem1.enc = pKeyInfo->enc;
75416          mem1.db = pKeyInfo->db;
75417          mem1.flags = MEM_Str;
75418          mem1.z = (char*)&aKey1[d1];
75419          rc = vdbeCompareMemString(
75420              &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
75421          );
75422        }else{
75423          int nCmp = MIN(mem1.n, pRhs->n);
75424          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
75425          if( rc==0 ) rc = mem1.n - pRhs->n;
75426        }
75427      }
75428    }
75429
75430    /* RHS is a blob */
75431    else if( pRhs->flags & MEM_Blob ){
75432      assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
75433      getVarint32(&aKey1[idx1], serial_type);
75434      testcase( serial_type==12 );
75435      if( serial_type<12 || (serial_type & 0x01) ){
75436        rc = -1;
75437      }else{
75438        int nStr = (serial_type - 12) / 2;
75439        testcase( (d1+nStr)==(unsigned)nKey1 );
75440        testcase( (d1+nStr+1)==(unsigned)nKey1 );
75441        if( (d1+nStr) > (unsigned)nKey1 ){
75442          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
75443          return 0;                /* Corruption */
75444        }else if( pRhs->flags & MEM_Zero ){
75445          if( !isAllZero((const char*)&aKey1[d1],nStr) ){
75446            rc = 1;
75447          }else{
75448            rc = nStr - pRhs->u.nZero;
75449          }
75450        }else{
75451          int nCmp = MIN(nStr, pRhs->n);
75452          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
75453          if( rc==0 ) rc = nStr - pRhs->n;
75454        }
75455      }
75456    }
75457
75458    /* RHS is null */
75459    else{
75460      serial_type = aKey1[idx1];
75461      rc = (serial_type!=0);
75462    }
75463
75464    if( rc!=0 ){
75465      if( pKeyInfo->aSortOrder[i] ){
75466        rc = -rc;
75467      }
75468      assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
75469      assert( mem1.szMalloc==0 );  /* See comment below */
75470      return rc;
75471    }
75472
75473    i++;
75474    pRhs++;
75475    d1 += sqlite3VdbeSerialTypeLen(serial_type);
75476    idx1 += sqlite3VarintLen(serial_type);
75477  }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
75478
75479  /* No memory allocation is ever used on mem1.  Prove this using
75480  ** the following assert().  If the assert() fails, it indicates a
75481  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
75482  assert( mem1.szMalloc==0 );
75483
75484  /* rc==0 here means that one or both of the keys ran out of fields and
75485  ** all the fields up to that point were equal. Return the default_rc
75486  ** value.  */
75487  assert( CORRUPT_DB
75488       || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
75489       || pKeyInfo->db->mallocFailed
75490  );
75491  pPKey2->eqSeen = 1;
75492  return pPKey2->default_rc;
75493}
75494SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
75495  int nKey1, const void *pKey1,   /* Left key */
75496  UnpackedRecord *pPKey2          /* Right key */
75497){
75498  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
75499}
75500
75501
75502/*
75503** This function is an optimized version of sqlite3VdbeRecordCompare()
75504** that (a) the first field of pPKey2 is an integer, and (b) the
75505** size-of-header varint at the start of (pKey1/nKey1) fits in a single
75506** byte (i.e. is less than 128).
75507**
75508** To avoid concerns about buffer overreads, this routine is only used
75509** on schemas where the maximum valid header size is 63 bytes or less.
75510*/
75511static int vdbeRecordCompareInt(
75512  int nKey1, const void *pKey1, /* Left key */
75513  UnpackedRecord *pPKey2        /* Right key */
75514){
75515  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
75516  int serial_type = ((const u8*)pKey1)[1];
75517  int res;
75518  u32 y;
75519  u64 x;
75520  i64 v;
75521  i64 lhs;
75522
75523  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
75524  assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
75525  switch( serial_type ){
75526    case 1: { /* 1-byte signed integer */
75527      lhs = ONE_BYTE_INT(aKey);
75528      testcase( lhs<0 );
75529      break;
75530    }
75531    case 2: { /* 2-byte signed integer */
75532      lhs = TWO_BYTE_INT(aKey);
75533      testcase( lhs<0 );
75534      break;
75535    }
75536    case 3: { /* 3-byte signed integer */
75537      lhs = THREE_BYTE_INT(aKey);
75538      testcase( lhs<0 );
75539      break;
75540    }
75541    case 4: { /* 4-byte signed integer */
75542      y = FOUR_BYTE_UINT(aKey);
75543      lhs = (i64)*(int*)&y;
75544      testcase( lhs<0 );
75545      break;
75546    }
75547    case 5: { /* 6-byte signed integer */
75548      lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
75549      testcase( lhs<0 );
75550      break;
75551    }
75552    case 6: { /* 8-byte signed integer */
75553      x = FOUR_BYTE_UINT(aKey);
75554      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
75555      lhs = *(i64*)&x;
75556      testcase( lhs<0 );
75557      break;
75558    }
75559    case 8:
75560      lhs = 0;
75561      break;
75562    case 9:
75563      lhs = 1;
75564      break;
75565
75566    /* This case could be removed without changing the results of running
75567    ** this code. Including it causes gcc to generate a faster switch
75568    ** statement (since the range of switch targets now starts at zero and
75569    ** is contiguous) but does not cause any duplicate code to be generated
75570    ** (as gcc is clever enough to combine the two like cases). Other
75571    ** compilers might be similar.  */
75572    case 0: case 7:
75573      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
75574
75575    default:
75576      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
75577  }
75578
75579  v = pPKey2->aMem[0].u.i;
75580  if( v>lhs ){
75581    res = pPKey2->r1;
75582  }else if( v<lhs ){
75583    res = pPKey2->r2;
75584  }else if( pPKey2->nField>1 ){
75585    /* The first fields of the two keys are equal. Compare the trailing
75586    ** fields.  */
75587    res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
75588  }else{
75589    /* The first fields of the two keys are equal and there are no trailing
75590    ** fields. Return pPKey2->default_rc in this case. */
75591    res = pPKey2->default_rc;
75592    pPKey2->eqSeen = 1;
75593  }
75594
75595  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
75596  return res;
75597}
75598
75599/*
75600** This function is an optimized version of sqlite3VdbeRecordCompare()
75601** that (a) the first field of pPKey2 is a string, that (b) the first field
75602** uses the collation sequence BINARY and (c) that the size-of-header varint
75603** at the start of (pKey1/nKey1) fits in a single byte.
75604*/
75605static int vdbeRecordCompareString(
75606  int nKey1, const void *pKey1, /* Left key */
75607  UnpackedRecord *pPKey2        /* Right key */
75608){
75609  const u8 *aKey1 = (const u8*)pKey1;
75610  int serial_type;
75611  int res;
75612
75613  assert( pPKey2->aMem[0].flags & MEM_Str );
75614  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
75615  getVarint32(&aKey1[1], serial_type);
75616  if( serial_type<12 ){
75617    res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
75618  }else if( !(serial_type & 0x01) ){
75619    res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
75620  }else{
75621    int nCmp;
75622    int nStr;
75623    int szHdr = aKey1[0];
75624
75625    nStr = (serial_type-12) / 2;
75626    if( (szHdr + nStr) > nKey1 ){
75627      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
75628      return 0;    /* Corruption */
75629    }
75630    nCmp = MIN( pPKey2->aMem[0].n, nStr );
75631    res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
75632
75633    if( res==0 ){
75634      res = nStr - pPKey2->aMem[0].n;
75635      if( res==0 ){
75636        if( pPKey2->nField>1 ){
75637          res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
75638        }else{
75639          res = pPKey2->default_rc;
75640          pPKey2->eqSeen = 1;
75641        }
75642      }else if( res>0 ){
75643        res = pPKey2->r2;
75644      }else{
75645        res = pPKey2->r1;
75646      }
75647    }else if( res>0 ){
75648      res = pPKey2->r2;
75649    }else{
75650      res = pPKey2->r1;
75651    }
75652  }
75653
75654  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
75655       || CORRUPT_DB
75656       || pPKey2->pKeyInfo->db->mallocFailed
75657  );
75658  return res;
75659}
75660
75661/*
75662** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
75663** suitable for comparing serialized records to the unpacked record passed
75664** as the only argument.
75665*/
75666SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
75667  /* varintRecordCompareInt() and varintRecordCompareString() both assume
75668  ** that the size-of-header varint that occurs at the start of each record
75669  ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
75670  ** also assumes that it is safe to overread a buffer by at least the
75671  ** maximum possible legal header size plus 8 bytes. Because there is
75672  ** guaranteed to be at least 74 (but not 136) bytes of padding following each
75673  ** buffer passed to varintRecordCompareInt() this makes it convenient to
75674  ** limit the size of the header to 64 bytes in cases where the first field
75675  ** is an integer.
75676  **
75677  ** The easiest way to enforce this limit is to consider only records with
75678  ** 13 fields or less. If the first field is an integer, the maximum legal
75679  ** header size is (12*5 + 1 + 1) bytes.  */
75680  if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
75681    int flags = p->aMem[0].flags;
75682    if( p->pKeyInfo->aSortOrder[0] ){
75683      p->r1 = 1;
75684      p->r2 = -1;
75685    }else{
75686      p->r1 = -1;
75687      p->r2 = 1;
75688    }
75689    if( (flags & MEM_Int) ){
75690      return vdbeRecordCompareInt;
75691    }
75692    testcase( flags & MEM_Real );
75693    testcase( flags & MEM_Null );
75694    testcase( flags & MEM_Blob );
75695    if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
75696      assert( flags & MEM_Str );
75697      return vdbeRecordCompareString;
75698    }
75699  }
75700
75701  return sqlite3VdbeRecordCompare;
75702}
75703
75704/*
75705** pCur points at an index entry created using the OP_MakeRecord opcode.
75706** Read the rowid (the last field in the record) and store it in *rowid.
75707** Return SQLITE_OK if everything works, or an error code otherwise.
75708**
75709** pCur might be pointing to text obtained from a corrupt database file.
75710** So the content cannot be trusted.  Do appropriate checks on the content.
75711*/
75712SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
75713  i64 nCellKey = 0;
75714  int rc;
75715  u32 szHdr;        /* Size of the header */
75716  u32 typeRowid;    /* Serial type of the rowid */
75717  u32 lenRowid;     /* Size of the rowid */
75718  Mem m, v;
75719
75720  /* Get the size of the index entry.  Only indices entries of less
75721  ** than 2GiB are support - anything large must be database corruption.
75722  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
75723  ** this code can safely assume that nCellKey is 32-bits
75724  */
75725  assert( sqlite3BtreeCursorIsValid(pCur) );
75726  nCellKey = sqlite3BtreePayloadSize(pCur);
75727  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
75728
75729  /* Read in the complete content of the index entry */
75730  sqlite3VdbeMemInit(&m, db, 0);
75731  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
75732  if( rc ){
75733    return rc;
75734  }
75735
75736  /* The index entry must begin with a header size */
75737  (void)getVarint32((u8*)m.z, szHdr);
75738  testcase( szHdr==3 );
75739  testcase( szHdr==m.n );
75740  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
75741    goto idx_rowid_corruption;
75742  }
75743
75744  /* The last field of the index should be an integer - the ROWID.
75745  ** Verify that the last entry really is an integer. */
75746  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
75747  testcase( typeRowid==1 );
75748  testcase( typeRowid==2 );
75749  testcase( typeRowid==3 );
75750  testcase( typeRowid==4 );
75751  testcase( typeRowid==5 );
75752  testcase( typeRowid==6 );
75753  testcase( typeRowid==8 );
75754  testcase( typeRowid==9 );
75755  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
75756    goto idx_rowid_corruption;
75757  }
75758  lenRowid = sqlite3SmallTypeSizes[typeRowid];
75759  testcase( (u32)m.n==szHdr+lenRowid );
75760  if( unlikely((u32)m.n<szHdr+lenRowid) ){
75761    goto idx_rowid_corruption;
75762  }
75763
75764  /* Fetch the integer off the end of the index record */
75765  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
75766  *rowid = v.u.i;
75767  sqlite3VdbeMemRelease(&m);
75768  return SQLITE_OK;
75769
75770  /* Jump here if database corruption is detected after m has been
75771  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
75772idx_rowid_corruption:
75773  testcase( m.szMalloc!=0 );
75774  sqlite3VdbeMemRelease(&m);
75775  return SQLITE_CORRUPT_BKPT;
75776}
75777
75778/*
75779** Compare the key of the index entry that cursor pC is pointing to against
75780** the key string in pUnpacked.  Write into *pRes a number
75781** that is negative, zero, or positive if pC is less than, equal to,
75782** or greater than pUnpacked.  Return SQLITE_OK on success.
75783**
75784** pUnpacked is either created without a rowid or is truncated so that it
75785** omits the rowid at the end.  The rowid at the end of the index entry
75786** is ignored as well.  Hence, this routine only compares the prefixes
75787** of the keys prior to the final rowid, not the entire key.
75788*/
75789SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
75790  sqlite3 *db,                     /* Database connection */
75791  VdbeCursor *pC,                  /* The cursor to compare against */
75792  UnpackedRecord *pUnpacked,       /* Unpacked version of key */
75793  int *res                         /* Write the comparison result here */
75794){
75795  i64 nCellKey = 0;
75796  int rc;
75797  BtCursor *pCur;
75798  Mem m;
75799
75800  assert( pC->eCurType==CURTYPE_BTREE );
75801  pCur = pC->uc.pCursor;
75802  assert( sqlite3BtreeCursorIsValid(pCur) );
75803  nCellKey = sqlite3BtreePayloadSize(pCur);
75804  /* nCellKey will always be between 0 and 0xffffffff because of the way
75805  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
75806  if( nCellKey<=0 || nCellKey>0x7fffffff ){
75807    *res = 0;
75808    return SQLITE_CORRUPT_BKPT;
75809  }
75810  sqlite3VdbeMemInit(&m, db, 0);
75811  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
75812  if( rc ){
75813    return rc;
75814  }
75815  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
75816  sqlite3VdbeMemRelease(&m);
75817  return SQLITE_OK;
75818}
75819
75820/*
75821** This routine sets the value to be returned by subsequent calls to
75822** sqlite3_changes() on the database handle 'db'.
75823*/
75824SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
75825  assert( sqlite3_mutex_held(db->mutex) );
75826  db->nChange = nChange;
75827  db->nTotalChange += nChange;
75828}
75829
75830/*
75831** Set a flag in the vdbe to update the change counter when it is finalised
75832** or reset.
75833*/
75834SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
75835  v->changeCntOn = 1;
75836}
75837
75838/*
75839** Mark every prepared statement associated with a database connection
75840** as expired.
75841**
75842** An expired statement means that recompilation of the statement is
75843** recommend.  Statements expire when things happen that make their
75844** programs obsolete.  Removing user-defined functions or collating
75845** sequences, or changing an authorization function are the types of
75846** things that make prepared statements obsolete.
75847*/
75848SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
75849  Vdbe *p;
75850  for(p = db->pVdbe; p; p=p->pNext){
75851    p->expired = 1;
75852  }
75853}
75854
75855/*
75856** Return the database associated with the Vdbe.
75857*/
75858SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
75859  return v->db;
75860}
75861
75862/*
75863** Return a pointer to an sqlite3_value structure containing the value bound
75864** parameter iVar of VM v. Except, if the value is an SQL NULL, return
75865** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
75866** constants) to the value before returning it.
75867**
75868** The returned value must be freed by the caller using sqlite3ValueFree().
75869*/
75870SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
75871  assert( iVar>0 );
75872  if( v ){
75873    Mem *pMem = &v->aVar[iVar-1];
75874    if( 0==(pMem->flags & MEM_Null) ){
75875      sqlite3_value *pRet = sqlite3ValueNew(v->db);
75876      if( pRet ){
75877        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
75878        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
75879      }
75880      return pRet;
75881    }
75882  }
75883  return 0;
75884}
75885
75886/*
75887** Configure SQL variable iVar so that binding a new value to it signals
75888** to sqlite3_reoptimize() that re-preparing the statement may result
75889** in a better query plan.
75890*/
75891SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
75892  assert( iVar>0 );
75893  if( iVar>=32 ){
75894    v->expmask |= 0x80000000;
75895  }else{
75896    v->expmask |= ((u32)1 << (iVar-1));
75897  }
75898}
75899
75900#ifndef SQLITE_OMIT_VIRTUALTABLE
75901/*
75902** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
75903** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
75904** in memory obtained from sqlite3DbMalloc).
75905*/
75906SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
75907  if( pVtab->zErrMsg ){
75908    sqlite3 *db = p->db;
75909    sqlite3DbFree(db, p->zErrMsg);
75910    p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
75911    sqlite3_free(pVtab->zErrMsg);
75912    pVtab->zErrMsg = 0;
75913  }
75914}
75915#endif /* SQLITE_OMIT_VIRTUALTABLE */
75916
75917#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
75918
75919/*
75920** If the second argument is not NULL, release any allocations associated
75921** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
75922** structure itself, using sqlite3DbFree().
75923**
75924** This function is used to free UnpackedRecord structures allocated by
75925** the vdbeUnpackRecord() function found in vdbeapi.c.
75926*/
75927static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
75928  if( p ){
75929    int i;
75930    for(i=0; i<nField; i++){
75931      Mem *pMem = &p->aMem[i];
75932      if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
75933    }
75934    sqlite3DbFree(db, p);
75935  }
75936}
75937#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
75938
75939#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
75940/*
75941** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
75942** then cursor passed as the second argument should point to the row about
75943** to be update or deleted. If the application calls sqlite3_preupdate_old(),
75944** the required value will be read from the row the cursor points to.
75945*/
75946SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
75947  Vdbe *v,                        /* Vdbe pre-update hook is invoked by */
75948  VdbeCursor *pCsr,               /* Cursor to grab old.* values from */
75949  int op,                         /* SQLITE_INSERT, UPDATE or DELETE */
75950  const char *zDb,                /* Database name */
75951  Table *pTab,                    /* Modified table */
75952  i64 iKey1,                      /* Initial key value */
75953  int iReg                        /* Register for new.* record */
75954){
75955  sqlite3 *db = v->db;
75956  i64 iKey2;
75957  PreUpdate preupdate;
75958  const char *zTbl = pTab->zName;
75959  static const u8 fakeSortOrder = 0;
75960
75961  assert( db->pPreUpdate==0 );
75962  memset(&preupdate, 0, sizeof(PreUpdate));
75963  if( HasRowid(pTab)==0 ){
75964    iKey1 = iKey2 = 0;
75965    preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
75966  }else{
75967    if( op==SQLITE_UPDATE ){
75968      iKey2 = v->aMem[iReg].u.i;
75969    }else{
75970      iKey2 = iKey1;
75971    }
75972  }
75973
75974  assert( pCsr->nField==pTab->nCol
75975       || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
75976  );
75977
75978  preupdate.v = v;
75979  preupdate.pCsr = pCsr;
75980  preupdate.op = op;
75981  preupdate.iNewReg = iReg;
75982  preupdate.keyinfo.db = db;
75983  preupdate.keyinfo.enc = ENC(db);
75984  preupdate.keyinfo.nField = pTab->nCol;
75985  preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
75986  preupdate.iKey1 = iKey1;
75987  preupdate.iKey2 = iKey2;
75988  preupdate.pTab = pTab;
75989
75990  db->pPreUpdate = &preupdate;
75991  db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
75992  db->pPreUpdate = 0;
75993  sqlite3DbFree(db, preupdate.aRecord);
75994  vdbeFreeUnpacked(db, preupdate.keyinfo.nField+1, preupdate.pUnpacked);
75995  vdbeFreeUnpacked(db, preupdate.keyinfo.nField+1, preupdate.pNewUnpacked);
75996  if( preupdate.aNew ){
75997    int i;
75998    for(i=0; i<pCsr->nField; i++){
75999      sqlite3VdbeMemRelease(&preupdate.aNew[i]);
76000    }
76001    sqlite3DbFree(db, preupdate.aNew);
76002  }
76003}
76004#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76005
76006/************** End of vdbeaux.c *********************************************/
76007/************** Begin file vdbeapi.c *****************************************/
76008/*
76009** 2004 May 26
76010**
76011** The author disclaims copyright to this source code.  In place of
76012** a legal notice, here is a blessing:
76013**
76014**    May you do good and not evil.
76015**    May you find forgiveness for yourself and forgive others.
76016**    May you share freely, never taking more than you give.
76017**
76018*************************************************************************
76019**
76020** This file contains code use to implement APIs that are part of the
76021** VDBE.
76022*/
76023/* #include "sqliteInt.h" */
76024/* #include "vdbeInt.h" */
76025
76026#ifndef SQLITE_OMIT_DEPRECATED
76027/*
76028** Return TRUE (non-zero) of the statement supplied as an argument needs
76029** to be recompiled.  A statement needs to be recompiled whenever the
76030** execution environment changes in a way that would alter the program
76031** that sqlite3_prepare() generates.  For example, if new functions or
76032** collating sequences are registered or if an authorizer function is
76033** added or changed.
76034*/
76035SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
76036  Vdbe *p = (Vdbe*)pStmt;
76037  return p==0 || p->expired;
76038}
76039#endif
76040
76041/*
76042** Check on a Vdbe to make sure it has not been finalized.  Log
76043** an error and return true if it has been finalized (or is otherwise
76044** invalid).  Return false if it is ok.
76045*/
76046static int vdbeSafety(Vdbe *p){
76047  if( p->db==0 ){
76048    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
76049    return 1;
76050  }else{
76051    return 0;
76052  }
76053}
76054static int vdbeSafetyNotNull(Vdbe *p){
76055  if( p==0 ){
76056    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
76057    return 1;
76058  }else{
76059    return vdbeSafety(p);
76060  }
76061}
76062
76063#ifndef SQLITE_OMIT_TRACE
76064/*
76065** Invoke the profile callback.  This routine is only called if we already
76066** know that the profile callback is defined and needs to be invoked.
76067*/
76068static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
76069  sqlite3_int64 iNow;
76070  sqlite3_int64 iElapse;
76071  assert( p->startTime>0 );
76072  assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
76073  assert( db->init.busy==0 );
76074  assert( p->zSql!=0 );
76075  sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
76076  iElapse = (iNow - p->startTime)*1000000;
76077  if( db->xProfile ){
76078    db->xProfile(db->pProfileArg, p->zSql, iElapse);
76079  }
76080  if( db->mTrace & SQLITE_TRACE_PROFILE ){
76081    db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
76082  }
76083  p->startTime = 0;
76084}
76085/*
76086** The checkProfileCallback(DB,P) macro checks to see if a profile callback
76087** is needed, and it invokes the callback if it is needed.
76088*/
76089# define checkProfileCallback(DB,P) \
76090   if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
76091#else
76092# define checkProfileCallback(DB,P)  /*no-op*/
76093#endif
76094
76095/*
76096** The following routine destroys a virtual machine that is created by
76097** the sqlite3_compile() routine. The integer returned is an SQLITE_
76098** success/failure code that describes the result of executing the virtual
76099** machine.
76100**
76101** This routine sets the error code and string returned by
76102** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
76103*/
76104SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
76105  int rc;
76106  if( pStmt==0 ){
76107    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
76108    ** pointer is a harmless no-op. */
76109    rc = SQLITE_OK;
76110  }else{
76111    Vdbe *v = (Vdbe*)pStmt;
76112    sqlite3 *db = v->db;
76113    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
76114    sqlite3_mutex_enter(db->mutex);
76115    checkProfileCallback(db, v);
76116    rc = sqlite3VdbeFinalize(v);
76117    rc = sqlite3ApiExit(db, rc);
76118    sqlite3LeaveMutexAndCloseZombie(db);
76119  }
76120  return rc;
76121}
76122
76123/*
76124** Terminate the current execution of an SQL statement and reset it
76125** back to its starting state so that it can be reused. A success code from
76126** the prior execution is returned.
76127**
76128** This routine sets the error code and string returned by
76129** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
76130*/
76131SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
76132  int rc;
76133  if( pStmt==0 ){
76134    rc = SQLITE_OK;
76135  }else{
76136    Vdbe *v = (Vdbe*)pStmt;
76137    sqlite3 *db = v->db;
76138    sqlite3_mutex_enter(db->mutex);
76139    checkProfileCallback(db, v);
76140    rc = sqlite3VdbeReset(v);
76141    sqlite3VdbeRewind(v);
76142    assert( (rc & (db->errMask))==rc );
76143    rc = sqlite3ApiExit(db, rc);
76144    sqlite3_mutex_leave(db->mutex);
76145  }
76146  return rc;
76147}
76148
76149/*
76150** Set all the parameters in the compiled SQL statement to NULL.
76151*/
76152SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
76153  int i;
76154  int rc = SQLITE_OK;
76155  Vdbe *p = (Vdbe*)pStmt;
76156#if SQLITE_THREADSAFE
76157  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
76158#endif
76159  sqlite3_mutex_enter(mutex);
76160  for(i=0; i<p->nVar; i++){
76161    sqlite3VdbeMemRelease(&p->aVar[i]);
76162    p->aVar[i].flags = MEM_Null;
76163  }
76164  assert( p->isPrepareV2 || p->expmask==0 );
76165  if( p->expmask ){
76166    p->expired = 1;
76167  }
76168  sqlite3_mutex_leave(mutex);
76169  return rc;
76170}
76171
76172
76173/**************************** sqlite3_value_  *******************************
76174** The following routines extract information from a Mem or sqlite3_value
76175** structure.
76176*/
76177SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
76178  Mem *p = (Mem*)pVal;
76179  if( p->flags & (MEM_Blob|MEM_Str) ){
76180    if( ExpandBlob(p)!=SQLITE_OK ){
76181      assert( p->flags==MEM_Null && p->z==0 );
76182      return 0;
76183    }
76184    p->flags |= MEM_Blob;
76185    return p->n ? p->z : 0;
76186  }else{
76187    return sqlite3_value_text(pVal);
76188  }
76189}
76190SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
76191  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
76192}
76193SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
76194  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
76195}
76196SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
76197  return sqlite3VdbeRealValue((Mem*)pVal);
76198}
76199SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
76200  return (int)sqlite3VdbeIntValue((Mem*)pVal);
76201}
76202SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
76203  return sqlite3VdbeIntValue((Mem*)pVal);
76204}
76205SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
76206  Mem *pMem = (Mem*)pVal;
76207  return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
76208}
76209SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
76210  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
76211}
76212#ifndef SQLITE_OMIT_UTF16
76213SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
76214  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
76215}
76216SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
76217  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
76218}
76219SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
76220  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
76221}
76222#endif /* SQLITE_OMIT_UTF16 */
76223/* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
76224** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
76225** point number string BLOB NULL
76226*/
76227SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
76228  static const u8 aType[] = {
76229     SQLITE_BLOB,     /* 0x00 */
76230     SQLITE_NULL,     /* 0x01 */
76231     SQLITE_TEXT,     /* 0x02 */
76232     SQLITE_NULL,     /* 0x03 */
76233     SQLITE_INTEGER,  /* 0x04 */
76234     SQLITE_NULL,     /* 0x05 */
76235     SQLITE_INTEGER,  /* 0x06 */
76236     SQLITE_NULL,     /* 0x07 */
76237     SQLITE_FLOAT,    /* 0x08 */
76238     SQLITE_NULL,     /* 0x09 */
76239     SQLITE_FLOAT,    /* 0x0a */
76240     SQLITE_NULL,     /* 0x0b */
76241     SQLITE_INTEGER,  /* 0x0c */
76242     SQLITE_NULL,     /* 0x0d */
76243     SQLITE_INTEGER,  /* 0x0e */
76244     SQLITE_NULL,     /* 0x0f */
76245     SQLITE_BLOB,     /* 0x10 */
76246     SQLITE_NULL,     /* 0x11 */
76247     SQLITE_TEXT,     /* 0x12 */
76248     SQLITE_NULL,     /* 0x13 */
76249     SQLITE_INTEGER,  /* 0x14 */
76250     SQLITE_NULL,     /* 0x15 */
76251     SQLITE_INTEGER,  /* 0x16 */
76252     SQLITE_NULL,     /* 0x17 */
76253     SQLITE_FLOAT,    /* 0x18 */
76254     SQLITE_NULL,     /* 0x19 */
76255     SQLITE_FLOAT,    /* 0x1a */
76256     SQLITE_NULL,     /* 0x1b */
76257     SQLITE_INTEGER,  /* 0x1c */
76258     SQLITE_NULL,     /* 0x1d */
76259     SQLITE_INTEGER,  /* 0x1e */
76260     SQLITE_NULL,     /* 0x1f */
76261  };
76262  return aType[pVal->flags&MEM_AffMask];
76263}
76264
76265/* Make a copy of an sqlite3_value object
76266*/
76267SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
76268  sqlite3_value *pNew;
76269  if( pOrig==0 ) return 0;
76270  pNew = sqlite3_malloc( sizeof(*pNew) );
76271  if( pNew==0 ) return 0;
76272  memset(pNew, 0, sizeof(*pNew));
76273  memcpy(pNew, pOrig, MEMCELLSIZE);
76274  pNew->flags &= ~MEM_Dyn;
76275  pNew->db = 0;
76276  if( pNew->flags&(MEM_Str|MEM_Blob) ){
76277    pNew->flags &= ~(MEM_Static|MEM_Dyn);
76278    pNew->flags |= MEM_Ephem;
76279    if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
76280      sqlite3ValueFree(pNew);
76281      pNew = 0;
76282    }
76283  }
76284  return pNew;
76285}
76286
76287/* Destroy an sqlite3_value object previously obtained from
76288** sqlite3_value_dup().
76289*/
76290SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
76291  sqlite3ValueFree(pOld);
76292}
76293
76294
76295/**************************** sqlite3_result_  *******************************
76296** The following routines are used by user-defined functions to specify
76297** the function result.
76298**
76299** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
76300** result as a string or blob but if the string or blob is too large, it
76301** then sets the error code to SQLITE_TOOBIG
76302**
76303** The invokeValueDestructor(P,X) routine invokes destructor function X()
76304** on value P is not going to be used and need to be destroyed.
76305*/
76306static void setResultStrOrError(
76307  sqlite3_context *pCtx,  /* Function context */
76308  const char *z,          /* String pointer */
76309  int n,                  /* Bytes in string, or negative */
76310  u8 enc,                 /* Encoding of z.  0 for BLOBs */
76311  void (*xDel)(void*)     /* Destructor function */
76312){
76313  if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
76314    sqlite3_result_error_toobig(pCtx);
76315  }
76316}
76317static int invokeValueDestructor(
76318  const void *p,             /* Value to destroy */
76319  void (*xDel)(void*),       /* The destructor */
76320  sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
76321){
76322  assert( xDel!=SQLITE_DYNAMIC );
76323  if( xDel==0 ){
76324    /* noop */
76325  }else if( xDel==SQLITE_TRANSIENT ){
76326    /* noop */
76327  }else{
76328    xDel((void*)p);
76329  }
76330  if( pCtx ) sqlite3_result_error_toobig(pCtx);
76331  return SQLITE_TOOBIG;
76332}
76333SQLITE_API void sqlite3_result_blob(
76334  sqlite3_context *pCtx,
76335  const void *z,
76336  int n,
76337  void (*xDel)(void *)
76338){
76339  assert( n>=0 );
76340  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76341  setResultStrOrError(pCtx, z, n, 0, xDel);
76342}
76343SQLITE_API void sqlite3_result_blob64(
76344  sqlite3_context *pCtx,
76345  const void *z,
76346  sqlite3_uint64 n,
76347  void (*xDel)(void *)
76348){
76349  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76350  assert( xDel!=SQLITE_DYNAMIC );
76351  if( n>0x7fffffff ){
76352    (void)invokeValueDestructor(z, xDel, pCtx);
76353  }else{
76354    setResultStrOrError(pCtx, z, (int)n, 0, xDel);
76355  }
76356}
76357SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
76358  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76359  sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
76360}
76361SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
76362  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76363  pCtx->isError = SQLITE_ERROR;
76364  pCtx->fErrorOrAux = 1;
76365  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
76366}
76367#ifndef SQLITE_OMIT_UTF16
76368SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
76369  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76370  pCtx->isError = SQLITE_ERROR;
76371  pCtx->fErrorOrAux = 1;
76372  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
76373}
76374#endif
76375SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
76376  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76377  sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
76378}
76379SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
76380  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76381  sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
76382}
76383SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
76384  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76385  sqlite3VdbeMemSetNull(pCtx->pOut);
76386}
76387SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
76388  Mem *pOut = pCtx->pOut;
76389  assert( sqlite3_mutex_held(pOut->db->mutex) );
76390  pOut->eSubtype = eSubtype & 0xff;
76391  pOut->flags |= MEM_Subtype;
76392}
76393SQLITE_API void sqlite3_result_text(
76394  sqlite3_context *pCtx,
76395  const char *z,
76396  int n,
76397  void (*xDel)(void *)
76398){
76399  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76400  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
76401}
76402SQLITE_API void sqlite3_result_text64(
76403  sqlite3_context *pCtx,
76404  const char *z,
76405  sqlite3_uint64 n,
76406  void (*xDel)(void *),
76407  unsigned char enc
76408){
76409  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76410  assert( xDel!=SQLITE_DYNAMIC );
76411  if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
76412  if( n>0x7fffffff ){
76413    (void)invokeValueDestructor(z, xDel, pCtx);
76414  }else{
76415    setResultStrOrError(pCtx, z, (int)n, enc, xDel);
76416  }
76417}
76418#ifndef SQLITE_OMIT_UTF16
76419SQLITE_API void sqlite3_result_text16(
76420  sqlite3_context *pCtx,
76421  const void *z,
76422  int n,
76423  void (*xDel)(void *)
76424){
76425  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76426  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
76427}
76428SQLITE_API void sqlite3_result_text16be(
76429  sqlite3_context *pCtx,
76430  const void *z,
76431  int n,
76432  void (*xDel)(void *)
76433){
76434  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76435  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
76436}
76437SQLITE_API void sqlite3_result_text16le(
76438  sqlite3_context *pCtx,
76439  const void *z,
76440  int n,
76441  void (*xDel)(void *)
76442){
76443  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76444  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
76445}
76446#endif /* SQLITE_OMIT_UTF16 */
76447SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
76448  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76449  sqlite3VdbeMemCopy(pCtx->pOut, pValue);
76450}
76451SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
76452  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76453  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
76454}
76455SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
76456  Mem *pOut = pCtx->pOut;
76457  assert( sqlite3_mutex_held(pOut->db->mutex) );
76458  if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
76459    return SQLITE_TOOBIG;
76460  }
76461  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
76462  return SQLITE_OK;
76463}
76464SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
76465  pCtx->isError = errCode;
76466  pCtx->fErrorOrAux = 1;
76467#ifdef SQLITE_DEBUG
76468  if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
76469#endif
76470  if( pCtx->pOut->flags & MEM_Null ){
76471    sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
76472                         SQLITE_UTF8, SQLITE_STATIC);
76473  }
76474}
76475
76476/* Force an SQLITE_TOOBIG error. */
76477SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
76478  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76479  pCtx->isError = SQLITE_TOOBIG;
76480  pCtx->fErrorOrAux = 1;
76481  sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
76482                       SQLITE_UTF8, SQLITE_STATIC);
76483}
76484
76485/* An SQLITE_NOMEM error. */
76486SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
76487  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76488  sqlite3VdbeMemSetNull(pCtx->pOut);
76489  pCtx->isError = SQLITE_NOMEM_BKPT;
76490  pCtx->fErrorOrAux = 1;
76491  sqlite3OomFault(pCtx->pOut->db);
76492}
76493
76494/*
76495** This function is called after a transaction has been committed. It
76496** invokes callbacks registered with sqlite3_wal_hook() as required.
76497*/
76498static int doWalCallbacks(sqlite3 *db){
76499  int rc = SQLITE_OK;
76500#ifndef SQLITE_OMIT_WAL
76501  int i;
76502  for(i=0; i<db->nDb; i++){
76503    Btree *pBt = db->aDb[i].pBt;
76504    if( pBt ){
76505      int nEntry;
76506      sqlite3BtreeEnter(pBt);
76507      nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
76508      sqlite3BtreeLeave(pBt);
76509      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
76510        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
76511      }
76512    }
76513  }
76514#endif
76515  return rc;
76516}
76517
76518
76519/*
76520** Execute the statement pStmt, either until a row of data is ready, the
76521** statement is completely executed or an error occurs.
76522**
76523** This routine implements the bulk of the logic behind the sqlite_step()
76524** API.  The only thing omitted is the automatic recompile if a
76525** schema change has occurred.  That detail is handled by the
76526** outer sqlite3_step() wrapper procedure.
76527*/
76528static int sqlite3Step(Vdbe *p){
76529  sqlite3 *db;
76530  int rc;
76531
76532  assert(p);
76533  if( p->magic!=VDBE_MAGIC_RUN ){
76534    /* We used to require that sqlite3_reset() be called before retrying
76535    ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
76536    ** with version 3.7.0, we changed this so that sqlite3_reset() would
76537    ** be called automatically instead of throwing the SQLITE_MISUSE error.
76538    ** This "automatic-reset" change is not technically an incompatibility,
76539    ** since any application that receives an SQLITE_MISUSE is broken by
76540    ** definition.
76541    **
76542    ** Nevertheless, some published applications that were originally written
76543    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
76544    ** returns, and those were broken by the automatic-reset change.  As a
76545    ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
76546    ** legacy behavior of returning SQLITE_MISUSE for cases where the
76547    ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
76548    ** or SQLITE_BUSY error.
76549    */
76550#ifdef SQLITE_OMIT_AUTORESET
76551    if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
76552      sqlite3_reset((sqlite3_stmt*)p);
76553    }else{
76554      return SQLITE_MISUSE_BKPT;
76555    }
76556#else
76557    sqlite3_reset((sqlite3_stmt*)p);
76558#endif
76559  }
76560
76561  /* Check that malloc() has not failed. If it has, return early. */
76562  db = p->db;
76563  if( db->mallocFailed ){
76564    p->rc = SQLITE_NOMEM;
76565    return SQLITE_NOMEM_BKPT;
76566  }
76567
76568  if( p->pc<=0 && p->expired ){
76569    p->rc = SQLITE_SCHEMA;
76570    rc = SQLITE_ERROR;
76571    goto end_of_step;
76572  }
76573  if( p->pc<0 ){
76574    /* If there are no other statements currently running, then
76575    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
76576    ** from interrupting a statement that has not yet started.
76577    */
76578    if( db->nVdbeActive==0 ){
76579      db->u1.isInterrupted = 0;
76580    }
76581
76582    assert( db->nVdbeWrite>0 || db->autoCommit==0
76583        || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
76584    );
76585
76586#ifndef SQLITE_OMIT_TRACE
76587    if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
76588        && !db->init.busy && p->zSql ){
76589      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
76590    }else{
76591      assert( p->startTime==0 );
76592    }
76593#endif
76594
76595    db->nVdbeActive++;
76596    if( p->readOnly==0 ) db->nVdbeWrite++;
76597    if( p->bIsReader ) db->nVdbeRead++;
76598    p->pc = 0;
76599  }
76600#ifdef SQLITE_DEBUG
76601  p->rcApp = SQLITE_OK;
76602#endif
76603#ifndef SQLITE_OMIT_EXPLAIN
76604  if( p->explain ){
76605    rc = sqlite3VdbeList(p);
76606  }else
76607#endif /* SQLITE_OMIT_EXPLAIN */
76608  {
76609    db->nVdbeExec++;
76610    rc = sqlite3VdbeExec(p);
76611    db->nVdbeExec--;
76612  }
76613
76614#ifndef SQLITE_OMIT_TRACE
76615  /* If the statement completed successfully, invoke the profile callback */
76616  if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
76617#endif
76618
76619  if( rc==SQLITE_DONE ){
76620    assert( p->rc==SQLITE_OK );
76621    p->rc = doWalCallbacks(db);
76622    if( p->rc!=SQLITE_OK ){
76623      rc = SQLITE_ERROR;
76624    }
76625  }
76626
76627  db->errCode = rc;
76628  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
76629    p->rc = SQLITE_NOMEM_BKPT;
76630  }
76631end_of_step:
76632  /* At this point local variable rc holds the value that should be
76633  ** returned if this statement was compiled using the legacy
76634  ** sqlite3_prepare() interface. According to the docs, this can only
76635  ** be one of the values in the first assert() below. Variable p->rc
76636  ** contains the value that would be returned if sqlite3_finalize()
76637  ** were called on statement p.
76638  */
76639  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
76640       || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
76641  );
76642  assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
76643  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
76644    /* If this statement was prepared using sqlite3_prepare_v2(), and an
76645    ** error has occurred, then return the error code in p->rc to the
76646    ** caller. Set the error code in the database handle to the same value.
76647    */
76648    rc = sqlite3VdbeTransferError(p);
76649  }
76650  return (rc&db->errMask);
76651}
76652
76653/*
76654** This is the top-level implementation of sqlite3_step().  Call
76655** sqlite3Step() to do most of the work.  If a schema error occurs,
76656** call sqlite3Reprepare() and try again.
76657*/
76658SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
76659  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
76660  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
76661  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
76662  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
76663  sqlite3 *db;             /* The database connection */
76664
76665  if( vdbeSafetyNotNull(v) ){
76666    return SQLITE_MISUSE_BKPT;
76667  }
76668  db = v->db;
76669  sqlite3_mutex_enter(db->mutex);
76670  v->doingRerun = 0;
76671  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
76672         && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
76673    int savedPc = v->pc;
76674    rc2 = rc = sqlite3Reprepare(v);
76675    if( rc!=SQLITE_OK) break;
76676    sqlite3_reset(pStmt);
76677    if( savedPc>=0 ) v->doingRerun = 1;
76678    assert( v->expired==0 );
76679  }
76680  if( rc2!=SQLITE_OK ){
76681    /* This case occurs after failing to recompile an sql statement.
76682    ** The error message from the SQL compiler has already been loaded
76683    ** into the database handle. This block copies the error message
76684    ** from the database handle into the statement and sets the statement
76685    ** program counter to 0 to ensure that when the statement is
76686    ** finalized or reset the parser error message is available via
76687    ** sqlite3_errmsg() and sqlite3_errcode().
76688    */
76689    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
76690    sqlite3DbFree(db, v->zErrMsg);
76691    if( !db->mallocFailed ){
76692      v->zErrMsg = sqlite3DbStrDup(db, zErr);
76693      v->rc = rc2;
76694    } else {
76695      v->zErrMsg = 0;
76696      v->rc = rc = SQLITE_NOMEM_BKPT;
76697    }
76698  }
76699  rc = sqlite3ApiExit(db, rc);
76700  sqlite3_mutex_leave(db->mutex);
76701  return rc;
76702}
76703
76704
76705/*
76706** Extract the user data from a sqlite3_context structure and return a
76707** pointer to it.
76708*/
76709SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
76710  assert( p && p->pFunc );
76711  return p->pFunc->pUserData;
76712}
76713
76714/*
76715** Extract the user data from a sqlite3_context structure and return a
76716** pointer to it.
76717**
76718** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
76719** returns a copy of the pointer to the database connection (the 1st
76720** parameter) of the sqlite3_create_function() and
76721** sqlite3_create_function16() routines that originally registered the
76722** application defined function.
76723*/
76724SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
76725  assert( p && p->pOut );
76726  return p->pOut->db;
76727}
76728
76729/*
76730** Return the current time for a statement.  If the current time
76731** is requested more than once within the same run of a single prepared
76732** statement, the exact same time is returned for each invocation regardless
76733** of the amount of time that elapses between invocations.  In other words,
76734** the time returned is always the time of the first call.
76735*/
76736SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
76737  int rc;
76738#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
76739  sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
76740  assert( p->pVdbe!=0 );
76741#else
76742  sqlite3_int64 iTime = 0;
76743  sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
76744#endif
76745  if( *piTime==0 ){
76746    rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
76747    if( rc ) *piTime = 0;
76748  }
76749  return *piTime;
76750}
76751
76752/*
76753** The following is the implementation of an SQL function that always
76754** fails with an error message stating that the function is used in the
76755** wrong context.  The sqlite3_overload_function() API might construct
76756** SQL function that use this routine so that the functions will exist
76757** for name resolution but are actually overloaded by the xFindFunction
76758** method of virtual tables.
76759*/
76760SQLITE_PRIVATE void sqlite3InvalidFunction(
76761  sqlite3_context *context,  /* The function calling context */
76762  int NotUsed,               /* Number of arguments to the function */
76763  sqlite3_value **NotUsed2   /* Value of each argument */
76764){
76765  const char *zName = context->pFunc->zName;
76766  char *zErr;
76767  UNUSED_PARAMETER2(NotUsed, NotUsed2);
76768  zErr = sqlite3_mprintf(
76769      "unable to use function %s in the requested context", zName);
76770  sqlite3_result_error(context, zErr, -1);
76771  sqlite3_free(zErr);
76772}
76773
76774/*
76775** Create a new aggregate context for p and return a pointer to
76776** its pMem->z element.
76777*/
76778static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
76779  Mem *pMem = p->pMem;
76780  assert( (pMem->flags & MEM_Agg)==0 );
76781  if( nByte<=0 ){
76782    sqlite3VdbeMemSetNull(pMem);
76783    pMem->z = 0;
76784  }else{
76785    sqlite3VdbeMemClearAndResize(pMem, nByte);
76786    pMem->flags = MEM_Agg;
76787    pMem->u.pDef = p->pFunc;
76788    if( pMem->z ){
76789      memset(pMem->z, 0, nByte);
76790    }
76791  }
76792  return (void*)pMem->z;
76793}
76794
76795/*
76796** Allocate or return the aggregate context for a user function.  A new
76797** context is allocated on the first call.  Subsequent calls return the
76798** same context that was returned on prior calls.
76799*/
76800SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
76801  assert( p && p->pFunc && p->pFunc->xFinalize );
76802  assert( sqlite3_mutex_held(p->pOut->db->mutex) );
76803  testcase( nByte<0 );
76804  if( (p->pMem->flags & MEM_Agg)==0 ){
76805    return createAggContext(p, nByte);
76806  }else{
76807    return (void*)p->pMem->z;
76808  }
76809}
76810
76811/*
76812** Return the auxiliary data pointer, if any, for the iArg'th argument to
76813** the user-function defined by pCtx.
76814*/
76815SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
76816  AuxData *pAuxData;
76817
76818  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76819#if SQLITE_ENABLE_STAT3_OR_STAT4
76820  if( pCtx->pVdbe==0 ) return 0;
76821#else
76822  assert( pCtx->pVdbe!=0 );
76823#endif
76824  for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
76825    if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
76826  }
76827
76828  return (pAuxData ? pAuxData->pAux : 0);
76829}
76830
76831/*
76832** Set the auxiliary data pointer and delete function, for the iArg'th
76833** argument to the user-function defined by pCtx. Any previous value is
76834** deleted by calling the delete function specified when it was set.
76835*/
76836SQLITE_API void sqlite3_set_auxdata(
76837  sqlite3_context *pCtx,
76838  int iArg,
76839  void *pAux,
76840  void (*xDelete)(void*)
76841){
76842  AuxData *pAuxData;
76843  Vdbe *pVdbe = pCtx->pVdbe;
76844
76845  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
76846  if( iArg<0 ) goto failed;
76847#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
76848  if( pVdbe==0 ) goto failed;
76849#else
76850  assert( pVdbe!=0 );
76851#endif
76852
76853  for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
76854    if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
76855  }
76856  if( pAuxData==0 ){
76857    pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
76858    if( !pAuxData ) goto failed;
76859    pAuxData->iOp = pCtx->iOp;
76860    pAuxData->iArg = iArg;
76861    pAuxData->pNext = pVdbe->pAuxData;
76862    pVdbe->pAuxData = pAuxData;
76863    if( pCtx->fErrorOrAux==0 ){
76864      pCtx->isError = 0;
76865      pCtx->fErrorOrAux = 1;
76866    }
76867  }else if( pAuxData->xDelete ){
76868    pAuxData->xDelete(pAuxData->pAux);
76869  }
76870
76871  pAuxData->pAux = pAux;
76872  pAuxData->xDelete = xDelete;
76873  return;
76874
76875failed:
76876  if( xDelete ){
76877    xDelete(pAux);
76878  }
76879}
76880
76881#ifndef SQLITE_OMIT_DEPRECATED
76882/*
76883** Return the number of times the Step function of an aggregate has been
76884** called.
76885**
76886** This function is deprecated.  Do not use it for new code.  It is
76887** provide only to avoid breaking legacy code.  New aggregate function
76888** implementations should keep their own counts within their aggregate
76889** context.
76890*/
76891SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
76892  assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
76893  return p->pMem->n;
76894}
76895#endif
76896
76897/*
76898** Return the number of columns in the result set for the statement pStmt.
76899*/
76900SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
76901  Vdbe *pVm = (Vdbe *)pStmt;
76902  return pVm ? pVm->nResColumn : 0;
76903}
76904
76905/*
76906** Return the number of values available from the current row of the
76907** currently executing statement pStmt.
76908*/
76909SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
76910  Vdbe *pVm = (Vdbe *)pStmt;
76911  if( pVm==0 || pVm->pResultSet==0 ) return 0;
76912  return pVm->nResColumn;
76913}
76914
76915/*
76916** Return a pointer to static memory containing an SQL NULL value.
76917*/
76918static const Mem *columnNullValue(void){
76919  /* Even though the Mem structure contains an element
76920  ** of type i64, on certain architectures (x86) with certain compiler
76921  ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
76922  ** instead of an 8-byte one. This all works fine, except that when
76923  ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
76924  ** that a Mem structure is located on an 8-byte boundary. To prevent
76925  ** these assert()s from failing, when building with SQLITE_DEBUG defined
76926  ** using gcc, we force nullMem to be 8-byte aligned using the magical
76927  ** __attribute__((aligned(8))) macro.  */
76928  static const Mem nullMem
76929#if defined(SQLITE_DEBUG) && defined(__GNUC__)
76930    __attribute__((aligned(8)))
76931#endif
76932    = {
76933        /* .u          = */ {0},
76934        /* .flags      = */ (u16)MEM_Null,
76935        /* .enc        = */ (u8)0,
76936        /* .eSubtype   = */ (u8)0,
76937        /* .n          = */ (int)0,
76938        /* .z          = */ (char*)0,
76939        /* .zMalloc    = */ (char*)0,
76940        /* .szMalloc   = */ (int)0,
76941        /* .uTemp      = */ (u32)0,
76942        /* .db         = */ (sqlite3*)0,
76943        /* .xDel       = */ (void(*)(void*))0,
76944#ifdef SQLITE_DEBUG
76945        /* .pScopyFrom = */ (Mem*)0,
76946        /* .pFiller    = */ (void*)0,
76947#endif
76948      };
76949  return &nullMem;
76950}
76951
76952/*
76953** Check to see if column iCol of the given statement is valid.  If
76954** it is, return a pointer to the Mem for the value of that column.
76955** If iCol is not valid, return a pointer to a Mem which has a value
76956** of NULL.
76957*/
76958static Mem *columnMem(sqlite3_stmt *pStmt, int i){
76959  Vdbe *pVm;
76960  Mem *pOut;
76961
76962  pVm = (Vdbe *)pStmt;
76963  if( pVm==0 ) return (Mem*)columnNullValue();
76964  assert( pVm->db );
76965  sqlite3_mutex_enter(pVm->db->mutex);
76966  if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
76967    pOut = &pVm->pResultSet[i];
76968  }else{
76969    sqlite3Error(pVm->db, SQLITE_RANGE);
76970    pOut = (Mem*)columnNullValue();
76971  }
76972  return pOut;
76973}
76974
76975/*
76976** This function is called after invoking an sqlite3_value_XXX function on a
76977** column value (i.e. a value returned by evaluating an SQL expression in the
76978** select list of a SELECT statement) that may cause a malloc() failure. If
76979** malloc() has failed, the threads mallocFailed flag is cleared and the result
76980** code of statement pStmt set to SQLITE_NOMEM.
76981**
76982** Specifically, this is called from within:
76983**
76984**     sqlite3_column_int()
76985**     sqlite3_column_int64()
76986**     sqlite3_column_text()
76987**     sqlite3_column_text16()
76988**     sqlite3_column_real()
76989**     sqlite3_column_bytes()
76990**     sqlite3_column_bytes16()
76991**     sqiite3_column_blob()
76992*/
76993static void columnMallocFailure(sqlite3_stmt *pStmt)
76994{
76995  /* If malloc() failed during an encoding conversion within an
76996  ** sqlite3_column_XXX API, then set the return code of the statement to
76997  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
76998  ** and _finalize() will return NOMEM.
76999  */
77000  Vdbe *p = (Vdbe *)pStmt;
77001  if( p ){
77002    assert( p->db!=0 );
77003    assert( sqlite3_mutex_held(p->db->mutex) );
77004    p->rc = sqlite3ApiExit(p->db, p->rc);
77005    sqlite3_mutex_leave(p->db->mutex);
77006  }
77007}
77008
77009/**************************** sqlite3_column_  *******************************
77010** The following routines are used to access elements of the current row
77011** in the result set.
77012*/
77013SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
77014  const void *val;
77015  val = sqlite3_value_blob( columnMem(pStmt,i) );
77016  /* Even though there is no encoding conversion, value_blob() might
77017  ** need to call malloc() to expand the result of a zeroblob()
77018  ** expression.
77019  */
77020  columnMallocFailure(pStmt);
77021  return val;
77022}
77023SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
77024  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
77025  columnMallocFailure(pStmt);
77026  return val;
77027}
77028SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
77029  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
77030  columnMallocFailure(pStmt);
77031  return val;
77032}
77033SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
77034  double val = sqlite3_value_double( columnMem(pStmt,i) );
77035  columnMallocFailure(pStmt);
77036  return val;
77037}
77038SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
77039  int val = sqlite3_value_int( columnMem(pStmt,i) );
77040  columnMallocFailure(pStmt);
77041  return val;
77042}
77043SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
77044  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
77045  columnMallocFailure(pStmt);
77046  return val;
77047}
77048SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
77049  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
77050  columnMallocFailure(pStmt);
77051  return val;
77052}
77053SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
77054  Mem *pOut = columnMem(pStmt, i);
77055  if( pOut->flags&MEM_Static ){
77056    pOut->flags &= ~MEM_Static;
77057    pOut->flags |= MEM_Ephem;
77058  }
77059  columnMallocFailure(pStmt);
77060  return (sqlite3_value *)pOut;
77061}
77062#ifndef SQLITE_OMIT_UTF16
77063SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
77064  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
77065  columnMallocFailure(pStmt);
77066  return val;
77067}
77068#endif /* SQLITE_OMIT_UTF16 */
77069SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
77070  int iType = sqlite3_value_type( columnMem(pStmt,i) );
77071  columnMallocFailure(pStmt);
77072  return iType;
77073}
77074
77075/*
77076** Convert the N-th element of pStmt->pColName[] into a string using
77077** xFunc() then return that string.  If N is out of range, return 0.
77078**
77079** There are up to 5 names for each column.  useType determines which
77080** name is returned.  Here are the names:
77081**
77082**    0      The column name as it should be displayed for output
77083**    1      The datatype name for the column
77084**    2      The name of the database that the column derives from
77085**    3      The name of the table that the column derives from
77086**    4      The name of the table column that the result column derives from
77087**
77088** If the result is not a simple column reference (if it is an expression
77089** or a constant) then useTypes 2, 3, and 4 return NULL.
77090*/
77091static const void *columnName(
77092  sqlite3_stmt *pStmt,
77093  int N,
77094  const void *(*xFunc)(Mem*),
77095  int useType
77096){
77097  const void *ret;
77098  Vdbe *p;
77099  int n;
77100  sqlite3 *db;
77101#ifdef SQLITE_ENABLE_API_ARMOR
77102  if( pStmt==0 ){
77103    (void)SQLITE_MISUSE_BKPT;
77104    return 0;
77105  }
77106#endif
77107  ret = 0;
77108  p = (Vdbe *)pStmt;
77109  db = p->db;
77110  assert( db!=0 );
77111  n = sqlite3_column_count(pStmt);
77112  if( N<n && N>=0 ){
77113    N += useType*n;
77114    sqlite3_mutex_enter(db->mutex);
77115    assert( db->mallocFailed==0 );
77116    ret = xFunc(&p->aColName[N]);
77117     /* A malloc may have failed inside of the xFunc() call. If this
77118    ** is the case, clear the mallocFailed flag and return NULL.
77119    */
77120    if( db->mallocFailed ){
77121      sqlite3OomClear(db);
77122      ret = 0;
77123    }
77124    sqlite3_mutex_leave(db->mutex);
77125  }
77126  return ret;
77127}
77128
77129/*
77130** Return the name of the Nth column of the result set returned by SQL
77131** statement pStmt.
77132*/
77133SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
77134  return columnName(
77135      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
77136}
77137#ifndef SQLITE_OMIT_UTF16
77138SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
77139  return columnName(
77140      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
77141}
77142#endif
77143
77144/*
77145** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
77146** not define OMIT_DECLTYPE.
77147*/
77148#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
77149# error "Must not define both SQLITE_OMIT_DECLTYPE \
77150         and SQLITE_ENABLE_COLUMN_METADATA"
77151#endif
77152
77153#ifndef SQLITE_OMIT_DECLTYPE
77154/*
77155** Return the column declaration type (if applicable) of the 'i'th column
77156** of the result set of SQL statement pStmt.
77157*/
77158SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
77159  return columnName(
77160      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
77161}
77162#ifndef SQLITE_OMIT_UTF16
77163SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
77164  return columnName(
77165      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
77166}
77167#endif /* SQLITE_OMIT_UTF16 */
77168#endif /* SQLITE_OMIT_DECLTYPE */
77169
77170#ifdef SQLITE_ENABLE_COLUMN_METADATA
77171/*
77172** Return the name of the database from which a result column derives.
77173** NULL is returned if the result column is an expression or constant or
77174** anything else which is not an unambiguous reference to a database column.
77175*/
77176SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
77177  return columnName(
77178      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
77179}
77180#ifndef SQLITE_OMIT_UTF16
77181SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
77182  return columnName(
77183      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
77184}
77185#endif /* SQLITE_OMIT_UTF16 */
77186
77187/*
77188** Return the name of the table from which a result column derives.
77189** NULL is returned if the result column is an expression or constant or
77190** anything else which is not an unambiguous reference to a database column.
77191*/
77192SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
77193  return columnName(
77194      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
77195}
77196#ifndef SQLITE_OMIT_UTF16
77197SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
77198  return columnName(
77199      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
77200}
77201#endif /* SQLITE_OMIT_UTF16 */
77202
77203/*
77204** Return the name of the table column from which a result column derives.
77205** NULL is returned if the result column is an expression or constant or
77206** anything else which is not an unambiguous reference to a database column.
77207*/
77208SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
77209  return columnName(
77210      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
77211}
77212#ifndef SQLITE_OMIT_UTF16
77213SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
77214  return columnName(
77215      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
77216}
77217#endif /* SQLITE_OMIT_UTF16 */
77218#endif /* SQLITE_ENABLE_COLUMN_METADATA */
77219
77220
77221/******************************* sqlite3_bind_  ***************************
77222**
77223** Routines used to attach values to wildcards in a compiled SQL statement.
77224*/
77225/*
77226** Unbind the value bound to variable i in virtual machine p. This is the
77227** the same as binding a NULL value to the column. If the "i" parameter is
77228** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
77229**
77230** A successful evaluation of this routine acquires the mutex on p.
77231** the mutex is released if any kind of error occurs.
77232**
77233** The error code stored in database p->db is overwritten with the return
77234** value in any case.
77235*/
77236static int vdbeUnbind(Vdbe *p, int i){
77237  Mem *pVar;
77238  if( vdbeSafetyNotNull(p) ){
77239    return SQLITE_MISUSE_BKPT;
77240  }
77241  sqlite3_mutex_enter(p->db->mutex);
77242  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
77243    sqlite3Error(p->db, SQLITE_MISUSE);
77244    sqlite3_mutex_leave(p->db->mutex);
77245    sqlite3_log(SQLITE_MISUSE,
77246        "bind on a busy prepared statement: [%s]", p->zSql);
77247    return SQLITE_MISUSE_BKPT;
77248  }
77249  if( i<1 || i>p->nVar ){
77250    sqlite3Error(p->db, SQLITE_RANGE);
77251    sqlite3_mutex_leave(p->db->mutex);
77252    return SQLITE_RANGE;
77253  }
77254  i--;
77255  pVar = &p->aVar[i];
77256  sqlite3VdbeMemRelease(pVar);
77257  pVar->flags = MEM_Null;
77258  sqlite3Error(p->db, SQLITE_OK);
77259
77260  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
77261  ** binding a new value to this variable invalidates the current query plan.
77262  **
77263  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
77264  ** parameter in the WHERE clause might influence the choice of query plan
77265  ** for a statement, then the statement will be automatically recompiled,
77266  ** as if there had been a schema change, on the first sqlite3_step() call
77267  ** following any change to the bindings of that parameter.
77268  */
77269  assert( p->isPrepareV2 || p->expmask==0 );
77270  if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
77271    p->expired = 1;
77272  }
77273  return SQLITE_OK;
77274}
77275
77276/*
77277** Bind a text or BLOB value.
77278*/
77279static int bindText(
77280  sqlite3_stmt *pStmt,   /* The statement to bind against */
77281  int i,                 /* Index of the parameter to bind */
77282  const void *zData,     /* Pointer to the data to be bound */
77283  int nData,             /* Number of bytes of data to be bound */
77284  void (*xDel)(void*),   /* Destructor for the data */
77285  u8 encoding            /* Encoding for the data */
77286){
77287  Vdbe *p = (Vdbe *)pStmt;
77288  Mem *pVar;
77289  int rc;
77290
77291  rc = vdbeUnbind(p, i);
77292  if( rc==SQLITE_OK ){
77293    if( zData!=0 ){
77294      pVar = &p->aVar[i-1];
77295      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
77296      if( rc==SQLITE_OK && encoding!=0 ){
77297        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
77298      }
77299      sqlite3Error(p->db, rc);
77300      rc = sqlite3ApiExit(p->db, rc);
77301    }
77302    sqlite3_mutex_leave(p->db->mutex);
77303  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
77304    xDel((void*)zData);
77305  }
77306  return rc;
77307}
77308
77309
77310/*
77311** Bind a blob value to an SQL statement variable.
77312*/
77313SQLITE_API int sqlite3_bind_blob(
77314  sqlite3_stmt *pStmt,
77315  int i,
77316  const void *zData,
77317  int nData,
77318  void (*xDel)(void*)
77319){
77320#ifdef SQLITE_ENABLE_API_ARMOR
77321  if( nData<0 ) return SQLITE_MISUSE_BKPT;
77322#endif
77323  return bindText(pStmt, i, zData, nData, xDel, 0);
77324}
77325SQLITE_API int sqlite3_bind_blob64(
77326  sqlite3_stmt *pStmt,
77327  int i,
77328  const void *zData,
77329  sqlite3_uint64 nData,
77330  void (*xDel)(void*)
77331){
77332  assert( xDel!=SQLITE_DYNAMIC );
77333  if( nData>0x7fffffff ){
77334    return invokeValueDestructor(zData, xDel, 0);
77335  }else{
77336    return bindText(pStmt, i, zData, (int)nData, xDel, 0);
77337  }
77338}
77339SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
77340  int rc;
77341  Vdbe *p = (Vdbe *)pStmt;
77342  rc = vdbeUnbind(p, i);
77343  if( rc==SQLITE_OK ){
77344    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
77345    sqlite3_mutex_leave(p->db->mutex);
77346  }
77347  return rc;
77348}
77349SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
77350  return sqlite3_bind_int64(p, i, (i64)iValue);
77351}
77352SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
77353  int rc;
77354  Vdbe *p = (Vdbe *)pStmt;
77355  rc = vdbeUnbind(p, i);
77356  if( rc==SQLITE_OK ){
77357    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
77358    sqlite3_mutex_leave(p->db->mutex);
77359  }
77360  return rc;
77361}
77362SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
77363  int rc;
77364  Vdbe *p = (Vdbe*)pStmt;
77365  rc = vdbeUnbind(p, i);
77366  if( rc==SQLITE_OK ){
77367    sqlite3_mutex_leave(p->db->mutex);
77368  }
77369  return rc;
77370}
77371SQLITE_API int sqlite3_bind_text(
77372  sqlite3_stmt *pStmt,
77373  int i,
77374  const char *zData,
77375  int nData,
77376  void (*xDel)(void*)
77377){
77378  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
77379}
77380SQLITE_API int sqlite3_bind_text64(
77381  sqlite3_stmt *pStmt,
77382  int i,
77383  const char *zData,
77384  sqlite3_uint64 nData,
77385  void (*xDel)(void*),
77386  unsigned char enc
77387){
77388  assert( xDel!=SQLITE_DYNAMIC );
77389  if( nData>0x7fffffff ){
77390    return invokeValueDestructor(zData, xDel, 0);
77391  }else{
77392    if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
77393    return bindText(pStmt, i, zData, (int)nData, xDel, enc);
77394  }
77395}
77396#ifndef SQLITE_OMIT_UTF16
77397SQLITE_API int sqlite3_bind_text16(
77398  sqlite3_stmt *pStmt,
77399  int i,
77400  const void *zData,
77401  int nData,
77402  void (*xDel)(void*)
77403){
77404  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
77405}
77406#endif /* SQLITE_OMIT_UTF16 */
77407SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
77408  int rc;
77409  switch( sqlite3_value_type((sqlite3_value*)pValue) ){
77410    case SQLITE_INTEGER: {
77411      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
77412      break;
77413    }
77414    case SQLITE_FLOAT: {
77415      rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
77416      break;
77417    }
77418    case SQLITE_BLOB: {
77419      if( pValue->flags & MEM_Zero ){
77420        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
77421      }else{
77422        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
77423      }
77424      break;
77425    }
77426    case SQLITE_TEXT: {
77427      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
77428                              pValue->enc);
77429      break;
77430    }
77431    default: {
77432      rc = sqlite3_bind_null(pStmt, i);
77433      break;
77434    }
77435  }
77436  return rc;
77437}
77438SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
77439  int rc;
77440  Vdbe *p = (Vdbe *)pStmt;
77441  rc = vdbeUnbind(p, i);
77442  if( rc==SQLITE_OK ){
77443    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
77444    sqlite3_mutex_leave(p->db->mutex);
77445  }
77446  return rc;
77447}
77448SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
77449  int rc;
77450  Vdbe *p = (Vdbe *)pStmt;
77451  sqlite3_mutex_enter(p->db->mutex);
77452  if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
77453    rc = SQLITE_TOOBIG;
77454  }else{
77455    assert( (n & 0x7FFFFFFF)==n );
77456    rc = sqlite3_bind_zeroblob(pStmt, i, n);
77457  }
77458  rc = sqlite3ApiExit(p->db, rc);
77459  sqlite3_mutex_leave(p->db->mutex);
77460  return rc;
77461}
77462
77463/*
77464** Return the number of wildcards that can be potentially bound to.
77465** This routine is added to support DBD::SQLite.
77466*/
77467SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
77468  Vdbe *p = (Vdbe*)pStmt;
77469  return p ? p->nVar : 0;
77470}
77471
77472/*
77473** Return the name of a wildcard parameter.  Return NULL if the index
77474** is out of range or if the wildcard is unnamed.
77475**
77476** The result is always UTF-8.
77477*/
77478SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
77479  Vdbe *p = (Vdbe*)pStmt;
77480  if( p==0 ) return 0;
77481  return sqlite3VListNumToName(p->pVList, i);
77482}
77483
77484/*
77485** Given a wildcard parameter name, return the index of the variable
77486** with that name.  If there is no variable with the given name,
77487** return 0.
77488*/
77489SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
77490  if( p==0 || zName==0 ) return 0;
77491  return sqlite3VListNameToNum(p->pVList, zName, nName);
77492}
77493SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
77494  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
77495}
77496
77497/*
77498** Transfer all bindings from the first statement over to the second.
77499*/
77500SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
77501  Vdbe *pFrom = (Vdbe*)pFromStmt;
77502  Vdbe *pTo = (Vdbe*)pToStmt;
77503  int i;
77504  assert( pTo->db==pFrom->db );
77505  assert( pTo->nVar==pFrom->nVar );
77506  sqlite3_mutex_enter(pTo->db->mutex);
77507  for(i=0; i<pFrom->nVar; i++){
77508    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
77509  }
77510  sqlite3_mutex_leave(pTo->db->mutex);
77511  return SQLITE_OK;
77512}
77513
77514#ifndef SQLITE_OMIT_DEPRECATED
77515/*
77516** Deprecated external interface.  Internal/core SQLite code
77517** should call sqlite3TransferBindings.
77518**
77519** It is misuse to call this routine with statements from different
77520** database connections.  But as this is a deprecated interface, we
77521** will not bother to check for that condition.
77522**
77523** If the two statements contain a different number of bindings, then
77524** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
77525** SQLITE_OK is returned.
77526*/
77527SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
77528  Vdbe *pFrom = (Vdbe*)pFromStmt;
77529  Vdbe *pTo = (Vdbe*)pToStmt;
77530  if( pFrom->nVar!=pTo->nVar ){
77531    return SQLITE_ERROR;
77532  }
77533  assert( pTo->isPrepareV2 || pTo->expmask==0 );
77534  if( pTo->expmask ){
77535    pTo->expired = 1;
77536  }
77537  assert( pFrom->isPrepareV2 || pFrom->expmask==0 );
77538  if( pFrom->expmask ){
77539    pFrom->expired = 1;
77540  }
77541  return sqlite3TransferBindings(pFromStmt, pToStmt);
77542}
77543#endif
77544
77545/*
77546** Return the sqlite3* database handle to which the prepared statement given
77547** in the argument belongs.  This is the same database handle that was
77548** the first argument to the sqlite3_prepare() that was used to create
77549** the statement in the first place.
77550*/
77551SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
77552  return pStmt ? ((Vdbe*)pStmt)->db : 0;
77553}
77554
77555/*
77556** Return true if the prepared statement is guaranteed to not modify the
77557** database.
77558*/
77559SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
77560  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
77561}
77562
77563/*
77564** Return true if the prepared statement is in need of being reset.
77565*/
77566SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
77567  Vdbe *v = (Vdbe*)pStmt;
77568  return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
77569}
77570
77571/*
77572** Return a pointer to the next prepared statement after pStmt associated
77573** with database connection pDb.  If pStmt is NULL, return the first
77574** prepared statement for the database connection.  Return NULL if there
77575** are no more.
77576*/
77577SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
77578  sqlite3_stmt *pNext;
77579#ifdef SQLITE_ENABLE_API_ARMOR
77580  if( !sqlite3SafetyCheckOk(pDb) ){
77581    (void)SQLITE_MISUSE_BKPT;
77582    return 0;
77583  }
77584#endif
77585  sqlite3_mutex_enter(pDb->mutex);
77586  if( pStmt==0 ){
77587    pNext = (sqlite3_stmt*)pDb->pVdbe;
77588  }else{
77589    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
77590  }
77591  sqlite3_mutex_leave(pDb->mutex);
77592  return pNext;
77593}
77594
77595/*
77596** Return the value of a status counter for a prepared statement
77597*/
77598SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
77599  Vdbe *pVdbe = (Vdbe*)pStmt;
77600  u32 v;
77601#ifdef SQLITE_ENABLE_API_ARMOR
77602  if( !pStmt ){
77603    (void)SQLITE_MISUSE_BKPT;
77604    return 0;
77605  }
77606#endif
77607  v = pVdbe->aCounter[op];
77608  if( resetFlag ) pVdbe->aCounter[op] = 0;
77609  return (int)v;
77610}
77611
77612/*
77613** Return the SQL associated with a prepared statement
77614*/
77615SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
77616  Vdbe *p = (Vdbe *)pStmt;
77617  return p ? p->zSql : 0;
77618}
77619
77620/*
77621** Return the SQL associated with a prepared statement with
77622** bound parameters expanded.  Space to hold the returned string is
77623** obtained from sqlite3_malloc().  The caller is responsible for
77624** freeing the returned string by passing it to sqlite3_free().
77625**
77626** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
77627** expanded bound parameters.
77628*/
77629SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
77630#ifdef SQLITE_OMIT_TRACE
77631  return 0;
77632#else
77633  char *z = 0;
77634  const char *zSql = sqlite3_sql(pStmt);
77635  if( zSql ){
77636    Vdbe *p = (Vdbe *)pStmt;
77637    sqlite3_mutex_enter(p->db->mutex);
77638    z = sqlite3VdbeExpandSql(p, zSql);
77639    sqlite3_mutex_leave(p->db->mutex);
77640  }
77641  return z;
77642#endif
77643}
77644
77645#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
77646/*
77647** Allocate and populate an UnpackedRecord structure based on the serialized
77648** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
77649** if successful, or a NULL pointer if an OOM error is encountered.
77650*/
77651static UnpackedRecord *vdbeUnpackRecord(
77652  KeyInfo *pKeyInfo,
77653  int nKey,
77654  const void *pKey
77655){
77656  UnpackedRecord *pRet;           /* Return value */
77657
77658  pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
77659  if( pRet ){
77660    memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1));
77661    sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
77662  }
77663  return pRet;
77664}
77665
77666/*
77667** This function is called from within a pre-update callback to retrieve
77668** a field of the row currently being updated or deleted.
77669*/
77670SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
77671  PreUpdate *p = db->pPreUpdate;
77672  Mem *pMem;
77673  int rc = SQLITE_OK;
77674
77675  /* Test that this call is being made from within an SQLITE_DELETE or
77676  ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
77677  if( !p || p->op==SQLITE_INSERT ){
77678    rc = SQLITE_MISUSE_BKPT;
77679    goto preupdate_old_out;
77680  }
77681  if( p->pPk ){
77682    iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
77683  }
77684  if( iIdx>=p->pCsr->nField || iIdx<0 ){
77685    rc = SQLITE_RANGE;
77686    goto preupdate_old_out;
77687  }
77688
77689  /* If the old.* record has not yet been loaded into memory, do so now. */
77690  if( p->pUnpacked==0 ){
77691    u32 nRec;
77692    u8 *aRec;
77693
77694    nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
77695    aRec = sqlite3DbMallocRaw(db, nRec);
77696    if( !aRec ) goto preupdate_old_out;
77697    rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
77698    if( rc==SQLITE_OK ){
77699      p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
77700      if( !p->pUnpacked ) rc = SQLITE_NOMEM;
77701    }
77702    if( rc!=SQLITE_OK ){
77703      sqlite3DbFree(db, aRec);
77704      goto preupdate_old_out;
77705    }
77706    p->aRecord = aRec;
77707  }
77708
77709  pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
77710  if( iIdx==p->pTab->iPKey ){
77711    sqlite3VdbeMemSetInt64(pMem, p->iKey1);
77712  }else if( iIdx>=p->pUnpacked->nField ){
77713    *ppValue = (sqlite3_value *)columnNullValue();
77714  }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
77715    if( pMem->flags & MEM_Int ){
77716      sqlite3VdbeMemRealify(pMem);
77717    }
77718  }
77719
77720 preupdate_old_out:
77721  sqlite3Error(db, rc);
77722  return sqlite3ApiExit(db, rc);
77723}
77724#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
77725
77726#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
77727/*
77728** This function is called from within a pre-update callback to retrieve
77729** the number of columns in the row being updated, deleted or inserted.
77730*/
77731SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
77732  PreUpdate *p = db->pPreUpdate;
77733  return (p ? p->keyinfo.nField : 0);
77734}
77735#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
77736
77737#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
77738/*
77739** This function is designed to be called from within a pre-update callback
77740** only. It returns zero if the change that caused the callback was made
77741** immediately by a user SQL statement. Or, if the change was made by a
77742** trigger program, it returns the number of trigger programs currently
77743** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
77744** top-level trigger etc.).
77745**
77746** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
77747** or SET DEFAULT action is considered a trigger.
77748*/
77749SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
77750  PreUpdate *p = db->pPreUpdate;
77751  return (p ? p->v->nFrame : 0);
77752}
77753#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
77754
77755#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
77756/*
77757** This function is called from within a pre-update callback to retrieve
77758** a field of the row currently being updated or inserted.
77759*/
77760SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
77761  PreUpdate *p = db->pPreUpdate;
77762  int rc = SQLITE_OK;
77763  Mem *pMem;
77764
77765  if( !p || p->op==SQLITE_DELETE ){
77766    rc = SQLITE_MISUSE_BKPT;
77767    goto preupdate_new_out;
77768  }
77769  if( p->pPk && p->op!=SQLITE_UPDATE ){
77770    iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
77771  }
77772  if( iIdx>=p->pCsr->nField || iIdx<0 ){
77773    rc = SQLITE_RANGE;
77774    goto preupdate_new_out;
77775  }
77776
77777  if( p->op==SQLITE_INSERT ){
77778    /* For an INSERT, memory cell p->iNewReg contains the serialized record
77779    ** that is being inserted. Deserialize it. */
77780    UnpackedRecord *pUnpack = p->pNewUnpacked;
77781    if( !pUnpack ){
77782      Mem *pData = &p->v->aMem[p->iNewReg];
77783      rc = ExpandBlob(pData);
77784      if( rc!=SQLITE_OK ) goto preupdate_new_out;
77785      pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
77786      if( !pUnpack ){
77787        rc = SQLITE_NOMEM;
77788        goto preupdate_new_out;
77789      }
77790      p->pNewUnpacked = pUnpack;
77791    }
77792    pMem = &pUnpack->aMem[iIdx];
77793    if( iIdx==p->pTab->iPKey ){
77794      sqlite3VdbeMemSetInt64(pMem, p->iKey2);
77795    }else if( iIdx>=pUnpack->nField ){
77796      pMem = (sqlite3_value *)columnNullValue();
77797    }
77798  }else{
77799    /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
77800    ** value. Make a copy of the cell contents and return a pointer to it.
77801    ** It is not safe to return a pointer to the memory cell itself as the
77802    ** caller may modify the value text encoding.
77803    */
77804    assert( p->op==SQLITE_UPDATE );
77805    if( !p->aNew ){
77806      p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
77807      if( !p->aNew ){
77808        rc = SQLITE_NOMEM;
77809        goto preupdate_new_out;
77810      }
77811    }
77812    assert( iIdx>=0 && iIdx<p->pCsr->nField );
77813    pMem = &p->aNew[iIdx];
77814    if( pMem->flags==0 ){
77815      if( iIdx==p->pTab->iPKey ){
77816        sqlite3VdbeMemSetInt64(pMem, p->iKey2);
77817      }else{
77818        rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
77819        if( rc!=SQLITE_OK ) goto preupdate_new_out;
77820      }
77821    }
77822  }
77823  *ppValue = pMem;
77824
77825 preupdate_new_out:
77826  sqlite3Error(db, rc);
77827  return sqlite3ApiExit(db, rc);
77828}
77829#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
77830
77831#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
77832/*
77833** Return status data for a single loop within query pStmt.
77834*/
77835SQLITE_API int sqlite3_stmt_scanstatus(
77836  sqlite3_stmt *pStmt,            /* Prepared statement being queried */
77837  int idx,                        /* Index of loop to report on */
77838  int iScanStatusOp,              /* Which metric to return */
77839  void *pOut                      /* OUT: Write the answer here */
77840){
77841  Vdbe *p = (Vdbe*)pStmt;
77842  ScanStatus *pScan;
77843  if( idx<0 || idx>=p->nScan ) return 1;
77844  pScan = &p->aScan[idx];
77845  switch( iScanStatusOp ){
77846    case SQLITE_SCANSTAT_NLOOP: {
77847      *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
77848      break;
77849    }
77850    case SQLITE_SCANSTAT_NVISIT: {
77851      *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
77852      break;
77853    }
77854    case SQLITE_SCANSTAT_EST: {
77855      double r = 1.0;
77856      LogEst x = pScan->nEst;
77857      while( x<100 ){
77858        x += 10;
77859        r *= 0.5;
77860      }
77861      *(double*)pOut = r*sqlite3LogEstToInt(x);
77862      break;
77863    }
77864    case SQLITE_SCANSTAT_NAME: {
77865      *(const char**)pOut = pScan->zName;
77866      break;
77867    }
77868    case SQLITE_SCANSTAT_EXPLAIN: {
77869      if( pScan->addrExplain ){
77870        *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
77871      }else{
77872        *(const char**)pOut = 0;
77873      }
77874      break;
77875    }
77876    case SQLITE_SCANSTAT_SELECTID: {
77877      if( pScan->addrExplain ){
77878        *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
77879      }else{
77880        *(int*)pOut = -1;
77881      }
77882      break;
77883    }
77884    default: {
77885      return 1;
77886    }
77887  }
77888  return 0;
77889}
77890
77891/*
77892** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
77893*/
77894SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
77895  Vdbe *p = (Vdbe*)pStmt;
77896  memset(p->anExec, 0, p->nOp * sizeof(i64));
77897}
77898#endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
77899
77900/************** End of vdbeapi.c *********************************************/
77901/************** Begin file vdbetrace.c ***************************************/
77902/*
77903** 2009 November 25
77904**
77905** The author disclaims copyright to this source code.  In place of
77906** a legal notice, here is a blessing:
77907**
77908**    May you do good and not evil.
77909**    May you find forgiveness for yourself and forgive others.
77910**    May you share freely, never taking more than you give.
77911**
77912*************************************************************************
77913**
77914** This file contains code used to insert the values of host parameters
77915** (aka "wildcards") into the SQL text output by sqlite3_trace().
77916**
77917** The Vdbe parse-tree explainer is also found here.
77918*/
77919/* #include "sqliteInt.h" */
77920/* #include "vdbeInt.h" */
77921
77922#ifndef SQLITE_OMIT_TRACE
77923
77924/*
77925** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
77926** bytes in this text up to but excluding the first character in
77927** a host parameter.  If the text contains no host parameters, return
77928** the total number of bytes in the text.
77929*/
77930static int findNextHostParameter(const char *zSql, int *pnToken){
77931  int tokenType;
77932  int nTotal = 0;
77933  int n;
77934
77935  *pnToken = 0;
77936  while( zSql[0] ){
77937    n = sqlite3GetToken((u8*)zSql, &tokenType);
77938    assert( n>0 && tokenType!=TK_ILLEGAL );
77939    if( tokenType==TK_VARIABLE ){
77940      *pnToken = n;
77941      break;
77942    }
77943    nTotal += n;
77944    zSql += n;
77945  }
77946  return nTotal;
77947}
77948
77949/*
77950** This function returns a pointer to a nul-terminated string in memory
77951** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
77952** string contains a copy of zRawSql but with host parameters expanded to
77953** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
77954** then the returned string holds a copy of zRawSql with "-- " prepended
77955** to each line of text.
77956**
77957** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
77958** then long strings and blobs are truncated to that many bytes.  This
77959** can be used to prevent unreasonably large trace strings when dealing
77960** with large (multi-megabyte) strings and blobs.
77961**
77962** The calling function is responsible for making sure the memory returned
77963** is eventually freed.
77964**
77965** ALGORITHM:  Scan the input string looking for host parameters in any of
77966** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
77967** string literals, quoted identifier names, and comments.  For text forms,
77968** the host parameter index is found by scanning the prepared
77969** statement for the corresponding OP_Variable opcode.  Once the host
77970** parameter index is known, locate the value in p->aVar[].  Then render
77971** the value as a literal in place of the host parameter name.
77972*/
77973SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
77974  Vdbe *p,                 /* The prepared statement being evaluated */
77975  const char *zRawSql      /* Raw text of the SQL statement */
77976){
77977  sqlite3 *db;             /* The database connection */
77978  int idx = 0;             /* Index of a host parameter */
77979  int nextIndex = 1;       /* Index of next ? host parameter */
77980  int n;                   /* Length of a token prefix */
77981  int nToken;              /* Length of the parameter token */
77982  int i;                   /* Loop counter */
77983  Mem *pVar;               /* Value of a host parameter */
77984  StrAccum out;            /* Accumulate the output here */
77985#ifndef SQLITE_OMIT_UTF16
77986  Mem utf8;                /* Used to convert UTF16 parameters into UTF8 for display */
77987#endif
77988  char zBase[100];         /* Initial working space */
77989
77990  db = p->db;
77991  sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
77992                      db->aLimit[SQLITE_LIMIT_LENGTH]);
77993  if( db->nVdbeExec>1 ){
77994    while( *zRawSql ){
77995      const char *zStart = zRawSql;
77996      while( *(zRawSql++)!='\n' && *zRawSql );
77997      sqlite3StrAccumAppend(&out, "-- ", 3);
77998      assert( (zRawSql - zStart) > 0 );
77999      sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
78000    }
78001  }else if( p->nVar==0 ){
78002    sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
78003  }else{
78004    while( zRawSql[0] ){
78005      n = findNextHostParameter(zRawSql, &nToken);
78006      assert( n>0 );
78007      sqlite3StrAccumAppend(&out, zRawSql, n);
78008      zRawSql += n;
78009      assert( zRawSql[0] || nToken==0 );
78010      if( nToken==0 ) break;
78011      if( zRawSql[0]=='?' ){
78012        if( nToken>1 ){
78013          assert( sqlite3Isdigit(zRawSql[1]) );
78014          sqlite3GetInt32(&zRawSql[1], &idx);
78015        }else{
78016          idx = nextIndex;
78017        }
78018      }else{
78019        assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
78020                zRawSql[0]=='@' || zRawSql[0]=='#' );
78021        testcase( zRawSql[0]==':' );
78022        testcase( zRawSql[0]=='$' );
78023        testcase( zRawSql[0]=='@' );
78024        testcase( zRawSql[0]=='#' );
78025        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
78026        assert( idx>0 );
78027      }
78028      zRawSql += nToken;
78029      nextIndex = idx + 1;
78030      assert( idx>0 && idx<=p->nVar );
78031      pVar = &p->aVar[idx-1];
78032      if( pVar->flags & MEM_Null ){
78033        sqlite3StrAccumAppend(&out, "NULL", 4);
78034      }else if( pVar->flags & MEM_Int ){
78035        sqlite3XPrintf(&out, "%lld", pVar->u.i);
78036      }else if( pVar->flags & MEM_Real ){
78037        sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
78038      }else if( pVar->flags & MEM_Str ){
78039        int nOut;  /* Number of bytes of the string text to include in output */
78040#ifndef SQLITE_OMIT_UTF16
78041        u8 enc = ENC(db);
78042        if( enc!=SQLITE_UTF8 ){
78043          memset(&utf8, 0, sizeof(utf8));
78044          utf8.db = db;
78045          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
78046          if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
78047            out.accError = STRACCUM_NOMEM;
78048            out.nAlloc = 0;
78049          }
78050          pVar = &utf8;
78051        }
78052#endif
78053        nOut = pVar->n;
78054#ifdef SQLITE_TRACE_SIZE_LIMIT
78055        if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
78056          nOut = SQLITE_TRACE_SIZE_LIMIT;
78057          while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
78058        }
78059#endif
78060        sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
78061#ifdef SQLITE_TRACE_SIZE_LIMIT
78062        if( nOut<pVar->n ){
78063          sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
78064        }
78065#endif
78066#ifndef SQLITE_OMIT_UTF16
78067        if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
78068#endif
78069      }else if( pVar->flags & MEM_Zero ){
78070        sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
78071      }else{
78072        int nOut;  /* Number of bytes of the blob to include in output */
78073        assert( pVar->flags & MEM_Blob );
78074        sqlite3StrAccumAppend(&out, "x'", 2);
78075        nOut = pVar->n;
78076#ifdef SQLITE_TRACE_SIZE_LIMIT
78077        if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
78078#endif
78079        for(i=0; i<nOut; i++){
78080          sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
78081        }
78082        sqlite3StrAccumAppend(&out, "'", 1);
78083#ifdef SQLITE_TRACE_SIZE_LIMIT
78084        if( nOut<pVar->n ){
78085          sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
78086        }
78087#endif
78088      }
78089    }
78090  }
78091  if( out.accError ) sqlite3StrAccumReset(&out);
78092  return sqlite3StrAccumFinish(&out);
78093}
78094
78095#endif /* #ifndef SQLITE_OMIT_TRACE */
78096
78097/************** End of vdbetrace.c *******************************************/
78098/************** Begin file vdbe.c ********************************************/
78099/*
78100** 2001 September 15
78101**
78102** The author disclaims copyright to this source code.  In place of
78103** a legal notice, here is a blessing:
78104**
78105**    May you do good and not evil.
78106**    May you find forgiveness for yourself and forgive others.
78107**    May you share freely, never taking more than you give.
78108**
78109*************************************************************************
78110** The code in this file implements the function that runs the
78111** bytecode of a prepared statement.
78112**
78113** Various scripts scan this source file in order to generate HTML
78114** documentation, headers files, or other derived files.  The formatting
78115** of the code in this file is, therefore, important.  See other comments
78116** in this file for details.  If in doubt, do not deviate from existing
78117** commenting and indentation practices when changing or adding code.
78118*/
78119/* #include "sqliteInt.h" */
78120/* #include "vdbeInt.h" */
78121
78122/*
78123** Invoke this macro on memory cells just prior to changing the
78124** value of the cell.  This macro verifies that shallow copies are
78125** not misused.  A shallow copy of a string or blob just copies a
78126** pointer to the string or blob, not the content.  If the original
78127** is changed while the copy is still in use, the string or blob might
78128** be changed out from under the copy.  This macro verifies that nothing
78129** like that ever happens.
78130*/
78131#ifdef SQLITE_DEBUG
78132# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
78133#else
78134# define memAboutToChange(P,M)
78135#endif
78136
78137/*
78138** The following global variable is incremented every time a cursor
78139** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
78140** procedures use this information to make sure that indices are
78141** working correctly.  This variable has no function other than to
78142** help verify the correct operation of the library.
78143*/
78144#ifdef SQLITE_TEST
78145SQLITE_API int sqlite3_search_count = 0;
78146#endif
78147
78148/*
78149** When this global variable is positive, it gets decremented once before
78150** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
78151** field of the sqlite3 structure is set in order to simulate an interrupt.
78152**
78153** This facility is used for testing purposes only.  It does not function
78154** in an ordinary build.
78155*/
78156#ifdef SQLITE_TEST
78157SQLITE_API int sqlite3_interrupt_count = 0;
78158#endif
78159
78160/*
78161** The next global variable is incremented each type the OP_Sort opcode
78162** is executed.  The test procedures use this information to make sure that
78163** sorting is occurring or not occurring at appropriate times.   This variable
78164** has no function other than to help verify the correct operation of the
78165** library.
78166*/
78167#ifdef SQLITE_TEST
78168SQLITE_API int sqlite3_sort_count = 0;
78169#endif
78170
78171/*
78172** The next global variable records the size of the largest MEM_Blob
78173** or MEM_Str that has been used by a VDBE opcode.  The test procedures
78174** use this information to make sure that the zero-blob functionality
78175** is working correctly.   This variable has no function other than to
78176** help verify the correct operation of the library.
78177*/
78178#ifdef SQLITE_TEST
78179SQLITE_API int sqlite3_max_blobsize = 0;
78180static void updateMaxBlobsize(Mem *p){
78181  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
78182    sqlite3_max_blobsize = p->n;
78183  }
78184}
78185#endif
78186
78187/*
78188** This macro evaluates to true if either the update hook or the preupdate
78189** hook are enabled for database connect DB.
78190*/
78191#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
78192# define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
78193#else
78194# define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
78195#endif
78196
78197/*
78198** The next global variable is incremented each time the OP_Found opcode
78199** is executed. This is used to test whether or not the foreign key
78200** operation implemented using OP_FkIsZero is working. This variable
78201** has no function other than to help verify the correct operation of the
78202** library.
78203*/
78204#ifdef SQLITE_TEST
78205SQLITE_API int sqlite3_found_count = 0;
78206#endif
78207
78208/*
78209** Test a register to see if it exceeds the current maximum blob size.
78210** If it does, record the new maximum blob size.
78211*/
78212#if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
78213# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
78214#else
78215# define UPDATE_MAX_BLOBSIZE(P)
78216#endif
78217
78218/*
78219** Invoke the VDBE coverage callback, if that callback is defined.  This
78220** feature is used for test suite validation only and does not appear an
78221** production builds.
78222**
78223** M is an integer, 2 or 3, that indices how many different ways the
78224** branch can go.  It is usually 2.  "I" is the direction the branch
78225** goes.  0 means falls through.  1 means branch is taken.  2 means the
78226** second alternative branch is taken.
78227**
78228** iSrcLine is the source code line (from the __LINE__ macro) that
78229** generated the VDBE instruction.  This instrumentation assumes that all
78230** source code is in a single file (the amalgamation).  Special values 1
78231** and 2 for the iSrcLine parameter mean that this particular branch is
78232** always taken or never taken, respectively.
78233*/
78234#if !defined(SQLITE_VDBE_COVERAGE)
78235# define VdbeBranchTaken(I,M)
78236#else
78237# define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
78238  static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
78239    if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
78240      M = iSrcLine;
78241      /* Assert the truth of VdbeCoverageAlwaysTaken() and
78242      ** VdbeCoverageNeverTaken() */
78243      assert( (M & I)==I );
78244    }else{
78245      if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
78246      sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
78247                                      iSrcLine,I,M);
78248    }
78249  }
78250#endif
78251
78252/*
78253** Convert the given register into a string if it isn't one
78254** already. Return non-zero if a malloc() fails.
78255*/
78256#define Stringify(P, enc) \
78257   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
78258     { goto no_mem; }
78259
78260/*
78261** An ephemeral string value (signified by the MEM_Ephem flag) contains
78262** a pointer to a dynamically allocated string where some other entity
78263** is responsible for deallocating that string.  Because the register
78264** does not control the string, it might be deleted without the register
78265** knowing it.
78266**
78267** This routine converts an ephemeral string into a dynamically allocated
78268** string that the register itself controls.  In other words, it
78269** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
78270*/
78271#define Deephemeralize(P) \
78272   if( ((P)->flags&MEM_Ephem)!=0 \
78273       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
78274
78275/* Return true if the cursor was opened using the OP_OpenSorter opcode. */
78276#define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
78277
78278/*
78279** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
78280** if we run out of memory.
78281*/
78282static VdbeCursor *allocateCursor(
78283  Vdbe *p,              /* The virtual machine */
78284  int iCur,             /* Index of the new VdbeCursor */
78285  int nField,           /* Number of fields in the table or index */
78286  int iDb,              /* Database the cursor belongs to, or -1 */
78287  u8 eCurType           /* Type of the new cursor */
78288){
78289  /* Find the memory cell that will be used to store the blob of memory
78290  ** required for this VdbeCursor structure. It is convenient to use a
78291  ** vdbe memory cell to manage the memory allocation required for a
78292  ** VdbeCursor structure for the following reasons:
78293  **
78294  **   * Sometimes cursor numbers are used for a couple of different
78295  **     purposes in a vdbe program. The different uses might require
78296  **     different sized allocations. Memory cells provide growable
78297  **     allocations.
78298  **
78299  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
78300  **     be freed lazily via the sqlite3_release_memory() API. This
78301  **     minimizes the number of malloc calls made by the system.
78302  **
78303  ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
78304  ** the top of the register space.  Cursor 1 is at Mem[p->nMem-1].
78305  ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
78306  */
78307  Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
78308
78309  int nByte;
78310  VdbeCursor *pCx = 0;
78311  nByte =
78312      ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
78313      (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
78314
78315  assert( iCur>=0 && iCur<p->nCursor );
78316  if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
78317    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
78318    p->apCsr[iCur] = 0;
78319  }
78320  if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
78321    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
78322    memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
78323    pCx->eCurType = eCurType;
78324    pCx->iDb = iDb;
78325    pCx->nField = nField;
78326    pCx->aOffset = &pCx->aType[nField];
78327    if( eCurType==CURTYPE_BTREE ){
78328      pCx->uc.pCursor = (BtCursor*)
78329          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
78330      sqlite3BtreeCursorZero(pCx->uc.pCursor);
78331    }
78332  }
78333  return pCx;
78334}
78335
78336/*
78337** Try to convert a value into a numeric representation if we can
78338** do so without loss of information.  In other words, if the string
78339** looks like a number, convert it into a number.  If it does not
78340** look like a number, leave it alone.
78341**
78342** If the bTryForInt flag is true, then extra effort is made to give
78343** an integer representation.  Strings that look like floating point
78344** values but which have no fractional component (example: '48.00')
78345** will have a MEM_Int representation when bTryForInt is true.
78346**
78347** If bTryForInt is false, then if the input string contains a decimal
78348** point or exponential notation, the result is only MEM_Real, even
78349** if there is an exact integer representation of the quantity.
78350*/
78351static void applyNumericAffinity(Mem *pRec, int bTryForInt){
78352  double rValue;
78353  i64 iValue;
78354  u8 enc = pRec->enc;
78355  assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
78356  if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
78357  if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
78358    pRec->u.i = iValue;
78359    pRec->flags |= MEM_Int;
78360  }else{
78361    pRec->u.r = rValue;
78362    pRec->flags |= MEM_Real;
78363    if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
78364  }
78365}
78366
78367/*
78368** Processing is determine by the affinity parameter:
78369**
78370** SQLITE_AFF_INTEGER:
78371** SQLITE_AFF_REAL:
78372** SQLITE_AFF_NUMERIC:
78373**    Try to convert pRec to an integer representation or a
78374**    floating-point representation if an integer representation
78375**    is not possible.  Note that the integer representation is
78376**    always preferred, even if the affinity is REAL, because
78377**    an integer representation is more space efficient on disk.
78378**
78379** SQLITE_AFF_TEXT:
78380**    Convert pRec to a text representation.
78381**
78382** SQLITE_AFF_BLOB:
78383**    No-op.  pRec is unchanged.
78384*/
78385static void applyAffinity(
78386  Mem *pRec,          /* The value to apply affinity to */
78387  char affinity,      /* The affinity to be applied */
78388  u8 enc              /* Use this text encoding */
78389){
78390  if( affinity>=SQLITE_AFF_NUMERIC ){
78391    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
78392             || affinity==SQLITE_AFF_NUMERIC );
78393    if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
78394      if( (pRec->flags & MEM_Real)==0 ){
78395        if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
78396      }else{
78397        sqlite3VdbeIntegerAffinity(pRec);
78398      }
78399    }
78400  }else if( affinity==SQLITE_AFF_TEXT ){
78401    /* Only attempt the conversion to TEXT if there is an integer or real
78402    ** representation (blob and NULL do not get converted) but no string
78403    ** representation.  It would be harmless to repeat the conversion if
78404    ** there is already a string rep, but it is pointless to waste those
78405    ** CPU cycles. */
78406    if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
78407      if( (pRec->flags&(MEM_Real|MEM_Int)) ){
78408        sqlite3VdbeMemStringify(pRec, enc, 1);
78409      }
78410    }
78411    pRec->flags &= ~(MEM_Real|MEM_Int);
78412  }
78413}
78414
78415/*
78416** Try to convert the type of a function argument or a result column
78417** into a numeric representation.  Use either INTEGER or REAL whichever
78418** is appropriate.  But only do the conversion if it is possible without
78419** loss of information and return the revised type of the argument.
78420*/
78421SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
78422  int eType = sqlite3_value_type(pVal);
78423  if( eType==SQLITE_TEXT ){
78424    Mem *pMem = (Mem*)pVal;
78425    applyNumericAffinity(pMem, 0);
78426    eType = sqlite3_value_type(pVal);
78427  }
78428  return eType;
78429}
78430
78431/*
78432** Exported version of applyAffinity(). This one works on sqlite3_value*,
78433** not the internal Mem* type.
78434*/
78435SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
78436  sqlite3_value *pVal,
78437  u8 affinity,
78438  u8 enc
78439){
78440  applyAffinity((Mem *)pVal, affinity, enc);
78441}
78442
78443/*
78444** pMem currently only holds a string type (or maybe a BLOB that we can
78445** interpret as a string if we want to).  Compute its corresponding
78446** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
78447** accordingly.
78448*/
78449static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
78450  assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
78451  assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
78452  if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
78453    return 0;
78454  }
78455  if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
78456    return MEM_Int;
78457  }
78458  return MEM_Real;
78459}
78460
78461/*
78462** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
78463** none.
78464**
78465** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
78466** But it does set pMem->u.r and pMem->u.i appropriately.
78467*/
78468static u16 numericType(Mem *pMem){
78469  if( pMem->flags & (MEM_Int|MEM_Real) ){
78470    return pMem->flags & (MEM_Int|MEM_Real);
78471  }
78472  if( pMem->flags & (MEM_Str|MEM_Blob) ){
78473    return computeNumericType(pMem);
78474  }
78475  return 0;
78476}
78477
78478#ifdef SQLITE_DEBUG
78479/*
78480** Write a nice string representation of the contents of cell pMem
78481** into buffer zBuf, length nBuf.
78482*/
78483SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
78484  char *zCsr = zBuf;
78485  int f = pMem->flags;
78486
78487  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
78488
78489  if( f&MEM_Blob ){
78490    int i;
78491    char c;
78492    if( f & MEM_Dyn ){
78493      c = 'z';
78494      assert( (f & (MEM_Static|MEM_Ephem))==0 );
78495    }else if( f & MEM_Static ){
78496      c = 't';
78497      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
78498    }else if( f & MEM_Ephem ){
78499      c = 'e';
78500      assert( (f & (MEM_Static|MEM_Dyn))==0 );
78501    }else{
78502      c = 's';
78503    }
78504    *(zCsr++) = c;
78505    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
78506    zCsr += sqlite3Strlen30(zCsr);
78507    for(i=0; i<16 && i<pMem->n; i++){
78508      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
78509      zCsr += sqlite3Strlen30(zCsr);
78510    }
78511    for(i=0; i<16 && i<pMem->n; i++){
78512      char z = pMem->z[i];
78513      if( z<32 || z>126 ) *zCsr++ = '.';
78514      else *zCsr++ = z;
78515    }
78516    *(zCsr++) = ']';
78517    if( f & MEM_Zero ){
78518      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
78519      zCsr += sqlite3Strlen30(zCsr);
78520    }
78521    *zCsr = '\0';
78522  }else if( f & MEM_Str ){
78523    int j, k;
78524    zBuf[0] = ' ';
78525    if( f & MEM_Dyn ){
78526      zBuf[1] = 'z';
78527      assert( (f & (MEM_Static|MEM_Ephem))==0 );
78528    }else if( f & MEM_Static ){
78529      zBuf[1] = 't';
78530      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
78531    }else if( f & MEM_Ephem ){
78532      zBuf[1] = 'e';
78533      assert( (f & (MEM_Static|MEM_Dyn))==0 );
78534    }else{
78535      zBuf[1] = 's';
78536    }
78537    k = 2;
78538    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
78539    k += sqlite3Strlen30(&zBuf[k]);
78540    zBuf[k++] = '[';
78541    for(j=0; j<15 && j<pMem->n; j++){
78542      u8 c = pMem->z[j];
78543      if( c>=0x20 && c<0x7f ){
78544        zBuf[k++] = c;
78545      }else{
78546        zBuf[k++] = '.';
78547      }
78548    }
78549    zBuf[k++] = ']';
78550    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
78551    k += sqlite3Strlen30(&zBuf[k]);
78552    zBuf[k++] = 0;
78553  }
78554}
78555#endif
78556
78557#ifdef SQLITE_DEBUG
78558/*
78559** Print the value of a register for tracing purposes:
78560*/
78561static void memTracePrint(Mem *p){
78562  if( p->flags & MEM_Undefined ){
78563    printf(" undefined");
78564  }else if( p->flags & MEM_Null ){
78565    printf(" NULL");
78566  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
78567    printf(" si:%lld", p->u.i);
78568  }else if( p->flags & MEM_Int ){
78569    printf(" i:%lld", p->u.i);
78570#ifndef SQLITE_OMIT_FLOATING_POINT
78571  }else if( p->flags & MEM_Real ){
78572    printf(" r:%g", p->u.r);
78573#endif
78574  }else if( p->flags & MEM_RowSet ){
78575    printf(" (rowset)");
78576  }else{
78577    char zBuf[200];
78578    sqlite3VdbeMemPrettyPrint(p, zBuf);
78579    printf(" %s", zBuf);
78580  }
78581  if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
78582}
78583static void registerTrace(int iReg, Mem *p){
78584  printf("REG[%d] = ", iReg);
78585  memTracePrint(p);
78586  printf("\n");
78587}
78588#endif
78589
78590#ifdef SQLITE_DEBUG
78591#  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
78592#else
78593#  define REGISTER_TRACE(R,M)
78594#endif
78595
78596
78597#ifdef VDBE_PROFILE
78598
78599/*
78600** hwtime.h contains inline assembler code for implementing
78601** high-performance timing routines.
78602*/
78603/************** Include hwtime.h in the middle of vdbe.c *********************/
78604/************** Begin file hwtime.h ******************************************/
78605/*
78606** 2008 May 27
78607**
78608** The author disclaims copyright to this source code.  In place of
78609** a legal notice, here is a blessing:
78610**
78611**    May you do good and not evil.
78612**    May you find forgiveness for yourself and forgive others.
78613**    May you share freely, never taking more than you give.
78614**
78615******************************************************************************
78616**
78617** This file contains inline asm code for retrieving "high-performance"
78618** counters for x86 class CPUs.
78619*/
78620#ifndef SQLITE_HWTIME_H
78621#define SQLITE_HWTIME_H
78622
78623/*
78624** The following routine only works on pentium-class (or newer) processors.
78625** It uses the RDTSC opcode to read the cycle count value out of the
78626** processor and returns that value.  This can be used for high-res
78627** profiling.
78628*/
78629#if (defined(__GNUC__) || defined(_MSC_VER)) && \
78630      (defined(i386) || defined(__i386__) || defined(_M_IX86))
78631
78632  #if defined(__GNUC__)
78633
78634  __inline__ sqlite_uint64 sqlite3Hwtime(void){
78635     unsigned int lo, hi;
78636     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
78637     return (sqlite_uint64)hi << 32 | lo;
78638  }
78639
78640  #elif defined(_MSC_VER)
78641
78642  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
78643     __asm {
78644        rdtsc
78645        ret       ; return value at EDX:EAX
78646     }
78647  }
78648
78649  #endif
78650
78651#elif (defined(__GNUC__) && defined(__x86_64__))
78652
78653  __inline__ sqlite_uint64 sqlite3Hwtime(void){
78654      unsigned long val;
78655      __asm__ __volatile__ ("rdtsc" : "=A" (val));
78656      return val;
78657  }
78658
78659#elif (defined(__GNUC__) && defined(__ppc__))
78660
78661  __inline__ sqlite_uint64 sqlite3Hwtime(void){
78662      unsigned long long retval;
78663      unsigned long junk;
78664      __asm__ __volatile__ ("\n\
78665          1:      mftbu   %1\n\
78666                  mftb    %L0\n\
78667                  mftbu   %0\n\
78668                  cmpw    %0,%1\n\
78669                  bne     1b"
78670                  : "=r" (retval), "=r" (junk));
78671      return retval;
78672  }
78673
78674#else
78675
78676  #error Need implementation of sqlite3Hwtime() for your platform.
78677
78678  /*
78679  ** To compile without implementing sqlite3Hwtime() for your platform,
78680  ** you can remove the above #error and use the following
78681  ** stub function.  You will lose timing support for many
78682  ** of the debugging and testing utilities, but it should at
78683  ** least compile and run.
78684  */
78685SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
78686
78687#endif
78688
78689#endif /* !defined(SQLITE_HWTIME_H) */
78690
78691/************** End of hwtime.h **********************************************/
78692/************** Continuing where we left off in vdbe.c ***********************/
78693
78694#endif
78695
78696#ifndef NDEBUG
78697/*
78698** This function is only called from within an assert() expression. It
78699** checks that the sqlite3.nTransaction variable is correctly set to
78700** the number of non-transaction savepoints currently in the
78701** linked list starting at sqlite3.pSavepoint.
78702**
78703** Usage:
78704**
78705**     assert( checkSavepointCount(db) );
78706*/
78707static int checkSavepointCount(sqlite3 *db){
78708  int n = 0;
78709  Savepoint *p;
78710  for(p=db->pSavepoint; p; p=p->pNext) n++;
78711  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
78712  return 1;
78713}
78714#endif
78715
78716/*
78717** Return the register of pOp->p2 after first preparing it to be
78718** overwritten with an integer value.
78719*/
78720static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
78721  sqlite3VdbeMemSetNull(pOut);
78722  pOut->flags = MEM_Int;
78723  return pOut;
78724}
78725static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
78726  Mem *pOut;
78727  assert( pOp->p2>0 );
78728  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
78729  pOut = &p->aMem[pOp->p2];
78730  memAboutToChange(p, pOut);
78731  if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
78732    return out2PrereleaseWithClear(pOut);
78733  }else{
78734    pOut->flags = MEM_Int;
78735    return pOut;
78736  }
78737}
78738
78739
78740/*
78741** Execute as much of a VDBE program as we can.
78742** This is the core of sqlite3_step().
78743*/
78744SQLITE_PRIVATE int sqlite3VdbeExec(
78745  Vdbe *p                    /* The VDBE */
78746){
78747  Op *aOp = p->aOp;          /* Copy of p->aOp */
78748  Op *pOp = aOp;             /* Current operation */
78749#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
78750  Op *pOrigOp;               /* Value of pOp at the top of the loop */
78751#endif
78752#ifdef SQLITE_DEBUG
78753  int nExtraDelete = 0;      /* Verifies FORDELETE and AUXDELETE flags */
78754#endif
78755  int rc = SQLITE_OK;        /* Value to return */
78756  sqlite3 *db = p->db;       /* The database */
78757  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
78758  u8 encoding = ENC(db);     /* The database encoding */
78759  int iCompare = 0;          /* Result of last comparison */
78760  unsigned nVmStep = 0;      /* Number of virtual machine steps */
78761#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
78762  unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
78763#endif
78764  Mem *aMem = p->aMem;       /* Copy of p->aMem */
78765  Mem *pIn1 = 0;             /* 1st input operand */
78766  Mem *pIn2 = 0;             /* 2nd input operand */
78767  Mem *pIn3 = 0;             /* 3rd input operand */
78768  Mem *pOut = 0;             /* Output operand */
78769#ifdef VDBE_PROFILE
78770  u64 start;                 /* CPU clock count at start of opcode */
78771#endif
78772  /*** INSERT STACK UNION HERE ***/
78773
78774  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
78775  sqlite3VdbeEnter(p);
78776  if( p->rc==SQLITE_NOMEM ){
78777    /* This happens if a malloc() inside a call to sqlite3_column_text() or
78778    ** sqlite3_column_text16() failed.  */
78779    goto no_mem;
78780  }
78781  assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
78782  assert( p->bIsReader || p->readOnly!=0 );
78783  p->iCurrentTime = 0;
78784  assert( p->explain==0 );
78785  p->pResultSet = 0;
78786  db->busyHandler.nBusy = 0;
78787  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
78788  sqlite3VdbeIOTraceSql(p);
78789#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
78790  if( db->xProgress ){
78791    u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
78792    assert( 0 < db->nProgressOps );
78793    nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
78794  }
78795#endif
78796#ifdef SQLITE_DEBUG
78797  sqlite3BeginBenignMalloc();
78798  if( p->pc==0
78799   && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
78800  ){
78801    int i;
78802    int once = 1;
78803    sqlite3VdbePrintSql(p);
78804    if( p->db->flags & SQLITE_VdbeListing ){
78805      printf("VDBE Program Listing:\n");
78806      for(i=0; i<p->nOp; i++){
78807        sqlite3VdbePrintOp(stdout, i, &aOp[i]);
78808      }
78809    }
78810    if( p->db->flags & SQLITE_VdbeEQP ){
78811      for(i=0; i<p->nOp; i++){
78812        if( aOp[i].opcode==OP_Explain ){
78813          if( once ) printf("VDBE Query Plan:\n");
78814          printf("%s\n", aOp[i].p4.z);
78815          once = 0;
78816        }
78817      }
78818    }
78819    if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
78820  }
78821  sqlite3EndBenignMalloc();
78822#endif
78823  for(pOp=&aOp[p->pc]; 1; pOp++){
78824    /* Errors are detected by individual opcodes, with an immediate
78825    ** jumps to abort_due_to_error. */
78826    assert( rc==SQLITE_OK );
78827
78828    assert( pOp>=aOp && pOp<&aOp[p->nOp]);
78829#ifdef VDBE_PROFILE
78830    start = sqlite3Hwtime();
78831#endif
78832    nVmStep++;
78833#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
78834    if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
78835#endif
78836
78837    /* Only allow tracing if SQLITE_DEBUG is defined.
78838    */
78839#ifdef SQLITE_DEBUG
78840    if( db->flags & SQLITE_VdbeTrace ){
78841      sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
78842    }
78843#endif
78844
78845
78846    /* Check to see if we need to simulate an interrupt.  This only happens
78847    ** if we have a special test build.
78848    */
78849#ifdef SQLITE_TEST
78850    if( sqlite3_interrupt_count>0 ){
78851      sqlite3_interrupt_count--;
78852      if( sqlite3_interrupt_count==0 ){
78853        sqlite3_interrupt(db);
78854      }
78855    }
78856#endif
78857
78858    /* Sanity checking on other operands */
78859#ifdef SQLITE_DEBUG
78860    {
78861      u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
78862      if( (opProperty & OPFLG_IN1)!=0 ){
78863        assert( pOp->p1>0 );
78864        assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
78865        assert( memIsValid(&aMem[pOp->p1]) );
78866        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
78867        REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
78868      }
78869      if( (opProperty & OPFLG_IN2)!=0 ){
78870        assert( pOp->p2>0 );
78871        assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
78872        assert( memIsValid(&aMem[pOp->p2]) );
78873        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
78874        REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
78875      }
78876      if( (opProperty & OPFLG_IN3)!=0 ){
78877        assert( pOp->p3>0 );
78878        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78879        assert( memIsValid(&aMem[pOp->p3]) );
78880        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
78881        REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
78882      }
78883      if( (opProperty & OPFLG_OUT2)!=0 ){
78884        assert( pOp->p2>0 );
78885        assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
78886        memAboutToChange(p, &aMem[pOp->p2]);
78887      }
78888      if( (opProperty & OPFLG_OUT3)!=0 ){
78889        assert( pOp->p3>0 );
78890        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78891        memAboutToChange(p, &aMem[pOp->p3]);
78892      }
78893    }
78894#endif
78895#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
78896    pOrigOp = pOp;
78897#endif
78898
78899    switch( pOp->opcode ){
78900
78901/*****************************************************************************
78902** What follows is a massive switch statement where each case implements a
78903** separate instruction in the virtual machine.  If we follow the usual
78904** indentation conventions, each case should be indented by 6 spaces.  But
78905** that is a lot of wasted space on the left margin.  So the code within
78906** the switch statement will break with convention and be flush-left. Another
78907** big comment (similar to this one) will mark the point in the code where
78908** we transition back to normal indentation.
78909**
78910** The formatting of each case is important.  The makefile for SQLite
78911** generates two C files "opcodes.h" and "opcodes.c" by scanning this
78912** file looking for lines that begin with "case OP_".  The opcodes.h files
78913** will be filled with #defines that give unique integer values to each
78914** opcode and the opcodes.c file is filled with an array of strings where
78915** each string is the symbolic name for the corresponding opcode.  If the
78916** case statement is followed by a comment of the form "/# same as ... #/"
78917** that comment is used to determine the particular value of the opcode.
78918**
78919** Other keywords in the comment that follows each case are used to
78920** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
78921** Keywords include: in1, in2, in3, out2, out3.  See
78922** the mkopcodeh.awk script for additional information.
78923**
78924** Documentation about VDBE opcodes is generated by scanning this file
78925** for lines of that contain "Opcode:".  That line and all subsequent
78926** comment lines are used in the generation of the opcode.html documentation
78927** file.
78928**
78929** SUMMARY:
78930**
78931**     Formatting is important to scripts that scan this file.
78932**     Do not deviate from the formatting style currently in use.
78933**
78934*****************************************************************************/
78935
78936/* Opcode:  Goto * P2 * * *
78937**
78938** An unconditional jump to address P2.
78939** The next instruction executed will be
78940** the one at index P2 from the beginning of
78941** the program.
78942**
78943** The P1 parameter is not actually used by this opcode.  However, it
78944** is sometimes set to 1 instead of 0 as a hint to the command-line shell
78945** that this Goto is the bottom of a loop and that the lines from P2 down
78946** to the current line should be indented for EXPLAIN output.
78947*/
78948case OP_Goto: {             /* jump */
78949jump_to_p2_and_check_for_interrupt:
78950  pOp = &aOp[pOp->p2 - 1];
78951
78952  /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
78953  ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
78954  ** completion.  Check to see if sqlite3_interrupt() has been called
78955  ** or if the progress callback needs to be invoked.
78956  **
78957  ** This code uses unstructured "goto" statements and does not look clean.
78958  ** But that is not due to sloppy coding habits. The code is written this
78959  ** way for performance, to avoid having to run the interrupt and progress
78960  ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
78961  ** faster according to "valgrind --tool=cachegrind" */
78962check_for_interrupt:
78963  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
78964#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
78965  /* Call the progress callback if it is configured and the required number
78966  ** of VDBE ops have been executed (either since this invocation of
78967  ** sqlite3VdbeExec() or since last time the progress callback was called).
78968  ** If the progress callback returns non-zero, exit the virtual machine with
78969  ** a return code SQLITE_ABORT.
78970  */
78971  if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
78972    assert( db->nProgressOps!=0 );
78973    nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
78974    if( db->xProgress(db->pProgressArg) ){
78975      rc = SQLITE_INTERRUPT;
78976      goto abort_due_to_error;
78977    }
78978  }
78979#endif
78980
78981  break;
78982}
78983
78984/* Opcode:  Gosub P1 P2 * * *
78985**
78986** Write the current address onto register P1
78987** and then jump to address P2.
78988*/
78989case OP_Gosub: {            /* jump */
78990  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
78991  pIn1 = &aMem[pOp->p1];
78992  assert( VdbeMemDynamic(pIn1)==0 );
78993  memAboutToChange(p, pIn1);
78994  pIn1->flags = MEM_Int;
78995  pIn1->u.i = (int)(pOp-aOp);
78996  REGISTER_TRACE(pOp->p1, pIn1);
78997
78998  /* Most jump operations do a goto to this spot in order to update
78999  ** the pOp pointer. */
79000jump_to_p2:
79001  pOp = &aOp[pOp->p2 - 1];
79002  break;
79003}
79004
79005/* Opcode:  Return P1 * * * *
79006**
79007** Jump to the next instruction after the address in register P1.  After
79008** the jump, register P1 becomes undefined.
79009*/
79010case OP_Return: {           /* in1 */
79011  pIn1 = &aMem[pOp->p1];
79012  assert( pIn1->flags==MEM_Int );
79013  pOp = &aOp[pIn1->u.i];
79014  pIn1->flags = MEM_Undefined;
79015  break;
79016}
79017
79018/* Opcode: InitCoroutine P1 P2 P3 * *
79019**
79020** Set up register P1 so that it will Yield to the coroutine
79021** located at address P3.
79022**
79023** If P2!=0 then the coroutine implementation immediately follows
79024** this opcode.  So jump over the coroutine implementation to
79025** address P2.
79026**
79027** See also: EndCoroutine
79028*/
79029case OP_InitCoroutine: {     /* jump */
79030  assert( pOp->p1>0 &&  pOp->p1<=(p->nMem+1 - p->nCursor) );
79031  assert( pOp->p2>=0 && pOp->p2<p->nOp );
79032  assert( pOp->p3>=0 && pOp->p3<p->nOp );
79033  pOut = &aMem[pOp->p1];
79034  assert( !VdbeMemDynamic(pOut) );
79035  pOut->u.i = pOp->p3 - 1;
79036  pOut->flags = MEM_Int;
79037  if( pOp->p2 ) goto jump_to_p2;
79038  break;
79039}
79040
79041/* Opcode:  EndCoroutine P1 * * * *
79042**
79043** The instruction at the address in register P1 is a Yield.
79044** Jump to the P2 parameter of that Yield.
79045** After the jump, register P1 becomes undefined.
79046**
79047** See also: InitCoroutine
79048*/
79049case OP_EndCoroutine: {           /* in1 */
79050  VdbeOp *pCaller;
79051  pIn1 = &aMem[pOp->p1];
79052  assert( pIn1->flags==MEM_Int );
79053  assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
79054  pCaller = &aOp[pIn1->u.i];
79055  assert( pCaller->opcode==OP_Yield );
79056  assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
79057  pOp = &aOp[pCaller->p2 - 1];
79058  pIn1->flags = MEM_Undefined;
79059  break;
79060}
79061
79062/* Opcode:  Yield P1 P2 * * *
79063**
79064** Swap the program counter with the value in register P1.  This
79065** has the effect of yielding to a coroutine.
79066**
79067** If the coroutine that is launched by this instruction ends with
79068** Yield or Return then continue to the next instruction.  But if
79069** the coroutine launched by this instruction ends with
79070** EndCoroutine, then jump to P2 rather than continuing with the
79071** next instruction.
79072**
79073** See also: InitCoroutine
79074*/
79075case OP_Yield: {            /* in1, jump */
79076  int pcDest;
79077  pIn1 = &aMem[pOp->p1];
79078  assert( VdbeMemDynamic(pIn1)==0 );
79079  pIn1->flags = MEM_Int;
79080  pcDest = (int)pIn1->u.i;
79081  pIn1->u.i = (int)(pOp - aOp);
79082  REGISTER_TRACE(pOp->p1, pIn1);
79083  pOp = &aOp[pcDest];
79084  break;
79085}
79086
79087/* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
79088** Synopsis: if r[P3]=null halt
79089**
79090** Check the value in register P3.  If it is NULL then Halt using
79091** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
79092** value in register P3 is not NULL, then this routine is a no-op.
79093** The P5 parameter should be 1.
79094*/
79095case OP_HaltIfNull: {      /* in3 */
79096  pIn3 = &aMem[pOp->p3];
79097  if( (pIn3->flags & MEM_Null)==0 ) break;
79098  /* Fall through into OP_Halt */
79099}
79100
79101/* Opcode:  Halt P1 P2 * P4 P5
79102**
79103** Exit immediately.  All open cursors, etc are closed
79104** automatically.
79105**
79106** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
79107** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
79108** For errors, it can be some other value.  If P1!=0 then P2 will determine
79109** whether or not to rollback the current transaction.  Do not rollback
79110** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
79111** then back out all changes that have occurred during this execution of the
79112** VDBE, but do not rollback the transaction.
79113**
79114** If P4 is not null then it is an error message string.
79115**
79116** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
79117**
79118**    0:  (no change)
79119**    1:  NOT NULL contraint failed: P4
79120**    2:  UNIQUE constraint failed: P4
79121**    3:  CHECK constraint failed: P4
79122**    4:  FOREIGN KEY constraint failed: P4
79123**
79124** If P5 is not zero and P4 is NULL, then everything after the ":" is
79125** omitted.
79126**
79127** There is an implied "Halt 0 0 0" instruction inserted at the very end of
79128** every program.  So a jump past the last instruction of the program
79129** is the same as executing Halt.
79130*/
79131case OP_Halt: {
79132  VdbeFrame *pFrame;
79133  int pcx;
79134
79135  pcx = (int)(pOp - aOp);
79136  if( pOp->p1==SQLITE_OK && p->pFrame ){
79137    /* Halt the sub-program. Return control to the parent frame. */
79138    pFrame = p->pFrame;
79139    p->pFrame = pFrame->pParent;
79140    p->nFrame--;
79141    sqlite3VdbeSetChanges(db, p->nChange);
79142    pcx = sqlite3VdbeFrameRestore(pFrame);
79143    if( pOp->p2==OE_Ignore ){
79144      /* Instruction pcx is the OP_Program that invoked the sub-program
79145      ** currently being halted. If the p2 instruction of this OP_Halt
79146      ** instruction is set to OE_Ignore, then the sub-program is throwing
79147      ** an IGNORE exception. In this case jump to the address specified
79148      ** as the p2 of the calling OP_Program.  */
79149      pcx = p->aOp[pcx].p2-1;
79150    }
79151    aOp = p->aOp;
79152    aMem = p->aMem;
79153    pOp = &aOp[pcx];
79154    break;
79155  }
79156  p->rc = pOp->p1;
79157  p->errorAction = (u8)pOp->p2;
79158  p->pc = pcx;
79159  assert( pOp->p5<=4 );
79160  if( p->rc ){
79161    if( pOp->p5 ){
79162      static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
79163                                             "FOREIGN KEY" };
79164      testcase( pOp->p5==1 );
79165      testcase( pOp->p5==2 );
79166      testcase( pOp->p5==3 );
79167      testcase( pOp->p5==4 );
79168      sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
79169      if( pOp->p4.z ){
79170        p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
79171      }
79172    }else{
79173      sqlite3VdbeError(p, "%s", pOp->p4.z);
79174    }
79175    sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
79176  }
79177  rc = sqlite3VdbeHalt(p);
79178  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
79179  if( rc==SQLITE_BUSY ){
79180    p->rc = SQLITE_BUSY;
79181  }else{
79182    assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
79183    assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
79184    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
79185  }
79186  goto vdbe_return;
79187}
79188
79189/* Opcode: Integer P1 P2 * * *
79190** Synopsis: r[P2]=P1
79191**
79192** The 32-bit integer value P1 is written into register P2.
79193*/
79194case OP_Integer: {         /* out2 */
79195  pOut = out2Prerelease(p, pOp);
79196  pOut->u.i = pOp->p1;
79197  break;
79198}
79199
79200/* Opcode: Int64 * P2 * P4 *
79201** Synopsis: r[P2]=P4
79202**
79203** P4 is a pointer to a 64-bit integer value.
79204** Write that value into register P2.
79205*/
79206case OP_Int64: {           /* out2 */
79207  pOut = out2Prerelease(p, pOp);
79208  assert( pOp->p4.pI64!=0 );
79209  pOut->u.i = *pOp->p4.pI64;
79210  break;
79211}
79212
79213#ifndef SQLITE_OMIT_FLOATING_POINT
79214/* Opcode: Real * P2 * P4 *
79215** Synopsis: r[P2]=P4
79216**
79217** P4 is a pointer to a 64-bit floating point value.
79218** Write that value into register P2.
79219*/
79220case OP_Real: {            /* same as TK_FLOAT, out2 */
79221  pOut = out2Prerelease(p, pOp);
79222  pOut->flags = MEM_Real;
79223  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
79224  pOut->u.r = *pOp->p4.pReal;
79225  break;
79226}
79227#endif
79228
79229/* Opcode: String8 * P2 * P4 *
79230** Synopsis: r[P2]='P4'
79231**
79232** P4 points to a nul terminated UTF-8 string. This opcode is transformed
79233** into a String opcode before it is executed for the first time.  During
79234** this transformation, the length of string P4 is computed and stored
79235** as the P1 parameter.
79236*/
79237case OP_String8: {         /* same as TK_STRING, out2 */
79238  assert( pOp->p4.z!=0 );
79239  pOut = out2Prerelease(p, pOp);
79240  pOp->opcode = OP_String;
79241  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
79242
79243#ifndef SQLITE_OMIT_UTF16
79244  if( encoding!=SQLITE_UTF8 ){
79245    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
79246    assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
79247    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
79248    assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
79249    assert( VdbeMemDynamic(pOut)==0 );
79250    pOut->szMalloc = 0;
79251    pOut->flags |= MEM_Static;
79252    if( pOp->p4type==P4_DYNAMIC ){
79253      sqlite3DbFree(db, pOp->p4.z);
79254    }
79255    pOp->p4type = P4_DYNAMIC;
79256    pOp->p4.z = pOut->z;
79257    pOp->p1 = pOut->n;
79258  }
79259  testcase( rc==SQLITE_TOOBIG );
79260#endif
79261  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
79262    goto too_big;
79263  }
79264  assert( rc==SQLITE_OK );
79265  /* Fall through to the next case, OP_String */
79266}
79267
79268/* Opcode: String P1 P2 P3 P4 P5
79269** Synopsis: r[P2]='P4' (len=P1)
79270**
79271** The string value P4 of length P1 (bytes) is stored in register P2.
79272**
79273** If P3 is not zero and the content of register P3 is equal to P5, then
79274** the datatype of the register P2 is converted to BLOB.  The content is
79275** the same sequence of bytes, it is merely interpreted as a BLOB instead
79276** of a string, as if it had been CAST.  In other words:
79277**
79278** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
79279*/
79280case OP_String: {          /* out2 */
79281  assert( pOp->p4.z!=0 );
79282  pOut = out2Prerelease(p, pOp);
79283  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
79284  pOut->z = pOp->p4.z;
79285  pOut->n = pOp->p1;
79286  pOut->enc = encoding;
79287  UPDATE_MAX_BLOBSIZE(pOut);
79288#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
79289  if( pOp->p3>0 ){
79290    assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
79291    pIn3 = &aMem[pOp->p3];
79292    assert( pIn3->flags & MEM_Int );
79293    if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
79294  }
79295#endif
79296  break;
79297}
79298
79299/* Opcode: Null P1 P2 P3 * *
79300** Synopsis: r[P2..P3]=NULL
79301**
79302** Write a NULL into registers P2.  If P3 greater than P2, then also write
79303** NULL into register P3 and every register in between P2 and P3.  If P3
79304** is less than P2 (typically P3 is zero) then only register P2 is
79305** set to NULL.
79306**
79307** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
79308** NULL values will not compare equal even if SQLITE_NULLEQ is set on
79309** OP_Ne or OP_Eq.
79310*/
79311case OP_Null: {           /* out2 */
79312  int cnt;
79313  u16 nullFlag;
79314  pOut = out2Prerelease(p, pOp);
79315  cnt = pOp->p3-pOp->p2;
79316  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
79317  pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
79318  pOut->n = 0;
79319  while( cnt>0 ){
79320    pOut++;
79321    memAboutToChange(p, pOut);
79322    sqlite3VdbeMemSetNull(pOut);
79323    pOut->flags = nullFlag;
79324    pOut->n = 0;
79325    cnt--;
79326  }
79327  break;
79328}
79329
79330/* Opcode: SoftNull P1 * * * *
79331** Synopsis: r[P1]=NULL
79332**
79333** Set register P1 to have the value NULL as seen by the OP_MakeRecord
79334** instruction, but do not free any string or blob memory associated with
79335** the register, so that if the value was a string or blob that was
79336** previously copied using OP_SCopy, the copies will continue to be valid.
79337*/
79338case OP_SoftNull: {
79339  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
79340  pOut = &aMem[pOp->p1];
79341  pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
79342  break;
79343}
79344
79345/* Opcode: Blob P1 P2 * P4 *
79346** Synopsis: r[P2]=P4 (len=P1)
79347**
79348** P4 points to a blob of data P1 bytes long.  Store this
79349** blob in register P2.
79350*/
79351case OP_Blob: {                /* out2 */
79352  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
79353  pOut = out2Prerelease(p, pOp);
79354  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
79355  pOut->enc = encoding;
79356  UPDATE_MAX_BLOBSIZE(pOut);
79357  break;
79358}
79359
79360/* Opcode: Variable P1 P2 * P4 *
79361** Synopsis: r[P2]=parameter(P1,P4)
79362**
79363** Transfer the values of bound parameter P1 into register P2
79364**
79365** If the parameter is named, then its name appears in P4.
79366** The P4 value is used by sqlite3_bind_parameter_name().
79367*/
79368case OP_Variable: {            /* out2 */
79369  Mem *pVar;       /* Value being transferred */
79370
79371  assert( pOp->p1>0 && pOp->p1<=p->nVar );
79372  assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
79373  pVar = &p->aVar[pOp->p1 - 1];
79374  if( sqlite3VdbeMemTooBig(pVar) ){
79375    goto too_big;
79376  }
79377  pOut = &aMem[pOp->p2];
79378  sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
79379  UPDATE_MAX_BLOBSIZE(pOut);
79380  break;
79381}
79382
79383/* Opcode: Move P1 P2 P3 * *
79384** Synopsis: r[P2@P3]=r[P1@P3]
79385**
79386** Move the P3 values in register P1..P1+P3-1 over into
79387** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
79388** left holding a NULL.  It is an error for register ranges
79389** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
79390** for P3 to be less than 1.
79391*/
79392case OP_Move: {
79393  int n;           /* Number of registers left to copy */
79394  int p1;          /* Register to copy from */
79395  int p2;          /* Register to copy to */
79396
79397  n = pOp->p3;
79398  p1 = pOp->p1;
79399  p2 = pOp->p2;
79400  assert( n>0 && p1>0 && p2>0 );
79401  assert( p1+n<=p2 || p2+n<=p1 );
79402
79403  pIn1 = &aMem[p1];
79404  pOut = &aMem[p2];
79405  do{
79406    assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
79407    assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
79408    assert( memIsValid(pIn1) );
79409    memAboutToChange(p, pOut);
79410    sqlite3VdbeMemMove(pOut, pIn1);
79411#ifdef SQLITE_DEBUG
79412    if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
79413      pOut->pScopyFrom += pOp->p2 - p1;
79414    }
79415#endif
79416    Deephemeralize(pOut);
79417    REGISTER_TRACE(p2++, pOut);
79418    pIn1++;
79419    pOut++;
79420  }while( --n );
79421  break;
79422}
79423
79424/* Opcode: Copy P1 P2 P3 * *
79425** Synopsis: r[P2@P3+1]=r[P1@P3+1]
79426**
79427** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
79428**
79429** This instruction makes a deep copy of the value.  A duplicate
79430** is made of any string or blob constant.  See also OP_SCopy.
79431*/
79432case OP_Copy: {
79433  int n;
79434
79435  n = pOp->p3;
79436  pIn1 = &aMem[pOp->p1];
79437  pOut = &aMem[pOp->p2];
79438  assert( pOut!=pIn1 );
79439  while( 1 ){
79440    sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
79441    Deephemeralize(pOut);
79442#ifdef SQLITE_DEBUG
79443    pOut->pScopyFrom = 0;
79444#endif
79445    REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
79446    if( (n--)==0 ) break;
79447    pOut++;
79448    pIn1++;
79449  }
79450  break;
79451}
79452
79453/* Opcode: SCopy P1 P2 * * *
79454** Synopsis: r[P2]=r[P1]
79455**
79456** Make a shallow copy of register P1 into register P2.
79457**
79458** This instruction makes a shallow copy of the value.  If the value
79459** is a string or blob, then the copy is only a pointer to the
79460** original and hence if the original changes so will the copy.
79461** Worse, if the original is deallocated, the copy becomes invalid.
79462** Thus the program must guarantee that the original will not change
79463** during the lifetime of the copy.  Use OP_Copy to make a complete
79464** copy.
79465*/
79466case OP_SCopy: {            /* out2 */
79467  pIn1 = &aMem[pOp->p1];
79468  pOut = &aMem[pOp->p2];
79469  assert( pOut!=pIn1 );
79470  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
79471#ifdef SQLITE_DEBUG
79472  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
79473#endif
79474  break;
79475}
79476
79477/* Opcode: IntCopy P1 P2 * * *
79478** Synopsis: r[P2]=r[P1]
79479**
79480** Transfer the integer value held in register P1 into register P2.
79481**
79482** This is an optimized version of SCopy that works only for integer
79483** values.
79484*/
79485case OP_IntCopy: {            /* out2 */
79486  pIn1 = &aMem[pOp->p1];
79487  assert( (pIn1->flags & MEM_Int)!=0 );
79488  pOut = &aMem[pOp->p2];
79489  sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
79490  break;
79491}
79492
79493/* Opcode: ResultRow P1 P2 * * *
79494** Synopsis: output=r[P1@P2]
79495**
79496** The registers P1 through P1+P2-1 contain a single row of
79497** results. This opcode causes the sqlite3_step() call to terminate
79498** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
79499** structure to provide access to the r(P1)..r(P1+P2-1) values as
79500** the result row.
79501*/
79502case OP_ResultRow: {
79503  Mem *pMem;
79504  int i;
79505  assert( p->nResColumn==pOp->p2 );
79506  assert( pOp->p1>0 );
79507  assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
79508
79509#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
79510  /* Run the progress counter just before returning.
79511  */
79512  if( db->xProgress!=0
79513   && nVmStep>=nProgressLimit
79514   && db->xProgress(db->pProgressArg)!=0
79515  ){
79516    rc = SQLITE_INTERRUPT;
79517    goto abort_due_to_error;
79518  }
79519#endif
79520
79521  /* If this statement has violated immediate foreign key constraints, do
79522  ** not return the number of rows modified. And do not RELEASE the statement
79523  ** transaction. It needs to be rolled back.  */
79524  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
79525    assert( db->flags&SQLITE_CountRows );
79526    assert( p->usesStmtJournal );
79527    goto abort_due_to_error;
79528  }
79529
79530  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
79531  ** DML statements invoke this opcode to return the number of rows
79532  ** modified to the user. This is the only way that a VM that
79533  ** opens a statement transaction may invoke this opcode.
79534  **
79535  ** In case this is such a statement, close any statement transaction
79536  ** opened by this VM before returning control to the user. This is to
79537  ** ensure that statement-transactions are always nested, not overlapping.
79538  ** If the open statement-transaction is not closed here, then the user
79539  ** may step another VM that opens its own statement transaction. This
79540  ** may lead to overlapping statement transactions.
79541  **
79542  ** The statement transaction is never a top-level transaction.  Hence
79543  ** the RELEASE call below can never fail.
79544  */
79545  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
79546  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
79547  assert( rc==SQLITE_OK );
79548
79549  /* Invalidate all ephemeral cursor row caches */
79550  p->cacheCtr = (p->cacheCtr + 2)|1;
79551
79552  /* Make sure the results of the current row are \000 terminated
79553  ** and have an assigned type.  The results are de-ephemeralized as
79554  ** a side effect.
79555  */
79556  pMem = p->pResultSet = &aMem[pOp->p1];
79557  for(i=0; i<pOp->p2; i++){
79558    assert( memIsValid(&pMem[i]) );
79559    Deephemeralize(&pMem[i]);
79560    assert( (pMem[i].flags & MEM_Ephem)==0
79561            || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
79562    sqlite3VdbeMemNulTerminate(&pMem[i]);
79563    REGISTER_TRACE(pOp->p1+i, &pMem[i]);
79564  }
79565  if( db->mallocFailed ) goto no_mem;
79566
79567  if( db->mTrace & SQLITE_TRACE_ROW ){
79568    db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
79569  }
79570
79571  /* Return SQLITE_ROW
79572  */
79573  p->pc = (int)(pOp - aOp) + 1;
79574  rc = SQLITE_ROW;
79575  goto vdbe_return;
79576}
79577
79578/* Opcode: Concat P1 P2 P3 * *
79579** Synopsis: r[P3]=r[P2]+r[P1]
79580**
79581** Add the text in register P1 onto the end of the text in
79582** register P2 and store the result in register P3.
79583** If either the P1 or P2 text are NULL then store NULL in P3.
79584**
79585**   P3 = P2 || P1
79586**
79587** It is illegal for P1 and P3 to be the same register. Sometimes,
79588** if P3 is the same register as P2, the implementation is able
79589** to avoid a memcpy().
79590*/
79591case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
79592  i64 nByte;
79593
79594  pIn1 = &aMem[pOp->p1];
79595  pIn2 = &aMem[pOp->p2];
79596  pOut = &aMem[pOp->p3];
79597  assert( pIn1!=pOut );
79598  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
79599    sqlite3VdbeMemSetNull(pOut);
79600    break;
79601  }
79602  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
79603  Stringify(pIn1, encoding);
79604  Stringify(pIn2, encoding);
79605  nByte = pIn1->n + pIn2->n;
79606  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
79607    goto too_big;
79608  }
79609  if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
79610    goto no_mem;
79611  }
79612  MemSetTypeFlag(pOut, MEM_Str);
79613  if( pOut!=pIn2 ){
79614    memcpy(pOut->z, pIn2->z, pIn2->n);
79615  }
79616  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
79617  pOut->z[nByte]=0;
79618  pOut->z[nByte+1] = 0;
79619  pOut->flags |= MEM_Term;
79620  pOut->n = (int)nByte;
79621  pOut->enc = encoding;
79622  UPDATE_MAX_BLOBSIZE(pOut);
79623  break;
79624}
79625
79626/* Opcode: Add P1 P2 P3 * *
79627** Synopsis: r[P3]=r[P1]+r[P2]
79628**
79629** Add the value in register P1 to the value in register P2
79630** and store the result in register P3.
79631** If either input is NULL, the result is NULL.
79632*/
79633/* Opcode: Multiply P1 P2 P3 * *
79634** Synopsis: r[P3]=r[P1]*r[P2]
79635**
79636**
79637** Multiply the value in register P1 by the value in register P2
79638** and store the result in register P3.
79639** If either input is NULL, the result is NULL.
79640*/
79641/* Opcode: Subtract P1 P2 P3 * *
79642** Synopsis: r[P3]=r[P2]-r[P1]
79643**
79644** Subtract the value in register P1 from the value in register P2
79645** and store the result in register P3.
79646** If either input is NULL, the result is NULL.
79647*/
79648/* Opcode: Divide P1 P2 P3 * *
79649** Synopsis: r[P3]=r[P2]/r[P1]
79650**
79651** Divide the value in register P1 by the value in register P2
79652** and store the result in register P3 (P3=P2/P1). If the value in
79653** register P1 is zero, then the result is NULL. If either input is
79654** NULL, the result is NULL.
79655*/
79656/* Opcode: Remainder P1 P2 P3 * *
79657** Synopsis: r[P3]=r[P2]%r[P1]
79658**
79659** Compute the remainder after integer register P2 is divided by
79660** register P1 and store the result in register P3.
79661** If the value in register P1 is zero the result is NULL.
79662** If either operand is NULL, the result is NULL.
79663*/
79664case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
79665case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
79666case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
79667case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
79668case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
79669  char bIntint;   /* Started out as two integer operands */
79670  u16 flags;      /* Combined MEM_* flags from both inputs */
79671  u16 type1;      /* Numeric type of left operand */
79672  u16 type2;      /* Numeric type of right operand */
79673  i64 iA;         /* Integer value of left operand */
79674  i64 iB;         /* Integer value of right operand */
79675  double rA;      /* Real value of left operand */
79676  double rB;      /* Real value of right operand */
79677
79678  pIn1 = &aMem[pOp->p1];
79679  type1 = numericType(pIn1);
79680  pIn2 = &aMem[pOp->p2];
79681  type2 = numericType(pIn2);
79682  pOut = &aMem[pOp->p3];
79683  flags = pIn1->flags | pIn2->flags;
79684  if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
79685  if( (type1 & type2 & MEM_Int)!=0 ){
79686    iA = pIn1->u.i;
79687    iB = pIn2->u.i;
79688    bIntint = 1;
79689    switch( pOp->opcode ){
79690      case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
79691      case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
79692      case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
79693      case OP_Divide: {
79694        if( iA==0 ) goto arithmetic_result_is_null;
79695        if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
79696        iB /= iA;
79697        break;
79698      }
79699      default: {
79700        if( iA==0 ) goto arithmetic_result_is_null;
79701        if( iA==-1 ) iA = 1;
79702        iB %= iA;
79703        break;
79704      }
79705    }
79706    pOut->u.i = iB;
79707    MemSetTypeFlag(pOut, MEM_Int);
79708  }else{
79709    bIntint = 0;
79710fp_math:
79711    rA = sqlite3VdbeRealValue(pIn1);
79712    rB = sqlite3VdbeRealValue(pIn2);
79713    switch( pOp->opcode ){
79714      case OP_Add:         rB += rA;       break;
79715      case OP_Subtract:    rB -= rA;       break;
79716      case OP_Multiply:    rB *= rA;       break;
79717      case OP_Divide: {
79718        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
79719        if( rA==(double)0 ) goto arithmetic_result_is_null;
79720        rB /= rA;
79721        break;
79722      }
79723      default: {
79724        iA = (i64)rA;
79725        iB = (i64)rB;
79726        if( iA==0 ) goto arithmetic_result_is_null;
79727        if( iA==-1 ) iA = 1;
79728        rB = (double)(iB % iA);
79729        break;
79730      }
79731    }
79732#ifdef SQLITE_OMIT_FLOATING_POINT
79733    pOut->u.i = rB;
79734    MemSetTypeFlag(pOut, MEM_Int);
79735#else
79736    if( sqlite3IsNaN(rB) ){
79737      goto arithmetic_result_is_null;
79738    }
79739    pOut->u.r = rB;
79740    MemSetTypeFlag(pOut, MEM_Real);
79741    if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
79742      sqlite3VdbeIntegerAffinity(pOut);
79743    }
79744#endif
79745  }
79746  break;
79747
79748arithmetic_result_is_null:
79749  sqlite3VdbeMemSetNull(pOut);
79750  break;
79751}
79752
79753/* Opcode: CollSeq P1 * * P4
79754**
79755** P4 is a pointer to a CollSeq struct. If the next call to a user function
79756** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
79757** be returned. This is used by the built-in min(), max() and nullif()
79758** functions.
79759**
79760** If P1 is not zero, then it is a register that a subsequent min() or
79761** max() aggregate will set to 1 if the current row is not the minimum or
79762** maximum.  The P1 register is initialized to 0 by this instruction.
79763**
79764** The interface used by the implementation of the aforementioned functions
79765** to retrieve the collation sequence set by this opcode is not available
79766** publicly.  Only built-in functions have access to this feature.
79767*/
79768case OP_CollSeq: {
79769  assert( pOp->p4type==P4_COLLSEQ );
79770  if( pOp->p1 ){
79771    sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
79772  }
79773  break;
79774}
79775
79776/* Opcode: Function0 P1 P2 P3 P4 P5
79777** Synopsis: r[P3]=func(r[P2@P5])
79778**
79779** Invoke a user function (P4 is a pointer to a FuncDef object that
79780** defines the function) with P5 arguments taken from register P2 and
79781** successors.  The result of the function is stored in register P3.
79782** Register P3 must not be one of the function inputs.
79783**
79784** P1 is a 32-bit bitmask indicating whether or not each argument to the
79785** function was determined to be constant at compile time. If the first
79786** argument was constant then bit 0 of P1 is set. This is used to determine
79787** whether meta data associated with a user function argument using the
79788** sqlite3_set_auxdata() API may be safely retained until the next
79789** invocation of this opcode.
79790**
79791** See also: Function, AggStep, AggFinal
79792*/
79793/* Opcode: Function P1 P2 P3 P4 P5
79794** Synopsis: r[P3]=func(r[P2@P5])
79795**
79796** Invoke a user function (P4 is a pointer to an sqlite3_context object that
79797** contains a pointer to the function to be run) with P5 arguments taken
79798** from register P2 and successors.  The result of the function is stored
79799** in register P3.  Register P3 must not be one of the function inputs.
79800**
79801** P1 is a 32-bit bitmask indicating whether or not each argument to the
79802** function was determined to be constant at compile time. If the first
79803** argument was constant then bit 0 of P1 is set. This is used to determine
79804** whether meta data associated with a user function argument using the
79805** sqlite3_set_auxdata() API may be safely retained until the next
79806** invocation of this opcode.
79807**
79808** SQL functions are initially coded as OP_Function0 with P4 pointing
79809** to a FuncDef object.  But on first evaluation, the P4 operand is
79810** automatically converted into an sqlite3_context object and the operation
79811** changed to this OP_Function opcode.  In this way, the initialization of
79812** the sqlite3_context object occurs only once, rather than once for each
79813** evaluation of the function.
79814**
79815** See also: Function0, AggStep, AggFinal
79816*/
79817case OP_Function0: {
79818  int n;
79819  sqlite3_context *pCtx;
79820
79821  assert( pOp->p4type==P4_FUNCDEF );
79822  n = pOp->p5;
79823  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
79824  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
79825  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
79826  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
79827  if( pCtx==0 ) goto no_mem;
79828  pCtx->pOut = 0;
79829  pCtx->pFunc = pOp->p4.pFunc;
79830  pCtx->iOp = (int)(pOp - aOp);
79831  pCtx->pVdbe = p;
79832  pCtx->argc = n;
79833  pOp->p4type = P4_FUNCCTX;
79834  pOp->p4.pCtx = pCtx;
79835  pOp->opcode = OP_Function;
79836  /* Fall through into OP_Function */
79837}
79838case OP_Function: {
79839  int i;
79840  sqlite3_context *pCtx;
79841
79842  assert( pOp->p4type==P4_FUNCCTX );
79843  pCtx = pOp->p4.pCtx;
79844
79845  /* If this function is inside of a trigger, the register array in aMem[]
79846  ** might change from one evaluation to the next.  The next block of code
79847  ** checks to see if the register array has changed, and if so it
79848  ** reinitializes the relavant parts of the sqlite3_context object */
79849  pOut = &aMem[pOp->p3];
79850  if( pCtx->pOut != pOut ){
79851    pCtx->pOut = pOut;
79852    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
79853  }
79854
79855  memAboutToChange(p, pOut);
79856#ifdef SQLITE_DEBUG
79857  for(i=0; i<pCtx->argc; i++){
79858    assert( memIsValid(pCtx->argv[i]) );
79859    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
79860  }
79861#endif
79862  MemSetTypeFlag(pOut, MEM_Null);
79863  pCtx->fErrorOrAux = 0;
79864  (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
79865
79866  /* If the function returned an error, throw an exception */
79867  if( pCtx->fErrorOrAux ){
79868    if( pCtx->isError ){
79869      sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
79870      rc = pCtx->isError;
79871    }
79872    sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
79873    if( rc ) goto abort_due_to_error;
79874  }
79875
79876  /* Copy the result of the function into register P3 */
79877  if( pOut->flags & (MEM_Str|MEM_Blob) ){
79878    sqlite3VdbeChangeEncoding(pOut, encoding);
79879    if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
79880  }
79881
79882  REGISTER_TRACE(pOp->p3, pOut);
79883  UPDATE_MAX_BLOBSIZE(pOut);
79884  break;
79885}
79886
79887/* Opcode: BitAnd P1 P2 P3 * *
79888** Synopsis: r[P3]=r[P1]&r[P2]
79889**
79890** Take the bit-wise AND of the values in register P1 and P2 and
79891** store the result in register P3.
79892** If either input is NULL, the result is NULL.
79893*/
79894/* Opcode: BitOr P1 P2 P3 * *
79895** Synopsis: r[P3]=r[P1]|r[P2]
79896**
79897** Take the bit-wise OR of the values in register P1 and P2 and
79898** store the result in register P3.
79899** If either input is NULL, the result is NULL.
79900*/
79901/* Opcode: ShiftLeft P1 P2 P3 * *
79902** Synopsis: r[P3]=r[P2]<<r[P1]
79903**
79904** Shift the integer value in register P2 to the left by the
79905** number of bits specified by the integer in register P1.
79906** Store the result in register P3.
79907** If either input is NULL, the result is NULL.
79908*/
79909/* Opcode: ShiftRight P1 P2 P3 * *
79910** Synopsis: r[P3]=r[P2]>>r[P1]
79911**
79912** Shift the integer value in register P2 to the right by the
79913** number of bits specified by the integer in register P1.
79914** Store the result in register P3.
79915** If either input is NULL, the result is NULL.
79916*/
79917case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
79918case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
79919case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
79920case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
79921  i64 iA;
79922  u64 uA;
79923  i64 iB;
79924  u8 op;
79925
79926  pIn1 = &aMem[pOp->p1];
79927  pIn2 = &aMem[pOp->p2];
79928  pOut = &aMem[pOp->p3];
79929  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
79930    sqlite3VdbeMemSetNull(pOut);
79931    break;
79932  }
79933  iA = sqlite3VdbeIntValue(pIn2);
79934  iB = sqlite3VdbeIntValue(pIn1);
79935  op = pOp->opcode;
79936  if( op==OP_BitAnd ){
79937    iA &= iB;
79938  }else if( op==OP_BitOr ){
79939    iA |= iB;
79940  }else if( iB!=0 ){
79941    assert( op==OP_ShiftRight || op==OP_ShiftLeft );
79942
79943    /* If shifting by a negative amount, shift in the other direction */
79944    if( iB<0 ){
79945      assert( OP_ShiftRight==OP_ShiftLeft+1 );
79946      op = 2*OP_ShiftLeft + 1 - op;
79947      iB = iB>(-64) ? -iB : 64;
79948    }
79949
79950    if( iB>=64 ){
79951      iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
79952    }else{
79953      memcpy(&uA, &iA, sizeof(uA));
79954      if( op==OP_ShiftLeft ){
79955        uA <<= iB;
79956      }else{
79957        uA >>= iB;
79958        /* Sign-extend on a right shift of a negative number */
79959        if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
79960      }
79961      memcpy(&iA, &uA, sizeof(iA));
79962    }
79963  }
79964  pOut->u.i = iA;
79965  MemSetTypeFlag(pOut, MEM_Int);
79966  break;
79967}
79968
79969/* Opcode: AddImm  P1 P2 * * *
79970** Synopsis: r[P1]=r[P1]+P2
79971**
79972** Add the constant P2 to the value in register P1.
79973** The result is always an integer.
79974**
79975** To force any register to be an integer, just add 0.
79976*/
79977case OP_AddImm: {            /* in1 */
79978  pIn1 = &aMem[pOp->p1];
79979  memAboutToChange(p, pIn1);
79980  sqlite3VdbeMemIntegerify(pIn1);
79981  pIn1->u.i += pOp->p2;
79982  break;
79983}
79984
79985/* Opcode: MustBeInt P1 P2 * * *
79986**
79987** Force the value in register P1 to be an integer.  If the value
79988** in P1 is not an integer and cannot be converted into an integer
79989** without data loss, then jump immediately to P2, or if P2==0
79990** raise an SQLITE_MISMATCH exception.
79991*/
79992case OP_MustBeInt: {            /* jump, in1 */
79993  pIn1 = &aMem[pOp->p1];
79994  if( (pIn1->flags & MEM_Int)==0 ){
79995    applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
79996    VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
79997    if( (pIn1->flags & MEM_Int)==0 ){
79998      if( pOp->p2==0 ){
79999        rc = SQLITE_MISMATCH;
80000        goto abort_due_to_error;
80001      }else{
80002        goto jump_to_p2;
80003      }
80004    }
80005  }
80006  MemSetTypeFlag(pIn1, MEM_Int);
80007  break;
80008}
80009
80010#ifndef SQLITE_OMIT_FLOATING_POINT
80011/* Opcode: RealAffinity P1 * * * *
80012**
80013** If register P1 holds an integer convert it to a real value.
80014**
80015** This opcode is used when extracting information from a column that
80016** has REAL affinity.  Such column values may still be stored as
80017** integers, for space efficiency, but after extraction we want them
80018** to have only a real value.
80019*/
80020case OP_RealAffinity: {                  /* in1 */
80021  pIn1 = &aMem[pOp->p1];
80022  if( pIn1->flags & MEM_Int ){
80023    sqlite3VdbeMemRealify(pIn1);
80024  }
80025  break;
80026}
80027#endif
80028
80029#ifndef SQLITE_OMIT_CAST
80030/* Opcode: Cast P1 P2 * * *
80031** Synopsis: affinity(r[P1])
80032**
80033** Force the value in register P1 to be the type defined by P2.
80034**
80035** <ul>
80036** <li value="97"> TEXT
80037** <li value="98"> BLOB
80038** <li value="99"> NUMERIC
80039** <li value="100"> INTEGER
80040** <li value="101"> REAL
80041** </ul>
80042**
80043** A NULL value is not changed by this routine.  It remains NULL.
80044*/
80045case OP_Cast: {                  /* in1 */
80046  assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
80047  testcase( pOp->p2==SQLITE_AFF_TEXT );
80048  testcase( pOp->p2==SQLITE_AFF_BLOB );
80049  testcase( pOp->p2==SQLITE_AFF_NUMERIC );
80050  testcase( pOp->p2==SQLITE_AFF_INTEGER );
80051  testcase( pOp->p2==SQLITE_AFF_REAL );
80052  pIn1 = &aMem[pOp->p1];
80053  memAboutToChange(p, pIn1);
80054  rc = ExpandBlob(pIn1);
80055  sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
80056  UPDATE_MAX_BLOBSIZE(pIn1);
80057  if( rc ) goto abort_due_to_error;
80058  break;
80059}
80060#endif /* SQLITE_OMIT_CAST */
80061
80062/* Opcode: Eq P1 P2 P3 P4 P5
80063** Synopsis: IF r[P3]==r[P1]
80064**
80065** Compare the values in register P1 and P3.  If reg(P3)==reg(P1) then
80066** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5, then
80067** store the result of comparison in register P2.
80068**
80069** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
80070** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
80071** to coerce both inputs according to this affinity before the
80072** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
80073** affinity is used. Note that the affinity conversions are stored
80074** back into the input registers P1 and P3.  So this opcode can cause
80075** persistent changes to registers P1 and P3.
80076**
80077** Once any conversions have taken place, and neither value is NULL,
80078** the values are compared. If both values are blobs then memcmp() is
80079** used to determine the results of the comparison.  If both values
80080** are text, then the appropriate collating function specified in
80081** P4 is used to do the comparison.  If P4 is not specified then
80082** memcmp() is used to compare text string.  If both values are
80083** numeric, then a numeric comparison is used. If the two values
80084** are of different types, then numbers are considered less than
80085** strings and strings are considered less than blobs.
80086**
80087** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
80088** true or false and is never NULL.  If both operands are NULL then the result
80089** of comparison is true.  If either operand is NULL then the result is false.
80090** If neither operand is NULL the result is the same as it would be if
80091** the SQLITE_NULLEQ flag were omitted from P5.
80092**
80093** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
80094** content of r[P2] is only changed if the new value is NULL or 0 (false).
80095** In other words, a prior r[P2] value will not be overwritten by 1 (true).
80096*/
80097/* Opcode: Ne P1 P2 P3 P4 P5
80098** Synopsis: IF r[P3]!=r[P1]
80099**
80100** This works just like the Eq opcode except that the jump is taken if
80101** the operands in registers P1 and P3 are not equal.  See the Eq opcode for
80102** additional information.
80103**
80104** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
80105** content of r[P2] is only changed if the new value is NULL or 1 (true).
80106** In other words, a prior r[P2] value will not be overwritten by 0 (false).
80107*/
80108/* Opcode: Lt P1 P2 P3 P4 P5
80109** Synopsis: IF r[P3]<r[P1]
80110**
80111** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
80112** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5 store
80113** the result of comparison (0 or 1 or NULL) into register P2.
80114**
80115** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
80116** reg(P3) is NULL then the take the jump.  If the SQLITE_JUMPIFNULL
80117** bit is clear then fall through if either operand is NULL.
80118**
80119** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
80120** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
80121** to coerce both inputs according to this affinity before the
80122** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
80123** affinity is used. Note that the affinity conversions are stored
80124** back into the input registers P1 and P3.  So this opcode can cause
80125** persistent changes to registers P1 and P3.
80126**
80127** Once any conversions have taken place, and neither value is NULL,
80128** the values are compared. If both values are blobs then memcmp() is
80129** used to determine the results of the comparison.  If both values
80130** are text, then the appropriate collating function specified in
80131** P4 is  used to do the comparison.  If P4 is not specified then
80132** memcmp() is used to compare text string.  If both values are
80133** numeric, then a numeric comparison is used. If the two values
80134** are of different types, then numbers are considered less than
80135** strings and strings are considered less than blobs.
80136*/
80137/* Opcode: Le P1 P2 P3 P4 P5
80138** Synopsis: IF r[P3]<=r[P1]
80139**
80140** This works just like the Lt opcode except that the jump is taken if
80141** the content of register P3 is less than or equal to the content of
80142** register P1.  See the Lt opcode for additional information.
80143*/
80144/* Opcode: Gt P1 P2 P3 P4 P5
80145** Synopsis: IF r[P3]>r[P1]
80146**
80147** This works just like the Lt opcode except that the jump is taken if
80148** the content of register P3 is greater than the content of
80149** register P1.  See the Lt opcode for additional information.
80150*/
80151/* Opcode: Ge P1 P2 P3 P4 P5
80152** Synopsis: IF r[P3]>=r[P1]
80153**
80154** This works just like the Lt opcode except that the jump is taken if
80155** the content of register P3 is greater than or equal to the content of
80156** register P1.  See the Lt opcode for additional information.
80157*/
80158case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
80159case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
80160case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
80161case OP_Le:               /* same as TK_LE, jump, in1, in3 */
80162case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
80163case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
80164  int res, res2;      /* Result of the comparison of pIn1 against pIn3 */
80165  char affinity;      /* Affinity to use for comparison */
80166  u16 flags1;         /* Copy of initial value of pIn1->flags */
80167  u16 flags3;         /* Copy of initial value of pIn3->flags */
80168
80169  pIn1 = &aMem[pOp->p1];
80170  pIn3 = &aMem[pOp->p3];
80171  flags1 = pIn1->flags;
80172  flags3 = pIn3->flags;
80173  if( (flags1 | flags3)&MEM_Null ){
80174    /* One or both operands are NULL */
80175    if( pOp->p5 & SQLITE_NULLEQ ){
80176      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
80177      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
80178      ** or not both operands are null.
80179      */
80180      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
80181      assert( (flags1 & MEM_Cleared)==0 );
80182      assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
80183      if( (flags1&flags3&MEM_Null)!=0
80184       && (flags3&MEM_Cleared)==0
80185      ){
80186        res = 0;  /* Operands are equal */
80187      }else{
80188        res = 1;  /* Operands are not equal */
80189      }
80190    }else{
80191      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
80192      ** then the result is always NULL.
80193      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
80194      */
80195      if( pOp->p5 & SQLITE_STOREP2 ){
80196        pOut = &aMem[pOp->p2];
80197        iCompare = 1;    /* Operands are not equal */
80198        memAboutToChange(p, pOut);
80199        MemSetTypeFlag(pOut, MEM_Null);
80200        REGISTER_TRACE(pOp->p2, pOut);
80201      }else{
80202        VdbeBranchTaken(2,3);
80203        if( pOp->p5 & SQLITE_JUMPIFNULL ){
80204          goto jump_to_p2;
80205        }
80206      }
80207      break;
80208    }
80209  }else{
80210    /* Neither operand is NULL.  Do a comparison. */
80211    affinity = pOp->p5 & SQLITE_AFF_MASK;
80212    if( affinity>=SQLITE_AFF_NUMERIC ){
80213      if( (flags1 | flags3)&MEM_Str ){
80214        if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
80215          applyNumericAffinity(pIn1,0);
80216          testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
80217          flags3 = pIn3->flags;
80218        }
80219        if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
80220          applyNumericAffinity(pIn3,0);
80221        }
80222      }
80223      /* Handle the common case of integer comparison here, as an
80224      ** optimization, to avoid a call to sqlite3MemCompare() */
80225      if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
80226        if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
80227        if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
80228        res = 0;
80229        goto compare_op;
80230      }
80231    }else if( affinity==SQLITE_AFF_TEXT ){
80232      if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
80233        testcase( pIn1->flags & MEM_Int );
80234        testcase( pIn1->flags & MEM_Real );
80235        sqlite3VdbeMemStringify(pIn1, encoding, 1);
80236        testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
80237        flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
80238        assert( pIn1!=pIn3 );
80239      }
80240      if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
80241        testcase( pIn3->flags & MEM_Int );
80242        testcase( pIn3->flags & MEM_Real );
80243        sqlite3VdbeMemStringify(pIn3, encoding, 1);
80244        testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
80245        flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
80246      }
80247    }
80248    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
80249    res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
80250  }
80251compare_op:
80252  switch( pOp->opcode ){
80253    case OP_Eq:    res2 = res==0;     break;
80254    case OP_Ne:    res2 = res;        break;
80255    case OP_Lt:    res2 = res<0;      break;
80256    case OP_Le:    res2 = res<=0;     break;
80257    case OP_Gt:    res2 = res>0;      break;
80258    default:       res2 = res>=0;     break;
80259  }
80260
80261  /* Undo any changes made by applyAffinity() to the input registers. */
80262  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
80263  pIn1->flags = flags1;
80264  assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
80265  pIn3->flags = flags3;
80266
80267  if( pOp->p5 & SQLITE_STOREP2 ){
80268    pOut = &aMem[pOp->p2];
80269    iCompare = res;
80270    res2 = res2!=0;  /* For this path res2 must be exactly 0 or 1 */
80271    if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
80272      /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
80273      ** and prevents OP_Ne from overwriting NULL with 0.  This flag
80274      ** is only used in contexts where either:
80275      **   (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
80276      **   (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
80277      ** Therefore it is not necessary to check the content of r[P2] for
80278      ** NULL. */
80279      assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
80280      assert( res2==0 || res2==1 );
80281      testcase( res2==0 && pOp->opcode==OP_Eq );
80282      testcase( res2==1 && pOp->opcode==OP_Eq );
80283      testcase( res2==0 && pOp->opcode==OP_Ne );
80284      testcase( res2==1 && pOp->opcode==OP_Ne );
80285      if( (pOp->opcode==OP_Eq)==res2 ) break;
80286    }
80287    memAboutToChange(p, pOut);
80288    MemSetTypeFlag(pOut, MEM_Int);
80289    pOut->u.i = res2;
80290    REGISTER_TRACE(pOp->p2, pOut);
80291  }else{
80292    VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
80293    if( res2 ){
80294      goto jump_to_p2;
80295    }
80296  }
80297  break;
80298}
80299
80300/* Opcode: ElseNotEq * P2 * * *
80301**
80302** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
80303** If result of an OP_Eq comparison on the same two operands
80304** would have be NULL or false (0), then then jump to P2.
80305** If the result of an OP_Eq comparison on the two previous operands
80306** would have been true (1), then fall through.
80307*/
80308case OP_ElseNotEq: {       /* same as TK_ESCAPE, jump */
80309  assert( pOp>aOp );
80310  assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
80311  assert( pOp[-1].p5 & SQLITE_STOREP2 );
80312  VdbeBranchTaken(iCompare!=0, 2);
80313  if( iCompare!=0 ) goto jump_to_p2;
80314  break;
80315}
80316
80317
80318/* Opcode: Permutation * * * P4 *
80319**
80320** Set the permutation used by the OP_Compare operator in the next
80321** instruction.  The permutation is stored in the P4 operand.
80322**
80323** The permutation is only valid until the next OP_Compare that has
80324** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
80325** occur immediately prior to the OP_Compare.
80326**
80327** The first integer in the P4 integer array is the length of the array
80328** and does not become part of the permutation.
80329*/
80330case OP_Permutation: {
80331  assert( pOp->p4type==P4_INTARRAY );
80332  assert( pOp->p4.ai );
80333  assert( pOp[1].opcode==OP_Compare );
80334  assert( pOp[1].p5 & OPFLAG_PERMUTE );
80335  break;
80336}
80337
80338/* Opcode: Compare P1 P2 P3 P4 P5
80339** Synopsis: r[P1@P3] <-> r[P2@P3]
80340**
80341** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
80342** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
80343** the comparison for use by the next OP_Jump instruct.
80344**
80345** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
80346** determined by the most recent OP_Permutation operator.  If the
80347** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
80348** order.
80349**
80350** P4 is a KeyInfo structure that defines collating sequences and sort
80351** orders for the comparison.  The permutation applies to registers
80352** only.  The KeyInfo elements are used sequentially.
80353**
80354** The comparison is a sort comparison, so NULLs compare equal,
80355** NULLs are less than numbers, numbers are less than strings,
80356** and strings are less than blobs.
80357*/
80358case OP_Compare: {
80359  int n;
80360  int i;
80361  int p1;
80362  int p2;
80363  const KeyInfo *pKeyInfo;
80364  int idx;
80365  CollSeq *pColl;    /* Collating sequence to use on this term */
80366  int bRev;          /* True for DESCENDING sort order */
80367  int *aPermute;     /* The permutation */
80368
80369  if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
80370    aPermute = 0;
80371  }else{
80372    assert( pOp>aOp );
80373    assert( pOp[-1].opcode==OP_Permutation );
80374    assert( pOp[-1].p4type==P4_INTARRAY );
80375    aPermute = pOp[-1].p4.ai + 1;
80376    assert( aPermute!=0 );
80377  }
80378  n = pOp->p3;
80379  pKeyInfo = pOp->p4.pKeyInfo;
80380  assert( n>0 );
80381  assert( pKeyInfo!=0 );
80382  p1 = pOp->p1;
80383  p2 = pOp->p2;
80384#ifdef SQLITE_DEBUG
80385  if( aPermute ){
80386    int k, mx = 0;
80387    for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
80388    assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
80389    assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
80390  }else{
80391    assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
80392    assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
80393  }
80394#endif /* SQLITE_DEBUG */
80395  for(i=0; i<n; i++){
80396    idx = aPermute ? aPermute[i] : i;
80397    assert( memIsValid(&aMem[p1+idx]) );
80398    assert( memIsValid(&aMem[p2+idx]) );
80399    REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
80400    REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
80401    assert( i<pKeyInfo->nField );
80402    pColl = pKeyInfo->aColl[i];
80403    bRev = pKeyInfo->aSortOrder[i];
80404    iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
80405    if( iCompare ){
80406      if( bRev ) iCompare = -iCompare;
80407      break;
80408    }
80409  }
80410  break;
80411}
80412
80413/* Opcode: Jump P1 P2 P3 * *
80414**
80415** Jump to the instruction at address P1, P2, or P3 depending on whether
80416** in the most recent OP_Compare instruction the P1 vector was less than
80417** equal to, or greater than the P2 vector, respectively.
80418*/
80419case OP_Jump: {             /* jump */
80420  if( iCompare<0 ){
80421    VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
80422  }else if( iCompare==0 ){
80423    VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
80424  }else{
80425    VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
80426  }
80427  break;
80428}
80429
80430/* Opcode: And P1 P2 P3 * *
80431** Synopsis: r[P3]=(r[P1] && r[P2])
80432**
80433** Take the logical AND of the values in registers P1 and P2 and
80434** write the result into register P3.
80435**
80436** If either P1 or P2 is 0 (false) then the result is 0 even if
80437** the other input is NULL.  A NULL and true or two NULLs give
80438** a NULL output.
80439*/
80440/* Opcode: Or P1 P2 P3 * *
80441** Synopsis: r[P3]=(r[P1] || r[P2])
80442**
80443** Take the logical OR of the values in register P1 and P2 and
80444** store the answer in register P3.
80445**
80446** If either P1 or P2 is nonzero (true) then the result is 1 (true)
80447** even if the other input is NULL.  A NULL and false or two NULLs
80448** give a NULL output.
80449*/
80450case OP_And:              /* same as TK_AND, in1, in2, out3 */
80451case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
80452  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
80453  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
80454
80455  pIn1 = &aMem[pOp->p1];
80456  if( pIn1->flags & MEM_Null ){
80457    v1 = 2;
80458  }else{
80459    v1 = sqlite3VdbeIntValue(pIn1)!=0;
80460  }
80461  pIn2 = &aMem[pOp->p2];
80462  if( pIn2->flags & MEM_Null ){
80463    v2 = 2;
80464  }else{
80465    v2 = sqlite3VdbeIntValue(pIn2)!=0;
80466  }
80467  if( pOp->opcode==OP_And ){
80468    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
80469    v1 = and_logic[v1*3+v2];
80470  }else{
80471    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
80472    v1 = or_logic[v1*3+v2];
80473  }
80474  pOut = &aMem[pOp->p3];
80475  if( v1==2 ){
80476    MemSetTypeFlag(pOut, MEM_Null);
80477  }else{
80478    pOut->u.i = v1;
80479    MemSetTypeFlag(pOut, MEM_Int);
80480  }
80481  break;
80482}
80483
80484/* Opcode: Not P1 P2 * * *
80485** Synopsis: r[P2]= !r[P1]
80486**
80487** Interpret the value in register P1 as a boolean value.  Store the
80488** boolean complement in register P2.  If the value in register P1 is
80489** NULL, then a NULL is stored in P2.
80490*/
80491case OP_Not: {                /* same as TK_NOT, in1, out2 */
80492  pIn1 = &aMem[pOp->p1];
80493  pOut = &aMem[pOp->p2];
80494  sqlite3VdbeMemSetNull(pOut);
80495  if( (pIn1->flags & MEM_Null)==0 ){
80496    pOut->flags = MEM_Int;
80497    pOut->u.i = !sqlite3VdbeIntValue(pIn1);
80498  }
80499  break;
80500}
80501
80502/* Opcode: BitNot P1 P2 * * *
80503** Synopsis: r[P1]= ~r[P1]
80504**
80505** Interpret the content of register P1 as an integer.  Store the
80506** ones-complement of the P1 value into register P2.  If P1 holds
80507** a NULL then store a NULL in P2.
80508*/
80509case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
80510  pIn1 = &aMem[pOp->p1];
80511  pOut = &aMem[pOp->p2];
80512  sqlite3VdbeMemSetNull(pOut);
80513  if( (pIn1->flags & MEM_Null)==0 ){
80514    pOut->flags = MEM_Int;
80515    pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
80516  }
80517  break;
80518}
80519
80520/* Opcode: Once P1 P2 * * *
80521**
80522** Fall through to the next instruction the first time this opcode is
80523** encountered on each invocation of the byte-code program.  Jump to P2
80524** on the second and all subsequent encounters during the same invocation.
80525**
80526** Top-level programs determine first invocation by comparing the P1
80527** operand against the P1 operand on the OP_Init opcode at the beginning
80528** of the program.  If the P1 values differ, then fall through and make
80529** the P1 of this opcode equal to the P1 of OP_Init.  If P1 values are
80530** the same then take the jump.
80531**
80532** For subprograms, there is a bitmask in the VdbeFrame that determines
80533** whether or not the jump should be taken.  The bitmask is necessary
80534** because the self-altering code trick does not work for recursive
80535** triggers.
80536*/
80537case OP_Once: {             /* jump */
80538  u32 iAddr;                /* Address of this instruction */
80539  assert( p->aOp[0].opcode==OP_Init );
80540  if( p->pFrame ){
80541    iAddr = (int)(pOp - p->aOp);
80542    if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
80543      VdbeBranchTaken(1, 2);
80544      goto jump_to_p2;
80545    }
80546    p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
80547  }else{
80548    if( p->aOp[0].p1==pOp->p1 ){
80549      VdbeBranchTaken(1, 2);
80550      goto jump_to_p2;
80551    }
80552  }
80553  VdbeBranchTaken(0, 2);
80554  pOp->p1 = p->aOp[0].p1;
80555  break;
80556}
80557
80558/* Opcode: If P1 P2 P3 * *
80559**
80560** Jump to P2 if the value in register P1 is true.  The value
80561** is considered true if it is numeric and non-zero.  If the value
80562** in P1 is NULL then take the jump if and only if P3 is non-zero.
80563*/
80564/* Opcode: IfNot P1 P2 P3 * *
80565**
80566** Jump to P2 if the value in register P1 is False.  The value
80567** is considered false if it has a numeric value of zero.  If the value
80568** in P1 is NULL then take the jump if and only if P3 is non-zero.
80569*/
80570case OP_If:                 /* jump, in1 */
80571case OP_IfNot: {            /* jump, in1 */
80572  int c;
80573  pIn1 = &aMem[pOp->p1];
80574  if( pIn1->flags & MEM_Null ){
80575    c = pOp->p3;
80576  }else{
80577#ifdef SQLITE_OMIT_FLOATING_POINT
80578    c = sqlite3VdbeIntValue(pIn1)!=0;
80579#else
80580    c = sqlite3VdbeRealValue(pIn1)!=0.0;
80581#endif
80582    if( pOp->opcode==OP_IfNot ) c = !c;
80583  }
80584  VdbeBranchTaken(c!=0, 2);
80585  if( c ){
80586    goto jump_to_p2;
80587  }
80588  break;
80589}
80590
80591/* Opcode: IsNull P1 P2 * * *
80592** Synopsis: if r[P1]==NULL goto P2
80593**
80594** Jump to P2 if the value in register P1 is NULL.
80595*/
80596case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
80597  pIn1 = &aMem[pOp->p1];
80598  VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
80599  if( (pIn1->flags & MEM_Null)!=0 ){
80600    goto jump_to_p2;
80601  }
80602  break;
80603}
80604
80605/* Opcode: NotNull P1 P2 * * *
80606** Synopsis: if r[P1]!=NULL goto P2
80607**
80608** Jump to P2 if the value in register P1 is not NULL.
80609*/
80610case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
80611  pIn1 = &aMem[pOp->p1];
80612  VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
80613  if( (pIn1->flags & MEM_Null)==0 ){
80614    goto jump_to_p2;
80615  }
80616  break;
80617}
80618
80619/* Opcode: Column P1 P2 P3 P4 P5
80620** Synopsis: r[P3]=PX
80621**
80622** Interpret the data that cursor P1 points to as a structure built using
80623** the MakeRecord instruction.  (See the MakeRecord opcode for additional
80624** information about the format of the data.)  Extract the P2-th column
80625** from this record.  If there are less that (P2+1)
80626** values in the record, extract a NULL.
80627**
80628** The value extracted is stored in register P3.
80629**
80630** If the column contains fewer than P2 fields, then extract a NULL.  Or,
80631** if the P4 argument is a P4_MEM use the value of the P4 argument as
80632** the result.
80633**
80634** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
80635** then the cache of the cursor is reset prior to extracting the column.
80636** The first OP_Column against a pseudo-table after the value of the content
80637** register has changed should have this bit set.
80638**
80639** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
80640** the result is guaranteed to only be used as the argument of a length()
80641** or typeof() function, respectively.  The loading of large blobs can be
80642** skipped for length() and all content loading can be skipped for typeof().
80643*/
80644case OP_Column: {
80645  int p2;            /* column number to retrieve */
80646  VdbeCursor *pC;    /* The VDBE cursor */
80647  BtCursor *pCrsr;   /* The BTree cursor */
80648  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
80649  int len;           /* The length of the serialized data for the column */
80650  int i;             /* Loop counter */
80651  Mem *pDest;        /* Where to write the extracted value */
80652  Mem sMem;          /* For storing the record being decoded */
80653  const u8 *zData;   /* Part of the record being decoded */
80654  const u8 *zHdr;    /* Next unparsed byte of the header */
80655  const u8 *zEndHdr; /* Pointer to first byte after the header */
80656  u32 offset;        /* Offset into the data */
80657  u64 offset64;      /* 64-bit offset */
80658  u32 avail;         /* Number of bytes of available data */
80659  u32 t;             /* A type code from the record header */
80660  Mem *pReg;         /* PseudoTable input register */
80661
80662  pC = p->apCsr[pOp->p1];
80663  p2 = pOp->p2;
80664
80665  /* If the cursor cache is stale, bring it up-to-date */
80666  rc = sqlite3VdbeCursorMoveto(&pC, &p2);
80667  if( rc ) goto abort_due_to_error;
80668
80669  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
80670  pDest = &aMem[pOp->p3];
80671  memAboutToChange(p, pDest);
80672  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80673  assert( pC!=0 );
80674  assert( p2<pC->nField );
80675  aOffset = pC->aOffset;
80676  assert( pC->eCurType!=CURTYPE_VTAB );
80677  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
80678  assert( pC->eCurType!=CURTYPE_SORTER );
80679
80680  if( pC->cacheStatus!=p->cacheCtr ){                /*OPTIMIZATION-IF-FALSE*/
80681    if( pC->nullRow ){
80682      if( pC->eCurType==CURTYPE_PSEUDO ){
80683        assert( pC->uc.pseudoTableReg>0 );
80684        pReg = &aMem[pC->uc.pseudoTableReg];
80685        assert( pReg->flags & MEM_Blob );
80686        assert( memIsValid(pReg) );
80687        pC->payloadSize = pC->szRow = avail = pReg->n;
80688        pC->aRow = (u8*)pReg->z;
80689      }else{
80690        sqlite3VdbeMemSetNull(pDest);
80691        goto op_column_out;
80692      }
80693    }else{
80694      pCrsr = pC->uc.pCursor;
80695      assert( pC->eCurType==CURTYPE_BTREE );
80696      assert( pCrsr );
80697      assert( sqlite3BtreeCursorIsValid(pCrsr) );
80698      pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
80699      pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &avail);
80700      assert( avail<=65536 );  /* Maximum page size is 64KiB */
80701      if( pC->payloadSize <= (u32)avail ){
80702        pC->szRow = pC->payloadSize;
80703      }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
80704        goto too_big;
80705      }else{
80706        pC->szRow = avail;
80707      }
80708    }
80709    pC->cacheStatus = p->cacheCtr;
80710    pC->iHdrOffset = getVarint32(pC->aRow, offset);
80711    pC->nHdrParsed = 0;
80712    aOffset[0] = offset;
80713
80714
80715    if( avail<offset ){      /*OPTIMIZATION-IF-FALSE*/
80716      /* pC->aRow does not have to hold the entire row, but it does at least
80717      ** need to cover the header of the record.  If pC->aRow does not contain
80718      ** the complete header, then set it to zero, forcing the header to be
80719      ** dynamically allocated. */
80720      pC->aRow = 0;
80721      pC->szRow = 0;
80722
80723      /* Make sure a corrupt database has not given us an oversize header.
80724      ** Do this now to avoid an oversize memory allocation.
80725      **
80726      ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
80727      ** types use so much data space that there can only be 4096 and 32 of
80728      ** them, respectively.  So the maximum header length results from a
80729      ** 3-byte type for each of the maximum of 32768 columns plus three
80730      ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
80731      */
80732      if( offset > 98307 || offset > pC->payloadSize ){
80733        rc = SQLITE_CORRUPT_BKPT;
80734        goto abort_due_to_error;
80735      }
80736    }else if( offset>0 ){ /*OPTIMIZATION-IF-TRUE*/
80737      /* The following goto is an optimization.  It can be omitted and
80738      ** everything will still work.  But OP_Column is measurably faster
80739      ** by skipping the subsequent conditional, which is always true.
80740      */
80741      zData = pC->aRow;
80742      assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
80743      goto op_column_read_header;
80744    }
80745  }
80746
80747  /* Make sure at least the first p2+1 entries of the header have been
80748  ** parsed and valid information is in aOffset[] and pC->aType[].
80749  */
80750  if( pC->nHdrParsed<=p2 ){
80751    /* If there is more header available for parsing in the record, try
80752    ** to extract additional fields up through the p2+1-th field
80753    */
80754    if( pC->iHdrOffset<aOffset[0] ){
80755      /* Make sure zData points to enough of the record to cover the header. */
80756      if( pC->aRow==0 ){
80757        memset(&sMem, 0, sizeof(sMem));
80758        rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
80759        if( rc!=SQLITE_OK ) goto abort_due_to_error;
80760        zData = (u8*)sMem.z;
80761      }else{
80762        zData = pC->aRow;
80763      }
80764
80765      /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
80766    op_column_read_header:
80767      i = pC->nHdrParsed;
80768      offset64 = aOffset[i];
80769      zHdr = zData + pC->iHdrOffset;
80770      zEndHdr = zData + aOffset[0];
80771      do{
80772        if( (t = zHdr[0])<0x80 ){
80773          zHdr++;
80774          offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
80775        }else{
80776          zHdr += sqlite3GetVarint32(zHdr, &t);
80777          offset64 += sqlite3VdbeSerialTypeLen(t);
80778        }
80779        pC->aType[i++] = t;
80780        aOffset[i] = (u32)(offset64 & 0xffffffff);
80781      }while( i<=p2 && zHdr<zEndHdr );
80782
80783      /* The record is corrupt if any of the following are true:
80784      ** (1) the bytes of the header extend past the declared header size
80785      ** (2) the entire header was used but not all data was used
80786      ** (3) the end of the data extends beyond the end of the record.
80787      */
80788      if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
80789       || (offset64 > pC->payloadSize)
80790      ){
80791        if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
80792        rc = SQLITE_CORRUPT_BKPT;
80793        goto abort_due_to_error;
80794      }
80795
80796      pC->nHdrParsed = i;
80797      pC->iHdrOffset = (u32)(zHdr - zData);
80798      if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
80799    }else{
80800      t = 0;
80801    }
80802
80803    /* If after trying to extract new entries from the header, nHdrParsed is
80804    ** still not up to p2, that means that the record has fewer than p2
80805    ** columns.  So the result will be either the default value or a NULL.
80806    */
80807    if( pC->nHdrParsed<=p2 ){
80808      if( pOp->p4type==P4_MEM ){
80809        sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
80810      }else{
80811        sqlite3VdbeMemSetNull(pDest);
80812      }
80813      goto op_column_out;
80814    }
80815  }else{
80816    t = pC->aType[p2];
80817  }
80818
80819  /* Extract the content for the p2+1-th column.  Control can only
80820  ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
80821  ** all valid.
80822  */
80823  assert( p2<pC->nHdrParsed );
80824  assert( rc==SQLITE_OK );
80825  assert( sqlite3VdbeCheckMemInvariants(pDest) );
80826  if( VdbeMemDynamic(pDest) ){
80827    sqlite3VdbeMemSetNull(pDest);
80828  }
80829  assert( t==pC->aType[p2] );
80830  if( pC->szRow>=aOffset[p2+1] ){
80831    /* This is the common case where the desired content fits on the original
80832    ** page - where the content is not on an overflow page */
80833    zData = pC->aRow + aOffset[p2];
80834    if( t<12 ){
80835      sqlite3VdbeSerialGet(zData, t, pDest);
80836    }else{
80837      /* If the column value is a string, we need a persistent value, not
80838      ** a MEM_Ephem value.  This branch is a fast short-cut that is equivalent
80839      ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
80840      */
80841      static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
80842      pDest->n = len = (t-12)/2;
80843      pDest->enc = encoding;
80844      if( pDest->szMalloc < len+2 ){
80845        pDest->flags = MEM_Null;
80846        if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
80847      }else{
80848        pDest->z = pDest->zMalloc;
80849      }
80850      memcpy(pDest->z, zData, len);
80851      pDest->z[len] = 0;
80852      pDest->z[len+1] = 0;
80853      pDest->flags = aFlag[t&1];
80854    }
80855  }else{
80856    pDest->enc = encoding;
80857    /* This branch happens only when content is on overflow pages */
80858    if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
80859          && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
80860     || (len = sqlite3VdbeSerialTypeLen(t))==0
80861    ){
80862      /* Content is irrelevant for
80863      **    1. the typeof() function,
80864      **    2. the length(X) function if X is a blob, and
80865      **    3. if the content length is zero.
80866      ** So we might as well use bogus content rather than reading
80867      ** content from disk.
80868      **
80869      ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
80870      ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
80871      ** read up to 16. So 16 bytes of bogus content is supplied.
80872      */
80873      static u8 aZero[16];  /* This is the bogus content */
80874      sqlite3VdbeSerialGet(aZero, t, pDest);
80875    }else{
80876      rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
80877      if( rc!=SQLITE_OK ) goto abort_due_to_error;
80878      sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
80879      pDest->flags &= ~MEM_Ephem;
80880    }
80881  }
80882
80883op_column_out:
80884  UPDATE_MAX_BLOBSIZE(pDest);
80885  REGISTER_TRACE(pOp->p3, pDest);
80886  break;
80887}
80888
80889/* Opcode: Affinity P1 P2 * P4 *
80890** Synopsis: affinity(r[P1@P2])
80891**
80892** Apply affinities to a range of P2 registers starting with P1.
80893**
80894** P4 is a string that is P2 characters long. The nth character of the
80895** string indicates the column affinity that should be used for the nth
80896** memory cell in the range.
80897*/
80898case OP_Affinity: {
80899  const char *zAffinity;   /* The affinity to be applied */
80900  char cAff;               /* A single character of affinity */
80901
80902  zAffinity = pOp->p4.z;
80903  assert( zAffinity!=0 );
80904  assert( zAffinity[pOp->p2]==0 );
80905  pIn1 = &aMem[pOp->p1];
80906  while( (cAff = *(zAffinity++))!=0 ){
80907    assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
80908    assert( memIsValid(pIn1) );
80909    applyAffinity(pIn1, cAff, encoding);
80910    pIn1++;
80911  }
80912  break;
80913}
80914
80915/* Opcode: MakeRecord P1 P2 P3 P4 *
80916** Synopsis: r[P3]=mkrec(r[P1@P2])
80917**
80918** Convert P2 registers beginning with P1 into the [record format]
80919** use as a data record in a database table or as a key
80920** in an index.  The OP_Column opcode can decode the record later.
80921**
80922** P4 may be a string that is P2 characters long.  The nth character of the
80923** string indicates the column affinity that should be used for the nth
80924** field of the index key.
80925**
80926** The mapping from character to affinity is given by the SQLITE_AFF_
80927** macros defined in sqliteInt.h.
80928**
80929** If P4 is NULL then all index fields have the affinity BLOB.
80930*/
80931case OP_MakeRecord: {
80932  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
80933  Mem *pRec;             /* The new record */
80934  u64 nData;             /* Number of bytes of data space */
80935  int nHdr;              /* Number of bytes of header space */
80936  i64 nByte;             /* Data space required for this record */
80937  i64 nZero;             /* Number of zero bytes at the end of the record */
80938  int nVarint;           /* Number of bytes in a varint */
80939  u32 serial_type;       /* Type field */
80940  Mem *pData0;           /* First field to be combined into the record */
80941  Mem *pLast;            /* Last field of the record */
80942  int nField;            /* Number of fields in the record */
80943  char *zAffinity;       /* The affinity string for the record */
80944  int file_format;       /* File format to use for encoding */
80945  int i;                 /* Space used in zNewRecord[] header */
80946  int j;                 /* Space used in zNewRecord[] content */
80947  u32 len;               /* Length of a field */
80948
80949  /* Assuming the record contains N fields, the record format looks
80950  ** like this:
80951  **
80952  ** ------------------------------------------------------------------------
80953  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
80954  ** ------------------------------------------------------------------------
80955  **
80956  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
80957  ** and so forth.
80958  **
80959  ** Each type field is a varint representing the serial type of the
80960  ** corresponding data element (see sqlite3VdbeSerialType()). The
80961  ** hdr-size field is also a varint which is the offset from the beginning
80962  ** of the record to data0.
80963  */
80964  nData = 0;         /* Number of bytes of data space */
80965  nHdr = 0;          /* Number of bytes of header space */
80966  nZero = 0;         /* Number of zero bytes at the end of the record */
80967  nField = pOp->p1;
80968  zAffinity = pOp->p4.z;
80969  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
80970  pData0 = &aMem[nField];
80971  nField = pOp->p2;
80972  pLast = &pData0[nField-1];
80973  file_format = p->minWriteFileFormat;
80974
80975  /* Identify the output register */
80976  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
80977  pOut = &aMem[pOp->p3];
80978  memAboutToChange(p, pOut);
80979
80980  /* Apply the requested affinity to all inputs
80981  */
80982  assert( pData0<=pLast );
80983  if( zAffinity ){
80984    pRec = pData0;
80985    do{
80986      applyAffinity(pRec++, *(zAffinity++), encoding);
80987      assert( zAffinity[0]==0 || pRec<=pLast );
80988    }while( zAffinity[0] );
80989  }
80990
80991#ifdef SQLITE_ENABLE_NULL_TRIM
80992  /* NULLs can be safely trimmed from the end of the record, as long as
80993  ** as the schema format is 2 or more and none of the omitted columns
80994  ** have a non-NULL default value.  Also, the record must be left with
80995  ** at least one field.  If P5>0 then it will be one more than the
80996  ** index of the right-most column with a non-NULL default value */
80997  if( pOp->p5 ){
80998    while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
80999      pLast--;
81000      nField--;
81001    }
81002  }
81003#endif
81004
81005  /* Loop through the elements that will make up the record to figure
81006  ** out how much space is required for the new record.
81007  */
81008  pRec = pLast;
81009  do{
81010    assert( memIsValid(pRec) );
81011    pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
81012    if( pRec->flags & MEM_Zero ){
81013      if( nData ){
81014        if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
81015      }else{
81016        nZero += pRec->u.nZero;
81017        len -= pRec->u.nZero;
81018      }
81019    }
81020    nData += len;
81021    testcase( serial_type==127 );
81022    testcase( serial_type==128 );
81023    nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
81024    if( pRec==pData0 ) break;
81025    pRec--;
81026  }while(1);
81027
81028  /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
81029  ** which determines the total number of bytes in the header. The varint
81030  ** value is the size of the header in bytes including the size varint
81031  ** itself. */
81032  testcase( nHdr==126 );
81033  testcase( nHdr==127 );
81034  if( nHdr<=126 ){
81035    /* The common case */
81036    nHdr += 1;
81037  }else{
81038    /* Rare case of a really large header */
81039    nVarint = sqlite3VarintLen(nHdr);
81040    nHdr += nVarint;
81041    if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
81042  }
81043  nByte = nHdr+nData;
81044  if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
81045    goto too_big;
81046  }
81047
81048  /* Make sure the output register has a buffer large enough to store
81049  ** the new record. The output register (pOp->p3) is not allowed to
81050  ** be one of the input registers (because the following call to
81051  ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
81052  */
81053  if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
81054    goto no_mem;
81055  }
81056  zNewRecord = (u8 *)pOut->z;
81057
81058  /* Write the record */
81059  i = putVarint32(zNewRecord, nHdr);
81060  j = nHdr;
81061  assert( pData0<=pLast );
81062  pRec = pData0;
81063  do{
81064    serial_type = pRec->uTemp;
81065    /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
81066    ** additional varints, one per column. */
81067    i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
81068    /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
81069    ** immediately follow the header. */
81070    j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
81071  }while( (++pRec)<=pLast );
81072  assert( i==nHdr );
81073  assert( j==nByte );
81074
81075  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
81076  pOut->n = (int)nByte;
81077  pOut->flags = MEM_Blob;
81078  if( nZero ){
81079    pOut->u.nZero = nZero;
81080    pOut->flags |= MEM_Zero;
81081  }
81082  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
81083  REGISTER_TRACE(pOp->p3, pOut);
81084  UPDATE_MAX_BLOBSIZE(pOut);
81085  break;
81086}
81087
81088/* Opcode: Count P1 P2 * * *
81089** Synopsis: r[P2]=count()
81090**
81091** Store the number of entries (an integer value) in the table or index
81092** opened by cursor P1 in register P2
81093*/
81094#ifndef SQLITE_OMIT_BTREECOUNT
81095case OP_Count: {         /* out2 */
81096  i64 nEntry;
81097  BtCursor *pCrsr;
81098
81099  assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
81100  pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
81101  assert( pCrsr );
81102  nEntry = 0;  /* Not needed.  Only used to silence a warning. */
81103  rc = sqlite3BtreeCount(pCrsr, &nEntry);
81104  if( rc ) goto abort_due_to_error;
81105  pOut = out2Prerelease(p, pOp);
81106  pOut->u.i = nEntry;
81107  break;
81108}
81109#endif
81110
81111/* Opcode: Savepoint P1 * * P4 *
81112**
81113** Open, release or rollback the savepoint named by parameter P4, depending
81114** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
81115** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
81116*/
81117case OP_Savepoint: {
81118  int p1;                         /* Value of P1 operand */
81119  char *zName;                    /* Name of savepoint */
81120  int nName;
81121  Savepoint *pNew;
81122  Savepoint *pSavepoint;
81123  Savepoint *pTmp;
81124  int iSavepoint;
81125  int ii;
81126
81127  p1 = pOp->p1;
81128  zName = pOp->p4.z;
81129
81130  /* Assert that the p1 parameter is valid. Also that if there is no open
81131  ** transaction, then there cannot be any savepoints.
81132  */
81133  assert( db->pSavepoint==0 || db->autoCommit==0 );
81134  assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
81135  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
81136  assert( checkSavepointCount(db) );
81137  assert( p->bIsReader );
81138
81139  if( p1==SAVEPOINT_BEGIN ){
81140    if( db->nVdbeWrite>0 ){
81141      /* A new savepoint cannot be created if there are active write
81142      ** statements (i.e. open read/write incremental blob handles).
81143      */
81144      sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
81145      rc = SQLITE_BUSY;
81146    }else{
81147      nName = sqlite3Strlen30(zName);
81148
81149#ifndef SQLITE_OMIT_VIRTUALTABLE
81150      /* This call is Ok even if this savepoint is actually a transaction
81151      ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
81152      ** If this is a transaction savepoint being opened, it is guaranteed
81153      ** that the db->aVTrans[] array is empty.  */
81154      assert( db->autoCommit==0 || db->nVTrans==0 );
81155      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
81156                                db->nStatement+db->nSavepoint);
81157      if( rc!=SQLITE_OK ) goto abort_due_to_error;
81158#endif
81159
81160      /* Create a new savepoint structure. */
81161      pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
81162      if( pNew ){
81163        pNew->zName = (char *)&pNew[1];
81164        memcpy(pNew->zName, zName, nName+1);
81165
81166        /* If there is no open transaction, then mark this as a special
81167        ** "transaction savepoint". */
81168        if( db->autoCommit ){
81169          db->autoCommit = 0;
81170          db->isTransactionSavepoint = 1;
81171        }else{
81172          db->nSavepoint++;
81173        }
81174
81175        /* Link the new savepoint into the database handle's list. */
81176        pNew->pNext = db->pSavepoint;
81177        db->pSavepoint = pNew;
81178        pNew->nDeferredCons = db->nDeferredCons;
81179        pNew->nDeferredImmCons = db->nDeferredImmCons;
81180      }
81181    }
81182  }else{
81183    iSavepoint = 0;
81184
81185    /* Find the named savepoint. If there is no such savepoint, then an
81186    ** an error is returned to the user.  */
81187    for(
81188      pSavepoint = db->pSavepoint;
81189      pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
81190      pSavepoint = pSavepoint->pNext
81191    ){
81192      iSavepoint++;
81193    }
81194    if( !pSavepoint ){
81195      sqlite3VdbeError(p, "no such savepoint: %s", zName);
81196      rc = SQLITE_ERROR;
81197    }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
81198      /* It is not possible to release (commit) a savepoint if there are
81199      ** active write statements.
81200      */
81201      sqlite3VdbeError(p, "cannot release savepoint - "
81202                          "SQL statements in progress");
81203      rc = SQLITE_BUSY;
81204    }else{
81205
81206      /* Determine whether or not this is a transaction savepoint. If so,
81207      ** and this is a RELEASE command, then the current transaction
81208      ** is committed.
81209      */
81210      int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
81211      if( isTransaction && p1==SAVEPOINT_RELEASE ){
81212        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
81213          goto vdbe_return;
81214        }
81215        db->autoCommit = 1;
81216        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
81217          p->pc = (int)(pOp - aOp);
81218          db->autoCommit = 0;
81219          p->rc = rc = SQLITE_BUSY;
81220          goto vdbe_return;
81221        }
81222        db->isTransactionSavepoint = 0;
81223        rc = p->rc;
81224      }else{
81225        int isSchemaChange;
81226        iSavepoint = db->nSavepoint - iSavepoint - 1;
81227        if( p1==SAVEPOINT_ROLLBACK ){
81228          isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
81229          for(ii=0; ii<db->nDb; ii++){
81230            rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
81231                                       SQLITE_ABORT_ROLLBACK,
81232                                       isSchemaChange==0);
81233            if( rc!=SQLITE_OK ) goto abort_due_to_error;
81234          }
81235        }else{
81236          isSchemaChange = 0;
81237        }
81238        for(ii=0; ii<db->nDb; ii++){
81239          rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
81240          if( rc!=SQLITE_OK ){
81241            goto abort_due_to_error;
81242          }
81243        }
81244        if( isSchemaChange ){
81245          sqlite3ExpirePreparedStatements(db);
81246          sqlite3ResetAllSchemasOfConnection(db);
81247          db->flags = (db->flags | SQLITE_InternChanges);
81248        }
81249      }
81250
81251      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
81252      ** savepoints nested inside of the savepoint being operated on. */
81253      while( db->pSavepoint!=pSavepoint ){
81254        pTmp = db->pSavepoint;
81255        db->pSavepoint = pTmp->pNext;
81256        sqlite3DbFree(db, pTmp);
81257        db->nSavepoint--;
81258      }
81259
81260      /* If it is a RELEASE, then destroy the savepoint being operated on
81261      ** too. If it is a ROLLBACK TO, then set the number of deferred
81262      ** constraint violations present in the database to the value stored
81263      ** when the savepoint was created.  */
81264      if( p1==SAVEPOINT_RELEASE ){
81265        assert( pSavepoint==db->pSavepoint );
81266        db->pSavepoint = pSavepoint->pNext;
81267        sqlite3DbFree(db, pSavepoint);
81268        if( !isTransaction ){
81269          db->nSavepoint--;
81270        }
81271      }else{
81272        db->nDeferredCons = pSavepoint->nDeferredCons;
81273        db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
81274      }
81275
81276      if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
81277        rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
81278        if( rc!=SQLITE_OK ) goto abort_due_to_error;
81279      }
81280    }
81281  }
81282  if( rc ) goto abort_due_to_error;
81283
81284  break;
81285}
81286
81287/* Opcode: AutoCommit P1 P2 * * *
81288**
81289** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
81290** back any currently active btree transactions. If there are any active
81291** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
81292** there are active writing VMs or active VMs that use shared cache.
81293**
81294** This instruction causes the VM to halt.
81295*/
81296case OP_AutoCommit: {
81297  int desiredAutoCommit;
81298  int iRollback;
81299
81300  desiredAutoCommit = pOp->p1;
81301  iRollback = pOp->p2;
81302  assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
81303  assert( desiredAutoCommit==1 || iRollback==0 );
81304  assert( db->nVdbeActive>0 );  /* At least this one VM is active */
81305  assert( p->bIsReader );
81306
81307  if( desiredAutoCommit!=db->autoCommit ){
81308    if( iRollback ){
81309      assert( desiredAutoCommit==1 );
81310      sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
81311      db->autoCommit = 1;
81312    }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
81313      /* If this instruction implements a COMMIT and other VMs are writing
81314      ** return an error indicating that the other VMs must complete first.
81315      */
81316      sqlite3VdbeError(p, "cannot commit transaction - "
81317                          "SQL statements in progress");
81318      rc = SQLITE_BUSY;
81319      goto abort_due_to_error;
81320    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
81321      goto vdbe_return;
81322    }else{
81323      db->autoCommit = (u8)desiredAutoCommit;
81324    }
81325    if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
81326      p->pc = (int)(pOp - aOp);
81327      db->autoCommit = (u8)(1-desiredAutoCommit);
81328      p->rc = rc = SQLITE_BUSY;
81329      goto vdbe_return;
81330    }
81331    assert( db->nStatement==0 );
81332    sqlite3CloseSavepoints(db);
81333    if( p->rc==SQLITE_OK ){
81334      rc = SQLITE_DONE;
81335    }else{
81336      rc = SQLITE_ERROR;
81337    }
81338    goto vdbe_return;
81339  }else{
81340    sqlite3VdbeError(p,
81341        (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
81342        (iRollback)?"cannot rollback - no transaction is active":
81343                   "cannot commit - no transaction is active"));
81344
81345    rc = SQLITE_ERROR;
81346    goto abort_due_to_error;
81347  }
81348  break;
81349}
81350
81351/* Opcode: Transaction P1 P2 P3 P4 P5
81352**
81353** Begin a transaction on database P1 if a transaction is not already
81354** active.
81355** If P2 is non-zero, then a write-transaction is started, or if a
81356** read-transaction is already active, it is upgraded to a write-transaction.
81357** If P2 is zero, then a read-transaction is started.
81358**
81359** P1 is the index of the database file on which the transaction is
81360** started.  Index 0 is the main database file and index 1 is the
81361** file used for temporary tables.  Indices of 2 or more are used for
81362** attached databases.
81363**
81364** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
81365** true (this flag is set if the Vdbe may modify more than one row and may
81366** throw an ABORT exception), a statement transaction may also be opened.
81367** More specifically, a statement transaction is opened iff the database
81368** connection is currently not in autocommit mode, or if there are other
81369** active statements. A statement transaction allows the changes made by this
81370** VDBE to be rolled back after an error without having to roll back the
81371** entire transaction. If no error is encountered, the statement transaction
81372** will automatically commit when the VDBE halts.
81373**
81374** If P5!=0 then this opcode also checks the schema cookie against P3
81375** and the schema generation counter against P4.
81376** The cookie changes its value whenever the database schema changes.
81377** This operation is used to detect when that the cookie has changed
81378** and that the current process needs to reread the schema.  If the schema
81379** cookie in P3 differs from the schema cookie in the database header or
81380** if the schema generation counter in P4 differs from the current
81381** generation counter, then an SQLITE_SCHEMA error is raised and execution
81382** halts.  The sqlite3_step() wrapper function might then reprepare the
81383** statement and rerun it from the beginning.
81384*/
81385case OP_Transaction: {
81386  Btree *pBt;
81387  int iMeta;
81388  int iGen;
81389
81390  assert( p->bIsReader );
81391  assert( p->readOnly==0 || pOp->p2==0 );
81392  assert( pOp->p1>=0 && pOp->p1<db->nDb );
81393  assert( DbMaskTest(p->btreeMask, pOp->p1) );
81394  if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
81395    rc = SQLITE_READONLY;
81396    goto abort_due_to_error;
81397  }
81398  pBt = db->aDb[pOp->p1].pBt;
81399
81400  if( pBt ){
81401    rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
81402    testcase( rc==SQLITE_BUSY_SNAPSHOT );
81403    testcase( rc==SQLITE_BUSY_RECOVERY );
81404    if( rc!=SQLITE_OK ){
81405      if( (rc&0xff)==SQLITE_BUSY ){
81406        p->pc = (int)(pOp - aOp);
81407        p->rc = rc;
81408        goto vdbe_return;
81409      }
81410      goto abort_due_to_error;
81411    }
81412
81413    if( pOp->p2 && p->usesStmtJournal
81414     && (db->autoCommit==0 || db->nVdbeRead>1)
81415    ){
81416      assert( sqlite3BtreeIsInTrans(pBt) );
81417      if( p->iStatement==0 ){
81418        assert( db->nStatement>=0 && db->nSavepoint>=0 );
81419        db->nStatement++;
81420        p->iStatement = db->nSavepoint + db->nStatement;
81421      }
81422
81423      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
81424      if( rc==SQLITE_OK ){
81425        rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
81426      }
81427
81428      /* Store the current value of the database handles deferred constraint
81429      ** counter. If the statement transaction needs to be rolled back,
81430      ** the value of this counter needs to be restored too.  */
81431      p->nStmtDefCons = db->nDeferredCons;
81432      p->nStmtDefImmCons = db->nDeferredImmCons;
81433    }
81434
81435    /* Gather the schema version number for checking:
81436    ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
81437    ** version is checked to ensure that the schema has not changed since the
81438    ** SQL statement was prepared.
81439    */
81440    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
81441    iGen = db->aDb[pOp->p1].pSchema->iGeneration;
81442  }else{
81443    iGen = iMeta = 0;
81444  }
81445  assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
81446  if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
81447    sqlite3DbFree(db, p->zErrMsg);
81448    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
81449    /* If the schema-cookie from the database file matches the cookie
81450    ** stored with the in-memory representation of the schema, do
81451    ** not reload the schema from the database file.
81452    **
81453    ** If virtual-tables are in use, this is not just an optimization.
81454    ** Often, v-tables store their data in other SQLite tables, which
81455    ** are queried from within xNext() and other v-table methods using
81456    ** prepared queries. If such a query is out-of-date, we do not want to
81457    ** discard the database schema, as the user code implementing the
81458    ** v-table would have to be ready for the sqlite3_vtab structure itself
81459    ** to be invalidated whenever sqlite3_step() is called from within
81460    ** a v-table method.
81461    */
81462    if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
81463      sqlite3ResetOneSchema(db, pOp->p1);
81464    }
81465    p->expired = 1;
81466    rc = SQLITE_SCHEMA;
81467  }
81468  if( rc ) goto abort_due_to_error;
81469  break;
81470}
81471
81472/* Opcode: ReadCookie P1 P2 P3 * *
81473**
81474** Read cookie number P3 from database P1 and write it into register P2.
81475** P3==1 is the schema version.  P3==2 is the database format.
81476** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
81477** the main database file and P1==1 is the database file used to store
81478** temporary tables.
81479**
81480** There must be a read-lock on the database (either a transaction
81481** must be started or there must be an open cursor) before
81482** executing this instruction.
81483*/
81484case OP_ReadCookie: {               /* out2 */
81485  int iMeta;
81486  int iDb;
81487  int iCookie;
81488
81489  assert( p->bIsReader );
81490  iDb = pOp->p1;
81491  iCookie = pOp->p3;
81492  assert( pOp->p3<SQLITE_N_BTREE_META );
81493  assert( iDb>=0 && iDb<db->nDb );
81494  assert( db->aDb[iDb].pBt!=0 );
81495  assert( DbMaskTest(p->btreeMask, iDb) );
81496
81497  sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
81498  pOut = out2Prerelease(p, pOp);
81499  pOut->u.i = iMeta;
81500  break;
81501}
81502
81503/* Opcode: SetCookie P1 P2 P3 * *
81504**
81505** Write the integer value P3 into cookie number P2 of database P1.
81506** P2==1 is the schema version.  P2==2 is the database format.
81507** P2==3 is the recommended pager cache
81508** size, and so forth.  P1==0 is the main database file and P1==1 is the
81509** database file used to store temporary tables.
81510**
81511** A transaction must be started before executing this opcode.
81512*/
81513case OP_SetCookie: {
81514  Db *pDb;
81515  assert( pOp->p2<SQLITE_N_BTREE_META );
81516  assert( pOp->p1>=0 && pOp->p1<db->nDb );
81517  assert( DbMaskTest(p->btreeMask, pOp->p1) );
81518  assert( p->readOnly==0 );
81519  pDb = &db->aDb[pOp->p1];
81520  assert( pDb->pBt!=0 );
81521  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
81522  /* See note about index shifting on OP_ReadCookie */
81523  rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
81524  if( pOp->p2==BTREE_SCHEMA_VERSION ){
81525    /* When the schema cookie changes, record the new cookie internally */
81526    pDb->pSchema->schema_cookie = pOp->p3;
81527    db->flags |= SQLITE_InternChanges;
81528  }else if( pOp->p2==BTREE_FILE_FORMAT ){
81529    /* Record changes in the file format */
81530    pDb->pSchema->file_format = pOp->p3;
81531  }
81532  if( pOp->p1==1 ){
81533    /* Invalidate all prepared statements whenever the TEMP database
81534    ** schema is changed.  Ticket #1644 */
81535    sqlite3ExpirePreparedStatements(db);
81536    p->expired = 0;
81537  }
81538  if( rc ) goto abort_due_to_error;
81539  break;
81540}
81541
81542/* Opcode: OpenRead P1 P2 P3 P4 P5
81543** Synopsis: root=P2 iDb=P3
81544**
81545** Open a read-only cursor for the database table whose root page is
81546** P2 in a database file.  The database file is determined by P3.
81547** P3==0 means the main database, P3==1 means the database used for
81548** temporary tables, and P3>1 means used the corresponding attached
81549** database.  Give the new cursor an identifier of P1.  The P1
81550** values need not be contiguous but all P1 values should be small integers.
81551** It is an error for P1 to be negative.
81552**
81553** If P5!=0 then use the content of register P2 as the root page, not
81554** the value of P2 itself.
81555**
81556** There will be a read lock on the database whenever there is an
81557** open cursor.  If the database was unlocked prior to this instruction
81558** then a read lock is acquired as part of this instruction.  A read
81559** lock allows other processes to read the database but prohibits
81560** any other process from modifying the database.  The read lock is
81561** released when all cursors are closed.  If this instruction attempts
81562** to get a read lock but fails, the script terminates with an
81563** SQLITE_BUSY error code.
81564**
81565** The P4 value may be either an integer (P4_INT32) or a pointer to
81566** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
81567** structure, then said structure defines the content and collating
81568** sequence of the index being opened. Otherwise, if P4 is an integer
81569** value, it is set to the number of columns in the table.
81570**
81571** See also: OpenWrite, ReopenIdx
81572*/
81573/* Opcode: ReopenIdx P1 P2 P3 P4 P5
81574** Synopsis: root=P2 iDb=P3
81575**
81576** The ReopenIdx opcode works exactly like ReadOpen except that it first
81577** checks to see if the cursor on P1 is already open with a root page
81578** number of P2 and if it is this opcode becomes a no-op.  In other words,
81579** if the cursor is already open, do not reopen it.
81580**
81581** The ReopenIdx opcode may only be used with P5==0 and with P4 being
81582** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
81583** every other ReopenIdx or OpenRead for the same cursor number.
81584**
81585** See the OpenRead opcode documentation for additional information.
81586*/
81587/* Opcode: OpenWrite P1 P2 P3 P4 P5
81588** Synopsis: root=P2 iDb=P3
81589**
81590** Open a read/write cursor named P1 on the table or index whose root
81591** page is P2.  Or if P5!=0 use the content of register P2 to find the
81592** root page.
81593**
81594** The P4 value may be either an integer (P4_INT32) or a pointer to
81595** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
81596** structure, then said structure defines the content and collating
81597** sequence of the index being opened. Otherwise, if P4 is an integer
81598** value, it is set to the number of columns in the table, or to the
81599** largest index of any column of the table that is actually used.
81600**
81601** This instruction works just like OpenRead except that it opens the cursor
81602** in read/write mode.  For a given table, there can be one or more read-only
81603** cursors or a single read/write cursor but not both.
81604**
81605** See also OpenRead.
81606*/
81607case OP_ReopenIdx: {
81608  int nField;
81609  KeyInfo *pKeyInfo;
81610  int p2;
81611  int iDb;
81612  int wrFlag;
81613  Btree *pX;
81614  VdbeCursor *pCur;
81615  Db *pDb;
81616
81617  assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
81618  assert( pOp->p4type==P4_KEYINFO );
81619  pCur = p->apCsr[pOp->p1];
81620  if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
81621    assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
81622    goto open_cursor_set_hints;
81623  }
81624  /* If the cursor is not currently open or is open on a different
81625  ** index, then fall through into OP_OpenRead to force a reopen */
81626case OP_OpenRead:
81627case OP_OpenWrite:
81628
81629  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
81630  assert( p->bIsReader );
81631  assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
81632          || p->readOnly==0 );
81633
81634  if( p->expired ){
81635    rc = SQLITE_ABORT_ROLLBACK;
81636    goto abort_due_to_error;
81637  }
81638
81639  nField = 0;
81640  pKeyInfo = 0;
81641  p2 = pOp->p2;
81642  iDb = pOp->p3;
81643  assert( iDb>=0 && iDb<db->nDb );
81644  assert( DbMaskTest(p->btreeMask, iDb) );
81645  pDb = &db->aDb[iDb];
81646  pX = pDb->pBt;
81647  assert( pX!=0 );
81648  if( pOp->opcode==OP_OpenWrite ){
81649    assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
81650    wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
81651    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81652    if( pDb->pSchema->file_format < p->minWriteFileFormat ){
81653      p->minWriteFileFormat = pDb->pSchema->file_format;
81654    }
81655  }else{
81656    wrFlag = 0;
81657  }
81658  if( pOp->p5 & OPFLAG_P2ISREG ){
81659    assert( p2>0 );
81660    assert( p2<=(p->nMem+1 - p->nCursor) );
81661    pIn2 = &aMem[p2];
81662    assert( memIsValid(pIn2) );
81663    assert( (pIn2->flags & MEM_Int)!=0 );
81664    sqlite3VdbeMemIntegerify(pIn2);
81665    p2 = (int)pIn2->u.i;
81666    /* The p2 value always comes from a prior OP_CreateTable opcode and
81667    ** that opcode will always set the p2 value to 2 or more or else fail.
81668    ** If there were a failure, the prepared statement would have halted
81669    ** before reaching this instruction. */
81670    assert( p2>=2 );
81671  }
81672  if( pOp->p4type==P4_KEYINFO ){
81673    pKeyInfo = pOp->p4.pKeyInfo;
81674    assert( pKeyInfo->enc==ENC(db) );
81675    assert( pKeyInfo->db==db );
81676    nField = pKeyInfo->nField+pKeyInfo->nXField;
81677  }else if( pOp->p4type==P4_INT32 ){
81678    nField = pOp->p4.i;
81679  }
81680  assert( pOp->p1>=0 );
81681  assert( nField>=0 );
81682  testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
81683  pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
81684  if( pCur==0 ) goto no_mem;
81685  pCur->nullRow = 1;
81686  pCur->isOrdered = 1;
81687  pCur->pgnoRoot = p2;
81688#ifdef SQLITE_DEBUG
81689  pCur->wrFlag = wrFlag;
81690#endif
81691  rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
81692  pCur->pKeyInfo = pKeyInfo;
81693  /* Set the VdbeCursor.isTable variable. Previous versions of
81694  ** SQLite used to check if the root-page flags were sane at this point
81695  ** and report database corruption if they were not, but this check has
81696  ** since moved into the btree layer.  */
81697  pCur->isTable = pOp->p4type!=P4_KEYINFO;
81698
81699open_cursor_set_hints:
81700  assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
81701  assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
81702  testcase( pOp->p5 & OPFLAG_BULKCSR );
81703#ifdef SQLITE_ENABLE_CURSOR_HINTS
81704  testcase( pOp->p2 & OPFLAG_SEEKEQ );
81705#endif
81706  sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
81707                               (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
81708  if( rc ) goto abort_due_to_error;
81709  break;
81710}
81711
81712/* Opcode: OpenEphemeral P1 P2 * P4 P5
81713** Synopsis: nColumn=P2
81714**
81715** Open a new cursor P1 to a transient table.
81716** The cursor is always opened read/write even if
81717** the main database is read-only.  The ephemeral
81718** table is deleted automatically when the cursor is closed.
81719**
81720** P2 is the number of columns in the ephemeral table.
81721** The cursor points to a BTree table if P4==0 and to a BTree index
81722** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
81723** that defines the format of keys in the index.
81724**
81725** The P5 parameter can be a mask of the BTREE_* flags defined
81726** in btree.h.  These flags control aspects of the operation of
81727** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
81728** added automatically.
81729*/
81730/* Opcode: OpenAutoindex P1 P2 * P4 *
81731** Synopsis: nColumn=P2
81732**
81733** This opcode works the same as OP_OpenEphemeral.  It has a
81734** different name to distinguish its use.  Tables created using
81735** by this opcode will be used for automatically created transient
81736** indices in joins.
81737*/
81738case OP_OpenAutoindex:
81739case OP_OpenEphemeral: {
81740  VdbeCursor *pCx;
81741  KeyInfo *pKeyInfo;
81742
81743  static const int vfsFlags =
81744      SQLITE_OPEN_READWRITE |
81745      SQLITE_OPEN_CREATE |
81746      SQLITE_OPEN_EXCLUSIVE |
81747      SQLITE_OPEN_DELETEONCLOSE |
81748      SQLITE_OPEN_TRANSIENT_DB;
81749  assert( pOp->p1>=0 );
81750  assert( pOp->p2>=0 );
81751  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
81752  if( pCx==0 ) goto no_mem;
81753  pCx->nullRow = 1;
81754  pCx->isEphemeral = 1;
81755  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
81756                        BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
81757  if( rc==SQLITE_OK ){
81758    rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1);
81759  }
81760  if( rc==SQLITE_OK ){
81761    /* If a transient index is required, create it by calling
81762    ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
81763    ** opening it. If a transient table is required, just use the
81764    ** automatically created table with root-page 1 (an BLOB_INTKEY table).
81765    */
81766    if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
81767      int pgno;
81768      assert( pOp->p4type==P4_KEYINFO );
81769      rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
81770      if( rc==SQLITE_OK ){
81771        assert( pgno==MASTER_ROOT+1 );
81772        assert( pKeyInfo->db==db );
81773        assert( pKeyInfo->enc==ENC(db) );
81774        rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
81775                                pKeyInfo, pCx->uc.pCursor);
81776      }
81777      pCx->isTable = 0;
81778    }else{
81779      rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
81780                              0, pCx->uc.pCursor);
81781      pCx->isTable = 1;
81782    }
81783  }
81784  if( rc ) goto abort_due_to_error;
81785  pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
81786  break;
81787}
81788
81789/* Opcode: SorterOpen P1 P2 P3 P4 *
81790**
81791** This opcode works like OP_OpenEphemeral except that it opens
81792** a transient index that is specifically designed to sort large
81793** tables using an external merge-sort algorithm.
81794**
81795** If argument P3 is non-zero, then it indicates that the sorter may
81796** assume that a stable sort considering the first P3 fields of each
81797** key is sufficient to produce the required results.
81798*/
81799case OP_SorterOpen: {
81800  VdbeCursor *pCx;
81801
81802  assert( pOp->p1>=0 );
81803  assert( pOp->p2>=0 );
81804  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
81805  if( pCx==0 ) goto no_mem;
81806  pCx->pKeyInfo = pOp->p4.pKeyInfo;
81807  assert( pCx->pKeyInfo->db==db );
81808  assert( pCx->pKeyInfo->enc==ENC(db) );
81809  rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
81810  if( rc ) goto abort_due_to_error;
81811  break;
81812}
81813
81814/* Opcode: SequenceTest P1 P2 * * *
81815** Synopsis: if( cursor[P1].ctr++ ) pc = P2
81816**
81817** P1 is a sorter cursor. If the sequence counter is currently zero, jump
81818** to P2. Regardless of whether or not the jump is taken, increment the
81819** the sequence value.
81820*/
81821case OP_SequenceTest: {
81822  VdbeCursor *pC;
81823  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81824  pC = p->apCsr[pOp->p1];
81825  assert( isSorter(pC) );
81826  if( (pC->seqCount++)==0 ){
81827    goto jump_to_p2;
81828  }
81829  break;
81830}
81831
81832/* Opcode: OpenPseudo P1 P2 P3 * *
81833** Synopsis: P3 columns in r[P2]
81834**
81835** Open a new cursor that points to a fake table that contains a single
81836** row of data.  The content of that one row is the content of memory
81837** register P2.  In other words, cursor P1 becomes an alias for the
81838** MEM_Blob content contained in register P2.
81839**
81840** A pseudo-table created by this opcode is used to hold a single
81841** row output from the sorter so that the row can be decomposed into
81842** individual columns using the OP_Column opcode.  The OP_Column opcode
81843** is the only cursor opcode that works with a pseudo-table.
81844**
81845** P3 is the number of fields in the records that will be stored by
81846** the pseudo-table.
81847*/
81848case OP_OpenPseudo: {
81849  VdbeCursor *pCx;
81850
81851  assert( pOp->p1>=0 );
81852  assert( pOp->p3>=0 );
81853  pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
81854  if( pCx==0 ) goto no_mem;
81855  pCx->nullRow = 1;
81856  pCx->uc.pseudoTableReg = pOp->p2;
81857  pCx->isTable = 1;
81858  assert( pOp->p5==0 );
81859  break;
81860}
81861
81862/* Opcode: Close P1 * * * *
81863**
81864** Close a cursor previously opened as P1.  If P1 is not
81865** currently open, this instruction is a no-op.
81866*/
81867case OP_Close: {
81868  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81869  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
81870  p->apCsr[pOp->p1] = 0;
81871  break;
81872}
81873
81874#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
81875/* Opcode: ColumnsUsed P1 * * P4 *
81876**
81877** This opcode (which only exists if SQLite was compiled with
81878** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
81879** table or index for cursor P1 are used.  P4 is a 64-bit integer
81880** (P4_INT64) in which the first 63 bits are one for each of the
81881** first 63 columns of the table or index that are actually used
81882** by the cursor.  The high-order bit is set if any column after
81883** the 64th is used.
81884*/
81885case OP_ColumnsUsed: {
81886  VdbeCursor *pC;
81887  pC = p->apCsr[pOp->p1];
81888  assert( pC->eCurType==CURTYPE_BTREE );
81889  pC->maskUsed = *(u64*)pOp->p4.pI64;
81890  break;
81891}
81892#endif
81893
81894/* Opcode: SeekGE P1 P2 P3 P4 *
81895** Synopsis: key=r[P3@P4]
81896**
81897** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
81898** use the value in register P3 as the key.  If cursor P1 refers
81899** to an SQL index, then P3 is the first in an array of P4 registers
81900** that are used as an unpacked index key.
81901**
81902** Reposition cursor P1 so that  it points to the smallest entry that
81903** is greater than or equal to the key value. If there are no records
81904** greater than or equal to the key and P2 is not zero, then jump to P2.
81905**
81906** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
81907** opcode will always land on a record that equally equals the key, or
81908** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
81909** opcode must be followed by an IdxLE opcode with the same arguments.
81910** The IdxLE opcode will be skipped if this opcode succeeds, but the
81911** IdxLE opcode will be used on subsequent loop iterations.
81912**
81913** This opcode leaves the cursor configured to move in forward order,
81914** from the beginning toward the end.  In other words, the cursor is
81915** configured to use Next, not Prev.
81916**
81917** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
81918*/
81919/* Opcode: SeekGT P1 P2 P3 P4 *
81920** Synopsis: key=r[P3@P4]
81921**
81922** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
81923** use the value in register P3 as a key. If cursor P1 refers
81924** to an SQL index, then P3 is the first in an array of P4 registers
81925** that are used as an unpacked index key.
81926**
81927** Reposition cursor P1 so that  it points to the smallest entry that
81928** is greater than the key value. If there are no records greater than
81929** the key and P2 is not zero, then jump to P2.
81930**
81931** This opcode leaves the cursor configured to move in forward order,
81932** from the beginning toward the end.  In other words, the cursor is
81933** configured to use Next, not Prev.
81934**
81935** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
81936*/
81937/* Opcode: SeekLT P1 P2 P3 P4 *
81938** Synopsis: key=r[P3@P4]
81939**
81940** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
81941** use the value in register P3 as a key. If cursor P1 refers
81942** to an SQL index, then P3 is the first in an array of P4 registers
81943** that are used as an unpacked index key.
81944**
81945** Reposition cursor P1 so that  it points to the largest entry that
81946** is less than the key value. If there are no records less than
81947** the key and P2 is not zero, then jump to P2.
81948**
81949** This opcode leaves the cursor configured to move in reverse order,
81950** from the end toward the beginning.  In other words, the cursor is
81951** configured to use Prev, not Next.
81952**
81953** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
81954*/
81955/* Opcode: SeekLE P1 P2 P3 P4 *
81956** Synopsis: key=r[P3@P4]
81957**
81958** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
81959** use the value in register P3 as a key. If cursor P1 refers
81960** to an SQL index, then P3 is the first in an array of P4 registers
81961** that are used as an unpacked index key.
81962**
81963** Reposition cursor P1 so that it points to the largest entry that
81964** is less than or equal to the key value. If there are no records
81965** less than or equal to the key and P2 is not zero, then jump to P2.
81966**
81967** This opcode leaves the cursor configured to move in reverse order,
81968** from the end toward the beginning.  In other words, the cursor is
81969** configured to use Prev, not Next.
81970**
81971** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
81972** opcode will always land on a record that equally equals the key, or
81973** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
81974** opcode must be followed by an IdxGE opcode with the same arguments.
81975** The IdxGE opcode will be skipped if this opcode succeeds, but the
81976** IdxGE opcode will be used on subsequent loop iterations.
81977**
81978** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
81979*/
81980case OP_SeekLT:         /* jump, in3 */
81981case OP_SeekLE:         /* jump, in3 */
81982case OP_SeekGE:         /* jump, in3 */
81983case OP_SeekGT: {       /* jump, in3 */
81984  int res;           /* Comparison result */
81985  int oc;            /* Opcode */
81986  VdbeCursor *pC;    /* The cursor to seek */
81987  UnpackedRecord r;  /* The key to seek for */
81988  int nField;        /* Number of columns or fields in the key */
81989  i64 iKey;          /* The rowid we are to seek to */
81990  int eqOnly;        /* Only interested in == results */
81991
81992  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81993  assert( pOp->p2!=0 );
81994  pC = p->apCsr[pOp->p1];
81995  assert( pC!=0 );
81996  assert( pC->eCurType==CURTYPE_BTREE );
81997  assert( OP_SeekLE == OP_SeekLT+1 );
81998  assert( OP_SeekGE == OP_SeekLT+2 );
81999  assert( OP_SeekGT == OP_SeekLT+3 );
82000  assert( pC->isOrdered );
82001  assert( pC->uc.pCursor!=0 );
82002  oc = pOp->opcode;
82003  eqOnly = 0;
82004  pC->nullRow = 0;
82005#ifdef SQLITE_DEBUG
82006  pC->seekOp = pOp->opcode;
82007#endif
82008
82009  if( pC->isTable ){
82010    /* The BTREE_SEEK_EQ flag is only set on index cursors */
82011    assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
82012              || CORRUPT_DB );
82013
82014    /* The input value in P3 might be of any type: integer, real, string,
82015    ** blob, or NULL.  But it needs to be an integer before we can do
82016    ** the seek, so convert it. */
82017    pIn3 = &aMem[pOp->p3];
82018    if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
82019      applyNumericAffinity(pIn3, 0);
82020    }
82021    iKey = sqlite3VdbeIntValue(pIn3);
82022
82023    /* If the P3 value could not be converted into an integer without
82024    ** loss of information, then special processing is required... */
82025    if( (pIn3->flags & MEM_Int)==0 ){
82026      if( (pIn3->flags & MEM_Real)==0 ){
82027        /* If the P3 value cannot be converted into any kind of a number,
82028        ** then the seek is not possible, so jump to P2 */
82029        VdbeBranchTaken(1,2); goto jump_to_p2;
82030        break;
82031      }
82032
82033      /* If the approximation iKey is larger than the actual real search
82034      ** term, substitute >= for > and < for <=. e.g. if the search term
82035      ** is 4.9 and the integer approximation 5:
82036      **
82037      **        (x >  4.9)    ->     (x >= 5)
82038      **        (x <= 4.9)    ->     (x <  5)
82039      */
82040      if( pIn3->u.r<(double)iKey ){
82041        assert( OP_SeekGE==(OP_SeekGT-1) );
82042        assert( OP_SeekLT==(OP_SeekLE-1) );
82043        assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
82044        if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
82045      }
82046
82047      /* If the approximation iKey is smaller than the actual real search
82048      ** term, substitute <= for < and > for >=.  */
82049      else if( pIn3->u.r>(double)iKey ){
82050        assert( OP_SeekLE==(OP_SeekLT+1) );
82051        assert( OP_SeekGT==(OP_SeekGE+1) );
82052        assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
82053        if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
82054      }
82055    }
82056    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
82057    pC->movetoTarget = iKey;  /* Used by OP_Delete */
82058    if( rc!=SQLITE_OK ){
82059      goto abort_due_to_error;
82060    }
82061  }else{
82062    /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
82063    ** OP_SeekLE opcodes are allowed, and these must be immediately followed
82064    ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
82065    */
82066    if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
82067      eqOnly = 1;
82068      assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
82069      assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
82070      assert( pOp[1].p1==pOp[0].p1 );
82071      assert( pOp[1].p2==pOp[0].p2 );
82072      assert( pOp[1].p3==pOp[0].p3 );
82073      assert( pOp[1].p4.i==pOp[0].p4.i );
82074    }
82075
82076    nField = pOp->p4.i;
82077    assert( pOp->p4type==P4_INT32 );
82078    assert( nField>0 );
82079    r.pKeyInfo = pC->pKeyInfo;
82080    r.nField = (u16)nField;
82081
82082    /* The next line of code computes as follows, only faster:
82083    **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
82084    **     r.default_rc = -1;
82085    **   }else{
82086    **     r.default_rc = +1;
82087    **   }
82088    */
82089    r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
82090    assert( oc!=OP_SeekGT || r.default_rc==-1 );
82091    assert( oc!=OP_SeekLE || r.default_rc==-1 );
82092    assert( oc!=OP_SeekGE || r.default_rc==+1 );
82093    assert( oc!=OP_SeekLT || r.default_rc==+1 );
82094
82095    r.aMem = &aMem[pOp->p3];
82096#ifdef SQLITE_DEBUG
82097    { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
82098#endif
82099    r.eqSeen = 0;
82100    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
82101    if( rc!=SQLITE_OK ){
82102      goto abort_due_to_error;
82103    }
82104    if( eqOnly && r.eqSeen==0 ){
82105      assert( res!=0 );
82106      goto seek_not_found;
82107    }
82108  }
82109  pC->deferredMoveto = 0;
82110  pC->cacheStatus = CACHE_STALE;
82111#ifdef SQLITE_TEST
82112  sqlite3_search_count++;
82113#endif
82114  if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
82115    if( res<0 || (res==0 && oc==OP_SeekGT) ){
82116      res = 0;
82117      rc = sqlite3BtreeNext(pC->uc.pCursor, &res);
82118      if( rc!=SQLITE_OK ) goto abort_due_to_error;
82119    }else{
82120      res = 0;
82121    }
82122  }else{
82123    assert( oc==OP_SeekLT || oc==OP_SeekLE );
82124    if( res>0 || (res==0 && oc==OP_SeekLT) ){
82125      res = 0;
82126      rc = sqlite3BtreePrevious(pC->uc.pCursor, &res);
82127      if( rc!=SQLITE_OK ) goto abort_due_to_error;
82128    }else{
82129      /* res might be negative because the table is empty.  Check to
82130      ** see if this is the case.
82131      */
82132      res = sqlite3BtreeEof(pC->uc.pCursor);
82133    }
82134  }
82135seek_not_found:
82136  assert( pOp->p2>0 );
82137  VdbeBranchTaken(res!=0,2);
82138  if( res ){
82139    goto jump_to_p2;
82140  }else if( eqOnly ){
82141    assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
82142    pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
82143  }
82144  break;
82145}
82146
82147/* Opcode: Found P1 P2 P3 P4 *
82148** Synopsis: key=r[P3@P4]
82149**
82150** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
82151** P4>0 then register P3 is the first of P4 registers that form an unpacked
82152** record.
82153**
82154** Cursor P1 is on an index btree.  If the record identified by P3 and P4
82155** is a prefix of any entry in P1 then a jump is made to P2 and
82156** P1 is left pointing at the matching entry.
82157**
82158** This operation leaves the cursor in a state where it can be
82159** advanced in the forward direction.  The Next instruction will work,
82160** but not the Prev instruction.
82161**
82162** See also: NotFound, NoConflict, NotExists. SeekGe
82163*/
82164/* Opcode: NotFound P1 P2 P3 P4 *
82165** Synopsis: key=r[P3@P4]
82166**
82167** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
82168** P4>0 then register P3 is the first of P4 registers that form an unpacked
82169** record.
82170**
82171** Cursor P1 is on an index btree.  If the record identified by P3 and P4
82172** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
82173** does contain an entry whose prefix matches the P3/P4 record then control
82174** falls through to the next instruction and P1 is left pointing at the
82175** matching entry.
82176**
82177** This operation leaves the cursor in a state where it cannot be
82178** advanced in either direction.  In other words, the Next and Prev
82179** opcodes do not work after this operation.
82180**
82181** See also: Found, NotExists, NoConflict
82182*/
82183/* Opcode: NoConflict P1 P2 P3 P4 *
82184** Synopsis: key=r[P3@P4]
82185**
82186** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
82187** P4>0 then register P3 is the first of P4 registers that form an unpacked
82188** record.
82189**
82190** Cursor P1 is on an index btree.  If the record identified by P3 and P4
82191** contains any NULL value, jump immediately to P2.  If all terms of the
82192** record are not-NULL then a check is done to determine if any row in the
82193** P1 index btree has a matching key prefix.  If there are no matches, jump
82194** immediately to P2.  If there is a match, fall through and leave the P1
82195** cursor pointing to the matching row.
82196**
82197** This opcode is similar to OP_NotFound with the exceptions that the
82198** branch is always taken if any part of the search key input is NULL.
82199**
82200** This operation leaves the cursor in a state where it cannot be
82201** advanced in either direction.  In other words, the Next and Prev
82202** opcodes do not work after this operation.
82203**
82204** See also: NotFound, Found, NotExists
82205*/
82206case OP_NoConflict:     /* jump, in3 */
82207case OP_NotFound:       /* jump, in3 */
82208case OP_Found: {        /* jump, in3 */
82209  int alreadyExists;
82210  int takeJump;
82211  int ii;
82212  VdbeCursor *pC;
82213  int res;
82214  UnpackedRecord *pFree;
82215  UnpackedRecord *pIdxKey;
82216  UnpackedRecord r;
82217
82218#ifdef SQLITE_TEST
82219  if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
82220#endif
82221
82222  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82223  assert( pOp->p4type==P4_INT32 );
82224  pC = p->apCsr[pOp->p1];
82225  assert( pC!=0 );
82226#ifdef SQLITE_DEBUG
82227  pC->seekOp = pOp->opcode;
82228#endif
82229  pIn3 = &aMem[pOp->p3];
82230  assert( pC->eCurType==CURTYPE_BTREE );
82231  assert( pC->uc.pCursor!=0 );
82232  assert( pC->isTable==0 );
82233  if( pOp->p4.i>0 ){
82234    r.pKeyInfo = pC->pKeyInfo;
82235    r.nField = (u16)pOp->p4.i;
82236    r.aMem = pIn3;
82237#ifdef SQLITE_DEBUG
82238    for(ii=0; ii<r.nField; ii++){
82239      assert( memIsValid(&r.aMem[ii]) );
82240      assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
82241      if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
82242    }
82243#endif
82244    pIdxKey = &r;
82245    pFree = 0;
82246  }else{
82247    pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
82248    if( pIdxKey==0 ) goto no_mem;
82249    assert( pIn3->flags & MEM_Blob );
82250    (void)ExpandBlob(pIn3);
82251    sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
82252  }
82253  pIdxKey->default_rc = 0;
82254  takeJump = 0;
82255  if( pOp->opcode==OP_NoConflict ){
82256    /* For the OP_NoConflict opcode, take the jump if any of the
82257    ** input fields are NULL, since any key with a NULL will not
82258    ** conflict */
82259    for(ii=0; ii<pIdxKey->nField; ii++){
82260      if( pIdxKey->aMem[ii].flags & MEM_Null ){
82261        takeJump = 1;
82262        break;
82263      }
82264    }
82265  }
82266  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
82267  if( pFree ) sqlite3DbFree(db, pFree);
82268  if( rc!=SQLITE_OK ){
82269    goto abort_due_to_error;
82270  }
82271  pC->seekResult = res;
82272  alreadyExists = (res==0);
82273  pC->nullRow = 1-alreadyExists;
82274  pC->deferredMoveto = 0;
82275  pC->cacheStatus = CACHE_STALE;
82276  if( pOp->opcode==OP_Found ){
82277    VdbeBranchTaken(alreadyExists!=0,2);
82278    if( alreadyExists ) goto jump_to_p2;
82279  }else{
82280    VdbeBranchTaken(takeJump||alreadyExists==0,2);
82281    if( takeJump || !alreadyExists ) goto jump_to_p2;
82282  }
82283  break;
82284}
82285
82286/* Opcode: SeekRowid P1 P2 P3 * *
82287** Synopsis: intkey=r[P3]
82288**
82289** P1 is the index of a cursor open on an SQL table btree (with integer
82290** keys).  If register P3 does not contain an integer or if P1 does not
82291** contain a record with rowid P3 then jump immediately to P2.
82292** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
82293** a record with rowid P3 then
82294** leave the cursor pointing at that record and fall through to the next
82295** instruction.
82296**
82297** The OP_NotExists opcode performs the same operation, but with OP_NotExists
82298** the P3 register must be guaranteed to contain an integer value.  With this
82299** opcode, register P3 might not contain an integer.
82300**
82301** The OP_NotFound opcode performs the same operation on index btrees
82302** (with arbitrary multi-value keys).
82303**
82304** This opcode leaves the cursor in a state where it cannot be advanced
82305** in either direction.  In other words, the Next and Prev opcodes will
82306** not work following this opcode.
82307**
82308** See also: Found, NotFound, NoConflict, SeekRowid
82309*/
82310/* Opcode: NotExists P1 P2 P3 * *
82311** Synopsis: intkey=r[P3]
82312**
82313** P1 is the index of a cursor open on an SQL table btree (with integer
82314** keys).  P3 is an integer rowid.  If P1 does not contain a record with
82315** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
82316** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
82317** leave the cursor pointing at that record and fall through to the next
82318** instruction.
82319**
82320** The OP_SeekRowid opcode performs the same operation but also allows the
82321** P3 register to contain a non-integer value, in which case the jump is
82322** always taken.  This opcode requires that P3 always contain an integer.
82323**
82324** The OP_NotFound opcode performs the same operation on index btrees
82325** (with arbitrary multi-value keys).
82326**
82327** This opcode leaves the cursor in a state where it cannot be advanced
82328** in either direction.  In other words, the Next and Prev opcodes will
82329** not work following this opcode.
82330**
82331** See also: Found, NotFound, NoConflict, SeekRowid
82332*/
82333case OP_SeekRowid: {        /* jump, in3 */
82334  VdbeCursor *pC;
82335  BtCursor *pCrsr;
82336  int res;
82337  u64 iKey;
82338
82339  pIn3 = &aMem[pOp->p3];
82340  if( (pIn3->flags & MEM_Int)==0 ){
82341    applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
82342    if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
82343  }
82344  /* Fall through into OP_NotExists */
82345case OP_NotExists:          /* jump, in3 */
82346  pIn3 = &aMem[pOp->p3];
82347  assert( pIn3->flags & MEM_Int );
82348  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82349  pC = p->apCsr[pOp->p1];
82350  assert( pC!=0 );
82351#ifdef SQLITE_DEBUG
82352  pC->seekOp = 0;
82353#endif
82354  assert( pC->isTable );
82355  assert( pC->eCurType==CURTYPE_BTREE );
82356  pCrsr = pC->uc.pCursor;
82357  assert( pCrsr!=0 );
82358  res = 0;
82359  iKey = pIn3->u.i;
82360  rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
82361  assert( rc==SQLITE_OK || res==0 );
82362  pC->movetoTarget = iKey;  /* Used by OP_Delete */
82363  pC->nullRow = 0;
82364  pC->cacheStatus = CACHE_STALE;
82365  pC->deferredMoveto = 0;
82366  VdbeBranchTaken(res!=0,2);
82367  pC->seekResult = res;
82368  if( res!=0 ){
82369    assert( rc==SQLITE_OK );
82370    if( pOp->p2==0 ){
82371      rc = SQLITE_CORRUPT_BKPT;
82372    }else{
82373      goto jump_to_p2;
82374    }
82375  }
82376  if( rc ) goto abort_due_to_error;
82377  break;
82378}
82379
82380/* Opcode: Sequence P1 P2 * * *
82381** Synopsis: r[P2]=cursor[P1].ctr++
82382**
82383** Find the next available sequence number for cursor P1.
82384** Write the sequence number into register P2.
82385** The sequence number on the cursor is incremented after this
82386** instruction.
82387*/
82388case OP_Sequence: {           /* out2 */
82389  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82390  assert( p->apCsr[pOp->p1]!=0 );
82391  assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
82392  pOut = out2Prerelease(p, pOp);
82393  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
82394  break;
82395}
82396
82397
82398/* Opcode: NewRowid P1 P2 P3 * *
82399** Synopsis: r[P2]=rowid
82400**
82401** Get a new integer record number (a.k.a "rowid") used as the key to a table.
82402** The record number is not previously used as a key in the database
82403** table that cursor P1 points to.  The new record number is written
82404** written to register P2.
82405**
82406** If P3>0 then P3 is a register in the root frame of this VDBE that holds
82407** the largest previously generated record number. No new record numbers are
82408** allowed to be less than this value. When this value reaches its maximum,
82409** an SQLITE_FULL error is generated. The P3 register is updated with the '
82410** generated record number. This P3 mechanism is used to help implement the
82411** AUTOINCREMENT feature.
82412*/
82413case OP_NewRowid: {           /* out2 */
82414  i64 v;                 /* The new rowid */
82415  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
82416  int res;               /* Result of an sqlite3BtreeLast() */
82417  int cnt;               /* Counter to limit the number of searches */
82418  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
82419  VdbeFrame *pFrame;     /* Root frame of VDBE */
82420
82421  v = 0;
82422  res = 0;
82423  pOut = out2Prerelease(p, pOp);
82424  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82425  pC = p->apCsr[pOp->p1];
82426  assert( pC!=0 );
82427  assert( pC->eCurType==CURTYPE_BTREE );
82428  assert( pC->uc.pCursor!=0 );
82429  {
82430    /* The next rowid or record number (different terms for the same
82431    ** thing) is obtained in a two-step algorithm.
82432    **
82433    ** First we attempt to find the largest existing rowid and add one
82434    ** to that.  But if the largest existing rowid is already the maximum
82435    ** positive integer, we have to fall through to the second
82436    ** probabilistic algorithm
82437    **
82438    ** The second algorithm is to select a rowid at random and see if
82439    ** it already exists in the table.  If it does not exist, we have
82440    ** succeeded.  If the random rowid does exist, we select a new one
82441    ** and try again, up to 100 times.
82442    */
82443    assert( pC->isTable );
82444
82445#ifdef SQLITE_32BIT_ROWID
82446#   define MAX_ROWID 0x7fffffff
82447#else
82448    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
82449    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
82450    ** to provide the constant while making all compilers happy.
82451    */
82452#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
82453#endif
82454
82455    if( !pC->useRandomRowid ){
82456      rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
82457      if( rc!=SQLITE_OK ){
82458        goto abort_due_to_error;
82459      }
82460      if( res ){
82461        v = 1;   /* IMP: R-61914-48074 */
82462      }else{
82463        assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
82464        v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
82465        if( v>=MAX_ROWID ){
82466          pC->useRandomRowid = 1;
82467        }else{
82468          v++;   /* IMP: R-29538-34987 */
82469        }
82470      }
82471    }
82472
82473#ifndef SQLITE_OMIT_AUTOINCREMENT
82474    if( pOp->p3 ){
82475      /* Assert that P3 is a valid memory cell. */
82476      assert( pOp->p3>0 );
82477      if( p->pFrame ){
82478        for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
82479        /* Assert that P3 is a valid memory cell. */
82480        assert( pOp->p3<=pFrame->nMem );
82481        pMem = &pFrame->aMem[pOp->p3];
82482      }else{
82483        /* Assert that P3 is a valid memory cell. */
82484        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
82485        pMem = &aMem[pOp->p3];
82486        memAboutToChange(p, pMem);
82487      }
82488      assert( memIsValid(pMem) );
82489
82490      REGISTER_TRACE(pOp->p3, pMem);
82491      sqlite3VdbeMemIntegerify(pMem);
82492      assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
82493      if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
82494        rc = SQLITE_FULL;   /* IMP: R-17817-00630 */
82495        goto abort_due_to_error;
82496      }
82497      if( v<pMem->u.i+1 ){
82498        v = pMem->u.i + 1;
82499      }
82500      pMem->u.i = v;
82501    }
82502#endif
82503    if( pC->useRandomRowid ){
82504      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
82505      ** largest possible integer (9223372036854775807) then the database
82506      ** engine starts picking positive candidate ROWIDs at random until
82507      ** it finds one that is not previously used. */
82508      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
82509                             ** an AUTOINCREMENT table. */
82510      cnt = 0;
82511      do{
82512        sqlite3_randomness(sizeof(v), &v);
82513        v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
82514      }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
82515                                                 0, &res))==SQLITE_OK)
82516            && (res==0)
82517            && (++cnt<100));
82518      if( rc ) goto abort_due_to_error;
82519      if( res==0 ){
82520        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
82521        goto abort_due_to_error;
82522      }
82523      assert( v>0 );  /* EV: R-40812-03570 */
82524    }
82525    pC->deferredMoveto = 0;
82526    pC->cacheStatus = CACHE_STALE;
82527  }
82528  pOut->u.i = v;
82529  break;
82530}
82531
82532/* Opcode: Insert P1 P2 P3 P4 P5
82533** Synopsis: intkey=r[P3] data=r[P2]
82534**
82535** Write an entry into the table of cursor P1.  A new entry is
82536** created if it doesn't already exist or the data for an existing
82537** entry is overwritten.  The data is the value MEM_Blob stored in register
82538** number P2. The key is stored in register P3. The key must
82539** be a MEM_Int.
82540**
82541** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
82542** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
82543** then rowid is stored for subsequent return by the
82544** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
82545**
82546** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
82547** run faster by avoiding an unnecessary seek on cursor P1.  However,
82548** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
82549** seeks on the cursor or if the most recent seek used a key equal to P3.
82550**
82551** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
82552** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
82553** is part of an INSERT operation.  The difference is only important to
82554** the update hook.
82555**
82556** Parameter P4 may point to a Table structure, or may be NULL. If it is
82557** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
82558** following a successful insert.
82559**
82560** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
82561** allocated, then ownership of P2 is transferred to the pseudo-cursor
82562** and register P2 becomes ephemeral.  If the cursor is changed, the
82563** value of register P2 will then change.  Make sure this does not
82564** cause any problems.)
82565**
82566** This instruction only works on tables.  The equivalent instruction
82567** for indices is OP_IdxInsert.
82568*/
82569/* Opcode: InsertInt P1 P2 P3 P4 P5
82570** Synopsis: intkey=P3 data=r[P2]
82571**
82572** This works exactly like OP_Insert except that the key is the
82573** integer value P3, not the value of the integer stored in register P3.
82574*/
82575case OP_Insert:
82576case OP_InsertInt: {
82577  Mem *pData;       /* MEM cell holding data for the record to be inserted */
82578  Mem *pKey;        /* MEM cell holding key  for the record */
82579  VdbeCursor *pC;   /* Cursor to table into which insert is written */
82580  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
82581  const char *zDb;  /* database name - used by the update hook */
82582  Table *pTab;      /* Table structure - used by update and pre-update hooks */
82583  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
82584  BtreePayload x;   /* Payload to be inserted */
82585
82586  op = 0;
82587  pData = &aMem[pOp->p2];
82588  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82589  assert( memIsValid(pData) );
82590  pC = p->apCsr[pOp->p1];
82591  assert( pC!=0 );
82592  assert( pC->eCurType==CURTYPE_BTREE );
82593  assert( pC->uc.pCursor!=0 );
82594  assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
82595  assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
82596  REGISTER_TRACE(pOp->p2, pData);
82597
82598  if( pOp->opcode==OP_Insert ){
82599    pKey = &aMem[pOp->p3];
82600    assert( pKey->flags & MEM_Int );
82601    assert( memIsValid(pKey) );
82602    REGISTER_TRACE(pOp->p3, pKey);
82603    x.nKey = pKey->u.i;
82604  }else{
82605    assert( pOp->opcode==OP_InsertInt );
82606    x.nKey = pOp->p3;
82607  }
82608
82609  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
82610    assert( pC->iDb>=0 );
82611    zDb = db->aDb[pC->iDb].zDbSName;
82612    pTab = pOp->p4.pTab;
82613    assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
82614    op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
82615  }else{
82616    pTab = 0; /* Not needed.  Silence a compiler warning. */
82617    zDb = 0;  /* Not needed.  Silence a compiler warning. */
82618  }
82619
82620#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
82621  /* Invoke the pre-update hook, if any */
82622  if( db->xPreUpdateCallback
82623   && pOp->p4type==P4_TABLE
82624   && !(pOp->p5 & OPFLAG_ISUPDATE)
82625  ){
82626    sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2);
82627  }
82628  if( pOp->p5 & OPFLAG_ISNOOP ) break;
82629#endif
82630
82631  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
82632  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
82633  if( pData->flags & MEM_Null ){
82634    x.pData = 0;
82635    x.nData = 0;
82636  }else{
82637    assert( pData->flags & (MEM_Blob|MEM_Str) );
82638    x.pData = pData->z;
82639    x.nData = pData->n;
82640  }
82641  seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
82642  if( pData->flags & MEM_Zero ){
82643    x.nZero = pData->u.nZero;
82644  }else{
82645    x.nZero = 0;
82646  }
82647  x.pKey = 0;
82648  rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
82649      (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
82650  );
82651  pC->deferredMoveto = 0;
82652  pC->cacheStatus = CACHE_STALE;
82653
82654  /* Invoke the update-hook if required. */
82655  if( rc ) goto abort_due_to_error;
82656  if( db->xUpdateCallback && op ){
82657    db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey);
82658  }
82659  break;
82660}
82661
82662/* Opcode: Delete P1 P2 P3 P4 P5
82663**
82664** Delete the record at which the P1 cursor is currently pointing.
82665**
82666** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
82667** the cursor will be left pointing at  either the next or the previous
82668** record in the table. If it is left pointing at the next record, then
82669** the next Next instruction will be a no-op. As a result, in this case
82670** it is ok to delete a record from within a Next loop. If
82671** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
82672** left in an undefined state.
82673**
82674** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
82675** delete one of several associated with deleting a table row and all its
82676** associated index entries.  Exactly one of those deletes is the "primary"
82677** delete.  The others are all on OPFLAG_FORDELETE cursors or else are
82678** marked with the AUXDELETE flag.
82679**
82680** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
82681** change count is incremented (otherwise not).
82682**
82683** P1 must not be pseudo-table.  It has to be a real table with
82684** multiple rows.
82685**
82686** If P4 is not NULL then it points to a Table object. In this case either
82687** the update or pre-update hook, or both, may be invoked. The P1 cursor must
82688** have been positioned using OP_NotFound prior to invoking this opcode in
82689** this case. Specifically, if one is configured, the pre-update hook is
82690** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
82691** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
82692**
82693** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
82694** of the memory cell that contains the value that the rowid of the row will
82695** be set to by the update.
82696*/
82697case OP_Delete: {
82698  VdbeCursor *pC;
82699  const char *zDb;
82700  Table *pTab;
82701  int opflags;
82702
82703  opflags = pOp->p2;
82704  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82705  pC = p->apCsr[pOp->p1];
82706  assert( pC!=0 );
82707  assert( pC->eCurType==CURTYPE_BTREE );
82708  assert( pC->uc.pCursor!=0 );
82709  assert( pC->deferredMoveto==0 );
82710
82711#ifdef SQLITE_DEBUG
82712  if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
82713    /* If p5 is zero, the seek operation that positioned the cursor prior to
82714    ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
82715    ** the row that is being deleted */
82716    i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
82717    assert( pC->movetoTarget==iKey );
82718  }
82719#endif
82720
82721  /* If the update-hook or pre-update-hook will be invoked, set zDb to
82722  ** the name of the db to pass as to it. Also set local pTab to a copy
82723  ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
82724  ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
82725  ** VdbeCursor.movetoTarget to the current rowid.  */
82726  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
82727    assert( pC->iDb>=0 );
82728    assert( pOp->p4.pTab!=0 );
82729    zDb = db->aDb[pC->iDb].zDbSName;
82730    pTab = pOp->p4.pTab;
82731    if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
82732      pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
82733    }
82734  }else{
82735    zDb = 0;   /* Not needed.  Silence a compiler warning. */
82736    pTab = 0;  /* Not needed.  Silence a compiler warning. */
82737  }
82738
82739#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
82740  /* Invoke the pre-update-hook if required. */
82741  if( db->xPreUpdateCallback && pOp->p4.pTab ){
82742    assert( !(opflags & OPFLAG_ISUPDATE)
82743         || HasRowid(pTab)==0
82744         || (aMem[pOp->p3].flags & MEM_Int)
82745    );
82746    sqlite3VdbePreUpdateHook(p, pC,
82747        (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
82748        zDb, pTab, pC->movetoTarget,
82749        pOp->p3
82750    );
82751  }
82752  if( opflags & OPFLAG_ISNOOP ) break;
82753#endif
82754
82755  /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
82756  assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
82757  assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
82758  assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
82759
82760#ifdef SQLITE_DEBUG
82761  if( p->pFrame==0 ){
82762    if( pC->isEphemeral==0
82763        && (pOp->p5 & OPFLAG_AUXDELETE)==0
82764        && (pC->wrFlag & OPFLAG_FORDELETE)==0
82765      ){
82766      nExtraDelete++;
82767    }
82768    if( pOp->p2 & OPFLAG_NCHANGE ){
82769      nExtraDelete--;
82770    }
82771  }
82772#endif
82773
82774  rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
82775  pC->cacheStatus = CACHE_STALE;
82776  pC->seekResult = 0;
82777  if( rc ) goto abort_due_to_error;
82778
82779  /* Invoke the update-hook if required. */
82780  if( opflags & OPFLAG_NCHANGE ){
82781    p->nChange++;
82782    if( db->xUpdateCallback && HasRowid(pTab) ){
82783      db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
82784          pC->movetoTarget);
82785      assert( pC->iDb>=0 );
82786    }
82787  }
82788
82789  break;
82790}
82791/* Opcode: ResetCount * * * * *
82792**
82793** The value of the change counter is copied to the database handle
82794** change counter (returned by subsequent calls to sqlite3_changes()).
82795** Then the VMs internal change counter resets to 0.
82796** This is used by trigger programs.
82797*/
82798case OP_ResetCount: {
82799  sqlite3VdbeSetChanges(db, p->nChange);
82800  p->nChange = 0;
82801  break;
82802}
82803
82804/* Opcode: SorterCompare P1 P2 P3 P4
82805** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
82806**
82807** P1 is a sorter cursor. This instruction compares a prefix of the
82808** record blob in register P3 against a prefix of the entry that
82809** the sorter cursor currently points to.  Only the first P4 fields
82810** of r[P3] and the sorter record are compared.
82811**
82812** If either P3 or the sorter contains a NULL in one of their significant
82813** fields (not counting the P4 fields at the end which are ignored) then
82814** the comparison is assumed to be equal.
82815**
82816** Fall through to next instruction if the two records compare equal to
82817** each other.  Jump to P2 if they are different.
82818*/
82819case OP_SorterCompare: {
82820  VdbeCursor *pC;
82821  int res;
82822  int nKeyCol;
82823
82824  pC = p->apCsr[pOp->p1];
82825  assert( isSorter(pC) );
82826  assert( pOp->p4type==P4_INT32 );
82827  pIn3 = &aMem[pOp->p3];
82828  nKeyCol = pOp->p4.i;
82829  res = 0;
82830  rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
82831  VdbeBranchTaken(res!=0,2);
82832  if( rc ) goto abort_due_to_error;
82833  if( res ) goto jump_to_p2;
82834  break;
82835};
82836
82837/* Opcode: SorterData P1 P2 P3 * *
82838** Synopsis: r[P2]=data
82839**
82840** Write into register P2 the current sorter data for sorter cursor P1.
82841** Then clear the column header cache on cursor P3.
82842**
82843** This opcode is normally use to move a record out of the sorter and into
82844** a register that is the source for a pseudo-table cursor created using
82845** OpenPseudo.  That pseudo-table cursor is the one that is identified by
82846** parameter P3.  Clearing the P3 column cache as part of this opcode saves
82847** us from having to issue a separate NullRow instruction to clear that cache.
82848*/
82849case OP_SorterData: {
82850  VdbeCursor *pC;
82851
82852  pOut = &aMem[pOp->p2];
82853  pC = p->apCsr[pOp->p1];
82854  assert( isSorter(pC) );
82855  rc = sqlite3VdbeSorterRowkey(pC, pOut);
82856  assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
82857  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82858  if( rc ) goto abort_due_to_error;
82859  p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
82860  break;
82861}
82862
82863/* Opcode: RowData P1 P2 P3 * *
82864** Synopsis: r[P2]=data
82865**
82866** Write into register P2 the complete row content for the row at
82867** which cursor P1 is currently pointing.
82868** There is no interpretation of the data.
82869** It is just copied onto the P2 register exactly as
82870** it is found in the database file.
82871**
82872** If cursor P1 is an index, then the content is the key of the row.
82873** If cursor P2 is a table, then the content extracted is the data.
82874**
82875** If the P1 cursor must be pointing to a valid row (not a NULL row)
82876** of a real table, not a pseudo-table.
82877**
82878** If P3!=0 then this opcode is allowed to make an ephermeral pointer
82879** into the database page.  That means that the content of the output
82880** register will be invalidated as soon as the cursor moves - including
82881** moves caused by other cursors that "save" the the current cursors
82882** position in order that they can write to the same table.  If P3==0
82883** then a copy of the data is made into memory.  P3!=0 is faster, but
82884** P3==0 is safer.
82885**
82886** If P3!=0 then the content of the P2 register is unsuitable for use
82887** in OP_Result and any OP_Result will invalidate the P2 register content.
82888** The P2 register content is invalidated by opcodes like OP_Function or
82889** by any use of another cursor pointing to the same table.
82890*/
82891case OP_RowData: {
82892  VdbeCursor *pC;
82893  BtCursor *pCrsr;
82894  u32 n;
82895
82896  pOut = out2Prerelease(p, pOp);
82897
82898  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82899  pC = p->apCsr[pOp->p1];
82900  assert( pC!=0 );
82901  assert( pC->eCurType==CURTYPE_BTREE );
82902  assert( isSorter(pC)==0 );
82903  assert( pC->nullRow==0 );
82904  assert( pC->uc.pCursor!=0 );
82905  pCrsr = pC->uc.pCursor;
82906
82907  /* The OP_RowData opcodes always follow OP_NotExists or
82908  ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
82909  ** that might invalidate the cursor.
82910  ** If this where not the case, on of the following assert()s
82911  ** would fail.  Should this ever change (because of changes in the code
82912  ** generator) then the fix would be to insert a call to
82913  ** sqlite3VdbeCursorMoveto().
82914  */
82915  assert( pC->deferredMoveto==0 );
82916  assert( sqlite3BtreeCursorIsValid(pCrsr) );
82917#if 0  /* Not required due to the previous to assert() statements */
82918  rc = sqlite3VdbeCursorMoveto(pC);
82919  if( rc!=SQLITE_OK ) goto abort_due_to_error;
82920#endif
82921
82922  n = sqlite3BtreePayloadSize(pCrsr);
82923  if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
82924    goto too_big;
82925  }
82926  testcase( n==0 );
82927  rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
82928  if( rc ) goto abort_due_to_error;
82929  if( !pOp->p3 ) Deephemeralize(pOut);
82930  UPDATE_MAX_BLOBSIZE(pOut);
82931  REGISTER_TRACE(pOp->p2, pOut);
82932  break;
82933}
82934
82935/* Opcode: Rowid P1 P2 * * *
82936** Synopsis: r[P2]=rowid
82937**
82938** Store in register P2 an integer which is the key of the table entry that
82939** P1 is currently point to.
82940**
82941** P1 can be either an ordinary table or a virtual table.  There used to
82942** be a separate OP_VRowid opcode for use with virtual tables, but this
82943** one opcode now works for both table types.
82944*/
82945case OP_Rowid: {                 /* out2 */
82946  VdbeCursor *pC;
82947  i64 v;
82948  sqlite3_vtab *pVtab;
82949  const sqlite3_module *pModule;
82950
82951  pOut = out2Prerelease(p, pOp);
82952  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82953  pC = p->apCsr[pOp->p1];
82954  assert( pC!=0 );
82955  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
82956  if( pC->nullRow ){
82957    pOut->flags = MEM_Null;
82958    break;
82959  }else if( pC->deferredMoveto ){
82960    v = pC->movetoTarget;
82961#ifndef SQLITE_OMIT_VIRTUALTABLE
82962  }else if( pC->eCurType==CURTYPE_VTAB ){
82963    assert( pC->uc.pVCur!=0 );
82964    pVtab = pC->uc.pVCur->pVtab;
82965    pModule = pVtab->pModule;
82966    assert( pModule->xRowid );
82967    rc = pModule->xRowid(pC->uc.pVCur, &v);
82968    sqlite3VtabImportErrmsg(p, pVtab);
82969    if( rc ) goto abort_due_to_error;
82970#endif /* SQLITE_OMIT_VIRTUALTABLE */
82971  }else{
82972    assert( pC->eCurType==CURTYPE_BTREE );
82973    assert( pC->uc.pCursor!=0 );
82974    rc = sqlite3VdbeCursorRestore(pC);
82975    if( rc ) goto abort_due_to_error;
82976    if( pC->nullRow ){
82977      pOut->flags = MEM_Null;
82978      break;
82979    }
82980    v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
82981  }
82982  pOut->u.i = v;
82983  break;
82984}
82985
82986/* Opcode: NullRow P1 * * * *
82987**
82988** Move the cursor P1 to a null row.  Any OP_Column operations
82989** that occur while the cursor is on the null row will always
82990** write a NULL.
82991*/
82992case OP_NullRow: {
82993  VdbeCursor *pC;
82994
82995  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82996  pC = p->apCsr[pOp->p1];
82997  assert( pC!=0 );
82998  pC->nullRow = 1;
82999  pC->cacheStatus = CACHE_STALE;
83000  if( pC->eCurType==CURTYPE_BTREE ){
83001    assert( pC->uc.pCursor!=0 );
83002    sqlite3BtreeClearCursor(pC->uc.pCursor);
83003  }
83004  break;
83005}
83006
83007/* Opcode: Last P1 P2 P3 * *
83008**
83009** The next use of the Rowid or Column or Prev instruction for P1
83010** will refer to the last entry in the database table or index.
83011** If the table or index is empty and P2>0, then jump immediately to P2.
83012** If P2 is 0 or if the table or index is not empty, fall through
83013** to the following instruction.
83014**
83015** This opcode leaves the cursor configured to move in reverse order,
83016** from the end toward the beginning.  In other words, the cursor is
83017** configured to use Prev, not Next.
83018**
83019** If P3 is -1, then the cursor is positioned at the end of the btree
83020** for the purpose of appending a new entry onto the btree.  In that
83021** case P2 must be 0.  It is assumed that the cursor is used only for
83022** appending and so if the cursor is valid, then the cursor must already
83023** be pointing at the end of the btree and so no changes are made to
83024** the cursor.
83025*/
83026case OP_Last: {        /* jump */
83027  VdbeCursor *pC;
83028  BtCursor *pCrsr;
83029  int res;
83030
83031  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83032  pC = p->apCsr[pOp->p1];
83033  assert( pC!=0 );
83034  assert( pC->eCurType==CURTYPE_BTREE );
83035  pCrsr = pC->uc.pCursor;
83036  res = 0;
83037  assert( pCrsr!=0 );
83038  pC->seekResult = pOp->p3;
83039#ifdef SQLITE_DEBUG
83040  pC->seekOp = OP_Last;
83041#endif
83042  if( pOp->p3==0 || !sqlite3BtreeCursorIsValidNN(pCrsr) ){
83043    rc = sqlite3BtreeLast(pCrsr, &res);
83044    pC->nullRow = (u8)res;
83045    pC->deferredMoveto = 0;
83046    pC->cacheStatus = CACHE_STALE;
83047    if( rc ) goto abort_due_to_error;
83048    if( pOp->p2>0 ){
83049      VdbeBranchTaken(res!=0,2);
83050      if( res ) goto jump_to_p2;
83051    }
83052  }else{
83053    assert( pOp->p2==0 );
83054  }
83055  break;
83056}
83057
83058/* Opcode: IfSmaller P1 P2 P3 * *
83059**
83060** Estimate the number of rows in the table P1.  Jump to P2 if that
83061** estimate is less than approximately 2**(0.1*P3).
83062*/
83063case OP_IfSmaller: {        /* jump */
83064  VdbeCursor *pC;
83065  BtCursor *pCrsr;
83066  int res;
83067  i64 sz;
83068
83069  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83070  pC = p->apCsr[pOp->p1];
83071  assert( pC!=0 );
83072  pCrsr = pC->uc.pCursor;
83073  assert( pCrsr );
83074  rc = sqlite3BtreeFirst(pCrsr, &res);
83075  if( rc ) goto abort_due_to_error;
83076  if( res==0 ){
83077    sz = sqlite3BtreeRowCountEst(pCrsr);
83078    if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
83079  }
83080  VdbeBranchTaken(res!=0,2);
83081  if( res ) goto jump_to_p2;
83082  break;
83083}
83084
83085
83086/* Opcode: SorterSort P1 P2 * * *
83087**
83088** After all records have been inserted into the Sorter object
83089** identified by P1, invoke this opcode to actually do the sorting.
83090** Jump to P2 if there are no records to be sorted.
83091**
83092** This opcode is an alias for OP_Sort and OP_Rewind that is used
83093** for Sorter objects.
83094*/
83095/* Opcode: Sort P1 P2 * * *
83096**
83097** This opcode does exactly the same thing as OP_Rewind except that
83098** it increments an undocumented global variable used for testing.
83099**
83100** Sorting is accomplished by writing records into a sorting index,
83101** then rewinding that index and playing it back from beginning to
83102** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
83103** rewinding so that the global variable will be incremented and
83104** regression tests can determine whether or not the optimizer is
83105** correctly optimizing out sorts.
83106*/
83107case OP_SorterSort:    /* jump */
83108case OP_Sort: {        /* jump */
83109#ifdef SQLITE_TEST
83110  sqlite3_sort_count++;
83111  sqlite3_search_count--;
83112#endif
83113  p->aCounter[SQLITE_STMTSTATUS_SORT]++;
83114  /* Fall through into OP_Rewind */
83115}
83116/* Opcode: Rewind P1 P2 * * *
83117**
83118** The next use of the Rowid or Column or Next instruction for P1
83119** will refer to the first entry in the database table or index.
83120** If the table or index is empty, jump immediately to P2.
83121** If the table or index is not empty, fall through to the following
83122** instruction.
83123**
83124** This opcode leaves the cursor configured to move in forward order,
83125** from the beginning toward the end.  In other words, the cursor is
83126** configured to use Next, not Prev.
83127*/
83128case OP_Rewind: {        /* jump */
83129  VdbeCursor *pC;
83130  BtCursor *pCrsr;
83131  int res;
83132
83133  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83134  pC = p->apCsr[pOp->p1];
83135  assert( pC!=0 );
83136  assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
83137  res = 1;
83138#ifdef SQLITE_DEBUG
83139  pC->seekOp = OP_Rewind;
83140#endif
83141  if( isSorter(pC) ){
83142    rc = sqlite3VdbeSorterRewind(pC, &res);
83143  }else{
83144    assert( pC->eCurType==CURTYPE_BTREE );
83145    pCrsr = pC->uc.pCursor;
83146    assert( pCrsr );
83147    rc = sqlite3BtreeFirst(pCrsr, &res);
83148    pC->deferredMoveto = 0;
83149    pC->cacheStatus = CACHE_STALE;
83150  }
83151  if( rc ) goto abort_due_to_error;
83152  pC->nullRow = (u8)res;
83153  assert( pOp->p2>0 && pOp->p2<p->nOp );
83154  VdbeBranchTaken(res!=0,2);
83155  if( res ) goto jump_to_p2;
83156  break;
83157}
83158
83159/* Opcode: Next P1 P2 P3 P4 P5
83160**
83161** Advance cursor P1 so that it points to the next key/data pair in its
83162** table or index.  If there are no more key/value pairs then fall through
83163** to the following instruction.  But if the cursor advance was successful,
83164** jump immediately to P2.
83165**
83166** The Next opcode is only valid following an SeekGT, SeekGE, or
83167** OP_Rewind opcode used to position the cursor.  Next is not allowed
83168** to follow SeekLT, SeekLE, or OP_Last.
83169**
83170** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
83171** been opened prior to this opcode or the program will segfault.
83172**
83173** The P3 value is a hint to the btree implementation. If P3==1, that
83174** means P1 is an SQL index and that this instruction could have been
83175** omitted if that index had been unique.  P3 is usually 0.  P3 is
83176** always either 0 or 1.
83177**
83178** P4 is always of type P4_ADVANCE. The function pointer points to
83179** sqlite3BtreeNext().
83180**
83181** If P5 is positive and the jump is taken, then event counter
83182** number P5-1 in the prepared statement is incremented.
83183**
83184** See also: Prev, NextIfOpen
83185*/
83186/* Opcode: NextIfOpen P1 P2 P3 P4 P5
83187**
83188** This opcode works just like Next except that if cursor P1 is not
83189** open it behaves a no-op.
83190*/
83191/* Opcode: Prev P1 P2 P3 P4 P5
83192**
83193** Back up cursor P1 so that it points to the previous key/data pair in its
83194** table or index.  If there is no previous key/value pairs then fall through
83195** to the following instruction.  But if the cursor backup was successful,
83196** jump immediately to P2.
83197**
83198**
83199** The Prev opcode is only valid following an SeekLT, SeekLE, or
83200** OP_Last opcode used to position the cursor.  Prev is not allowed
83201** to follow SeekGT, SeekGE, or OP_Rewind.
83202**
83203** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
83204** not open then the behavior is undefined.
83205**
83206** The P3 value is a hint to the btree implementation. If P3==1, that
83207** means P1 is an SQL index and that this instruction could have been
83208** omitted if that index had been unique.  P3 is usually 0.  P3 is
83209** always either 0 or 1.
83210**
83211** P4 is always of type P4_ADVANCE. The function pointer points to
83212** sqlite3BtreePrevious().
83213**
83214** If P5 is positive and the jump is taken, then event counter
83215** number P5-1 in the prepared statement is incremented.
83216*/
83217/* Opcode: PrevIfOpen P1 P2 P3 P4 P5
83218**
83219** This opcode works just like Prev except that if cursor P1 is not
83220** open it behaves a no-op.
83221*/
83222/* Opcode: SorterNext P1 P2 * * P5
83223**
83224** This opcode works just like OP_Next except that P1 must be a
83225** sorter object for which the OP_SorterSort opcode has been
83226** invoked.  This opcode advances the cursor to the next sorted
83227** record, or jumps to P2 if there are no more sorted records.
83228*/
83229case OP_SorterNext: {  /* jump */
83230  VdbeCursor *pC;
83231  int res;
83232
83233  pC = p->apCsr[pOp->p1];
83234  assert( isSorter(pC) );
83235  res = 0;
83236  rc = sqlite3VdbeSorterNext(db, pC, &res);
83237  goto next_tail;
83238case OP_PrevIfOpen:    /* jump */
83239case OP_NextIfOpen:    /* jump */
83240  if( p->apCsr[pOp->p1]==0 ) break;
83241  /* Fall through */
83242case OP_Prev:          /* jump */
83243case OP_Next:          /* jump */
83244  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83245  assert( pOp->p5<ArraySize(p->aCounter) );
83246  pC = p->apCsr[pOp->p1];
83247  res = pOp->p3;
83248  assert( pC!=0 );
83249  assert( pC->deferredMoveto==0 );
83250  assert( pC->eCurType==CURTYPE_BTREE );
83251  assert( res==0 || (res==1 && pC->isTable==0) );
83252  testcase( res==1 );
83253  assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
83254  assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
83255  assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
83256  assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
83257
83258  /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
83259  ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
83260  assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
83261       || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
83262       || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
83263  assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
83264       || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
83265       || pC->seekOp==OP_Last );
83266
83267  rc = pOp->p4.xAdvance(pC->uc.pCursor, &res);
83268next_tail:
83269  pC->cacheStatus = CACHE_STALE;
83270  VdbeBranchTaken(res==0,2);
83271  if( rc ) goto abort_due_to_error;
83272  if( res==0 ){
83273    pC->nullRow = 0;
83274    p->aCounter[pOp->p5]++;
83275#ifdef SQLITE_TEST
83276    sqlite3_search_count++;
83277#endif
83278    goto jump_to_p2_and_check_for_interrupt;
83279  }else{
83280    pC->nullRow = 1;
83281  }
83282  goto check_for_interrupt;
83283}
83284
83285/* Opcode: IdxInsert P1 P2 P3 P4 P5
83286** Synopsis: key=r[P2]
83287**
83288** Register P2 holds an SQL index key made using the
83289** MakeRecord instructions.  This opcode writes that key
83290** into the index P1.  Data for the entry is nil.
83291**
83292** If P4 is not zero, then it is the number of values in the unpacked
83293** key of reg(P2).  In that case, P3 is the index of the first register
83294** for the unpacked key.  The availability of the unpacked key can sometimes
83295** be an optimization.
83296**
83297** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
83298** that this insert is likely to be an append.
83299**
83300** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
83301** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
83302** then the change counter is unchanged.
83303**
83304** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
83305** run faster by avoiding an unnecessary seek on cursor P1.  However,
83306** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
83307** seeks on the cursor or if the most recent seek used a key equivalent
83308** to P2.
83309**
83310** This instruction only works for indices.  The equivalent instruction
83311** for tables is OP_Insert.
83312*/
83313/* Opcode: SorterInsert P1 P2 * * *
83314** Synopsis: key=r[P2]
83315**
83316** Register P2 holds an SQL index key made using the
83317** MakeRecord instructions.  This opcode writes that key
83318** into the sorter P1.  Data for the entry is nil.
83319*/
83320case OP_SorterInsert:       /* in2 */
83321case OP_IdxInsert: {        /* in2 */
83322  VdbeCursor *pC;
83323  BtreePayload x;
83324
83325  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83326  pC = p->apCsr[pOp->p1];
83327  assert( pC!=0 );
83328  assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
83329  pIn2 = &aMem[pOp->p2];
83330  assert( pIn2->flags & MEM_Blob );
83331  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
83332  assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
83333  assert( pC->isTable==0 );
83334  rc = ExpandBlob(pIn2);
83335  if( rc ) goto abort_due_to_error;
83336  if( pOp->opcode==OP_SorterInsert ){
83337    rc = sqlite3VdbeSorterWrite(pC, pIn2);
83338  }else{
83339    x.nKey = pIn2->n;
83340    x.pKey = pIn2->z;
83341    x.aMem = aMem + pOp->p3;
83342    x.nMem = (u16)pOp->p4.i;
83343    rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
83344         (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
83345        ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
83346        );
83347    assert( pC->deferredMoveto==0 );
83348    pC->cacheStatus = CACHE_STALE;
83349  }
83350  if( rc) goto abort_due_to_error;
83351  break;
83352}
83353
83354/* Opcode: IdxDelete P1 P2 P3 * *
83355** Synopsis: key=r[P2@P3]
83356**
83357** The content of P3 registers starting at register P2 form
83358** an unpacked index key. This opcode removes that entry from the
83359** index opened by cursor P1.
83360*/
83361case OP_IdxDelete: {
83362  VdbeCursor *pC;
83363  BtCursor *pCrsr;
83364  int res;
83365  UnpackedRecord r;
83366
83367  assert( pOp->p3>0 );
83368  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
83369  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83370  pC = p->apCsr[pOp->p1];
83371  assert( pC!=0 );
83372  assert( pC->eCurType==CURTYPE_BTREE );
83373  pCrsr = pC->uc.pCursor;
83374  assert( pCrsr!=0 );
83375  assert( pOp->p5==0 );
83376  r.pKeyInfo = pC->pKeyInfo;
83377  r.nField = (u16)pOp->p3;
83378  r.default_rc = 0;
83379  r.aMem = &aMem[pOp->p2];
83380  rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
83381  if( rc ) goto abort_due_to_error;
83382  if( res==0 ){
83383    rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
83384    if( rc ) goto abort_due_to_error;
83385  }
83386  assert( pC->deferredMoveto==0 );
83387  pC->cacheStatus = CACHE_STALE;
83388  pC->seekResult = 0;
83389  break;
83390}
83391
83392/* Opcode: Seek P1 * P3 P4 *
83393** Synopsis: Move P3 to P1.rowid
83394**
83395** P1 is an open index cursor and P3 is a cursor on the corresponding
83396** table.  This opcode does a deferred seek of the P3 table cursor
83397** to the row that corresponds to the current row of P1.
83398**
83399** This is a deferred seek.  Nothing actually happens until
83400** the cursor is used to read a record.  That way, if no reads
83401** occur, no unnecessary I/O happens.
83402**
83403** P4 may be an array of integers (type P4_INTARRAY) containing
83404** one entry for each column in the P3 table.  If array entry a(i)
83405** is non-zero, then reading column a(i)-1 from cursor P3 is
83406** equivalent to performing the deferred seek and then reading column i
83407** from P1.  This information is stored in P3 and used to redirect
83408** reads against P3 over to P1, thus possibly avoiding the need to
83409** seek and read cursor P3.
83410*/
83411/* Opcode: IdxRowid P1 P2 * * *
83412** Synopsis: r[P2]=rowid
83413**
83414** Write into register P2 an integer which is the last entry in the record at
83415** the end of the index key pointed to by cursor P1.  This integer should be
83416** the rowid of the table entry to which this index entry points.
83417**
83418** See also: Rowid, MakeRecord.
83419*/
83420case OP_Seek:
83421case OP_IdxRowid: {              /* out2 */
83422  VdbeCursor *pC;                /* The P1 index cursor */
83423  VdbeCursor *pTabCur;           /* The P2 table cursor (OP_Seek only) */
83424  i64 rowid;                     /* Rowid that P1 current points to */
83425
83426  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83427  pC = p->apCsr[pOp->p1];
83428  assert( pC!=0 );
83429  assert( pC->eCurType==CURTYPE_BTREE );
83430  assert( pC->uc.pCursor!=0 );
83431  assert( pC->isTable==0 );
83432  assert( pC->deferredMoveto==0 );
83433  assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
83434
83435  /* The IdxRowid and Seek opcodes are combined because of the commonality
83436  ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
83437  rc = sqlite3VdbeCursorRestore(pC);
83438
83439  /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
83440  ** out from under the cursor.  That will never happens for an IdxRowid
83441  ** or Seek opcode */
83442  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
83443
83444  if( !pC->nullRow ){
83445    rowid = 0;  /* Not needed.  Only used to silence a warning. */
83446    rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
83447    if( rc!=SQLITE_OK ){
83448      goto abort_due_to_error;
83449    }
83450    if( pOp->opcode==OP_Seek ){
83451      assert( pOp->p3>=0 && pOp->p3<p->nCursor );
83452      pTabCur = p->apCsr[pOp->p3];
83453      assert( pTabCur!=0 );
83454      assert( pTabCur->eCurType==CURTYPE_BTREE );
83455      assert( pTabCur->uc.pCursor!=0 );
83456      assert( pTabCur->isTable );
83457      pTabCur->nullRow = 0;
83458      pTabCur->movetoTarget = rowid;
83459      pTabCur->deferredMoveto = 1;
83460      assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
83461      pTabCur->aAltMap = pOp->p4.ai;
83462      pTabCur->pAltCursor = pC;
83463    }else{
83464      pOut = out2Prerelease(p, pOp);
83465      pOut->u.i = rowid;
83466    }
83467  }else{
83468    assert( pOp->opcode==OP_IdxRowid );
83469    sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
83470  }
83471  break;
83472}
83473
83474/* Opcode: IdxGE P1 P2 P3 P4 P5
83475** Synopsis: key=r[P3@P4]
83476**
83477** The P4 register values beginning with P3 form an unpacked index
83478** key that omits the PRIMARY KEY.  Compare this key value against the index
83479** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
83480** fields at the end.
83481**
83482** If the P1 index entry is greater than or equal to the key value
83483** then jump to P2.  Otherwise fall through to the next instruction.
83484*/
83485/* Opcode: IdxGT P1 P2 P3 P4 P5
83486** Synopsis: key=r[P3@P4]
83487**
83488** The P4 register values beginning with P3 form an unpacked index
83489** key that omits the PRIMARY KEY.  Compare this key value against the index
83490** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
83491** fields at the end.
83492**
83493** If the P1 index entry is greater than the key value
83494** then jump to P2.  Otherwise fall through to the next instruction.
83495*/
83496/* Opcode: IdxLT P1 P2 P3 P4 P5
83497** Synopsis: key=r[P3@P4]
83498**
83499** The P4 register values beginning with P3 form an unpacked index
83500** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
83501** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
83502** ROWID on the P1 index.
83503**
83504** If the P1 index entry is less than the key value then jump to P2.
83505** Otherwise fall through to the next instruction.
83506*/
83507/* Opcode: IdxLE P1 P2 P3 P4 P5
83508** Synopsis: key=r[P3@P4]
83509**
83510** The P4 register values beginning with P3 form an unpacked index
83511** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
83512** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
83513** ROWID on the P1 index.
83514**
83515** If the P1 index entry is less than or equal to the key value then jump
83516** to P2. Otherwise fall through to the next instruction.
83517*/
83518case OP_IdxLE:          /* jump */
83519case OP_IdxGT:          /* jump */
83520case OP_IdxLT:          /* jump */
83521case OP_IdxGE:  {       /* jump */
83522  VdbeCursor *pC;
83523  int res;
83524  UnpackedRecord r;
83525
83526  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83527  pC = p->apCsr[pOp->p1];
83528  assert( pC!=0 );
83529  assert( pC->isOrdered );
83530  assert( pC->eCurType==CURTYPE_BTREE );
83531  assert( pC->uc.pCursor!=0);
83532  assert( pC->deferredMoveto==0 );
83533  assert( pOp->p5==0 || pOp->p5==1 );
83534  assert( pOp->p4type==P4_INT32 );
83535  r.pKeyInfo = pC->pKeyInfo;
83536  r.nField = (u16)pOp->p4.i;
83537  if( pOp->opcode<OP_IdxLT ){
83538    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
83539    r.default_rc = -1;
83540  }else{
83541    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
83542    r.default_rc = 0;
83543  }
83544  r.aMem = &aMem[pOp->p3];
83545#ifdef SQLITE_DEBUG
83546  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
83547#endif
83548  res = 0;  /* Not needed.  Only used to silence a warning. */
83549  rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
83550  assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
83551  if( (pOp->opcode&1)==(OP_IdxLT&1) ){
83552    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
83553    res = -res;
83554  }else{
83555    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
83556    res++;
83557  }
83558  VdbeBranchTaken(res>0,2);
83559  if( rc ) goto abort_due_to_error;
83560  if( res>0 ) goto jump_to_p2;
83561  break;
83562}
83563
83564/* Opcode: Destroy P1 P2 P3 * *
83565**
83566** Delete an entire database table or index whose root page in the database
83567** file is given by P1.
83568**
83569** The table being destroyed is in the main database file if P3==0.  If
83570** P3==1 then the table to be clear is in the auxiliary database file
83571** that is used to store tables create using CREATE TEMPORARY TABLE.
83572**
83573** If AUTOVACUUM is enabled then it is possible that another root page
83574** might be moved into the newly deleted root page in order to keep all
83575** root pages contiguous at the beginning of the database.  The former
83576** value of the root page that moved - its value before the move occurred -
83577** is stored in register P2.  If no page
83578** movement was required (because the table being dropped was already
83579** the last one in the database) then a zero is stored in register P2.
83580** If AUTOVACUUM is disabled then a zero is stored in register P2.
83581**
83582** See also: Clear
83583*/
83584case OP_Destroy: {     /* out2 */
83585  int iMoved;
83586  int iDb;
83587
83588  assert( p->readOnly==0 );
83589  assert( pOp->p1>1 );
83590  pOut = out2Prerelease(p, pOp);
83591  pOut->flags = MEM_Null;
83592  if( db->nVdbeRead > db->nVDestroy+1 ){
83593    rc = SQLITE_LOCKED;
83594    p->errorAction = OE_Abort;
83595    goto abort_due_to_error;
83596  }else{
83597    iDb = pOp->p3;
83598    assert( DbMaskTest(p->btreeMask, iDb) );
83599    iMoved = 0;  /* Not needed.  Only to silence a warning. */
83600    rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
83601    pOut->flags = MEM_Int;
83602    pOut->u.i = iMoved;
83603    if( rc ) goto abort_due_to_error;
83604#ifndef SQLITE_OMIT_AUTOVACUUM
83605    if( iMoved!=0 ){
83606      sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
83607      /* All OP_Destroy operations occur on the same btree */
83608      assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
83609      resetSchemaOnFault = iDb+1;
83610    }
83611#endif
83612  }
83613  break;
83614}
83615
83616/* Opcode: Clear P1 P2 P3
83617**
83618** Delete all contents of the database table or index whose root page
83619** in the database file is given by P1.  But, unlike Destroy, do not
83620** remove the table or index from the database file.
83621**
83622** The table being clear is in the main database file if P2==0.  If
83623** P2==1 then the table to be clear is in the auxiliary database file
83624** that is used to store tables create using CREATE TEMPORARY TABLE.
83625**
83626** If the P3 value is non-zero, then the table referred to must be an
83627** intkey table (an SQL table, not an index). In this case the row change
83628** count is incremented by the number of rows in the table being cleared.
83629** If P3 is greater than zero, then the value stored in register P3 is
83630** also incremented by the number of rows in the table being cleared.
83631**
83632** See also: Destroy
83633*/
83634case OP_Clear: {
83635  int nChange;
83636
83637  nChange = 0;
83638  assert( p->readOnly==0 );
83639  assert( DbMaskTest(p->btreeMask, pOp->p2) );
83640  rc = sqlite3BtreeClearTable(
83641      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
83642  );
83643  if( pOp->p3 ){
83644    p->nChange += nChange;
83645    if( pOp->p3>0 ){
83646      assert( memIsValid(&aMem[pOp->p3]) );
83647      memAboutToChange(p, &aMem[pOp->p3]);
83648      aMem[pOp->p3].u.i += nChange;
83649    }
83650  }
83651  if( rc ) goto abort_due_to_error;
83652  break;
83653}
83654
83655/* Opcode: ResetSorter P1 * * * *
83656**
83657** Delete all contents from the ephemeral table or sorter
83658** that is open on cursor P1.
83659**
83660** This opcode only works for cursors used for sorting and
83661** opened with OP_OpenEphemeral or OP_SorterOpen.
83662*/
83663case OP_ResetSorter: {
83664  VdbeCursor *pC;
83665
83666  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83667  pC = p->apCsr[pOp->p1];
83668  assert( pC!=0 );
83669  if( isSorter(pC) ){
83670    sqlite3VdbeSorterReset(db, pC->uc.pSorter);
83671  }else{
83672    assert( pC->eCurType==CURTYPE_BTREE );
83673    assert( pC->isEphemeral );
83674    rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
83675    if( rc ) goto abort_due_to_error;
83676  }
83677  break;
83678}
83679
83680/* Opcode: CreateTable P1 P2 * * *
83681** Synopsis: r[P2]=root iDb=P1
83682**
83683** Allocate a new table in the main database file if P1==0 or in the
83684** auxiliary database file if P1==1 or in an attached database if
83685** P1>1.  Write the root page number of the new table into
83686** register P2
83687**
83688** The difference between a table and an index is this:  A table must
83689** have a 4-byte integer key and can have arbitrary data.  An index
83690** has an arbitrary key but no data.
83691**
83692** See also: CreateIndex
83693*/
83694/* Opcode: CreateIndex P1 P2 * * *
83695** Synopsis: r[P2]=root iDb=P1
83696**
83697** Allocate a new index in the main database file if P1==0 or in the
83698** auxiliary database file if P1==1 or in an attached database if
83699** P1>1.  Write the root page number of the new table into
83700** register P2.
83701**
83702** See documentation on OP_CreateTable for additional information.
83703*/
83704case OP_CreateIndex:            /* out2 */
83705case OP_CreateTable: {          /* out2 */
83706  int pgno;
83707  int flags;
83708  Db *pDb;
83709
83710  pOut = out2Prerelease(p, pOp);
83711  pgno = 0;
83712  assert( pOp->p1>=0 && pOp->p1<db->nDb );
83713  assert( DbMaskTest(p->btreeMask, pOp->p1) );
83714  assert( p->readOnly==0 );
83715  pDb = &db->aDb[pOp->p1];
83716  assert( pDb->pBt!=0 );
83717  if( pOp->opcode==OP_CreateTable ){
83718    /* flags = BTREE_INTKEY; */
83719    flags = BTREE_INTKEY;
83720  }else{
83721    flags = BTREE_BLOBKEY;
83722  }
83723  rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
83724  if( rc ) goto abort_due_to_error;
83725  pOut->u.i = pgno;
83726  break;
83727}
83728
83729/* Opcode: SqlExec * * * P4 *
83730**
83731** Run the SQL statement or statements specified in the P4 string.
83732*/
83733case OP_SqlExec: {
83734  db->nSqlExec++;
83735  rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
83736  db->nSqlExec--;
83737  if( rc ) goto abort_due_to_error;
83738  break;
83739}
83740
83741/* Opcode: ParseSchema P1 * * P4 *
83742**
83743** Read and parse all entries from the SQLITE_MASTER table of database P1
83744** that match the WHERE clause P4.
83745**
83746** This opcode invokes the parser to create a new virtual machine,
83747** then runs the new virtual machine.  It is thus a re-entrant opcode.
83748*/
83749case OP_ParseSchema: {
83750  int iDb;
83751  const char *zMaster;
83752  char *zSql;
83753  InitData initData;
83754
83755  /* Any prepared statement that invokes this opcode will hold mutexes
83756  ** on every btree.  This is a prerequisite for invoking
83757  ** sqlite3InitCallback().
83758  */
83759#ifdef SQLITE_DEBUG
83760  for(iDb=0; iDb<db->nDb; iDb++){
83761    assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
83762  }
83763#endif
83764
83765  iDb = pOp->p1;
83766  assert( iDb>=0 && iDb<db->nDb );
83767  assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
83768  /* Used to be a conditional */ {
83769    zMaster = MASTER_NAME;
83770    initData.db = db;
83771    initData.iDb = pOp->p1;
83772    initData.pzErrMsg = &p->zErrMsg;
83773    zSql = sqlite3MPrintf(db,
83774       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
83775       db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
83776    if( zSql==0 ){
83777      rc = SQLITE_NOMEM_BKPT;
83778    }else{
83779      assert( db->init.busy==0 );
83780      db->init.busy = 1;
83781      initData.rc = SQLITE_OK;
83782      assert( !db->mallocFailed );
83783      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
83784      if( rc==SQLITE_OK ) rc = initData.rc;
83785      sqlite3DbFree(db, zSql);
83786      db->init.busy = 0;
83787    }
83788  }
83789  if( rc ){
83790    sqlite3ResetAllSchemasOfConnection(db);
83791    if( rc==SQLITE_NOMEM ){
83792      goto no_mem;
83793    }
83794    goto abort_due_to_error;
83795  }
83796  break;
83797}
83798
83799#if !defined(SQLITE_OMIT_ANALYZE)
83800/* Opcode: LoadAnalysis P1 * * * *
83801**
83802** Read the sqlite_stat1 table for database P1 and load the content
83803** of that table into the internal index hash table.  This will cause
83804** the analysis to be used when preparing all subsequent queries.
83805*/
83806case OP_LoadAnalysis: {
83807  assert( pOp->p1>=0 && pOp->p1<db->nDb );
83808  rc = sqlite3AnalysisLoad(db, pOp->p1);
83809  if( rc ) goto abort_due_to_error;
83810  break;
83811}
83812#endif /* !defined(SQLITE_OMIT_ANALYZE) */
83813
83814/* Opcode: DropTable P1 * * P4 *
83815**
83816** Remove the internal (in-memory) data structures that describe
83817** the table named P4 in database P1.  This is called after a table
83818** is dropped from disk (using the Destroy opcode) in order to keep
83819** the internal representation of the
83820** schema consistent with what is on disk.
83821*/
83822case OP_DropTable: {
83823  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
83824  break;
83825}
83826
83827/* Opcode: DropIndex P1 * * P4 *
83828**
83829** Remove the internal (in-memory) data structures that describe
83830** the index named P4 in database P1.  This is called after an index
83831** is dropped from disk (using the Destroy opcode)
83832** in order to keep the internal representation of the
83833** schema consistent with what is on disk.
83834*/
83835case OP_DropIndex: {
83836  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
83837  break;
83838}
83839
83840/* Opcode: DropTrigger P1 * * P4 *
83841**
83842** Remove the internal (in-memory) data structures that describe
83843** the trigger named P4 in database P1.  This is called after a trigger
83844** is dropped from disk (using the Destroy opcode) in order to keep
83845** the internal representation of the
83846** schema consistent with what is on disk.
83847*/
83848case OP_DropTrigger: {
83849  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
83850  break;
83851}
83852
83853
83854#ifndef SQLITE_OMIT_INTEGRITY_CHECK
83855/* Opcode: IntegrityCk P1 P2 P3 P4 P5
83856**
83857** Do an analysis of the currently open database.  Store in
83858** register P1 the text of an error message describing any problems.
83859** If no problems are found, store a NULL in register P1.
83860**
83861** The register P3 contains one less than the maximum number of allowed errors.
83862** At most reg(P3) errors will be reported.
83863** In other words, the analysis stops as soon as reg(P1) errors are
83864** seen.  Reg(P1) is updated with the number of errors remaining.
83865**
83866** The root page numbers of all tables in the database are integers
83867** stored in P4_INTARRAY argument.
83868**
83869** If P5 is not zero, the check is done on the auxiliary database
83870** file, not the main database file.
83871**
83872** This opcode is used to implement the integrity_check pragma.
83873*/
83874case OP_IntegrityCk: {
83875  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
83876  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
83877  int nErr;       /* Number of errors reported */
83878  char *z;        /* Text of the error report */
83879  Mem *pnErr;     /* Register keeping track of errors remaining */
83880
83881  assert( p->bIsReader );
83882  nRoot = pOp->p2;
83883  aRoot = pOp->p4.ai;
83884  assert( nRoot>0 );
83885  assert( aRoot[nRoot]==0 );
83886  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
83887  pnErr = &aMem[pOp->p3];
83888  assert( (pnErr->flags & MEM_Int)!=0 );
83889  assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
83890  pIn1 = &aMem[pOp->p1];
83891  assert( pOp->p5<db->nDb );
83892  assert( DbMaskTest(p->btreeMask, pOp->p5) );
83893  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
83894                                 (int)pnErr->u.i+1, &nErr);
83895  sqlite3VdbeMemSetNull(pIn1);
83896  if( nErr==0 ){
83897    assert( z==0 );
83898  }else if( z==0 ){
83899    goto no_mem;
83900  }else{
83901    pnErr->u.i -= nErr-1;
83902    sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
83903  }
83904  UPDATE_MAX_BLOBSIZE(pIn1);
83905  sqlite3VdbeChangeEncoding(pIn1, encoding);
83906  break;
83907}
83908#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
83909
83910/* Opcode: RowSetAdd P1 P2 * * *
83911** Synopsis: rowset(P1)=r[P2]
83912**
83913** Insert the integer value held by register P2 into a boolean index
83914** held in register P1.
83915**
83916** An assertion fails if P2 is not an integer.
83917*/
83918case OP_RowSetAdd: {       /* in1, in2 */
83919  pIn1 = &aMem[pOp->p1];
83920  pIn2 = &aMem[pOp->p2];
83921  assert( (pIn2->flags & MEM_Int)!=0 );
83922  if( (pIn1->flags & MEM_RowSet)==0 ){
83923    sqlite3VdbeMemSetRowSet(pIn1);
83924    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
83925  }
83926  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
83927  break;
83928}
83929
83930/* Opcode: RowSetRead P1 P2 P3 * *
83931** Synopsis: r[P3]=rowset(P1)
83932**
83933** Extract the smallest value from boolean index P1 and put that value into
83934** register P3.  Or, if boolean index P1 is initially empty, leave P3
83935** unchanged and jump to instruction P2.
83936*/
83937case OP_RowSetRead: {       /* jump, in1, out3 */
83938  i64 val;
83939
83940  pIn1 = &aMem[pOp->p1];
83941  if( (pIn1->flags & MEM_RowSet)==0
83942   || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
83943  ){
83944    /* The boolean index is empty */
83945    sqlite3VdbeMemSetNull(pIn1);
83946    VdbeBranchTaken(1,2);
83947    goto jump_to_p2_and_check_for_interrupt;
83948  }else{
83949    /* A value was pulled from the index */
83950    VdbeBranchTaken(0,2);
83951    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
83952  }
83953  goto check_for_interrupt;
83954}
83955
83956/* Opcode: RowSetTest P1 P2 P3 P4
83957** Synopsis: if r[P3] in rowset(P1) goto P2
83958**
83959** Register P3 is assumed to hold a 64-bit integer value. If register P1
83960** contains a RowSet object and that RowSet object contains
83961** the value held in P3, jump to register P2. Otherwise, insert the
83962** integer in P3 into the RowSet and continue on to the
83963** next opcode.
83964**
83965** The RowSet object is optimized for the case where successive sets
83966** of integers, where each set contains no duplicates. Each set
83967** of values is identified by a unique P4 value. The first set
83968** must have P4==0, the final set P4=-1.  P4 must be either -1 or
83969** non-negative.  For non-negative values of P4 only the lower 4
83970** bits are significant.
83971**
83972** This allows optimizations: (a) when P4==0 there is no need to test
83973** the rowset object for P3, as it is guaranteed not to contain it,
83974** (b) when P4==-1 there is no need to insert the value, as it will
83975** never be tested for, and (c) when a value that is part of set X is
83976** inserted, there is no need to search to see if the same value was
83977** previously inserted as part of set X (only if it was previously
83978** inserted as part of some other set).
83979*/
83980case OP_RowSetTest: {                     /* jump, in1, in3 */
83981  int iSet;
83982  int exists;
83983
83984  pIn1 = &aMem[pOp->p1];
83985  pIn3 = &aMem[pOp->p3];
83986  iSet = pOp->p4.i;
83987  assert( pIn3->flags&MEM_Int );
83988
83989  /* If there is anything other than a rowset object in memory cell P1,
83990  ** delete it now and initialize P1 with an empty rowset
83991  */
83992  if( (pIn1->flags & MEM_RowSet)==0 ){
83993    sqlite3VdbeMemSetRowSet(pIn1);
83994    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
83995  }
83996
83997  assert( pOp->p4type==P4_INT32 );
83998  assert( iSet==-1 || iSet>=0 );
83999  if( iSet ){
84000    exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
84001    VdbeBranchTaken(exists!=0,2);
84002    if( exists ) goto jump_to_p2;
84003  }
84004  if( iSet>=0 ){
84005    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
84006  }
84007  break;
84008}
84009
84010
84011#ifndef SQLITE_OMIT_TRIGGER
84012
84013/* Opcode: Program P1 P2 P3 P4 P5
84014**
84015** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
84016**
84017** P1 contains the address of the memory cell that contains the first memory
84018** cell in an array of values used as arguments to the sub-program. P2
84019** contains the address to jump to if the sub-program throws an IGNORE
84020** exception using the RAISE() function. Register P3 contains the address
84021** of a memory cell in this (the parent) VM that is used to allocate the
84022** memory required by the sub-vdbe at runtime.
84023**
84024** P4 is a pointer to the VM containing the trigger program.
84025**
84026** If P5 is non-zero, then recursive program invocation is enabled.
84027*/
84028case OP_Program: {        /* jump */
84029  int nMem;               /* Number of memory registers for sub-program */
84030  int nByte;              /* Bytes of runtime space required for sub-program */
84031  Mem *pRt;               /* Register to allocate runtime space */
84032  Mem *pMem;              /* Used to iterate through memory cells */
84033  Mem *pEnd;              /* Last memory cell in new array */
84034  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
84035  SubProgram *pProgram;   /* Sub-program to execute */
84036  void *t;                /* Token identifying trigger */
84037
84038  pProgram = pOp->p4.pProgram;
84039  pRt = &aMem[pOp->p3];
84040  assert( pProgram->nOp>0 );
84041
84042  /* If the p5 flag is clear, then recursive invocation of triggers is
84043  ** disabled for backwards compatibility (p5 is set if this sub-program
84044  ** is really a trigger, not a foreign key action, and the flag set
84045  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
84046  **
84047  ** It is recursive invocation of triggers, at the SQL level, that is
84048  ** disabled. In some cases a single trigger may generate more than one
84049  ** SubProgram (if the trigger may be executed with more than one different
84050  ** ON CONFLICT algorithm). SubProgram structures associated with a
84051  ** single trigger all have the same value for the SubProgram.token
84052  ** variable.  */
84053  if( pOp->p5 ){
84054    t = pProgram->token;
84055    for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
84056    if( pFrame ) break;
84057  }
84058
84059  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
84060    rc = SQLITE_ERROR;
84061    sqlite3VdbeError(p, "too many levels of trigger recursion");
84062    goto abort_due_to_error;
84063  }
84064
84065  /* Register pRt is used to store the memory required to save the state
84066  ** of the current program, and the memory required at runtime to execute
84067  ** the trigger program. If this trigger has been fired before, then pRt
84068  ** is already allocated. Otherwise, it must be initialized.  */
84069  if( (pRt->flags&MEM_Frame)==0 ){
84070    /* SubProgram.nMem is set to the number of memory cells used by the
84071    ** program stored in SubProgram.aOp. As well as these, one memory
84072    ** cell is required for each cursor used by the program. Set local
84073    ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
84074    */
84075    nMem = pProgram->nMem + pProgram->nCsr;
84076    assert( nMem>0 );
84077    if( pProgram->nCsr==0 ) nMem++;
84078    nByte = ROUND8(sizeof(VdbeFrame))
84079              + nMem * sizeof(Mem)
84080              + pProgram->nCsr * sizeof(VdbeCursor*)
84081              + (pProgram->nOp + 7)/8;
84082    pFrame = sqlite3DbMallocZero(db, nByte);
84083    if( !pFrame ){
84084      goto no_mem;
84085    }
84086    sqlite3VdbeMemRelease(pRt);
84087    pRt->flags = MEM_Frame;
84088    pRt->u.pFrame = pFrame;
84089
84090    pFrame->v = p;
84091    pFrame->nChildMem = nMem;
84092    pFrame->nChildCsr = pProgram->nCsr;
84093    pFrame->pc = (int)(pOp - aOp);
84094    pFrame->aMem = p->aMem;
84095    pFrame->nMem = p->nMem;
84096    pFrame->apCsr = p->apCsr;
84097    pFrame->nCursor = p->nCursor;
84098    pFrame->aOp = p->aOp;
84099    pFrame->nOp = p->nOp;
84100    pFrame->token = pProgram->token;
84101#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
84102    pFrame->anExec = p->anExec;
84103#endif
84104
84105    pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
84106    for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
84107      pMem->flags = MEM_Undefined;
84108      pMem->db = db;
84109    }
84110  }else{
84111    pFrame = pRt->u.pFrame;
84112    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
84113        || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
84114    assert( pProgram->nCsr==pFrame->nChildCsr );
84115    assert( (int)(pOp - aOp)==pFrame->pc );
84116  }
84117
84118  p->nFrame++;
84119  pFrame->pParent = p->pFrame;
84120  pFrame->lastRowid = db->lastRowid;
84121  pFrame->nChange = p->nChange;
84122  pFrame->nDbChange = p->db->nChange;
84123  assert( pFrame->pAuxData==0 );
84124  pFrame->pAuxData = p->pAuxData;
84125  p->pAuxData = 0;
84126  p->nChange = 0;
84127  p->pFrame = pFrame;
84128  p->aMem = aMem = VdbeFrameMem(pFrame);
84129  p->nMem = pFrame->nChildMem;
84130  p->nCursor = (u16)pFrame->nChildCsr;
84131  p->apCsr = (VdbeCursor **)&aMem[p->nMem];
84132  pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
84133  memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
84134  p->aOp = aOp = pProgram->aOp;
84135  p->nOp = pProgram->nOp;
84136#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
84137  p->anExec = 0;
84138#endif
84139  pOp = &aOp[-1];
84140
84141  break;
84142}
84143
84144/* Opcode: Param P1 P2 * * *
84145**
84146** This opcode is only ever present in sub-programs called via the
84147** OP_Program instruction. Copy a value currently stored in a memory
84148** cell of the calling (parent) frame to cell P2 in the current frames
84149** address space. This is used by trigger programs to access the new.*
84150** and old.* values.
84151**
84152** The address of the cell in the parent frame is determined by adding
84153** the value of the P1 argument to the value of the P1 argument to the
84154** calling OP_Program instruction.
84155*/
84156case OP_Param: {           /* out2 */
84157  VdbeFrame *pFrame;
84158  Mem *pIn;
84159  pOut = out2Prerelease(p, pOp);
84160  pFrame = p->pFrame;
84161  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
84162  sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
84163  break;
84164}
84165
84166#endif /* #ifndef SQLITE_OMIT_TRIGGER */
84167
84168#ifndef SQLITE_OMIT_FOREIGN_KEY
84169/* Opcode: FkCounter P1 P2 * * *
84170** Synopsis: fkctr[P1]+=P2
84171**
84172** Increment a "constraint counter" by P2 (P2 may be negative or positive).
84173** If P1 is non-zero, the database constraint counter is incremented
84174** (deferred foreign key constraints). Otherwise, if P1 is zero, the
84175** statement counter is incremented (immediate foreign key constraints).
84176*/
84177case OP_FkCounter: {
84178  if( db->flags & SQLITE_DeferFKs ){
84179    db->nDeferredImmCons += pOp->p2;
84180  }else if( pOp->p1 ){
84181    db->nDeferredCons += pOp->p2;
84182  }else{
84183    p->nFkConstraint += pOp->p2;
84184  }
84185  break;
84186}
84187
84188/* Opcode: FkIfZero P1 P2 * * *
84189** Synopsis: if fkctr[P1]==0 goto P2
84190**
84191** This opcode tests if a foreign key constraint-counter is currently zero.
84192** If so, jump to instruction P2. Otherwise, fall through to the next
84193** instruction.
84194**
84195** If P1 is non-zero, then the jump is taken if the database constraint-counter
84196** is zero (the one that counts deferred constraint violations). If P1 is
84197** zero, the jump is taken if the statement constraint-counter is zero
84198** (immediate foreign key constraint violations).
84199*/
84200case OP_FkIfZero: {         /* jump */
84201  if( pOp->p1 ){
84202    VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
84203    if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
84204  }else{
84205    VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
84206    if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
84207  }
84208  break;
84209}
84210#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
84211
84212#ifndef SQLITE_OMIT_AUTOINCREMENT
84213/* Opcode: MemMax P1 P2 * * *
84214** Synopsis: r[P1]=max(r[P1],r[P2])
84215**
84216** P1 is a register in the root frame of this VM (the root frame is
84217** different from the current frame if this instruction is being executed
84218** within a sub-program). Set the value of register P1 to the maximum of
84219** its current value and the value in register P2.
84220**
84221** This instruction throws an error if the memory cell is not initially
84222** an integer.
84223*/
84224case OP_MemMax: {        /* in2 */
84225  VdbeFrame *pFrame;
84226  if( p->pFrame ){
84227    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
84228    pIn1 = &pFrame->aMem[pOp->p1];
84229  }else{
84230    pIn1 = &aMem[pOp->p1];
84231  }
84232  assert( memIsValid(pIn1) );
84233  sqlite3VdbeMemIntegerify(pIn1);
84234  pIn2 = &aMem[pOp->p2];
84235  sqlite3VdbeMemIntegerify(pIn2);
84236  if( pIn1->u.i<pIn2->u.i){
84237    pIn1->u.i = pIn2->u.i;
84238  }
84239  break;
84240}
84241#endif /* SQLITE_OMIT_AUTOINCREMENT */
84242
84243/* Opcode: IfPos P1 P2 P3 * *
84244** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
84245**
84246** Register P1 must contain an integer.
84247** If the value of register P1 is 1 or greater, subtract P3 from the
84248** value in P1 and jump to P2.
84249**
84250** If the initial value of register P1 is less than 1, then the
84251** value is unchanged and control passes through to the next instruction.
84252*/
84253case OP_IfPos: {        /* jump, in1 */
84254  pIn1 = &aMem[pOp->p1];
84255  assert( pIn1->flags&MEM_Int );
84256  VdbeBranchTaken( pIn1->u.i>0, 2);
84257  if( pIn1->u.i>0 ){
84258    pIn1->u.i -= pOp->p3;
84259    goto jump_to_p2;
84260  }
84261  break;
84262}
84263
84264/* Opcode: OffsetLimit P1 P2 P3 * *
84265** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
84266**
84267** This opcode performs a commonly used computation associated with
84268** LIMIT and OFFSET process.  r[P1] holds the limit counter.  r[P3]
84269** holds the offset counter.  The opcode computes the combined value
84270** of the LIMIT and OFFSET and stores that value in r[P2].  The r[P2]
84271** value computed is the total number of rows that will need to be
84272** visited in order to complete the query.
84273**
84274** If r[P3] is zero or negative, that means there is no OFFSET
84275** and r[P2] is set to be the value of the LIMIT, r[P1].
84276**
84277** if r[P1] is zero or negative, that means there is no LIMIT
84278** and r[P2] is set to -1.
84279**
84280** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
84281*/
84282case OP_OffsetLimit: {    /* in1, out2, in3 */
84283  i64 x;
84284  pIn1 = &aMem[pOp->p1];
84285  pIn3 = &aMem[pOp->p3];
84286  pOut = out2Prerelease(p, pOp);
84287  assert( pIn1->flags & MEM_Int );
84288  assert( pIn3->flags & MEM_Int );
84289  x = pIn1->u.i;
84290  if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
84291    /* If the LIMIT is less than or equal to zero, loop forever.  This
84292    ** is documented.  But also, if the LIMIT+OFFSET exceeds 2^63 then
84293    ** also loop forever.  This is undocumented.  In fact, one could argue
84294    ** that the loop should terminate.  But assuming 1 billion iterations
84295    ** per second (far exceeding the capabilities of any current hardware)
84296    ** it would take nearly 300 years to actually reach the limit.  So
84297    ** looping forever is a reasonable approximation. */
84298    pOut->u.i = -1;
84299  }else{
84300    pOut->u.i = x;
84301  }
84302  break;
84303}
84304
84305/* Opcode: IfNotZero P1 P2 * * *
84306** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
84307**
84308** Register P1 must contain an integer.  If the content of register P1 is
84309** initially greater than zero, then decrement the value in register P1.
84310** If it is non-zero (negative or positive) and then also jump to P2.
84311** If register P1 is initially zero, leave it unchanged and fall through.
84312*/
84313case OP_IfNotZero: {        /* jump, in1 */
84314  pIn1 = &aMem[pOp->p1];
84315  assert( pIn1->flags&MEM_Int );
84316  VdbeBranchTaken(pIn1->u.i<0, 2);
84317  if( pIn1->u.i ){
84318     if( pIn1->u.i>0 ) pIn1->u.i--;
84319     goto jump_to_p2;
84320  }
84321  break;
84322}
84323
84324/* Opcode: DecrJumpZero P1 P2 * * *
84325** Synopsis: if (--r[P1])==0 goto P2
84326**
84327** Register P1 must hold an integer.  Decrement the value in P1
84328** and jump to P2 if the new value is exactly zero.
84329*/
84330case OP_DecrJumpZero: {      /* jump, in1 */
84331  pIn1 = &aMem[pOp->p1];
84332  assert( pIn1->flags&MEM_Int );
84333  if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
84334  VdbeBranchTaken(pIn1->u.i==0, 2);
84335  if( pIn1->u.i==0 ) goto jump_to_p2;
84336  break;
84337}
84338
84339
84340/* Opcode: AggStep0 * P2 P3 P4 P5
84341** Synopsis: accum=r[P3] step(r[P2@P5])
84342**
84343** Execute the step function for an aggregate.  The
84344** function has P5 arguments.   P4 is a pointer to the FuncDef
84345** structure that specifies the function.  Register P3 is the
84346** accumulator.
84347**
84348** The P5 arguments are taken from register P2 and its
84349** successors.
84350*/
84351/* Opcode: AggStep * P2 P3 P4 P5
84352** Synopsis: accum=r[P3] step(r[P2@P5])
84353**
84354** Execute the step function for an aggregate.  The
84355** function has P5 arguments.   P4 is a pointer to an sqlite3_context
84356** object that is used to run the function.  Register P3 is
84357** as the accumulator.
84358**
84359** The P5 arguments are taken from register P2 and its
84360** successors.
84361**
84362** This opcode is initially coded as OP_AggStep0.  On first evaluation,
84363** the FuncDef stored in P4 is converted into an sqlite3_context and
84364** the opcode is changed.  In this way, the initialization of the
84365** sqlite3_context only happens once, instead of on each call to the
84366** step function.
84367*/
84368case OP_AggStep0: {
84369  int n;
84370  sqlite3_context *pCtx;
84371
84372  assert( pOp->p4type==P4_FUNCDEF );
84373  n = pOp->p5;
84374  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
84375  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
84376  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
84377  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
84378  if( pCtx==0 ) goto no_mem;
84379  pCtx->pMem = 0;
84380  pCtx->pFunc = pOp->p4.pFunc;
84381  pCtx->iOp = (int)(pOp - aOp);
84382  pCtx->pVdbe = p;
84383  pCtx->argc = n;
84384  pOp->p4type = P4_FUNCCTX;
84385  pOp->p4.pCtx = pCtx;
84386  pOp->opcode = OP_AggStep;
84387  /* Fall through into OP_AggStep */
84388}
84389case OP_AggStep: {
84390  int i;
84391  sqlite3_context *pCtx;
84392  Mem *pMem;
84393  Mem t;
84394
84395  assert( pOp->p4type==P4_FUNCCTX );
84396  pCtx = pOp->p4.pCtx;
84397  pMem = &aMem[pOp->p3];
84398
84399  /* If this function is inside of a trigger, the register array in aMem[]
84400  ** might change from one evaluation to the next.  The next block of code
84401  ** checks to see if the register array has changed, and if so it
84402  ** reinitializes the relavant parts of the sqlite3_context object */
84403  if( pCtx->pMem != pMem ){
84404    pCtx->pMem = pMem;
84405    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
84406  }
84407
84408#ifdef SQLITE_DEBUG
84409  for(i=0; i<pCtx->argc; i++){
84410    assert( memIsValid(pCtx->argv[i]) );
84411    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
84412  }
84413#endif
84414
84415  pMem->n++;
84416  sqlite3VdbeMemInit(&t, db, MEM_Null);
84417  pCtx->pOut = &t;
84418  pCtx->fErrorOrAux = 0;
84419  pCtx->skipFlag = 0;
84420  (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
84421  if( pCtx->fErrorOrAux ){
84422    if( pCtx->isError ){
84423      sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
84424      rc = pCtx->isError;
84425    }
84426    sqlite3VdbeMemRelease(&t);
84427    if( rc ) goto abort_due_to_error;
84428  }else{
84429    assert( t.flags==MEM_Null );
84430  }
84431  if( pCtx->skipFlag ){
84432    assert( pOp[-1].opcode==OP_CollSeq );
84433    i = pOp[-1].p1;
84434    if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
84435  }
84436  break;
84437}
84438
84439/* Opcode: AggFinal P1 P2 * P4 *
84440** Synopsis: accum=r[P1] N=P2
84441**
84442** Execute the finalizer function for an aggregate.  P1 is
84443** the memory location that is the accumulator for the aggregate.
84444**
84445** P2 is the number of arguments that the step function takes and
84446** P4 is a pointer to the FuncDef for this function.  The P2
84447** argument is not used by this opcode.  It is only there to disambiguate
84448** functions that can take varying numbers of arguments.  The
84449** P4 argument is only needed for the degenerate case where
84450** the step function was not previously called.
84451*/
84452case OP_AggFinal: {
84453  Mem *pMem;
84454  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
84455  pMem = &aMem[pOp->p1];
84456  assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
84457  rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
84458  if( rc ){
84459    sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
84460    goto abort_due_to_error;
84461  }
84462  sqlite3VdbeChangeEncoding(pMem, encoding);
84463  UPDATE_MAX_BLOBSIZE(pMem);
84464  if( sqlite3VdbeMemTooBig(pMem) ){
84465    goto too_big;
84466  }
84467  break;
84468}
84469
84470#ifndef SQLITE_OMIT_WAL
84471/* Opcode: Checkpoint P1 P2 P3 * *
84472**
84473** Checkpoint database P1. This is a no-op if P1 is not currently in
84474** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
84475** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
84476** SQLITE_BUSY or not, respectively.  Write the number of pages in the
84477** WAL after the checkpoint into mem[P3+1] and the number of pages
84478** in the WAL that have been checkpointed after the checkpoint
84479** completes into mem[P3+2].  However on an error, mem[P3+1] and
84480** mem[P3+2] are initialized to -1.
84481*/
84482case OP_Checkpoint: {
84483  int i;                          /* Loop counter */
84484  int aRes[3];                    /* Results */
84485  Mem *pMem;                      /* Write results here */
84486
84487  assert( p->readOnly==0 );
84488  aRes[0] = 0;
84489  aRes[1] = aRes[2] = -1;
84490  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
84491       || pOp->p2==SQLITE_CHECKPOINT_FULL
84492       || pOp->p2==SQLITE_CHECKPOINT_RESTART
84493       || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
84494  );
84495  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
84496  if( rc ){
84497    if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
84498    rc = SQLITE_OK;
84499    aRes[0] = 1;
84500  }
84501  for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
84502    sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
84503  }
84504  break;
84505};
84506#endif
84507
84508#ifndef SQLITE_OMIT_PRAGMA
84509/* Opcode: JournalMode P1 P2 P3 * *
84510**
84511** Change the journal mode of database P1 to P3. P3 must be one of the
84512** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
84513** modes (delete, truncate, persist, off and memory), this is a simple
84514** operation. No IO is required.
84515**
84516** If changing into or out of WAL mode the procedure is more complicated.
84517**
84518** Write a string containing the final journal-mode to register P2.
84519*/
84520case OP_JournalMode: {    /* out2 */
84521  Btree *pBt;                     /* Btree to change journal mode of */
84522  Pager *pPager;                  /* Pager associated with pBt */
84523  int eNew;                       /* New journal mode */
84524  int eOld;                       /* The old journal mode */
84525#ifndef SQLITE_OMIT_WAL
84526  const char *zFilename;          /* Name of database file for pPager */
84527#endif
84528
84529  pOut = out2Prerelease(p, pOp);
84530  eNew = pOp->p3;
84531  assert( eNew==PAGER_JOURNALMODE_DELETE
84532       || eNew==PAGER_JOURNALMODE_TRUNCATE
84533       || eNew==PAGER_JOURNALMODE_PERSIST
84534       || eNew==PAGER_JOURNALMODE_OFF
84535       || eNew==PAGER_JOURNALMODE_MEMORY
84536       || eNew==PAGER_JOURNALMODE_WAL
84537       || eNew==PAGER_JOURNALMODE_QUERY
84538  );
84539  assert( pOp->p1>=0 && pOp->p1<db->nDb );
84540  assert( p->readOnly==0 );
84541
84542  pBt = db->aDb[pOp->p1].pBt;
84543  pPager = sqlite3BtreePager(pBt);
84544  eOld = sqlite3PagerGetJournalMode(pPager);
84545  if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
84546  if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
84547
84548#ifndef SQLITE_OMIT_WAL
84549  zFilename = sqlite3PagerFilename(pPager, 1);
84550
84551  /* Do not allow a transition to journal_mode=WAL for a database
84552  ** in temporary storage or if the VFS does not support shared memory
84553  */
84554  if( eNew==PAGER_JOURNALMODE_WAL
84555   && (sqlite3Strlen30(zFilename)==0           /* Temp file */
84556       || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
84557  ){
84558    eNew = eOld;
84559  }
84560
84561  if( (eNew!=eOld)
84562   && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
84563  ){
84564    if( !db->autoCommit || db->nVdbeRead>1 ){
84565      rc = SQLITE_ERROR;
84566      sqlite3VdbeError(p,
84567          "cannot change %s wal mode from within a transaction",
84568          (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
84569      );
84570      goto abort_due_to_error;
84571    }else{
84572
84573      if( eOld==PAGER_JOURNALMODE_WAL ){
84574        /* If leaving WAL mode, close the log file. If successful, the call
84575        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
84576        ** file. An EXCLUSIVE lock may still be held on the database file
84577        ** after a successful return.
84578        */
84579        rc = sqlite3PagerCloseWal(pPager, db);
84580        if( rc==SQLITE_OK ){
84581          sqlite3PagerSetJournalMode(pPager, eNew);
84582        }
84583      }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
84584        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
84585        ** as an intermediate */
84586        sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
84587      }
84588
84589      /* Open a transaction on the database file. Regardless of the journal
84590      ** mode, this transaction always uses a rollback journal.
84591      */
84592      assert( sqlite3BtreeIsInTrans(pBt)==0 );
84593      if( rc==SQLITE_OK ){
84594        rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
84595      }
84596    }
84597  }
84598#endif /* ifndef SQLITE_OMIT_WAL */
84599
84600  if( rc ) eNew = eOld;
84601  eNew = sqlite3PagerSetJournalMode(pPager, eNew);
84602
84603  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
84604  pOut->z = (char *)sqlite3JournalModename(eNew);
84605  pOut->n = sqlite3Strlen30(pOut->z);
84606  pOut->enc = SQLITE_UTF8;
84607  sqlite3VdbeChangeEncoding(pOut, encoding);
84608  if( rc ) goto abort_due_to_error;
84609  break;
84610};
84611#endif /* SQLITE_OMIT_PRAGMA */
84612
84613#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
84614/* Opcode: Vacuum P1 * * * *
84615**
84616** Vacuum the entire database P1.  P1 is 0 for "main", and 2 or more
84617** for an attached database.  The "temp" database may not be vacuumed.
84618*/
84619case OP_Vacuum: {
84620  assert( p->readOnly==0 );
84621  rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
84622  if( rc ) goto abort_due_to_error;
84623  break;
84624}
84625#endif
84626
84627#if !defined(SQLITE_OMIT_AUTOVACUUM)
84628/* Opcode: IncrVacuum P1 P2 * * *
84629**
84630** Perform a single step of the incremental vacuum procedure on
84631** the P1 database. If the vacuum has finished, jump to instruction
84632** P2. Otherwise, fall through to the next instruction.
84633*/
84634case OP_IncrVacuum: {        /* jump */
84635  Btree *pBt;
84636
84637  assert( pOp->p1>=0 && pOp->p1<db->nDb );
84638  assert( DbMaskTest(p->btreeMask, pOp->p1) );
84639  assert( p->readOnly==0 );
84640  pBt = db->aDb[pOp->p1].pBt;
84641  rc = sqlite3BtreeIncrVacuum(pBt);
84642  VdbeBranchTaken(rc==SQLITE_DONE,2);
84643  if( rc ){
84644    if( rc!=SQLITE_DONE ) goto abort_due_to_error;
84645    rc = SQLITE_OK;
84646    goto jump_to_p2;
84647  }
84648  break;
84649}
84650#endif
84651
84652/* Opcode: Expire P1 * * * *
84653**
84654** Cause precompiled statements to expire.  When an expired statement
84655** is executed using sqlite3_step() it will either automatically
84656** reprepare itself (if it was originally created using sqlite3_prepare_v2())
84657** or it will fail with SQLITE_SCHEMA.
84658**
84659** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
84660** then only the currently executing statement is expired.
84661*/
84662case OP_Expire: {
84663  if( !pOp->p1 ){
84664    sqlite3ExpirePreparedStatements(db);
84665  }else{
84666    p->expired = 1;
84667  }
84668  break;
84669}
84670
84671#ifndef SQLITE_OMIT_SHARED_CACHE
84672/* Opcode: TableLock P1 P2 P3 P4 *
84673** Synopsis: iDb=P1 root=P2 write=P3
84674**
84675** Obtain a lock on a particular table. This instruction is only used when
84676** the shared-cache feature is enabled.
84677**
84678** P1 is the index of the database in sqlite3.aDb[] of the database
84679** on which the lock is acquired.  A readlock is obtained if P3==0 or
84680** a write lock if P3==1.
84681**
84682** P2 contains the root-page of the table to lock.
84683**
84684** P4 contains a pointer to the name of the table being locked. This is only
84685** used to generate an error message if the lock cannot be obtained.
84686*/
84687case OP_TableLock: {
84688  u8 isWriteLock = (u8)pOp->p3;
84689  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
84690    int p1 = pOp->p1;
84691    assert( p1>=0 && p1<db->nDb );
84692    assert( DbMaskTest(p->btreeMask, p1) );
84693    assert( isWriteLock==0 || isWriteLock==1 );
84694    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
84695    if( rc ){
84696      if( (rc&0xFF)==SQLITE_LOCKED ){
84697        const char *z = pOp->p4.z;
84698        sqlite3VdbeError(p, "database table is locked: %s", z);
84699      }
84700      goto abort_due_to_error;
84701    }
84702  }
84703  break;
84704}
84705#endif /* SQLITE_OMIT_SHARED_CACHE */
84706
84707#ifndef SQLITE_OMIT_VIRTUALTABLE
84708/* Opcode: VBegin * * * P4 *
84709**
84710** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
84711** xBegin method for that table.
84712**
84713** Also, whether or not P4 is set, check that this is not being called from
84714** within a callback to a virtual table xSync() method. If it is, the error
84715** code will be set to SQLITE_LOCKED.
84716*/
84717case OP_VBegin: {
84718  VTable *pVTab;
84719  pVTab = pOp->p4.pVtab;
84720  rc = sqlite3VtabBegin(db, pVTab);
84721  if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
84722  if( rc ) goto abort_due_to_error;
84723  break;
84724}
84725#endif /* SQLITE_OMIT_VIRTUALTABLE */
84726
84727#ifndef SQLITE_OMIT_VIRTUALTABLE
84728/* Opcode: VCreate P1 P2 * * *
84729**
84730** P2 is a register that holds the name of a virtual table in database
84731** P1. Call the xCreate method for that table.
84732*/
84733case OP_VCreate: {
84734  Mem sMem;          /* For storing the record being decoded */
84735  const char *zTab;  /* Name of the virtual table */
84736
84737  memset(&sMem, 0, sizeof(sMem));
84738  sMem.db = db;
84739  /* Because P2 is always a static string, it is impossible for the
84740  ** sqlite3VdbeMemCopy() to fail */
84741  assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
84742  assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
84743  rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
84744  assert( rc==SQLITE_OK );
84745  zTab = (const char*)sqlite3_value_text(&sMem);
84746  assert( zTab || db->mallocFailed );
84747  if( zTab ){
84748    rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
84749  }
84750  sqlite3VdbeMemRelease(&sMem);
84751  if( rc ) goto abort_due_to_error;
84752  break;
84753}
84754#endif /* SQLITE_OMIT_VIRTUALTABLE */
84755
84756#ifndef SQLITE_OMIT_VIRTUALTABLE
84757/* Opcode: VDestroy P1 * * P4 *
84758**
84759** P4 is the name of a virtual table in database P1.  Call the xDestroy method
84760** of that table.
84761*/
84762case OP_VDestroy: {
84763  db->nVDestroy++;
84764  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
84765  db->nVDestroy--;
84766  if( rc ) goto abort_due_to_error;
84767  break;
84768}
84769#endif /* SQLITE_OMIT_VIRTUALTABLE */
84770
84771#ifndef SQLITE_OMIT_VIRTUALTABLE
84772/* Opcode: VOpen P1 * * P4 *
84773**
84774** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
84775** P1 is a cursor number.  This opcode opens a cursor to the virtual
84776** table and stores that cursor in P1.
84777*/
84778case OP_VOpen: {
84779  VdbeCursor *pCur;
84780  sqlite3_vtab_cursor *pVCur;
84781  sqlite3_vtab *pVtab;
84782  const sqlite3_module *pModule;
84783
84784  assert( p->bIsReader );
84785  pCur = 0;
84786  pVCur = 0;
84787  pVtab = pOp->p4.pVtab->pVtab;
84788  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
84789    rc = SQLITE_LOCKED;
84790    goto abort_due_to_error;
84791  }
84792  pModule = pVtab->pModule;
84793  rc = pModule->xOpen(pVtab, &pVCur);
84794  sqlite3VtabImportErrmsg(p, pVtab);
84795  if( rc ) goto abort_due_to_error;
84796
84797  /* Initialize sqlite3_vtab_cursor base class */
84798  pVCur->pVtab = pVtab;
84799
84800  /* Initialize vdbe cursor object */
84801  pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
84802  if( pCur ){
84803    pCur->uc.pVCur = pVCur;
84804    pVtab->nRef++;
84805  }else{
84806    assert( db->mallocFailed );
84807    pModule->xClose(pVCur);
84808    goto no_mem;
84809  }
84810  break;
84811}
84812#endif /* SQLITE_OMIT_VIRTUALTABLE */
84813
84814#ifndef SQLITE_OMIT_VIRTUALTABLE
84815/* Opcode: VFilter P1 P2 P3 P4 *
84816** Synopsis: iplan=r[P3] zplan='P4'
84817**
84818** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
84819** the filtered result set is empty.
84820**
84821** P4 is either NULL or a string that was generated by the xBestIndex
84822** method of the module.  The interpretation of the P4 string is left
84823** to the module implementation.
84824**
84825** This opcode invokes the xFilter method on the virtual table specified
84826** by P1.  The integer query plan parameter to xFilter is stored in register
84827** P3. Register P3+1 stores the argc parameter to be passed to the
84828** xFilter method. Registers P3+2..P3+1+argc are the argc
84829** additional parameters which are passed to
84830** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
84831**
84832** A jump is made to P2 if the result set after filtering would be empty.
84833*/
84834case OP_VFilter: {   /* jump */
84835  int nArg;
84836  int iQuery;
84837  const sqlite3_module *pModule;
84838  Mem *pQuery;
84839  Mem *pArgc;
84840  sqlite3_vtab_cursor *pVCur;
84841  sqlite3_vtab *pVtab;
84842  VdbeCursor *pCur;
84843  int res;
84844  int i;
84845  Mem **apArg;
84846
84847  pQuery = &aMem[pOp->p3];
84848  pArgc = &pQuery[1];
84849  pCur = p->apCsr[pOp->p1];
84850  assert( memIsValid(pQuery) );
84851  REGISTER_TRACE(pOp->p3, pQuery);
84852  assert( pCur->eCurType==CURTYPE_VTAB );
84853  pVCur = pCur->uc.pVCur;
84854  pVtab = pVCur->pVtab;
84855  pModule = pVtab->pModule;
84856
84857  /* Grab the index number and argc parameters */
84858  assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
84859  nArg = (int)pArgc->u.i;
84860  iQuery = (int)pQuery->u.i;
84861
84862  /* Invoke the xFilter method */
84863  res = 0;
84864  apArg = p->apArg;
84865  for(i = 0; i<nArg; i++){
84866    apArg[i] = &pArgc[i+1];
84867  }
84868  rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
84869  sqlite3VtabImportErrmsg(p, pVtab);
84870  if( rc ) goto abort_due_to_error;
84871  res = pModule->xEof(pVCur);
84872  pCur->nullRow = 0;
84873  VdbeBranchTaken(res!=0,2);
84874  if( res ) goto jump_to_p2;
84875  break;
84876}
84877#endif /* SQLITE_OMIT_VIRTUALTABLE */
84878
84879#ifndef SQLITE_OMIT_VIRTUALTABLE
84880/* Opcode: VColumn P1 P2 P3 * *
84881** Synopsis: r[P3]=vcolumn(P2)
84882**
84883** Store the value of the P2-th column of
84884** the row of the virtual-table that the
84885** P1 cursor is pointing to into register P3.
84886*/
84887case OP_VColumn: {
84888  sqlite3_vtab *pVtab;
84889  const sqlite3_module *pModule;
84890  Mem *pDest;
84891  sqlite3_context sContext;
84892
84893  VdbeCursor *pCur = p->apCsr[pOp->p1];
84894  assert( pCur->eCurType==CURTYPE_VTAB );
84895  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
84896  pDest = &aMem[pOp->p3];
84897  memAboutToChange(p, pDest);
84898  if( pCur->nullRow ){
84899    sqlite3VdbeMemSetNull(pDest);
84900    break;
84901  }
84902  pVtab = pCur->uc.pVCur->pVtab;
84903  pModule = pVtab->pModule;
84904  assert( pModule->xColumn );
84905  memset(&sContext, 0, sizeof(sContext));
84906  sContext.pOut = pDest;
84907  MemSetTypeFlag(pDest, MEM_Null);
84908  rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
84909  sqlite3VtabImportErrmsg(p, pVtab);
84910  if( sContext.isError ){
84911    rc = sContext.isError;
84912  }
84913  sqlite3VdbeChangeEncoding(pDest, encoding);
84914  REGISTER_TRACE(pOp->p3, pDest);
84915  UPDATE_MAX_BLOBSIZE(pDest);
84916
84917  if( sqlite3VdbeMemTooBig(pDest) ){
84918    goto too_big;
84919  }
84920  if( rc ) goto abort_due_to_error;
84921  break;
84922}
84923#endif /* SQLITE_OMIT_VIRTUALTABLE */
84924
84925#ifndef SQLITE_OMIT_VIRTUALTABLE
84926/* Opcode: VNext P1 P2 * * *
84927**
84928** Advance virtual table P1 to the next row in its result set and
84929** jump to instruction P2.  Or, if the virtual table has reached
84930** the end of its result set, then fall through to the next instruction.
84931*/
84932case OP_VNext: {   /* jump */
84933  sqlite3_vtab *pVtab;
84934  const sqlite3_module *pModule;
84935  int res;
84936  VdbeCursor *pCur;
84937
84938  res = 0;
84939  pCur = p->apCsr[pOp->p1];
84940  assert( pCur->eCurType==CURTYPE_VTAB );
84941  if( pCur->nullRow ){
84942    break;
84943  }
84944  pVtab = pCur->uc.pVCur->pVtab;
84945  pModule = pVtab->pModule;
84946  assert( pModule->xNext );
84947
84948  /* Invoke the xNext() method of the module. There is no way for the
84949  ** underlying implementation to return an error if one occurs during
84950  ** xNext(). Instead, if an error occurs, true is returned (indicating that
84951  ** data is available) and the error code returned when xColumn or
84952  ** some other method is next invoked on the save virtual table cursor.
84953  */
84954  rc = pModule->xNext(pCur->uc.pVCur);
84955  sqlite3VtabImportErrmsg(p, pVtab);
84956  if( rc ) goto abort_due_to_error;
84957  res = pModule->xEof(pCur->uc.pVCur);
84958  VdbeBranchTaken(!res,2);
84959  if( !res ){
84960    /* If there is data, jump to P2 */
84961    goto jump_to_p2_and_check_for_interrupt;
84962  }
84963  goto check_for_interrupt;
84964}
84965#endif /* SQLITE_OMIT_VIRTUALTABLE */
84966
84967#ifndef SQLITE_OMIT_VIRTUALTABLE
84968/* Opcode: VRename P1 * * P4 *
84969**
84970** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
84971** This opcode invokes the corresponding xRename method. The value
84972** in register P1 is passed as the zName argument to the xRename method.
84973*/
84974case OP_VRename: {
84975  sqlite3_vtab *pVtab;
84976  Mem *pName;
84977
84978  pVtab = pOp->p4.pVtab->pVtab;
84979  pName = &aMem[pOp->p1];
84980  assert( pVtab->pModule->xRename );
84981  assert( memIsValid(pName) );
84982  assert( p->readOnly==0 );
84983  REGISTER_TRACE(pOp->p1, pName);
84984  assert( pName->flags & MEM_Str );
84985  testcase( pName->enc==SQLITE_UTF8 );
84986  testcase( pName->enc==SQLITE_UTF16BE );
84987  testcase( pName->enc==SQLITE_UTF16LE );
84988  rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
84989  if( rc ) goto abort_due_to_error;
84990  rc = pVtab->pModule->xRename(pVtab, pName->z);
84991  sqlite3VtabImportErrmsg(p, pVtab);
84992  p->expired = 0;
84993  if( rc ) goto abort_due_to_error;
84994  break;
84995}
84996#endif
84997
84998#ifndef SQLITE_OMIT_VIRTUALTABLE
84999/* Opcode: VUpdate P1 P2 P3 P4 P5
85000** Synopsis: data=r[P3@P2]
85001**
85002** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
85003** This opcode invokes the corresponding xUpdate method. P2 values
85004** are contiguous memory cells starting at P3 to pass to the xUpdate
85005** invocation. The value in register (P3+P2-1) corresponds to the
85006** p2th element of the argv array passed to xUpdate.
85007**
85008** The xUpdate method will do a DELETE or an INSERT or both.
85009** The argv[0] element (which corresponds to memory cell P3)
85010** is the rowid of a row to delete.  If argv[0] is NULL then no
85011** deletion occurs.  The argv[1] element is the rowid of the new
85012** row.  This can be NULL to have the virtual table select the new
85013** rowid for itself.  The subsequent elements in the array are
85014** the values of columns in the new row.
85015**
85016** If P2==1 then no insert is performed.  argv[0] is the rowid of
85017** a row to delete.
85018**
85019** P1 is a boolean flag. If it is set to true and the xUpdate call
85020** is successful, then the value returned by sqlite3_last_insert_rowid()
85021** is set to the value of the rowid for the row just inserted.
85022**
85023** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
85024** apply in the case of a constraint failure on an insert or update.
85025*/
85026case OP_VUpdate: {
85027  sqlite3_vtab *pVtab;
85028  const sqlite3_module *pModule;
85029  int nArg;
85030  int i;
85031  sqlite_int64 rowid;
85032  Mem **apArg;
85033  Mem *pX;
85034
85035  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
85036       || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
85037  );
85038  assert( p->readOnly==0 );
85039  pVtab = pOp->p4.pVtab->pVtab;
85040  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
85041    rc = SQLITE_LOCKED;
85042    goto abort_due_to_error;
85043  }
85044  pModule = pVtab->pModule;
85045  nArg = pOp->p2;
85046  assert( pOp->p4type==P4_VTAB );
85047  if( ALWAYS(pModule->xUpdate) ){
85048    u8 vtabOnConflict = db->vtabOnConflict;
85049    apArg = p->apArg;
85050    pX = &aMem[pOp->p3];
85051    for(i=0; i<nArg; i++){
85052      assert( memIsValid(pX) );
85053      memAboutToChange(p, pX);
85054      apArg[i] = pX;
85055      pX++;
85056    }
85057    db->vtabOnConflict = pOp->p5;
85058    rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
85059    db->vtabOnConflict = vtabOnConflict;
85060    sqlite3VtabImportErrmsg(p, pVtab);
85061    if( rc==SQLITE_OK && pOp->p1 ){
85062      assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
85063      db->lastRowid = rowid;
85064    }
85065    if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
85066      if( pOp->p5==OE_Ignore ){
85067        rc = SQLITE_OK;
85068      }else{
85069        p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
85070      }
85071    }else{
85072      p->nChange++;
85073    }
85074    if( rc ) goto abort_due_to_error;
85075  }
85076  break;
85077}
85078#endif /* SQLITE_OMIT_VIRTUALTABLE */
85079
85080#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
85081/* Opcode: Pagecount P1 P2 * * *
85082**
85083** Write the current number of pages in database P1 to memory cell P2.
85084*/
85085case OP_Pagecount: {            /* out2 */
85086  pOut = out2Prerelease(p, pOp);
85087  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
85088  break;
85089}
85090#endif
85091
85092
85093#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
85094/* Opcode: MaxPgcnt P1 P2 P3 * *
85095**
85096** Try to set the maximum page count for database P1 to the value in P3.
85097** Do not let the maximum page count fall below the current page count and
85098** do not change the maximum page count value if P3==0.
85099**
85100** Store the maximum page count after the change in register P2.
85101*/
85102case OP_MaxPgcnt: {            /* out2 */
85103  unsigned int newMax;
85104  Btree *pBt;
85105
85106  pOut = out2Prerelease(p, pOp);
85107  pBt = db->aDb[pOp->p1].pBt;
85108  newMax = 0;
85109  if( pOp->p3 ){
85110    newMax = sqlite3BtreeLastPage(pBt);
85111    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
85112  }
85113  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
85114  break;
85115}
85116#endif
85117
85118
85119/* Opcode: Init P1 P2 * P4 *
85120** Synopsis: Start at P2
85121**
85122** Programs contain a single instance of this opcode as the very first
85123** opcode.
85124**
85125** If tracing is enabled (by the sqlite3_trace()) interface, then
85126** the UTF-8 string contained in P4 is emitted on the trace callback.
85127** Or if P4 is blank, use the string returned by sqlite3_sql().
85128**
85129** If P2 is not zero, jump to instruction P2.
85130**
85131** Increment the value of P1 so that OP_Once opcodes will jump the
85132** first time they are evaluated for this run.
85133*/
85134case OP_Init: {          /* jump */
85135  char *zTrace;
85136  int i;
85137
85138  /* If the P4 argument is not NULL, then it must be an SQL comment string.
85139  ** The "--" string is broken up to prevent false-positives with srcck1.c.
85140  **
85141  ** This assert() provides evidence for:
85142  ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
85143  ** would have been returned by the legacy sqlite3_trace() interface by
85144  ** using the X argument when X begins with "--" and invoking
85145  ** sqlite3_expanded_sql(P) otherwise.
85146  */
85147  assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
85148  assert( pOp==p->aOp );  /* Always instruction 0 */
85149
85150#ifndef SQLITE_OMIT_TRACE
85151  if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
85152   && !p->doingRerun
85153   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
85154  ){
85155#ifndef SQLITE_OMIT_DEPRECATED
85156    if( db->mTrace & SQLITE_TRACE_LEGACY ){
85157      void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
85158      char *z = sqlite3VdbeExpandSql(p, zTrace);
85159      x(db->pTraceArg, z);
85160      sqlite3_free(z);
85161    }else
85162#endif
85163    if( db->nVdbeExec>1 ){
85164      char *z = sqlite3MPrintf(db, "-- %s", zTrace);
85165      (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
85166      sqlite3DbFree(db, z);
85167    }else{
85168      (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
85169    }
85170  }
85171#ifdef SQLITE_USE_FCNTL_TRACE
85172  zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
85173  if( zTrace ){
85174    int j;
85175    for(j=0; j<db->nDb; j++){
85176      if( DbMaskTest(p->btreeMask, j)==0 ) continue;
85177      sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
85178    }
85179  }
85180#endif /* SQLITE_USE_FCNTL_TRACE */
85181#ifdef SQLITE_DEBUG
85182  if( (db->flags & SQLITE_SqlTrace)!=0
85183   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
85184  ){
85185    sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
85186  }
85187#endif /* SQLITE_DEBUG */
85188#endif /* SQLITE_OMIT_TRACE */
85189  assert( pOp->p2>0 );
85190  if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
85191    for(i=1; i<p->nOp; i++){
85192      if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
85193    }
85194    pOp->p1 = 0;
85195  }
85196  pOp->p1++;
85197  goto jump_to_p2;
85198}
85199
85200#ifdef SQLITE_ENABLE_CURSOR_HINTS
85201/* Opcode: CursorHint P1 * * P4 *
85202**
85203** Provide a hint to cursor P1 that it only needs to return rows that
85204** satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer
85205** to values currently held in registers.  TK_COLUMN terms in the P4
85206** expression refer to columns in the b-tree to which cursor P1 is pointing.
85207*/
85208case OP_CursorHint: {
85209  VdbeCursor *pC;
85210
85211  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
85212  assert( pOp->p4type==P4_EXPR );
85213  pC = p->apCsr[pOp->p1];
85214  if( pC ){
85215    assert( pC->eCurType==CURTYPE_BTREE );
85216    sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
85217                           pOp->p4.pExpr, aMem);
85218  }
85219  break;
85220}
85221#endif /* SQLITE_ENABLE_CURSOR_HINTS */
85222
85223/* Opcode: Noop * * * * *
85224**
85225** Do nothing.  This instruction is often useful as a jump
85226** destination.
85227*/
85228/*
85229** The magic Explain opcode are only inserted when explain==2 (which
85230** is to say when the EXPLAIN QUERY PLAN syntax is used.)
85231** This opcode records information from the optimizer.  It is the
85232** the same as a no-op.  This opcodesnever appears in a real VM program.
85233*/
85234default: {          /* This is really OP_Noop and OP_Explain */
85235  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
85236  break;
85237}
85238
85239/*****************************************************************************
85240** The cases of the switch statement above this line should all be indented
85241** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
85242** readability.  From this point on down, the normal indentation rules are
85243** restored.
85244*****************************************************************************/
85245    }
85246
85247#ifdef VDBE_PROFILE
85248    {
85249      u64 endTime = sqlite3Hwtime();
85250      if( endTime>start ) pOrigOp->cycles += endTime - start;
85251      pOrigOp->cnt++;
85252    }
85253#endif
85254
85255    /* The following code adds nothing to the actual functionality
85256    ** of the program.  It is only here for testing and debugging.
85257    ** On the other hand, it does burn CPU cycles every time through
85258    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
85259    */
85260#ifndef NDEBUG
85261    assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
85262
85263#ifdef SQLITE_DEBUG
85264    if( db->flags & SQLITE_VdbeTrace ){
85265      u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
85266      if( rc!=0 ) printf("rc=%d\n",rc);
85267      if( opProperty & (OPFLG_OUT2) ){
85268        registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
85269      }
85270      if( opProperty & OPFLG_OUT3 ){
85271        registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
85272      }
85273    }
85274#endif  /* SQLITE_DEBUG */
85275#endif  /* NDEBUG */
85276  }  /* The end of the for(;;) loop the loops through opcodes */
85277
85278  /* If we reach this point, it means that execution is finished with
85279  ** an error of some kind.
85280  */
85281abort_due_to_error:
85282  if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
85283  assert( rc );
85284  if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
85285    sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
85286  }
85287  p->rc = rc;
85288  sqlite3SystemError(db, rc);
85289  testcase( sqlite3GlobalConfig.xLog!=0 );
85290  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
85291                   (int)(pOp - aOp), p->zSql, p->zErrMsg);
85292  sqlite3VdbeHalt(p);
85293  if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
85294  rc = SQLITE_ERROR;
85295  if( resetSchemaOnFault>0 ){
85296    sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
85297  }
85298
85299  /* This is the only way out of this procedure.  We have to
85300  ** release the mutexes on btrees that were acquired at the
85301  ** top. */
85302vdbe_return:
85303  testcase( nVmStep>0 );
85304  p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
85305  sqlite3VdbeLeave(p);
85306  assert( rc!=SQLITE_OK || nExtraDelete==0
85307       || sqlite3_strlike("DELETE%",p->zSql,0)!=0
85308  );
85309  return rc;
85310
85311  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
85312  ** is encountered.
85313  */
85314too_big:
85315  sqlite3VdbeError(p, "string or blob too big");
85316  rc = SQLITE_TOOBIG;
85317  goto abort_due_to_error;
85318
85319  /* Jump to here if a malloc() fails.
85320  */
85321no_mem:
85322  sqlite3OomFault(db);
85323  sqlite3VdbeError(p, "out of memory");
85324  rc = SQLITE_NOMEM_BKPT;
85325  goto abort_due_to_error;
85326
85327  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
85328  ** flag.
85329  */
85330abort_due_to_interrupt:
85331  assert( db->u1.isInterrupted );
85332  rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
85333  p->rc = rc;
85334  sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
85335  goto abort_due_to_error;
85336}
85337
85338
85339/************** End of vdbe.c ************************************************/
85340/************** Begin file vdbeblob.c ****************************************/
85341/*
85342** 2007 May 1
85343**
85344** The author disclaims copyright to this source code.  In place of
85345** a legal notice, here is a blessing:
85346**
85347**    May you do good and not evil.
85348**    May you find forgiveness for yourself and forgive others.
85349**    May you share freely, never taking more than you give.
85350**
85351*************************************************************************
85352**
85353** This file contains code used to implement incremental BLOB I/O.
85354*/
85355
85356/* #include "sqliteInt.h" */
85357/* #include "vdbeInt.h" */
85358
85359#ifndef SQLITE_OMIT_INCRBLOB
85360
85361/*
85362** Valid sqlite3_blob* handles point to Incrblob structures.
85363*/
85364typedef struct Incrblob Incrblob;
85365struct Incrblob {
85366  int nByte;              /* Size of open blob, in bytes */
85367  int iOffset;            /* Byte offset of blob in cursor data */
85368  u16 iCol;               /* Table column this handle is open on */
85369  BtCursor *pCsr;         /* Cursor pointing at blob row */
85370  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
85371  sqlite3 *db;            /* The associated database */
85372  char *zDb;              /* Database name */
85373  Table *pTab;            /* Table object */
85374};
85375
85376
85377/*
85378** This function is used by both blob_open() and blob_reopen(). It seeks
85379** the b-tree cursor associated with blob handle p to point to row iRow.
85380** If successful, SQLITE_OK is returned and subsequent calls to
85381** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
85382**
85383** If an error occurs, or if the specified row does not exist or does not
85384** contain a value of type TEXT or BLOB in the column nominated when the
85385** blob handle was opened, then an error code is returned and *pzErr may
85386** be set to point to a buffer containing an error message. It is the
85387** responsibility of the caller to free the error message buffer using
85388** sqlite3DbFree().
85389**
85390** If an error does occur, then the b-tree cursor is closed. All subsequent
85391** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
85392** immediately return SQLITE_ABORT.
85393*/
85394static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
85395  int rc;                         /* Error code */
85396  char *zErr = 0;                 /* Error message */
85397  Vdbe *v = (Vdbe *)p->pStmt;
85398
85399  /* Set the value of register r[1] in the SQL statement to integer iRow.
85400  ** This is done directly as a performance optimization
85401  */
85402  v->aMem[1].flags = MEM_Int;
85403  v->aMem[1].u.i = iRow;
85404
85405  /* If the statement has been run before (and is paused at the OP_ResultRow)
85406  ** then back it up to the point where it does the OP_SeekRowid.  This could
85407  ** have been down with an extra OP_Goto, but simply setting the program
85408  ** counter is faster. */
85409  if( v->pc>3 ){
85410    v->pc = 3;
85411    rc = sqlite3VdbeExec(v);
85412  }else{
85413    rc = sqlite3_step(p->pStmt);
85414  }
85415  if( rc==SQLITE_ROW ){
85416    VdbeCursor *pC = v->apCsr[0];
85417    u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
85418    testcase( pC->nHdrParsed==p->iCol );
85419    testcase( pC->nHdrParsed==p->iCol+1 );
85420    if( type<12 ){
85421      zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
85422          type==0?"null": type==7?"real": "integer"
85423      );
85424      rc = SQLITE_ERROR;
85425      sqlite3_finalize(p->pStmt);
85426      p->pStmt = 0;
85427    }else{
85428      p->iOffset = pC->aType[p->iCol + pC->nField];
85429      p->nByte = sqlite3VdbeSerialTypeLen(type);
85430      p->pCsr =  pC->uc.pCursor;
85431      sqlite3BtreeIncrblobCursor(p->pCsr);
85432    }
85433  }
85434
85435  if( rc==SQLITE_ROW ){
85436    rc = SQLITE_OK;
85437  }else if( p->pStmt ){
85438    rc = sqlite3_finalize(p->pStmt);
85439    p->pStmt = 0;
85440    if( rc==SQLITE_OK ){
85441      zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
85442      rc = SQLITE_ERROR;
85443    }else{
85444      zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
85445    }
85446  }
85447
85448  assert( rc!=SQLITE_OK || zErr==0 );
85449  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
85450
85451  *pzErr = zErr;
85452  return rc;
85453}
85454
85455/*
85456** Open a blob handle.
85457*/
85458SQLITE_API int sqlite3_blob_open(
85459  sqlite3* db,            /* The database connection */
85460  const char *zDb,        /* The attached database containing the blob */
85461  const char *zTable,     /* The table containing the blob */
85462  const char *zColumn,    /* The column containing the blob */
85463  sqlite_int64 iRow,      /* The row containing the glob */
85464  int wrFlag,             /* True -> read/write access, false -> read-only */
85465  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
85466){
85467  int nAttempt = 0;
85468  int iCol;               /* Index of zColumn in row-record */
85469  int rc = SQLITE_OK;
85470  char *zErr = 0;
85471  Table *pTab;
85472  Parse *pParse = 0;
85473  Incrblob *pBlob = 0;
85474
85475#ifdef SQLITE_ENABLE_API_ARMOR
85476  if( ppBlob==0 ){
85477    return SQLITE_MISUSE_BKPT;
85478  }
85479#endif
85480  *ppBlob = 0;
85481#ifdef SQLITE_ENABLE_API_ARMOR
85482  if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
85483    return SQLITE_MISUSE_BKPT;
85484  }
85485#endif
85486  wrFlag = !!wrFlag;                /* wrFlag = (wrFlag ? 1 : 0); */
85487
85488  sqlite3_mutex_enter(db->mutex);
85489
85490  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
85491  if( !pBlob ) goto blob_open_out;
85492  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
85493  if( !pParse ) goto blob_open_out;
85494
85495  do {
85496    memset(pParse, 0, sizeof(Parse));
85497    pParse->db = db;
85498    sqlite3DbFree(db, zErr);
85499    zErr = 0;
85500
85501    sqlite3BtreeEnterAll(db);
85502    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
85503    if( pTab && IsVirtual(pTab) ){
85504      pTab = 0;
85505      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
85506    }
85507    if( pTab && !HasRowid(pTab) ){
85508      pTab = 0;
85509      sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
85510    }
85511#ifndef SQLITE_OMIT_VIEW
85512    if( pTab && pTab->pSelect ){
85513      pTab = 0;
85514      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
85515    }
85516#endif
85517    if( !pTab ){
85518      if( pParse->zErrMsg ){
85519        sqlite3DbFree(db, zErr);
85520        zErr = pParse->zErrMsg;
85521        pParse->zErrMsg = 0;
85522      }
85523      rc = SQLITE_ERROR;
85524      sqlite3BtreeLeaveAll(db);
85525      goto blob_open_out;
85526    }
85527    pBlob->pTab = pTab;
85528    pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
85529
85530    /* Now search pTab for the exact column. */
85531    for(iCol=0; iCol<pTab->nCol; iCol++) {
85532      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
85533        break;
85534      }
85535    }
85536    if( iCol==pTab->nCol ){
85537      sqlite3DbFree(db, zErr);
85538      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
85539      rc = SQLITE_ERROR;
85540      sqlite3BtreeLeaveAll(db);
85541      goto blob_open_out;
85542    }
85543
85544    /* If the value is being opened for writing, check that the
85545    ** column is not indexed, and that it is not part of a foreign key.
85546    */
85547    if( wrFlag ){
85548      const char *zFault = 0;
85549      Index *pIdx;
85550#ifndef SQLITE_OMIT_FOREIGN_KEY
85551      if( db->flags&SQLITE_ForeignKeys ){
85552        /* Check that the column is not part of an FK child key definition. It
85553        ** is not necessary to check if it is part of a parent key, as parent
85554        ** key columns must be indexed. The check below will pick up this
85555        ** case.  */
85556        FKey *pFKey;
85557        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
85558          int j;
85559          for(j=0; j<pFKey->nCol; j++){
85560            if( pFKey->aCol[j].iFrom==iCol ){
85561              zFault = "foreign key";
85562            }
85563          }
85564        }
85565      }
85566#endif
85567      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85568        int j;
85569        for(j=0; j<pIdx->nKeyCol; j++){
85570          /* FIXME: Be smarter about indexes that use expressions */
85571          if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
85572            zFault = "indexed";
85573          }
85574        }
85575      }
85576      if( zFault ){
85577        sqlite3DbFree(db, zErr);
85578        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
85579        rc = SQLITE_ERROR;
85580        sqlite3BtreeLeaveAll(db);
85581        goto blob_open_out;
85582      }
85583    }
85584
85585    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
85586    assert( pBlob->pStmt || db->mallocFailed );
85587    if( pBlob->pStmt ){
85588
85589      /* This VDBE program seeks a btree cursor to the identified
85590      ** db/table/row entry. The reason for using a vdbe program instead
85591      ** of writing code to use the b-tree layer directly is that the
85592      ** vdbe program will take advantage of the various transaction,
85593      ** locking and error handling infrastructure built into the vdbe.
85594      **
85595      ** After seeking the cursor, the vdbe executes an OP_ResultRow.
85596      ** Code external to the Vdbe then "borrows" the b-tree cursor and
85597      ** uses it to implement the blob_read(), blob_write() and
85598      ** blob_bytes() functions.
85599      **
85600      ** The sqlite3_blob_close() function finalizes the vdbe program,
85601      ** which closes the b-tree cursor and (possibly) commits the
85602      ** transaction.
85603      */
85604      static const int iLn = VDBE_OFFSET_LINENO(2);
85605      static const VdbeOpList openBlob[] = {
85606        {OP_TableLock,      0, 0, 0},  /* 0: Acquire a read or write lock */
85607        {OP_OpenRead,       0, 0, 0},  /* 1: Open a cursor */
85608        /* blobSeekToRow() will initialize r[1] to the desired rowid */
85609        {OP_NotExists,      0, 5, 1},  /* 2: Seek the cursor to rowid=r[1] */
85610        {OP_Column,         0, 0, 1},  /* 3  */
85611        {OP_ResultRow,      1, 0, 0},  /* 4  */
85612        {OP_Halt,           0, 0, 0},  /* 5  */
85613      };
85614      Vdbe *v = (Vdbe *)pBlob->pStmt;
85615      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85616      VdbeOp *aOp;
85617
85618      sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
85619                           pTab->pSchema->schema_cookie,
85620                           pTab->pSchema->iGeneration);
85621      sqlite3VdbeChangeP5(v, 1);
85622      aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
85623
85624      /* Make sure a mutex is held on the table to be accessed */
85625      sqlite3VdbeUsesBtree(v, iDb);
85626
85627      if( db->mallocFailed==0 ){
85628        assert( aOp!=0 );
85629        /* Configure the OP_TableLock instruction */
85630#ifdef SQLITE_OMIT_SHARED_CACHE
85631        aOp[0].opcode = OP_Noop;
85632#else
85633        aOp[0].p1 = iDb;
85634        aOp[0].p2 = pTab->tnum;
85635        aOp[0].p3 = wrFlag;
85636        sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
85637      }
85638      if( db->mallocFailed==0 ){
85639#endif
85640
85641        /* Remove either the OP_OpenWrite or OpenRead. Set the P2
85642        ** parameter of the other to pTab->tnum.  */
85643        if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
85644        aOp[1].p2 = pTab->tnum;
85645        aOp[1].p3 = iDb;
85646
85647        /* Configure the number of columns. Configure the cursor to
85648        ** think that the table has one more column than it really
85649        ** does. An OP_Column to retrieve this imaginary column will
85650        ** always return an SQL NULL. This is useful because it means
85651        ** we can invoke OP_Column to fill in the vdbe cursors type
85652        ** and offset cache without causing any IO.
85653        */
85654        aOp[1].p4type = P4_INT32;
85655        aOp[1].p4.i = pTab->nCol+1;
85656        aOp[3].p2 = pTab->nCol;
85657
85658        pParse->nVar = 0;
85659        pParse->nMem = 1;
85660        pParse->nTab = 1;
85661        sqlite3VdbeMakeReady(v, pParse);
85662      }
85663    }
85664
85665    pBlob->iCol = iCol;
85666    pBlob->db = db;
85667    sqlite3BtreeLeaveAll(db);
85668    if( db->mallocFailed ){
85669      goto blob_open_out;
85670    }
85671    rc = blobSeekToRow(pBlob, iRow, &zErr);
85672  } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
85673
85674blob_open_out:
85675  if( rc==SQLITE_OK && db->mallocFailed==0 ){
85676    *ppBlob = (sqlite3_blob *)pBlob;
85677  }else{
85678    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
85679    sqlite3DbFree(db, pBlob);
85680  }
85681  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
85682  sqlite3DbFree(db, zErr);
85683  sqlite3ParserReset(pParse);
85684  sqlite3StackFree(db, pParse);
85685  rc = sqlite3ApiExit(db, rc);
85686  sqlite3_mutex_leave(db->mutex);
85687  return rc;
85688}
85689
85690/*
85691** Close a blob handle that was previously created using
85692** sqlite3_blob_open().
85693*/
85694SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
85695  Incrblob *p = (Incrblob *)pBlob;
85696  int rc;
85697  sqlite3 *db;
85698
85699  if( p ){
85700    db = p->db;
85701    sqlite3_mutex_enter(db->mutex);
85702    rc = sqlite3_finalize(p->pStmt);
85703    sqlite3DbFree(db, p);
85704    sqlite3_mutex_leave(db->mutex);
85705  }else{
85706    rc = SQLITE_OK;
85707  }
85708  return rc;
85709}
85710
85711/*
85712** Perform a read or write operation on a blob
85713*/
85714static int blobReadWrite(
85715  sqlite3_blob *pBlob,
85716  void *z,
85717  int n,
85718  int iOffset,
85719  int (*xCall)(BtCursor*, u32, u32, void*)
85720){
85721  int rc;
85722  Incrblob *p = (Incrblob *)pBlob;
85723  Vdbe *v;
85724  sqlite3 *db;
85725
85726  if( p==0 ) return SQLITE_MISUSE_BKPT;
85727  db = p->db;
85728  sqlite3_mutex_enter(db->mutex);
85729  v = (Vdbe*)p->pStmt;
85730
85731  if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
85732    /* Request is out of range. Return a transient error. */
85733    rc = SQLITE_ERROR;
85734  }else if( v==0 ){
85735    /* If there is no statement handle, then the blob-handle has
85736    ** already been invalidated. Return SQLITE_ABORT in this case.
85737    */
85738    rc = SQLITE_ABORT;
85739  }else{
85740    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
85741    ** returned, clean-up the statement handle.
85742    */
85743    assert( db == v->db );
85744    sqlite3BtreeEnterCursor(p->pCsr);
85745
85746#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
85747    if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
85748      /* If a pre-update hook is registered and this is a write cursor,
85749      ** invoke it here.
85750      **
85751      ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
85752      ** operation should really be an SQLITE_UPDATE. This is probably
85753      ** incorrect, but is convenient because at this point the new.* values
85754      ** are not easily obtainable. And for the sessions module, an
85755      ** SQLITE_UPDATE where the PK columns do not change is handled in the
85756      ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
85757      ** slightly more efficient). Since you cannot write to a PK column
85758      ** using the incremental-blob API, this works. For the sessions module
85759      ** anyhow.
85760      */
85761      sqlite3_int64 iKey;
85762      iKey = sqlite3BtreeIntegerKey(p->pCsr);
85763      sqlite3VdbePreUpdateHook(
85764          v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
85765      );
85766    }
85767#endif
85768
85769    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
85770    sqlite3BtreeLeaveCursor(p->pCsr);
85771    if( rc==SQLITE_ABORT ){
85772      sqlite3VdbeFinalize(v);
85773      p->pStmt = 0;
85774    }else{
85775      v->rc = rc;
85776    }
85777  }
85778  sqlite3Error(db, rc);
85779  rc = sqlite3ApiExit(db, rc);
85780  sqlite3_mutex_leave(db->mutex);
85781  return rc;
85782}
85783
85784/*
85785** Read data from a blob handle.
85786*/
85787SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
85788  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
85789}
85790
85791/*
85792** Write data to a blob handle.
85793*/
85794SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
85795  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
85796}
85797
85798/*
85799** Query a blob handle for the size of the data.
85800**
85801** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
85802** so no mutex is required for access.
85803*/
85804SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
85805  Incrblob *p = (Incrblob *)pBlob;
85806  return (p && p->pStmt) ? p->nByte : 0;
85807}
85808
85809/*
85810** Move an existing blob handle to point to a different row of the same
85811** database table.
85812**
85813** If an error occurs, or if the specified row does not exist or does not
85814** contain a blob or text value, then an error code is returned and the
85815** database handle error code and message set. If this happens, then all
85816** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
85817** immediately return SQLITE_ABORT.
85818*/
85819SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
85820  int rc;
85821  Incrblob *p = (Incrblob *)pBlob;
85822  sqlite3 *db;
85823
85824  if( p==0 ) return SQLITE_MISUSE_BKPT;
85825  db = p->db;
85826  sqlite3_mutex_enter(db->mutex);
85827
85828  if( p->pStmt==0 ){
85829    /* If there is no statement handle, then the blob-handle has
85830    ** already been invalidated. Return SQLITE_ABORT in this case.
85831    */
85832    rc = SQLITE_ABORT;
85833  }else{
85834    char *zErr;
85835    rc = blobSeekToRow(p, iRow, &zErr);
85836    if( rc!=SQLITE_OK ){
85837      sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
85838      sqlite3DbFree(db, zErr);
85839    }
85840    assert( rc!=SQLITE_SCHEMA );
85841  }
85842
85843  rc = sqlite3ApiExit(db, rc);
85844  assert( rc==SQLITE_OK || p->pStmt==0 );
85845  sqlite3_mutex_leave(db->mutex);
85846  return rc;
85847}
85848
85849#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
85850
85851/************** End of vdbeblob.c ********************************************/
85852/************** Begin file vdbesort.c ****************************************/
85853/*
85854** 2011-07-09
85855**
85856** The author disclaims copyright to this source code.  In place of
85857** a legal notice, here is a blessing:
85858**
85859**    May you do good and not evil.
85860**    May you find forgiveness for yourself and forgive others.
85861**    May you share freely, never taking more than you give.
85862**
85863*************************************************************************
85864** This file contains code for the VdbeSorter object, used in concert with
85865** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
85866** or by SELECT statements with ORDER BY clauses that cannot be satisfied
85867** using indexes and without LIMIT clauses.
85868**
85869** The VdbeSorter object implements a multi-threaded external merge sort
85870** algorithm that is efficient even if the number of elements being sorted
85871** exceeds the available memory.
85872**
85873** Here is the (internal, non-API) interface between this module and the
85874** rest of the SQLite system:
85875**
85876**    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.
85877**
85878**    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter
85879**                                  object.  The row is a binary blob in the
85880**                                  OP_MakeRecord format that contains both
85881**                                  the ORDER BY key columns and result columns
85882**                                  in the case of a SELECT w/ ORDER BY, or
85883**                                  the complete record for an index entry
85884**                                  in the case of a CREATE INDEX.
85885**
85886**    sqlite3VdbeSorterRewind()     Sort all content previously added.
85887**                                  Position the read cursor on the
85888**                                  first sorted element.
85889**
85890**    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted
85891**                                  element.
85892**
85893**    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the
85894**                                  row currently under the read cursor.
85895**
85896**    sqlite3VdbeSorterCompare()    Compare the binary blob for the row
85897**                                  currently under the read cursor against
85898**                                  another binary blob X and report if
85899**                                  X is strictly less than the read cursor.
85900**                                  Used to enforce uniqueness in a
85901**                                  CREATE UNIQUE INDEX statement.
85902**
85903**    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim
85904**                                  all resources.
85905**
85906**    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This
85907**                                  is like Close() followed by Init() only
85908**                                  much faster.
85909**
85910** The interfaces above must be called in a particular order.  Write() can
85911** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
85912** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
85913**
85914**   Init()
85915**   for each record: Write()
85916**   Rewind()
85917**     Rowkey()/Compare()
85918**   Next()
85919**   Close()
85920**
85921** Algorithm:
85922**
85923** Records passed to the sorter via calls to Write() are initially held
85924** unsorted in main memory. Assuming the amount of memory used never exceeds
85925** a threshold, when Rewind() is called the set of records is sorted using
85926** an in-memory merge sort. In this case, no temporary files are required
85927** and subsequent calls to Rowkey(), Next() and Compare() read records
85928** directly from main memory.
85929**
85930** If the amount of space used to store records in main memory exceeds the
85931** threshold, then the set of records currently in memory are sorted and
85932** written to a temporary file in "Packed Memory Array" (PMA) format.
85933** A PMA created at this point is known as a "level-0 PMA". Higher levels
85934** of PMAs may be created by merging existing PMAs together - for example
85935** merging two or more level-0 PMAs together creates a level-1 PMA.
85936**
85937** The threshold for the amount of main memory to use before flushing
85938** records to a PMA is roughly the same as the limit configured for the
85939** page-cache of the main database. Specifically, the threshold is set to
85940** the value returned by "PRAGMA main.page_size" multipled by
85941** that returned by "PRAGMA main.cache_size", in bytes.
85942**
85943** If the sorter is running in single-threaded mode, then all PMAs generated
85944** are appended to a single temporary file. Or, if the sorter is running in
85945** multi-threaded mode then up to (N+1) temporary files may be opened, where
85946** N is the configured number of worker threads. In this case, instead of
85947** sorting the records and writing the PMA to a temporary file itself, the
85948** calling thread usually launches a worker thread to do so. Except, if
85949** there are already N worker threads running, the main thread does the work
85950** itself.
85951**
85952** The sorter is running in multi-threaded mode if (a) the library was built
85953** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
85954** than zero, and (b) worker threads have been enabled at runtime by calling
85955** "PRAGMA threads=N" with some value of N greater than 0.
85956**
85957** When Rewind() is called, any data remaining in memory is flushed to a
85958** final PMA. So at this point the data is stored in some number of sorted
85959** PMAs within temporary files on disk.
85960**
85961** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
85962** sorter is running in single-threaded mode, then these PMAs are merged
85963** incrementally as keys are retreived from the sorter by the VDBE.  The
85964** MergeEngine object, described in further detail below, performs this
85965** merge.
85966**
85967** Or, if running in multi-threaded mode, then a background thread is
85968** launched to merge the existing PMAs. Once the background thread has
85969** merged T bytes of data into a single sorted PMA, the main thread
85970** begins reading keys from that PMA while the background thread proceeds
85971** with merging the next T bytes of data. And so on.
85972**
85973** Parameter T is set to half the value of the memory threshold used
85974** by Write() above to determine when to create a new PMA.
85975**
85976** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
85977** Rewind() is called, then a hierarchy of incremental-merges is used.
85978** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
85979** disk are merged together. Then T bytes of data from the second set, and
85980** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
85981** PMAs at a time. This done is to improve locality.
85982**
85983** If running in multi-threaded mode and there are more than
85984** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
85985** than one background thread may be created. Specifically, there may be
85986** one background thread for each temporary file on disk, and one background
85987** thread to merge the output of each of the others to a single PMA for
85988** the main thread to read from.
85989*/
85990/* #include "sqliteInt.h" */
85991/* #include "vdbeInt.h" */
85992
85993/*
85994** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
85995** messages to stderr that may be helpful in understanding the performance
85996** characteristics of the sorter in multi-threaded mode.
85997*/
85998#if 0
85999# define SQLITE_DEBUG_SORTER_THREADS 1
86000#endif
86001
86002/*
86003** Hard-coded maximum amount of data to accumulate in memory before flushing
86004** to a level 0 PMA. The purpose of this limit is to prevent various integer
86005** overflows. 512MiB.
86006*/
86007#define SQLITE_MAX_PMASZ    (1<<29)
86008
86009/*
86010** Private objects used by the sorter
86011*/
86012typedef struct MergeEngine MergeEngine;     /* Merge PMAs together */
86013typedef struct PmaReader PmaReader;         /* Incrementally read one PMA */
86014typedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */
86015typedef struct SorterRecord SorterRecord;   /* A record being sorted */
86016typedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */
86017typedef struct SorterFile SorterFile;       /* Temporary file object wrapper */
86018typedef struct SorterList SorterList;       /* In-memory list of records */
86019typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
86020
86021/*
86022** A container for a temp file handle and the current amount of data
86023** stored in the file.
86024*/
86025struct SorterFile {
86026  sqlite3_file *pFd;              /* File handle */
86027  i64 iEof;                       /* Bytes of data stored in pFd */
86028};
86029
86030/*
86031** An in-memory list of objects to be sorted.
86032**
86033** If aMemory==0 then each object is allocated separately and the objects
86034** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects
86035** are stored in the aMemory[] bulk memory, one right after the other, and
86036** are connected using SorterRecord.u.iNext.
86037*/
86038struct SorterList {
86039  SorterRecord *pList;            /* Linked list of records */
86040  u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
86041  int szPMA;                      /* Size of pList as PMA in bytes */
86042};
86043
86044/*
86045** The MergeEngine object is used to combine two or more smaller PMAs into
86046** one big PMA using a merge operation.  Separate PMAs all need to be
86047** combined into one big PMA in order to be able to step through the sorted
86048** records in order.
86049**
86050** The aReadr[] array contains a PmaReader object for each of the PMAs being
86051** merged.  An aReadr[] object either points to a valid key or else is at EOF.
86052** ("EOF" means "End Of File".  When aReadr[] is at EOF there is no more data.)
86053** For the purposes of the paragraphs below, we assume that the array is
86054** actually N elements in size, where N is the smallest power of 2 greater
86055** to or equal to the number of PMAs being merged. The extra aReadr[] elements
86056** are treated as if they are empty (always at EOF).
86057**
86058** The aTree[] array is also N elements in size. The value of N is stored in
86059** the MergeEngine.nTree variable.
86060**
86061** The final (N/2) elements of aTree[] contain the results of comparing
86062** pairs of PMA keys together. Element i contains the result of
86063** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
86064** aTree element is set to the index of it.
86065**
86066** For the purposes of this comparison, EOF is considered greater than any
86067** other key value. If the keys are equal (only possible with two EOF
86068** values), it doesn't matter which index is stored.
86069**
86070** The (N/4) elements of aTree[] that precede the final (N/2) described
86071** above contains the index of the smallest of each block of 4 PmaReaders
86072** And so on. So that aTree[1] contains the index of the PmaReader that
86073** currently points to the smallest key value. aTree[0] is unused.
86074**
86075** Example:
86076**
86077**     aReadr[0] -> Banana
86078**     aReadr[1] -> Feijoa
86079**     aReadr[2] -> Elderberry
86080**     aReadr[3] -> Currant
86081**     aReadr[4] -> Grapefruit
86082**     aReadr[5] -> Apple
86083**     aReadr[6] -> Durian
86084**     aReadr[7] -> EOF
86085**
86086**     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
86087**
86088** The current element is "Apple" (the value of the key indicated by
86089** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
86090** be advanced to the next key in its segment. Say the next key is
86091** "Eggplant":
86092**
86093**     aReadr[5] -> Eggplant
86094**
86095** The contents of aTree[] are updated first by comparing the new PmaReader
86096** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
86097** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
86098** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
86099** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
86100** so the value written into element 1 of the array is 0. As follows:
86101**
86102**     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
86103**
86104** In other words, each time we advance to the next sorter element, log2(N)
86105** key comparison operations are required, where N is the number of segments
86106** being merged (rounded up to the next power of 2).
86107*/
86108struct MergeEngine {
86109  int nTree;                 /* Used size of aTree/aReadr (power of 2) */
86110  SortSubtask *pTask;        /* Used by this thread only */
86111  int *aTree;                /* Current state of incremental merge */
86112  PmaReader *aReadr;         /* Array of PmaReaders to merge data from */
86113};
86114
86115/*
86116** This object represents a single thread of control in a sort operation.
86117** Exactly VdbeSorter.nTask instances of this object are allocated
86118** as part of each VdbeSorter object. Instances are never allocated any
86119** other way. VdbeSorter.nTask is set to the number of worker threads allowed
86120** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for
86121** single-threaded operation, there is exactly one instance of this object
86122** and for multi-threaded operation there are two or more instances.
86123**
86124** Essentially, this structure contains all those fields of the VdbeSorter
86125** structure for which each thread requires a separate instance. For example,
86126** each thread requries its own UnpackedRecord object to unpack records in
86127** as part of comparison operations.
86128**
86129** Before a background thread is launched, variable bDone is set to 0. Then,
86130** right before it exits, the thread itself sets bDone to 1. This is used for
86131** two purposes:
86132**
86133**   1. When flushing the contents of memory to a level-0 PMA on disk, to
86134**      attempt to select a SortSubtask for which there is not already an
86135**      active background thread (since doing so causes the main thread
86136**      to block until it finishes).
86137**
86138**   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
86139**      to sqlite3ThreadJoin() is likely to block. Cases that are likely to
86140**      block provoke debugging output.
86141**
86142** In both cases, the effects of the main thread seeing (bDone==0) even
86143** after the thread has finished are not dire. So we don't worry about
86144** memory barriers and such here.
86145*/
86146typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
86147struct SortSubtask {
86148  SQLiteThread *pThread;          /* Background thread, if any */
86149  int bDone;                      /* Set if thread is finished but not joined */
86150  VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
86151  UnpackedRecord *pUnpacked;      /* Space to unpack a record */
86152  SorterList list;                /* List for thread to write to a PMA */
86153  int nPMA;                       /* Number of PMAs currently in file */
86154  SorterCompare xCompare;         /* Compare function to use */
86155  SorterFile file;                /* Temp file for level-0 PMAs */
86156  SorterFile file2;               /* Space for other PMAs */
86157};
86158
86159
86160/*
86161** Main sorter structure. A single instance of this is allocated for each
86162** sorter cursor created by the VDBE.
86163**
86164** mxKeysize:
86165**   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
86166**   this variable is updated so as to be set to the size on disk of the
86167**   largest record in the sorter.
86168*/
86169struct VdbeSorter {
86170  int mnPmaSize;                  /* Minimum PMA size, in bytes */
86171  int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
86172  int mxKeysize;                  /* Largest serialized key seen so far */
86173  int pgsz;                       /* Main database page size */
86174  PmaReader *pReader;             /* Readr data from here after Rewind() */
86175  MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */
86176  sqlite3 *db;                    /* Database connection */
86177  KeyInfo *pKeyInfo;              /* How to compare records */
86178  UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */
86179  SorterList list;                /* List of in-memory records */
86180  int iMemory;                    /* Offset of free space in list.aMemory */
86181  int nMemory;                    /* Size of list.aMemory allocation in bytes */
86182  u8 bUsePMA;                     /* True if one or more PMAs created */
86183  u8 bUseThreads;                 /* True to use background threads */
86184  u8 iPrev;                       /* Previous thread used to flush PMA */
86185  u8 nTask;                       /* Size of aTask[] array */
86186  u8 typeMask;
86187  SortSubtask aTask[1];           /* One or more subtasks */
86188};
86189
86190#define SORTER_TYPE_INTEGER 0x01
86191#define SORTER_TYPE_TEXT    0x02
86192
86193/*
86194** An instance of the following object is used to read records out of a
86195** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.
86196** aKey might point into aMap or into aBuffer.  If neither of those locations
86197** contain a contiguous representation of the key, then aAlloc is allocated
86198** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
86199**
86200** pFd==0 at EOF.
86201*/
86202struct PmaReader {
86203  i64 iReadOff;               /* Current read offset */
86204  i64 iEof;                   /* 1 byte past EOF for this PmaReader */
86205  int nAlloc;                 /* Bytes of space at aAlloc */
86206  int nKey;                   /* Number of bytes in key */
86207  sqlite3_file *pFd;          /* File handle we are reading from */
86208  u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */
86209  u8 *aKey;                   /* Pointer to current key */
86210  u8 *aBuffer;                /* Current read buffer */
86211  int nBuffer;                /* Size of read buffer in bytes */
86212  u8 *aMap;                   /* Pointer to mapping of entire file */
86213  IncrMerger *pIncr;          /* Incremental merger */
86214};
86215
86216/*
86217** Normally, a PmaReader object iterates through an existing PMA stored
86218** within a temp file. However, if the PmaReader.pIncr variable points to
86219** an object of the following type, it may be used to iterate/merge through
86220** multiple PMAs simultaneously.
86221**
86222** There are two types of IncrMerger object - single (bUseThread==0) and
86223** multi-threaded (bUseThread==1).
86224**
86225** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
86226** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
86227** size. When the IncrMerger is initialized, it reads enough data from
86228** pMerger to populate aFile[0]. It then sets variables within the
86229** corresponding PmaReader object to read from that file and kicks off
86230** a background thread to populate aFile[1] with the next mxSz bytes of
86231** sorted record data from pMerger.
86232**
86233** When the PmaReader reaches the end of aFile[0], it blocks until the
86234** background thread has finished populating aFile[1]. It then exchanges
86235** the contents of the aFile[0] and aFile[1] variables within this structure,
86236** sets the PmaReader fields to read from the new aFile[0] and kicks off
86237** another background thread to populate the new aFile[1]. And so on, until
86238** the contents of pMerger are exhausted.
86239**
86240** A single-threaded IncrMerger does not open any temporary files of its
86241** own. Instead, it has exclusive access to mxSz bytes of space beginning
86242** at offset iStartOff of file pTask->file2. And instead of using a
86243** background thread to prepare data for the PmaReader, with a single
86244** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
86245** keys from pMerger by the calling thread whenever the PmaReader runs out
86246** of data.
86247*/
86248struct IncrMerger {
86249  SortSubtask *pTask;             /* Task that owns this merger */
86250  MergeEngine *pMerger;           /* Merge engine thread reads data from */
86251  i64 iStartOff;                  /* Offset to start writing file at */
86252  int mxSz;                       /* Maximum bytes of data to store */
86253  int bEof;                       /* Set to true when merge is finished */
86254  int bUseThread;                 /* True to use a bg thread for this object */
86255  SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */
86256};
86257
86258/*
86259** An instance of this object is used for writing a PMA.
86260**
86261** The PMA is written one record at a time.  Each record is of an arbitrary
86262** size.  But I/O is more efficient if it occurs in page-sized blocks where
86263** each block is aligned on a page boundary.  This object caches writes to
86264** the PMA so that aligned, page-size blocks are written.
86265*/
86266struct PmaWriter {
86267  int eFWErr;                     /* Non-zero if in an error state */
86268  u8 *aBuffer;                    /* Pointer to write buffer */
86269  int nBuffer;                    /* Size of write buffer in bytes */
86270  int iBufStart;                  /* First byte of buffer to write */
86271  int iBufEnd;                    /* Last byte of buffer to write */
86272  i64 iWriteOff;                  /* Offset of start of buffer in file */
86273  sqlite3_file *pFd;              /* File handle to write to */
86274};
86275
86276/*
86277** This object is the header on a single record while that record is being
86278** held in memory and prior to being written out as part of a PMA.
86279**
86280** How the linked list is connected depends on how memory is being managed
86281** by this module. If using a separate allocation for each in-memory record
86282** (VdbeSorter.list.aMemory==0), then the list is always connected using the
86283** SorterRecord.u.pNext pointers.
86284**
86285** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
86286** then while records are being accumulated the list is linked using the
86287** SorterRecord.u.iNext offset. This is because the aMemory[] array may
86288** be sqlite3Realloc()ed while records are being accumulated. Once the VM
86289** has finished passing records to the sorter, or when the in-memory buffer
86290** is full, the list is sorted. As part of the sorting process, it is
86291** converted to use the SorterRecord.u.pNext pointers. See function
86292** vdbeSorterSort() for details.
86293*/
86294struct SorterRecord {
86295  int nVal;                       /* Size of the record in bytes */
86296  union {
86297    SorterRecord *pNext;          /* Pointer to next record in list */
86298    int iNext;                    /* Offset within aMemory of next record */
86299  } u;
86300  /* The data for the record immediately follows this header */
86301};
86302
86303/* Return a pointer to the buffer containing the record data for SorterRecord
86304** object p. Should be used as if:
86305**
86306**   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
86307*/
86308#define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
86309
86310
86311/* Maximum number of PMAs that a single MergeEngine can merge */
86312#define SORTER_MAX_MERGE_COUNT 16
86313
86314static int vdbeIncrSwap(IncrMerger*);
86315static void vdbeIncrFree(IncrMerger *);
86316
86317/*
86318** Free all memory belonging to the PmaReader object passed as the
86319** argument. All structure fields are set to zero before returning.
86320*/
86321static void vdbePmaReaderClear(PmaReader *pReadr){
86322  sqlite3_free(pReadr->aAlloc);
86323  sqlite3_free(pReadr->aBuffer);
86324  if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
86325  vdbeIncrFree(pReadr->pIncr);
86326  memset(pReadr, 0, sizeof(PmaReader));
86327}
86328
86329/*
86330** Read the next nByte bytes of data from the PMA p.
86331** If successful, set *ppOut to point to a buffer containing the data
86332** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
86333** error code.
86334**
86335** The buffer returned in *ppOut is only valid until the
86336** next call to this function.
86337*/
86338static int vdbePmaReadBlob(
86339  PmaReader *p,                   /* PmaReader from which to take the blob */
86340  int nByte,                      /* Bytes of data to read */
86341  u8 **ppOut                      /* OUT: Pointer to buffer containing data */
86342){
86343  int iBuf;                       /* Offset within buffer to read from */
86344  int nAvail;                     /* Bytes of data available in buffer */
86345
86346  if( p->aMap ){
86347    *ppOut = &p->aMap[p->iReadOff];
86348    p->iReadOff += nByte;
86349    return SQLITE_OK;
86350  }
86351
86352  assert( p->aBuffer );
86353
86354  /* If there is no more data to be read from the buffer, read the next
86355  ** p->nBuffer bytes of data from the file into it. Or, if there are less
86356  ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
86357  iBuf = p->iReadOff % p->nBuffer;
86358  if( iBuf==0 ){
86359    int nRead;                    /* Bytes to read from disk */
86360    int rc;                       /* sqlite3OsRead() return code */
86361
86362    /* Determine how many bytes of data to read. */
86363    if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
86364      nRead = p->nBuffer;
86365    }else{
86366      nRead = (int)(p->iEof - p->iReadOff);
86367    }
86368    assert( nRead>0 );
86369
86370    /* Readr data from the file. Return early if an error occurs. */
86371    rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
86372    assert( rc!=SQLITE_IOERR_SHORT_READ );
86373    if( rc!=SQLITE_OK ) return rc;
86374  }
86375  nAvail = p->nBuffer - iBuf;
86376
86377  if( nByte<=nAvail ){
86378    /* The requested data is available in the in-memory buffer. In this
86379    ** case there is no need to make a copy of the data, just return a
86380    ** pointer into the buffer to the caller.  */
86381    *ppOut = &p->aBuffer[iBuf];
86382    p->iReadOff += nByte;
86383  }else{
86384    /* The requested data is not all available in the in-memory buffer.
86385    ** In this case, allocate space at p->aAlloc[] to copy the requested
86386    ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
86387    int nRem;                     /* Bytes remaining to copy */
86388
86389    /* Extend the p->aAlloc[] allocation if required. */
86390    if( p->nAlloc<nByte ){
86391      u8 *aNew;
86392      int nNew = MAX(128, p->nAlloc*2);
86393      while( nByte>nNew ) nNew = nNew*2;
86394      aNew = sqlite3Realloc(p->aAlloc, nNew);
86395      if( !aNew ) return SQLITE_NOMEM_BKPT;
86396      p->nAlloc = nNew;
86397      p->aAlloc = aNew;
86398    }
86399
86400    /* Copy as much data as is available in the buffer into the start of
86401    ** p->aAlloc[].  */
86402    memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
86403    p->iReadOff += nAvail;
86404    nRem = nByte - nAvail;
86405
86406    /* The following loop copies up to p->nBuffer bytes per iteration into
86407    ** the p->aAlloc[] buffer.  */
86408    while( nRem>0 ){
86409      int rc;                     /* vdbePmaReadBlob() return code */
86410      int nCopy;                  /* Number of bytes to copy */
86411      u8 *aNext;                  /* Pointer to buffer to copy data from */
86412
86413      nCopy = nRem;
86414      if( nRem>p->nBuffer ) nCopy = p->nBuffer;
86415      rc = vdbePmaReadBlob(p, nCopy, &aNext);
86416      if( rc!=SQLITE_OK ) return rc;
86417      assert( aNext!=p->aAlloc );
86418      memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
86419      nRem -= nCopy;
86420    }
86421
86422    *ppOut = p->aAlloc;
86423  }
86424
86425  return SQLITE_OK;
86426}
86427
86428/*
86429** Read a varint from the stream of data accessed by p. Set *pnOut to
86430** the value read.
86431*/
86432static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
86433  int iBuf;
86434
86435  if( p->aMap ){
86436    p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
86437  }else{
86438    iBuf = p->iReadOff % p->nBuffer;
86439    if( iBuf && (p->nBuffer-iBuf)>=9 ){
86440      p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
86441    }else{
86442      u8 aVarint[16], *a;
86443      int i = 0, rc;
86444      do{
86445        rc = vdbePmaReadBlob(p, 1, &a);
86446        if( rc ) return rc;
86447        aVarint[(i++)&0xf] = a[0];
86448      }while( (a[0]&0x80)!=0 );
86449      sqlite3GetVarint(aVarint, pnOut);
86450    }
86451  }
86452
86453  return SQLITE_OK;
86454}
86455
86456/*
86457** Attempt to memory map file pFile. If successful, set *pp to point to the
86458** new mapping and return SQLITE_OK. If the mapping is not attempted
86459** (because the file is too large or the VFS layer is configured not to use
86460** mmap), return SQLITE_OK and set *pp to NULL.
86461**
86462** Or, if an error occurs, return an SQLite error code. The final value of
86463** *pp is undefined in this case.
86464*/
86465static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
86466  int rc = SQLITE_OK;
86467  if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
86468    sqlite3_file *pFd = pFile->pFd;
86469    if( pFd->pMethods->iVersion>=3 ){
86470      rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
86471      testcase( rc!=SQLITE_OK );
86472    }
86473  }
86474  return rc;
86475}
86476
86477/*
86478** Attach PmaReader pReadr to file pFile (if it is not already attached to
86479** that file) and seek it to offset iOff within the file.  Return SQLITE_OK
86480** if successful, or an SQLite error code if an error occurs.
86481*/
86482static int vdbePmaReaderSeek(
86483  SortSubtask *pTask,             /* Task context */
86484  PmaReader *pReadr,              /* Reader whose cursor is to be moved */
86485  SorterFile *pFile,              /* Sorter file to read from */
86486  i64 iOff                        /* Offset in pFile */
86487){
86488  int rc = SQLITE_OK;
86489
86490  assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
86491
86492  if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
86493  if( pReadr->aMap ){
86494    sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
86495    pReadr->aMap = 0;
86496  }
86497  pReadr->iReadOff = iOff;
86498  pReadr->iEof = pFile->iEof;
86499  pReadr->pFd = pFile->pFd;
86500
86501  rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
86502  if( rc==SQLITE_OK && pReadr->aMap==0 ){
86503    int pgsz = pTask->pSorter->pgsz;
86504    int iBuf = pReadr->iReadOff % pgsz;
86505    if( pReadr->aBuffer==0 ){
86506      pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
86507      if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
86508      pReadr->nBuffer = pgsz;
86509    }
86510    if( rc==SQLITE_OK && iBuf ){
86511      int nRead = pgsz - iBuf;
86512      if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
86513        nRead = (int)(pReadr->iEof - pReadr->iReadOff);
86514      }
86515      rc = sqlite3OsRead(
86516          pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
86517      );
86518      testcase( rc!=SQLITE_OK );
86519    }
86520  }
86521
86522  return rc;
86523}
86524
86525/*
86526** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
86527** no error occurs, or an SQLite error code if one does.
86528*/
86529static int vdbePmaReaderNext(PmaReader *pReadr){
86530  int rc = SQLITE_OK;             /* Return Code */
86531  u64 nRec = 0;                   /* Size of record in bytes */
86532
86533
86534  if( pReadr->iReadOff>=pReadr->iEof ){
86535    IncrMerger *pIncr = pReadr->pIncr;
86536    int bEof = 1;
86537    if( pIncr ){
86538      rc = vdbeIncrSwap(pIncr);
86539      if( rc==SQLITE_OK && pIncr->bEof==0 ){
86540        rc = vdbePmaReaderSeek(
86541            pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
86542        );
86543        bEof = 0;
86544      }
86545    }
86546
86547    if( bEof ){
86548      /* This is an EOF condition */
86549      vdbePmaReaderClear(pReadr);
86550      testcase( rc!=SQLITE_OK );
86551      return rc;
86552    }
86553  }
86554
86555  if( rc==SQLITE_OK ){
86556    rc = vdbePmaReadVarint(pReadr, &nRec);
86557  }
86558  if( rc==SQLITE_OK ){
86559    pReadr->nKey = (int)nRec;
86560    rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
86561    testcase( rc!=SQLITE_OK );
86562  }
86563
86564  return rc;
86565}
86566
86567/*
86568** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
86569** starting at offset iStart and ending at offset iEof-1. This function
86570** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
86571** PMA is empty).
86572**
86573** If the pnByte parameter is NULL, then it is assumed that the file
86574** contains a single PMA, and that that PMA omits the initial length varint.
86575*/
86576static int vdbePmaReaderInit(
86577  SortSubtask *pTask,             /* Task context */
86578  SorterFile *pFile,              /* Sorter file to read from */
86579  i64 iStart,                     /* Start offset in pFile */
86580  PmaReader *pReadr,              /* PmaReader to populate */
86581  i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
86582){
86583  int rc;
86584
86585  assert( pFile->iEof>iStart );
86586  assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
86587  assert( pReadr->aBuffer==0 );
86588  assert( pReadr->aMap==0 );
86589
86590  rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
86591  if( rc==SQLITE_OK ){
86592    u64 nByte = 0;                 /* Size of PMA in bytes */
86593    rc = vdbePmaReadVarint(pReadr, &nByte);
86594    pReadr->iEof = pReadr->iReadOff + nByte;
86595    *pnByte += nByte;
86596  }
86597
86598  if( rc==SQLITE_OK ){
86599    rc = vdbePmaReaderNext(pReadr);
86600  }
86601  return rc;
86602}
86603
86604/*
86605** A version of vdbeSorterCompare() that assumes that it has already been
86606** determined that the first field of key1 is equal to the first field of
86607** key2.
86608*/
86609static int vdbeSorterCompareTail(
86610  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
86611  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
86612  const void *pKey1, int nKey1,   /* Left side of comparison */
86613  const void *pKey2, int nKey2    /* Right side of comparison */
86614){
86615  UnpackedRecord *r2 = pTask->pUnpacked;
86616  if( *pbKey2Cached==0 ){
86617    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
86618    *pbKey2Cached = 1;
86619  }
86620  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
86621}
86622
86623/*
86624** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
86625** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
86626** used by the comparison. Return the result of the comparison.
86627**
86628** If IN/OUT parameter *pbKey2Cached is true when this function is called,
86629** it is assumed that (pTask->pUnpacked) contains the unpacked version
86630** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
86631** version of key2 and *pbKey2Cached set to true before returning.
86632**
86633** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
86634** to SQLITE_NOMEM.
86635*/
86636static int vdbeSorterCompare(
86637  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
86638  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
86639  const void *pKey1, int nKey1,   /* Left side of comparison */
86640  const void *pKey2, int nKey2    /* Right side of comparison */
86641){
86642  UnpackedRecord *r2 = pTask->pUnpacked;
86643  if( !*pbKey2Cached ){
86644    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
86645    *pbKey2Cached = 1;
86646  }
86647  return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
86648}
86649
86650/*
86651** A specially optimized version of vdbeSorterCompare() that assumes that
86652** the first field of each key is a TEXT value and that the collation
86653** sequence to compare them with is BINARY.
86654*/
86655static int vdbeSorterCompareText(
86656  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
86657  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
86658  const void *pKey1, int nKey1,   /* Left side of comparison */
86659  const void *pKey2, int nKey2    /* Right side of comparison */
86660){
86661  const u8 * const p1 = (const u8 * const)pKey1;
86662  const u8 * const p2 = (const u8 * const)pKey2;
86663  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
86664  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
86665
86666  int n1;
86667  int n2;
86668  int res;
86669
86670  getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
86671  getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
86672  res = memcmp(v1, v2, MIN(n1, n2));
86673  if( res==0 ){
86674    res = n1 - n2;
86675  }
86676
86677  if( res==0 ){
86678    if( pTask->pSorter->pKeyInfo->nField>1 ){
86679      res = vdbeSorterCompareTail(
86680          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
86681      );
86682    }
86683  }else{
86684    if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
86685      res = res * -1;
86686    }
86687  }
86688
86689  return res;
86690}
86691
86692/*
86693** A specially optimized version of vdbeSorterCompare() that assumes that
86694** the first field of each key is an INTEGER value.
86695*/
86696static int vdbeSorterCompareInt(
86697  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
86698  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
86699  const void *pKey1, int nKey1,   /* Left side of comparison */
86700  const void *pKey2, int nKey2    /* Right side of comparison */
86701){
86702  const u8 * const p1 = (const u8 * const)pKey1;
86703  const u8 * const p2 = (const u8 * const)pKey2;
86704  const int s1 = p1[1];                 /* Left hand serial type */
86705  const int s2 = p2[1];                 /* Right hand serial type */
86706  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
86707  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
86708  int res;                              /* Return value */
86709
86710  assert( (s1>0 && s1<7) || s1==8 || s1==9 );
86711  assert( (s2>0 && s2<7) || s2==8 || s2==9 );
86712
86713  if( s1>7 && s2>7 ){
86714    res = s1 - s2;
86715  }else{
86716    if( s1==s2 ){
86717      if( (*v1 ^ *v2) & 0x80 ){
86718        /* The two values have different signs */
86719        res = (*v1 & 0x80) ? -1 : +1;
86720      }else{
86721        /* The two values have the same sign. Compare using memcmp(). */
86722        static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
86723        int i;
86724        res = 0;
86725        for(i=0; i<aLen[s1]; i++){
86726          if( (res = v1[i] - v2[i]) ) break;
86727        }
86728      }
86729    }else{
86730      if( s2>7 ){
86731        res = +1;
86732      }else if( s1>7 ){
86733        res = -1;
86734      }else{
86735        res = s1 - s2;
86736      }
86737      assert( res!=0 );
86738
86739      if( res>0 ){
86740        if( *v1 & 0x80 ) res = -1;
86741      }else{
86742        if( *v2 & 0x80 ) res = +1;
86743      }
86744    }
86745  }
86746
86747  if( res==0 ){
86748    if( pTask->pSorter->pKeyInfo->nField>1 ){
86749      res = vdbeSorterCompareTail(
86750          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
86751      );
86752    }
86753  }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
86754    res = res * -1;
86755  }
86756
86757  return res;
86758}
86759
86760/*
86761** Initialize the temporary index cursor just opened as a sorter cursor.
86762**
86763** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
86764** to determine the number of fields that should be compared from the
86765** records being sorted. However, if the value passed as argument nField
86766** is non-zero and the sorter is able to guarantee a stable sort, nField
86767** is used instead. This is used when sorting records for a CREATE INDEX
86768** statement. In this case, keys are always delivered to the sorter in
86769** order of the primary key, which happens to be make up the final part
86770** of the records being sorted. So if the sort is stable, there is never
86771** any reason to compare PK fields and they can be ignored for a small
86772** performance boost.
86773**
86774** The sorter can guarantee a stable sort when running in single-threaded
86775** mode, but not in multi-threaded mode.
86776**
86777** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
86778*/
86779SQLITE_PRIVATE int sqlite3VdbeSorterInit(
86780  sqlite3 *db,                    /* Database connection (for malloc()) */
86781  int nField,                     /* Number of key fields in each record */
86782  VdbeCursor *pCsr                /* Cursor that holds the new sorter */
86783){
86784  int pgsz;                       /* Page size of main database */
86785  int i;                          /* Used to iterate through aTask[] */
86786  VdbeSorter *pSorter;            /* The new sorter */
86787  KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */
86788  int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */
86789  int sz;                         /* Size of pSorter in bytes */
86790  int rc = SQLITE_OK;
86791#if SQLITE_MAX_WORKER_THREADS==0
86792# define nWorker 0
86793#else
86794  int nWorker;
86795#endif
86796
86797  /* Initialize the upper limit on the number of worker threads */
86798#if SQLITE_MAX_WORKER_THREADS>0
86799  if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
86800    nWorker = 0;
86801  }else{
86802    nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
86803  }
86804#endif
86805
86806  /* Do not allow the total number of threads (main thread + all workers)
86807  ** to exceed the maximum merge count */
86808#if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
86809  if( nWorker>=SORTER_MAX_MERGE_COUNT ){
86810    nWorker = SORTER_MAX_MERGE_COUNT-1;
86811  }
86812#endif
86813
86814  assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
86815  assert( pCsr->eCurType==CURTYPE_SORTER );
86816  szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
86817  sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
86818
86819  pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
86820  pCsr->uc.pSorter = pSorter;
86821  if( pSorter==0 ){
86822    rc = SQLITE_NOMEM_BKPT;
86823  }else{
86824    pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
86825    memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
86826    pKeyInfo->db = 0;
86827    if( nField && nWorker==0 ){
86828      pKeyInfo->nXField += (pKeyInfo->nField - nField);
86829      pKeyInfo->nField = nField;
86830    }
86831    pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
86832    pSorter->nTask = nWorker + 1;
86833    pSorter->iPrev = (u8)(nWorker - 1);
86834    pSorter->bUseThreads = (pSorter->nTask>1);
86835    pSorter->db = db;
86836    for(i=0; i<pSorter->nTask; i++){
86837      SortSubtask *pTask = &pSorter->aTask[i];
86838      pTask->pSorter = pSorter;
86839    }
86840
86841    if( !sqlite3TempInMemory(db) ){
86842      i64 mxCache;                /* Cache size in bytes*/
86843      u32 szPma = sqlite3GlobalConfig.szPma;
86844      pSorter->mnPmaSize = szPma * pgsz;
86845
86846      mxCache = db->aDb[0].pSchema->cache_size;
86847      if( mxCache<0 ){
86848        /* A negative cache-size value C indicates that the cache is abs(C)
86849        ** KiB in size.  */
86850        mxCache = mxCache * -1024;
86851      }else{
86852        mxCache = mxCache * pgsz;
86853      }
86854      mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
86855      pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
86856
86857      /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
86858      ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
86859      ** large heap allocations.
86860      */
86861      if( sqlite3GlobalConfig.pScratch==0 ){
86862        assert( pSorter->iMemory==0 );
86863        pSorter->nMemory = pgsz;
86864        pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
86865        if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
86866      }
86867    }
86868
86869    if( (pKeyInfo->nField+pKeyInfo->nXField)<13
86870     && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
86871    ){
86872      pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
86873    }
86874  }
86875
86876  return rc;
86877}
86878#undef nWorker   /* Defined at the top of this function */
86879
86880/*
86881** Free the list of sorted records starting at pRecord.
86882*/
86883static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
86884  SorterRecord *p;
86885  SorterRecord *pNext;
86886  for(p=pRecord; p; p=pNext){
86887    pNext = p->u.pNext;
86888    sqlite3DbFree(db, p);
86889  }
86890}
86891
86892/*
86893** Free all resources owned by the object indicated by argument pTask. All
86894** fields of *pTask are zeroed before returning.
86895*/
86896static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
86897  sqlite3DbFree(db, pTask->pUnpacked);
86898#if SQLITE_MAX_WORKER_THREADS>0
86899  /* pTask->list.aMemory can only be non-zero if it was handed memory
86900  ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */
86901  if( pTask->list.aMemory ){
86902    sqlite3_free(pTask->list.aMemory);
86903  }else
86904#endif
86905  {
86906    assert( pTask->list.aMemory==0 );
86907    vdbeSorterRecordFree(0, pTask->list.pList);
86908  }
86909  if( pTask->file.pFd ){
86910    sqlite3OsCloseFree(pTask->file.pFd);
86911  }
86912  if( pTask->file2.pFd ){
86913    sqlite3OsCloseFree(pTask->file2.pFd);
86914  }
86915  memset(pTask, 0, sizeof(SortSubtask));
86916}
86917
86918#ifdef SQLITE_DEBUG_SORTER_THREADS
86919static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
86920  i64 t;
86921  int iTask = (pTask - pTask->pSorter->aTask);
86922  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
86923  fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
86924}
86925static void vdbeSorterRewindDebug(const char *zEvent){
86926  i64 t;
86927  sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
86928  fprintf(stderr, "%lld:X %s\n", t, zEvent);
86929}
86930static void vdbeSorterPopulateDebug(
86931  SortSubtask *pTask,
86932  const char *zEvent
86933){
86934  i64 t;
86935  int iTask = (pTask - pTask->pSorter->aTask);
86936  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
86937  fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
86938}
86939static void vdbeSorterBlockDebug(
86940  SortSubtask *pTask,
86941  int bBlocked,
86942  const char *zEvent
86943){
86944  if( bBlocked ){
86945    i64 t;
86946    sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
86947    fprintf(stderr, "%lld:main %s\n", t, zEvent);
86948  }
86949}
86950#else
86951# define vdbeSorterWorkDebug(x,y)
86952# define vdbeSorterRewindDebug(y)
86953# define vdbeSorterPopulateDebug(x,y)
86954# define vdbeSorterBlockDebug(x,y,z)
86955#endif
86956
86957#if SQLITE_MAX_WORKER_THREADS>0
86958/*
86959** Join thread pTask->thread.
86960*/
86961static int vdbeSorterJoinThread(SortSubtask *pTask){
86962  int rc = SQLITE_OK;
86963  if( pTask->pThread ){
86964#ifdef SQLITE_DEBUG_SORTER_THREADS
86965    int bDone = pTask->bDone;
86966#endif
86967    void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
86968    vdbeSorterBlockDebug(pTask, !bDone, "enter");
86969    (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
86970    vdbeSorterBlockDebug(pTask, !bDone, "exit");
86971    rc = SQLITE_PTR_TO_INT(pRet);
86972    assert( pTask->bDone==1 );
86973    pTask->bDone = 0;
86974    pTask->pThread = 0;
86975  }
86976  return rc;
86977}
86978
86979/*
86980** Launch a background thread to run xTask(pIn).
86981*/
86982static int vdbeSorterCreateThread(
86983  SortSubtask *pTask,             /* Thread will use this task object */
86984  void *(*xTask)(void*),          /* Routine to run in a separate thread */
86985  void *pIn                       /* Argument passed into xTask() */
86986){
86987  assert( pTask->pThread==0 && pTask->bDone==0 );
86988  return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
86989}
86990
86991/*
86992** Join all outstanding threads launched by SorterWrite() to create
86993** level-0 PMAs.
86994*/
86995static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
86996  int rc = rcin;
86997  int i;
86998
86999  /* This function is always called by the main user thread.
87000  **
87001  ** If this function is being called after SorterRewind() has been called,
87002  ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
87003  ** is currently attempt to join one of the other threads. To avoid a race
87004  ** condition where this thread also attempts to join the same object, join
87005  ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
87006  for(i=pSorter->nTask-1; i>=0; i--){
87007    SortSubtask *pTask = &pSorter->aTask[i];
87008    int rc2 = vdbeSorterJoinThread(pTask);
87009    if( rc==SQLITE_OK ) rc = rc2;
87010  }
87011  return rc;
87012}
87013#else
87014# define vdbeSorterJoinAll(x,rcin) (rcin)
87015# define vdbeSorterJoinThread(pTask) SQLITE_OK
87016#endif
87017
87018/*
87019** Allocate a new MergeEngine object capable of handling up to
87020** nReader PmaReader inputs.
87021**
87022** nReader is automatically rounded up to the next power of two.
87023** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
87024*/
87025static MergeEngine *vdbeMergeEngineNew(int nReader){
87026  int N = 2;                      /* Smallest power of two >= nReader */
87027  int nByte;                      /* Total bytes of space to allocate */
87028  MergeEngine *pNew;              /* Pointer to allocated object to return */
87029
87030  assert( nReader<=SORTER_MAX_MERGE_COUNT );
87031
87032  while( N<nReader ) N += N;
87033  nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
87034
87035  pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
87036  if( pNew ){
87037    pNew->nTree = N;
87038    pNew->pTask = 0;
87039    pNew->aReadr = (PmaReader*)&pNew[1];
87040    pNew->aTree = (int*)&pNew->aReadr[N];
87041  }
87042  return pNew;
87043}
87044
87045/*
87046** Free the MergeEngine object passed as the only argument.
87047*/
87048static void vdbeMergeEngineFree(MergeEngine *pMerger){
87049  int i;
87050  if( pMerger ){
87051    for(i=0; i<pMerger->nTree; i++){
87052      vdbePmaReaderClear(&pMerger->aReadr[i]);
87053    }
87054  }
87055  sqlite3_free(pMerger);
87056}
87057
87058/*
87059** Free all resources associated with the IncrMerger object indicated by
87060** the first argument.
87061*/
87062static void vdbeIncrFree(IncrMerger *pIncr){
87063  if( pIncr ){
87064#if SQLITE_MAX_WORKER_THREADS>0
87065    if( pIncr->bUseThread ){
87066      vdbeSorterJoinThread(pIncr->pTask);
87067      if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
87068      if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
87069    }
87070#endif
87071    vdbeMergeEngineFree(pIncr->pMerger);
87072    sqlite3_free(pIncr);
87073  }
87074}
87075
87076/*
87077** Reset a sorting cursor back to its original empty state.
87078*/
87079SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
87080  int i;
87081  (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
87082  assert( pSorter->bUseThreads || pSorter->pReader==0 );
87083#if SQLITE_MAX_WORKER_THREADS>0
87084  if( pSorter->pReader ){
87085    vdbePmaReaderClear(pSorter->pReader);
87086    sqlite3DbFree(db, pSorter->pReader);
87087    pSorter->pReader = 0;
87088  }
87089#endif
87090  vdbeMergeEngineFree(pSorter->pMerger);
87091  pSorter->pMerger = 0;
87092  for(i=0; i<pSorter->nTask; i++){
87093    SortSubtask *pTask = &pSorter->aTask[i];
87094    vdbeSortSubtaskCleanup(db, pTask);
87095    pTask->pSorter = pSorter;
87096  }
87097  if( pSorter->list.aMemory==0 ){
87098    vdbeSorterRecordFree(0, pSorter->list.pList);
87099  }
87100  pSorter->list.pList = 0;
87101  pSorter->list.szPMA = 0;
87102  pSorter->bUsePMA = 0;
87103  pSorter->iMemory = 0;
87104  pSorter->mxKeysize = 0;
87105  sqlite3DbFree(db, pSorter->pUnpacked);
87106  pSorter->pUnpacked = 0;
87107}
87108
87109/*
87110** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
87111*/
87112SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
87113  VdbeSorter *pSorter;
87114  assert( pCsr->eCurType==CURTYPE_SORTER );
87115  pSorter = pCsr->uc.pSorter;
87116  if( pSorter ){
87117    sqlite3VdbeSorterReset(db, pSorter);
87118    sqlite3_free(pSorter->list.aMemory);
87119    sqlite3DbFree(db, pSorter);
87120    pCsr->uc.pSorter = 0;
87121  }
87122}
87123
87124#if SQLITE_MAX_MMAP_SIZE>0
87125/*
87126** The first argument is a file-handle open on a temporary file. The file
87127** is guaranteed to be nByte bytes or smaller in size. This function
87128** attempts to extend the file to nByte bytes in size and to ensure that
87129** the VFS has memory mapped it.
87130**
87131** Whether or not the file does end up memory mapped of course depends on
87132** the specific VFS implementation.
87133*/
87134static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
87135  if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
87136    void *p = 0;
87137    int chunksize = 4*1024;
87138    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
87139    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
87140    sqlite3OsFetch(pFd, 0, (int)nByte, &p);
87141    sqlite3OsUnfetch(pFd, 0, p);
87142  }
87143}
87144#else
87145# define vdbeSorterExtendFile(x,y,z)
87146#endif
87147
87148/*
87149** Allocate space for a file-handle and open a temporary file. If successful,
87150** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
87151** Otherwise, set *ppFd to 0 and return an SQLite error code.
87152*/
87153static int vdbeSorterOpenTempFile(
87154  sqlite3 *db,                    /* Database handle doing sort */
87155  i64 nExtend,                    /* Attempt to extend file to this size */
87156  sqlite3_file **ppFd
87157){
87158  int rc;
87159  if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
87160  rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
87161      SQLITE_OPEN_TEMP_JOURNAL |
87162      SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
87163      SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc
87164  );
87165  if( rc==SQLITE_OK ){
87166    i64 max = SQLITE_MAX_MMAP_SIZE;
87167    sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
87168    if( nExtend>0 ){
87169      vdbeSorterExtendFile(db, *ppFd, nExtend);
87170    }
87171  }
87172  return rc;
87173}
87174
87175/*
87176** If it has not already been allocated, allocate the UnpackedRecord
87177** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
87178** if no allocation was required), or SQLITE_NOMEM otherwise.
87179*/
87180static int vdbeSortAllocUnpacked(SortSubtask *pTask){
87181  if( pTask->pUnpacked==0 ){
87182    pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
87183    if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
87184    pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
87185    pTask->pUnpacked->errCode = 0;
87186  }
87187  return SQLITE_OK;
87188}
87189
87190
87191/*
87192** Merge the two sorted lists p1 and p2 into a single list.
87193*/
87194static SorterRecord *vdbeSorterMerge(
87195  SortSubtask *pTask,             /* Calling thread context */
87196  SorterRecord *p1,               /* First list to merge */
87197  SorterRecord *p2                /* Second list to merge */
87198){
87199  SorterRecord *pFinal = 0;
87200  SorterRecord **pp = &pFinal;
87201  int bCached = 0;
87202
87203  assert( p1!=0 && p2!=0 );
87204  for(;;){
87205    int res;
87206    res = pTask->xCompare(
87207        pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
87208    );
87209
87210    if( res<=0 ){
87211      *pp = p1;
87212      pp = &p1->u.pNext;
87213      p1 = p1->u.pNext;
87214      if( p1==0 ){
87215        *pp = p2;
87216        break;
87217      }
87218    }else{
87219      *pp = p2;
87220      pp = &p2->u.pNext;
87221      p2 = p2->u.pNext;
87222      bCached = 0;
87223      if( p2==0 ){
87224        *pp = p1;
87225        break;
87226      }
87227    }
87228  }
87229  return pFinal;
87230}
87231
87232/*
87233** Return the SorterCompare function to compare values collected by the
87234** sorter object passed as the only argument.
87235*/
87236static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
87237  if( p->typeMask==SORTER_TYPE_INTEGER ){
87238    return vdbeSorterCompareInt;
87239  }else if( p->typeMask==SORTER_TYPE_TEXT ){
87240    return vdbeSorterCompareText;
87241  }
87242  return vdbeSorterCompare;
87243}
87244
87245/*
87246** Sort the linked list of records headed at pTask->pList. Return
87247** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
87248** an error occurs.
87249*/
87250static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
87251  int i;
87252  SorterRecord **aSlot;
87253  SorterRecord *p;
87254  int rc;
87255
87256  rc = vdbeSortAllocUnpacked(pTask);
87257  if( rc!=SQLITE_OK ) return rc;
87258
87259  p = pList->pList;
87260  pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
87261
87262  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
87263  if( !aSlot ){
87264    return SQLITE_NOMEM_BKPT;
87265  }
87266
87267  while( p ){
87268    SorterRecord *pNext;
87269    if( pList->aMemory ){
87270      if( (u8*)p==pList->aMemory ){
87271        pNext = 0;
87272      }else{
87273        assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
87274        pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
87275      }
87276    }else{
87277      pNext = p->u.pNext;
87278    }
87279
87280    p->u.pNext = 0;
87281    for(i=0; aSlot[i]; i++){
87282      p = vdbeSorterMerge(pTask, p, aSlot[i]);
87283      aSlot[i] = 0;
87284    }
87285    aSlot[i] = p;
87286    p = pNext;
87287  }
87288
87289  p = 0;
87290  for(i=0; i<64; i++){
87291    if( aSlot[i]==0 ) continue;
87292    p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
87293  }
87294  pList->pList = p;
87295
87296  sqlite3_free(aSlot);
87297  assert( pTask->pUnpacked->errCode==SQLITE_OK
87298       || pTask->pUnpacked->errCode==SQLITE_NOMEM
87299  );
87300  return pTask->pUnpacked->errCode;
87301}
87302
87303/*
87304** Initialize a PMA-writer object.
87305*/
87306static void vdbePmaWriterInit(
87307  sqlite3_file *pFd,              /* File handle to write to */
87308  PmaWriter *p,                   /* Object to populate */
87309  int nBuf,                       /* Buffer size */
87310  i64 iStart                      /* Offset of pFd to begin writing at */
87311){
87312  memset(p, 0, sizeof(PmaWriter));
87313  p->aBuffer = (u8*)sqlite3Malloc(nBuf);
87314  if( !p->aBuffer ){
87315    p->eFWErr = SQLITE_NOMEM_BKPT;
87316  }else{
87317    p->iBufEnd = p->iBufStart = (iStart % nBuf);
87318    p->iWriteOff = iStart - p->iBufStart;
87319    p->nBuffer = nBuf;
87320    p->pFd = pFd;
87321  }
87322}
87323
87324/*
87325** Write nData bytes of data to the PMA. Return SQLITE_OK
87326** if successful, or an SQLite error code if an error occurs.
87327*/
87328static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
87329  int nRem = nData;
87330  while( nRem>0 && p->eFWErr==0 ){
87331    int nCopy = nRem;
87332    if( nCopy>(p->nBuffer - p->iBufEnd) ){
87333      nCopy = p->nBuffer - p->iBufEnd;
87334    }
87335
87336    memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
87337    p->iBufEnd += nCopy;
87338    if( p->iBufEnd==p->nBuffer ){
87339      p->eFWErr = sqlite3OsWrite(p->pFd,
87340          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
87341          p->iWriteOff + p->iBufStart
87342      );
87343      p->iBufStart = p->iBufEnd = 0;
87344      p->iWriteOff += p->nBuffer;
87345    }
87346    assert( p->iBufEnd<p->nBuffer );
87347
87348    nRem -= nCopy;
87349  }
87350}
87351
87352/*
87353** Flush any buffered data to disk and clean up the PMA-writer object.
87354** The results of using the PMA-writer after this call are undefined.
87355** Return SQLITE_OK if flushing the buffered data succeeds or is not
87356** required. Otherwise, return an SQLite error code.
87357**
87358** Before returning, set *piEof to the offset immediately following the
87359** last byte written to the file.
87360*/
87361static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
87362  int rc;
87363  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
87364    p->eFWErr = sqlite3OsWrite(p->pFd,
87365        &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
87366        p->iWriteOff + p->iBufStart
87367    );
87368  }
87369  *piEof = (p->iWriteOff + p->iBufEnd);
87370  sqlite3_free(p->aBuffer);
87371  rc = p->eFWErr;
87372  memset(p, 0, sizeof(PmaWriter));
87373  return rc;
87374}
87375
87376/*
87377** Write value iVal encoded as a varint to the PMA. Return
87378** SQLITE_OK if successful, or an SQLite error code if an error occurs.
87379*/
87380static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
87381  int nByte;
87382  u8 aByte[10];
87383  nByte = sqlite3PutVarint(aByte, iVal);
87384  vdbePmaWriteBlob(p, aByte, nByte);
87385}
87386
87387/*
87388** Write the current contents of in-memory linked-list pList to a level-0
87389** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
87390** successful, or an SQLite error code otherwise.
87391**
87392** The format of a PMA is:
87393**
87394**     * A varint. This varint contains the total number of bytes of content
87395**       in the PMA (not including the varint itself).
87396**
87397**     * One or more records packed end-to-end in order of ascending keys.
87398**       Each record consists of a varint followed by a blob of data (the
87399**       key). The varint is the number of bytes in the blob of data.
87400*/
87401static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
87402  sqlite3 *db = pTask->pSorter->db;
87403  int rc = SQLITE_OK;             /* Return code */
87404  PmaWriter writer;               /* Object used to write to the file */
87405
87406#ifdef SQLITE_DEBUG
87407  /* Set iSz to the expected size of file pTask->file after writing the PMA.
87408  ** This is used by an assert() statement at the end of this function.  */
87409  i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
87410#endif
87411
87412  vdbeSorterWorkDebug(pTask, "enter");
87413  memset(&writer, 0, sizeof(PmaWriter));
87414  assert( pList->szPMA>0 );
87415
87416  /* If the first temporary PMA file has not been opened, open it now. */
87417  if( pTask->file.pFd==0 ){
87418    rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
87419    assert( rc!=SQLITE_OK || pTask->file.pFd );
87420    assert( pTask->file.iEof==0 );
87421    assert( pTask->nPMA==0 );
87422  }
87423
87424  /* Try to get the file to memory map */
87425  if( rc==SQLITE_OK ){
87426    vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
87427  }
87428
87429  /* Sort the list */
87430  if( rc==SQLITE_OK ){
87431    rc = vdbeSorterSort(pTask, pList);
87432  }
87433
87434  if( rc==SQLITE_OK ){
87435    SorterRecord *p;
87436    SorterRecord *pNext = 0;
87437
87438    vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
87439                      pTask->file.iEof);
87440    pTask->nPMA++;
87441    vdbePmaWriteVarint(&writer, pList->szPMA);
87442    for(p=pList->pList; p; p=pNext){
87443      pNext = p->u.pNext;
87444      vdbePmaWriteVarint(&writer, p->nVal);
87445      vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
87446      if( pList->aMemory==0 ) sqlite3_free(p);
87447    }
87448    pList->pList = p;
87449    rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
87450  }
87451
87452  vdbeSorterWorkDebug(pTask, "exit");
87453  assert( rc!=SQLITE_OK || pList->pList==0 );
87454  assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
87455  return rc;
87456}
87457
87458/*
87459** Advance the MergeEngine to its next entry.
87460** Set *pbEof to true there is no next entry because
87461** the MergeEngine has reached the end of all its inputs.
87462**
87463** Return SQLITE_OK if successful or an error code if an error occurs.
87464*/
87465static int vdbeMergeEngineStep(
87466  MergeEngine *pMerger,      /* The merge engine to advance to the next row */
87467  int *pbEof                 /* Set TRUE at EOF.  Set false for more content */
87468){
87469  int rc;
87470  int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
87471  SortSubtask *pTask = pMerger->pTask;
87472
87473  /* Advance the current PmaReader */
87474  rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
87475
87476  /* Update contents of aTree[] */
87477  if( rc==SQLITE_OK ){
87478    int i;                      /* Index of aTree[] to recalculate */
87479    PmaReader *pReadr1;         /* First PmaReader to compare */
87480    PmaReader *pReadr2;         /* Second PmaReader to compare */
87481    int bCached = 0;
87482
87483    /* Find the first two PmaReaders to compare. The one that was just
87484    ** advanced (iPrev) and the one next to it in the array.  */
87485    pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
87486    pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
87487
87488    for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
87489      /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
87490      int iRes;
87491      if( pReadr1->pFd==0 ){
87492        iRes = +1;
87493      }else if( pReadr2->pFd==0 ){
87494        iRes = -1;
87495      }else{
87496        iRes = pTask->xCompare(pTask, &bCached,
87497            pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
87498        );
87499      }
87500
87501      /* If pReadr1 contained the smaller value, set aTree[i] to its index.
87502      ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
87503      ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
87504      ** pKey2 to point to the record belonging to pReadr2.
87505      **
87506      ** Alternatively, if pReadr2 contains the smaller of the two values,
87507      ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
87508      ** was actually called above, then pTask->pUnpacked now contains
87509      ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
87510      ** vdbeSorterCompare() from decoding pReadr2 again.
87511      **
87512      ** If the two values were equal, then the value from the oldest
87513      ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
87514      ** is sorted from oldest to newest, so pReadr1 contains older values
87515      ** than pReadr2 iff (pReadr1<pReadr2).  */
87516      if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
87517        pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
87518        pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
87519        bCached = 0;
87520      }else{
87521        if( pReadr1->pFd ) bCached = 0;
87522        pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
87523        pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
87524      }
87525    }
87526    *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
87527  }
87528
87529  return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
87530}
87531
87532#if SQLITE_MAX_WORKER_THREADS>0
87533/*
87534** The main routine for background threads that write level-0 PMAs.
87535*/
87536static void *vdbeSorterFlushThread(void *pCtx){
87537  SortSubtask *pTask = (SortSubtask*)pCtx;
87538  int rc;                         /* Return code */
87539  assert( pTask->bDone==0 );
87540  rc = vdbeSorterListToPMA(pTask, &pTask->list);
87541  pTask->bDone = 1;
87542  return SQLITE_INT_TO_PTR(rc);
87543}
87544#endif /* SQLITE_MAX_WORKER_THREADS>0 */
87545
87546/*
87547** Flush the current contents of VdbeSorter.list to a new PMA, possibly
87548** using a background thread.
87549*/
87550static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
87551#if SQLITE_MAX_WORKER_THREADS==0
87552  pSorter->bUsePMA = 1;
87553  return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
87554#else
87555  int rc = SQLITE_OK;
87556  int i;
87557  SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
87558  int nWorker = (pSorter->nTask-1);
87559
87560  /* Set the flag to indicate that at least one PMA has been written.
87561  ** Or will be, anyhow.  */
87562  pSorter->bUsePMA = 1;
87563
87564  /* Select a sub-task to sort and flush the current list of in-memory
87565  ** records to disk. If the sorter is running in multi-threaded mode,
87566  ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
87567  ** the background thread from a sub-tasks previous turn is still running,
87568  ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
87569  ** fall back to using the final sub-task. The first (pSorter->nTask-1)
87570  ** sub-tasks are prefered as they use background threads - the final
87571  ** sub-task uses the main thread. */
87572  for(i=0; i<nWorker; i++){
87573    int iTest = (pSorter->iPrev + i + 1) % nWorker;
87574    pTask = &pSorter->aTask[iTest];
87575    if( pTask->bDone ){
87576      rc = vdbeSorterJoinThread(pTask);
87577    }
87578    if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
87579  }
87580
87581  if( rc==SQLITE_OK ){
87582    if( i==nWorker ){
87583      /* Use the foreground thread for this operation */
87584      rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
87585    }else{
87586      /* Launch a background thread for this operation */
87587      u8 *aMem = pTask->list.aMemory;
87588      void *pCtx = (void*)pTask;
87589
87590      assert( pTask->pThread==0 && pTask->bDone==0 );
87591      assert( pTask->list.pList==0 );
87592      assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
87593
87594      pSorter->iPrev = (u8)(pTask - pSorter->aTask);
87595      pTask->list = pSorter->list;
87596      pSorter->list.pList = 0;
87597      pSorter->list.szPMA = 0;
87598      if( aMem ){
87599        pSorter->list.aMemory = aMem;
87600        pSorter->nMemory = sqlite3MallocSize(aMem);
87601      }else if( pSorter->list.aMemory ){
87602        pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
87603        if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
87604      }
87605
87606      rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
87607    }
87608  }
87609
87610  return rc;
87611#endif /* SQLITE_MAX_WORKER_THREADS!=0 */
87612}
87613
87614/*
87615** Add a record to the sorter.
87616*/
87617SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
87618  const VdbeCursor *pCsr,         /* Sorter cursor */
87619  Mem *pVal                       /* Memory cell containing record */
87620){
87621  VdbeSorter *pSorter;
87622  int rc = SQLITE_OK;             /* Return Code */
87623  SorterRecord *pNew;             /* New list element */
87624  int bFlush;                     /* True to flush contents of memory to PMA */
87625  int nReq;                       /* Bytes of memory required */
87626  int nPMA;                       /* Bytes of PMA space required */
87627  int t;                          /* serial type of first record field */
87628
87629  assert( pCsr->eCurType==CURTYPE_SORTER );
87630  pSorter = pCsr->uc.pSorter;
87631  getVarint32((const u8*)&pVal->z[1], t);
87632  if( t>0 && t<10 && t!=7 ){
87633    pSorter->typeMask &= SORTER_TYPE_INTEGER;
87634  }else if( t>10 && (t & 0x01) ){
87635    pSorter->typeMask &= SORTER_TYPE_TEXT;
87636  }else{
87637    pSorter->typeMask = 0;
87638  }
87639
87640  assert( pSorter );
87641
87642  /* Figure out whether or not the current contents of memory should be
87643  ** flushed to a PMA before continuing. If so, do so.
87644  **
87645  ** If using the single large allocation mode (pSorter->aMemory!=0), then
87646  ** flush the contents of memory to a new PMA if (a) at least one value is
87647  ** already in memory and (b) the new value will not fit in memory.
87648  **
87649  ** Or, if using separate allocations for each record, flush the contents
87650  ** of memory to a PMA if either of the following are true:
87651  **
87652  **   * The total memory allocated for the in-memory list is greater
87653  **     than (page-size * cache-size), or
87654  **
87655  **   * The total memory allocated for the in-memory list is greater
87656  **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
87657  */
87658  nReq = pVal->n + sizeof(SorterRecord);
87659  nPMA = pVal->n + sqlite3VarintLen(pVal->n);
87660  if( pSorter->mxPmaSize ){
87661    if( pSorter->list.aMemory ){
87662      bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
87663    }else{
87664      bFlush = (
87665          (pSorter->list.szPMA > pSorter->mxPmaSize)
87666       || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
87667      );
87668    }
87669    if( bFlush ){
87670      rc = vdbeSorterFlushPMA(pSorter);
87671      pSorter->list.szPMA = 0;
87672      pSorter->iMemory = 0;
87673      assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
87674    }
87675  }
87676
87677  pSorter->list.szPMA += nPMA;
87678  if( nPMA>pSorter->mxKeysize ){
87679    pSorter->mxKeysize = nPMA;
87680  }
87681
87682  if( pSorter->list.aMemory ){
87683    int nMin = pSorter->iMemory + nReq;
87684
87685    if( nMin>pSorter->nMemory ){
87686      u8 *aNew;
87687      int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
87688      int nNew = pSorter->nMemory * 2;
87689      while( nNew < nMin ) nNew = nNew*2;
87690      if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
87691      if( nNew < nMin ) nNew = nMin;
87692
87693      aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
87694      if( !aNew ) return SQLITE_NOMEM_BKPT;
87695      pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
87696      pSorter->list.aMemory = aNew;
87697      pSorter->nMemory = nNew;
87698    }
87699
87700    pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
87701    pSorter->iMemory += ROUND8(nReq);
87702    if( pSorter->list.pList ){
87703      pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
87704    }
87705  }else{
87706    pNew = (SorterRecord *)sqlite3Malloc(nReq);
87707    if( pNew==0 ){
87708      return SQLITE_NOMEM_BKPT;
87709    }
87710    pNew->u.pNext = pSorter->list.pList;
87711  }
87712
87713  memcpy(SRVAL(pNew), pVal->z, pVal->n);
87714  pNew->nVal = pVal->n;
87715  pSorter->list.pList = pNew;
87716
87717  return rc;
87718}
87719
87720/*
87721** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
87722** of the data stored in aFile[1] is the same as that used by regular PMAs,
87723** except that the number-of-bytes varint is omitted from the start.
87724*/
87725static int vdbeIncrPopulate(IncrMerger *pIncr){
87726  int rc = SQLITE_OK;
87727  int rc2;
87728  i64 iStart = pIncr->iStartOff;
87729  SorterFile *pOut = &pIncr->aFile[1];
87730  SortSubtask *pTask = pIncr->pTask;
87731  MergeEngine *pMerger = pIncr->pMerger;
87732  PmaWriter writer;
87733  assert( pIncr->bEof==0 );
87734
87735  vdbeSorterPopulateDebug(pTask, "enter");
87736
87737  vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
87738  while( rc==SQLITE_OK ){
87739    int dummy;
87740    PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
87741    int nKey = pReader->nKey;
87742    i64 iEof = writer.iWriteOff + writer.iBufEnd;
87743
87744    /* Check if the output file is full or if the input has been exhausted.
87745    ** In either case exit the loop. */
87746    if( pReader->pFd==0 ) break;
87747    if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
87748
87749    /* Write the next key to the output. */
87750    vdbePmaWriteVarint(&writer, nKey);
87751    vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
87752    assert( pIncr->pMerger->pTask==pTask );
87753    rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
87754  }
87755
87756  rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
87757  if( rc==SQLITE_OK ) rc = rc2;
87758  vdbeSorterPopulateDebug(pTask, "exit");
87759  return rc;
87760}
87761
87762#if SQLITE_MAX_WORKER_THREADS>0
87763/*
87764** The main routine for background threads that populate aFile[1] of
87765** multi-threaded IncrMerger objects.
87766*/
87767static void *vdbeIncrPopulateThread(void *pCtx){
87768  IncrMerger *pIncr = (IncrMerger*)pCtx;
87769  void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
87770  pIncr->pTask->bDone = 1;
87771  return pRet;
87772}
87773
87774/*
87775** Launch a background thread to populate aFile[1] of pIncr.
87776*/
87777static int vdbeIncrBgPopulate(IncrMerger *pIncr){
87778  void *p = (void*)pIncr;
87779  assert( pIncr->bUseThread );
87780  return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
87781}
87782#endif
87783
87784/*
87785** This function is called when the PmaReader corresponding to pIncr has
87786** finished reading the contents of aFile[0]. Its purpose is to "refill"
87787** aFile[0] such that the PmaReader should start rereading it from the
87788** beginning.
87789**
87790** For single-threaded objects, this is accomplished by literally reading
87791** keys from pIncr->pMerger and repopulating aFile[0].
87792**
87793** For multi-threaded objects, all that is required is to wait until the
87794** background thread is finished (if it is not already) and then swap
87795** aFile[0] and aFile[1] in place. If the contents of pMerger have not
87796** been exhausted, this function also launches a new background thread
87797** to populate the new aFile[1].
87798**
87799** SQLITE_OK is returned on success, or an SQLite error code otherwise.
87800*/
87801static int vdbeIncrSwap(IncrMerger *pIncr){
87802  int rc = SQLITE_OK;
87803
87804#if SQLITE_MAX_WORKER_THREADS>0
87805  if( pIncr->bUseThread ){
87806    rc = vdbeSorterJoinThread(pIncr->pTask);
87807
87808    if( rc==SQLITE_OK ){
87809      SorterFile f0 = pIncr->aFile[0];
87810      pIncr->aFile[0] = pIncr->aFile[1];
87811      pIncr->aFile[1] = f0;
87812    }
87813
87814    if( rc==SQLITE_OK ){
87815      if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
87816        pIncr->bEof = 1;
87817      }else{
87818        rc = vdbeIncrBgPopulate(pIncr);
87819      }
87820    }
87821  }else
87822#endif
87823  {
87824    rc = vdbeIncrPopulate(pIncr);
87825    pIncr->aFile[0] = pIncr->aFile[1];
87826    if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
87827      pIncr->bEof = 1;
87828    }
87829  }
87830
87831  return rc;
87832}
87833
87834/*
87835** Allocate and return a new IncrMerger object to read data from pMerger.
87836**
87837** If an OOM condition is encountered, return NULL. In this case free the
87838** pMerger argument before returning.
87839*/
87840static int vdbeIncrMergerNew(
87841  SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */
87842  MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */
87843  IncrMerger **ppOut      /* Write the new IncrMerger here */
87844){
87845  int rc = SQLITE_OK;
87846  IncrMerger *pIncr = *ppOut = (IncrMerger*)
87847       (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
87848  if( pIncr ){
87849    pIncr->pMerger = pMerger;
87850    pIncr->pTask = pTask;
87851    pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
87852    pTask->file2.iEof += pIncr->mxSz;
87853  }else{
87854    vdbeMergeEngineFree(pMerger);
87855    rc = SQLITE_NOMEM_BKPT;
87856  }
87857  return rc;
87858}
87859
87860#if SQLITE_MAX_WORKER_THREADS>0
87861/*
87862** Set the "use-threads" flag on object pIncr.
87863*/
87864static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
87865  pIncr->bUseThread = 1;
87866  pIncr->pTask->file2.iEof -= pIncr->mxSz;
87867}
87868#endif /* SQLITE_MAX_WORKER_THREADS>0 */
87869
87870
87871
87872/*
87873** Recompute pMerger->aTree[iOut] by comparing the next keys on the
87874** two PmaReaders that feed that entry.  Neither of the PmaReaders
87875** are advanced.  This routine merely does the comparison.
87876*/
87877static void vdbeMergeEngineCompare(
87878  MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */
87879  int iOut               /* Store the result in pMerger->aTree[iOut] */
87880){
87881  int i1;
87882  int i2;
87883  int iRes;
87884  PmaReader *p1;
87885  PmaReader *p2;
87886
87887  assert( iOut<pMerger->nTree && iOut>0 );
87888
87889  if( iOut>=(pMerger->nTree/2) ){
87890    i1 = (iOut - pMerger->nTree/2) * 2;
87891    i2 = i1 + 1;
87892  }else{
87893    i1 = pMerger->aTree[iOut*2];
87894    i2 = pMerger->aTree[iOut*2+1];
87895  }
87896
87897  p1 = &pMerger->aReadr[i1];
87898  p2 = &pMerger->aReadr[i2];
87899
87900  if( p1->pFd==0 ){
87901    iRes = i2;
87902  }else if( p2->pFd==0 ){
87903    iRes = i1;
87904  }else{
87905    SortSubtask *pTask = pMerger->pTask;
87906    int bCached = 0;
87907    int res;
87908    assert( pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */
87909    res = pTask->xCompare(
87910        pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
87911    );
87912    if( res<=0 ){
87913      iRes = i1;
87914    }else{
87915      iRes = i2;
87916    }
87917  }
87918
87919  pMerger->aTree[iOut] = iRes;
87920}
87921
87922/*
87923** Allowed values for the eMode parameter to vdbeMergeEngineInit()
87924** and vdbePmaReaderIncrMergeInit().
87925**
87926** Only INCRINIT_NORMAL is valid in single-threaded builds (when
87927** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used
87928** when there exists one or more separate worker threads.
87929*/
87930#define INCRINIT_NORMAL 0
87931#define INCRINIT_TASK   1
87932#define INCRINIT_ROOT   2
87933
87934/*
87935** Forward reference required as the vdbeIncrMergeInit() and
87936** vdbePmaReaderIncrInit() routines are called mutually recursively when
87937** building a merge tree.
87938*/
87939static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
87940
87941/*
87942** Initialize the MergeEngine object passed as the second argument. Once this
87943** function returns, the first key of merged data may be read from the
87944** MergeEngine object in the usual fashion.
87945**
87946** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
87947** objects attached to the PmaReader objects that the merger reads from have
87948** already been populated, but that they have not yet populated aFile[0] and
87949** set the PmaReader objects up to read from it. In this case all that is
87950** required is to call vdbePmaReaderNext() on each PmaReader to point it at
87951** its first key.
87952**
87953** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
87954** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
87955** to pMerger.
87956**
87957** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
87958*/
87959static int vdbeMergeEngineInit(
87960  SortSubtask *pTask,             /* Thread that will run pMerger */
87961  MergeEngine *pMerger,           /* MergeEngine to initialize */
87962  int eMode                       /* One of the INCRINIT_XXX constants */
87963){
87964  int rc = SQLITE_OK;             /* Return code */
87965  int i;                          /* For looping over PmaReader objects */
87966  int nTree = pMerger->nTree;
87967
87968  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
87969  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
87970
87971  /* Verify that the MergeEngine is assigned to a single thread */
87972  assert( pMerger->pTask==0 );
87973  pMerger->pTask = pTask;
87974
87975  for(i=0; i<nTree; i++){
87976    if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
87977      /* PmaReaders should be normally initialized in order, as if they are
87978      ** reading from the same temp file this makes for more linear file IO.
87979      ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
87980      ** in use it will block the vdbePmaReaderNext() call while it uses
87981      ** the main thread to fill its buffer. So calling PmaReaderNext()
87982      ** on this PmaReader before any of the multi-threaded PmaReaders takes
87983      ** better advantage of multi-processor hardware. */
87984      rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
87985    }else{
87986      rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
87987    }
87988    if( rc!=SQLITE_OK ) return rc;
87989  }
87990
87991  for(i=pMerger->nTree-1; i>0; i--){
87992    vdbeMergeEngineCompare(pMerger, i);
87993  }
87994  return pTask->pUnpacked->errCode;
87995}
87996
87997/*
87998** The PmaReader passed as the first argument is guaranteed to be an
87999** incremental-reader (pReadr->pIncr!=0). This function serves to open
88000** and/or initialize the temp file related fields of the IncrMerge
88001** object at (pReadr->pIncr).
88002**
88003** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
88004** in the sub-tree headed by pReadr are also initialized. Data is then
88005** loaded into the buffers belonging to pReadr and it is set to point to
88006** the first key in its range.
88007**
88008** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
88009** to be a multi-threaded PmaReader and this function is being called in a
88010** background thread. In this case all PmaReaders in the sub-tree are
88011** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
88012** pReadr is populated. However, pReadr itself is not set up to point
88013** to its first key. A call to vdbePmaReaderNext() is still required to do
88014** that.
88015**
88016** The reason this function does not call vdbePmaReaderNext() immediately
88017** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
88018** to block on thread (pTask->thread) before accessing aFile[1]. But, since
88019** this entire function is being run by thread (pTask->thread), that will
88020** lead to the current background thread attempting to join itself.
88021**
88022** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
88023** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
88024** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
88025** In this case vdbePmaReaderNext() is called on all child PmaReaders and
88026** the current PmaReader set to point to the first key in its range.
88027**
88028** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
88029*/
88030static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
88031  int rc = SQLITE_OK;
88032  IncrMerger *pIncr = pReadr->pIncr;
88033  SortSubtask *pTask = pIncr->pTask;
88034  sqlite3 *db = pTask->pSorter->db;
88035
88036  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
88037  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
88038
88039  rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
88040
88041  /* Set up the required files for pIncr. A multi-theaded IncrMerge object
88042  ** requires two temp files to itself, whereas a single-threaded object
88043  ** only requires a region of pTask->file2. */
88044  if( rc==SQLITE_OK ){
88045    int mxSz = pIncr->mxSz;
88046#if SQLITE_MAX_WORKER_THREADS>0
88047    if( pIncr->bUseThread ){
88048      rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
88049      if( rc==SQLITE_OK ){
88050        rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
88051      }
88052    }else
88053#endif
88054    /*if( !pIncr->bUseThread )*/{
88055      if( pTask->file2.pFd==0 ){
88056        assert( pTask->file2.iEof>0 );
88057        rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
88058        pTask->file2.iEof = 0;
88059      }
88060      if( rc==SQLITE_OK ){
88061        pIncr->aFile[1].pFd = pTask->file2.pFd;
88062        pIncr->iStartOff = pTask->file2.iEof;
88063        pTask->file2.iEof += mxSz;
88064      }
88065    }
88066  }
88067
88068#if SQLITE_MAX_WORKER_THREADS>0
88069  if( rc==SQLITE_OK && pIncr->bUseThread ){
88070    /* Use the current thread to populate aFile[1], even though this
88071    ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
88072    ** then this function is already running in background thread
88073    ** pIncr->pTask->thread.
88074    **
88075    ** If this is the INCRINIT_ROOT object, then it is running in the
88076    ** main VDBE thread. But that is Ok, as that thread cannot return
88077    ** control to the VDBE or proceed with anything useful until the
88078    ** first results are ready from this merger object anyway.
88079    */
88080    assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
88081    rc = vdbeIncrPopulate(pIncr);
88082  }
88083#endif
88084
88085  if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
88086    rc = vdbePmaReaderNext(pReadr);
88087  }
88088
88089  return rc;
88090}
88091
88092#if SQLITE_MAX_WORKER_THREADS>0
88093/*
88094** The main routine for vdbePmaReaderIncrMergeInit() operations run in
88095** background threads.
88096*/
88097static void *vdbePmaReaderBgIncrInit(void *pCtx){
88098  PmaReader *pReader = (PmaReader*)pCtx;
88099  void *pRet = SQLITE_INT_TO_PTR(
88100                  vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
88101               );
88102  pReader->pIncr->pTask->bDone = 1;
88103  return pRet;
88104}
88105#endif
88106
88107/*
88108** If the PmaReader passed as the first argument is not an incremental-reader
88109** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
88110** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
88111** this routine to initialize the incremental merge.
88112**
88113** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
88114** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
88115** Or, if the IncrMerger is single threaded, the same function is called
88116** using the current thread.
88117*/
88118static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
88119  IncrMerger *pIncr = pReadr->pIncr;   /* Incremental merger */
88120  int rc = SQLITE_OK;                  /* Return code */
88121  if( pIncr ){
88122#if SQLITE_MAX_WORKER_THREADS>0
88123    assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
88124    if( pIncr->bUseThread ){
88125      void *pCtx = (void*)pReadr;
88126      rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
88127    }else
88128#endif
88129    {
88130      rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
88131    }
88132  }
88133  return rc;
88134}
88135
88136/*
88137** Allocate a new MergeEngine object to merge the contents of nPMA level-0
88138** PMAs from pTask->file. If no error occurs, set *ppOut to point to
88139** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
88140** to NULL and return an SQLite error code.
88141**
88142** When this function is called, *piOffset is set to the offset of the
88143** first PMA to read from pTask->file. Assuming no error occurs, it is
88144** set to the offset immediately following the last byte of the last
88145** PMA before returning. If an error does occur, then the final value of
88146** *piOffset is undefined.
88147*/
88148static int vdbeMergeEngineLevel0(
88149  SortSubtask *pTask,             /* Sorter task to read from */
88150  int nPMA,                       /* Number of PMAs to read */
88151  i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */
88152  MergeEngine **ppOut             /* OUT: New merge-engine */
88153){
88154  MergeEngine *pNew;              /* Merge engine to return */
88155  i64 iOff = *piOffset;
88156  int i;
88157  int rc = SQLITE_OK;
88158
88159  *ppOut = pNew = vdbeMergeEngineNew(nPMA);
88160  if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
88161
88162  for(i=0; i<nPMA && rc==SQLITE_OK; i++){
88163    i64 nDummy = 0;
88164    PmaReader *pReadr = &pNew->aReadr[i];
88165    rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
88166    iOff = pReadr->iEof;
88167  }
88168
88169  if( rc!=SQLITE_OK ){
88170    vdbeMergeEngineFree(pNew);
88171    *ppOut = 0;
88172  }
88173  *piOffset = iOff;
88174  return rc;
88175}
88176
88177/*
88178** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
88179** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
88180**
88181** i.e.
88182**
88183**   nPMA<=16    -> TreeDepth() == 0
88184**   nPMA<=256   -> TreeDepth() == 1
88185**   nPMA<=65536 -> TreeDepth() == 2
88186*/
88187static int vdbeSorterTreeDepth(int nPMA){
88188  int nDepth = 0;
88189  i64 nDiv = SORTER_MAX_MERGE_COUNT;
88190  while( nDiv < (i64)nPMA ){
88191    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
88192    nDepth++;
88193  }
88194  return nDepth;
88195}
88196
88197/*
88198** pRoot is the root of an incremental merge-tree with depth nDepth (according
88199** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
88200** tree, counting from zero. This function adds pLeaf to the tree.
88201**
88202** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
88203** code is returned and pLeaf is freed.
88204*/
88205static int vdbeSorterAddToTree(
88206  SortSubtask *pTask,             /* Task context */
88207  int nDepth,                     /* Depth of tree according to TreeDepth() */
88208  int iSeq,                       /* Sequence number of leaf within tree */
88209  MergeEngine *pRoot,             /* Root of tree */
88210  MergeEngine *pLeaf              /* Leaf to add to tree */
88211){
88212  int rc = SQLITE_OK;
88213  int nDiv = 1;
88214  int i;
88215  MergeEngine *p = pRoot;
88216  IncrMerger *pIncr;
88217
88218  rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
88219
88220  for(i=1; i<nDepth; i++){
88221    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
88222  }
88223
88224  for(i=1; i<nDepth && rc==SQLITE_OK; i++){
88225    int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
88226    PmaReader *pReadr = &p->aReadr[iIter];
88227
88228    if( pReadr->pIncr==0 ){
88229      MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
88230      if( pNew==0 ){
88231        rc = SQLITE_NOMEM_BKPT;
88232      }else{
88233        rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
88234      }
88235    }
88236    if( rc==SQLITE_OK ){
88237      p = pReadr->pIncr->pMerger;
88238      nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
88239    }
88240  }
88241
88242  if( rc==SQLITE_OK ){
88243    p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
88244  }else{
88245    vdbeIncrFree(pIncr);
88246  }
88247  return rc;
88248}
88249
88250/*
88251** This function is called as part of a SorterRewind() operation on a sorter
88252** that has already written two or more level-0 PMAs to one or more temp
88253** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
88254** can be used to incrementally merge all PMAs on disk.
88255**
88256** If successful, SQLITE_OK is returned and *ppOut set to point to the
88257** MergeEngine object at the root of the tree before returning. Or, if an
88258** error occurs, an SQLite error code is returned and the final value
88259** of *ppOut is undefined.
88260*/
88261static int vdbeSorterMergeTreeBuild(
88262  VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */
88263  MergeEngine **ppOut        /* Write the MergeEngine here */
88264){
88265  MergeEngine *pMain = 0;
88266  int rc = SQLITE_OK;
88267  int iTask;
88268
88269#if SQLITE_MAX_WORKER_THREADS>0
88270  /* If the sorter uses more than one task, then create the top-level
88271  ** MergeEngine here. This MergeEngine will read data from exactly
88272  ** one PmaReader per sub-task.  */
88273  assert( pSorter->bUseThreads || pSorter->nTask==1 );
88274  if( pSorter->nTask>1 ){
88275    pMain = vdbeMergeEngineNew(pSorter->nTask);
88276    if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
88277  }
88278#endif
88279
88280  for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
88281    SortSubtask *pTask = &pSorter->aTask[iTask];
88282    assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
88283    if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
88284      MergeEngine *pRoot = 0;     /* Root node of tree for this task */
88285      int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
88286      i64 iReadOff = 0;
88287
88288      if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
88289        rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
88290      }else{
88291        int i;
88292        int iSeq = 0;
88293        pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
88294        if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
88295        for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
88296          MergeEngine *pMerger = 0; /* New level-0 PMA merger */
88297          int nReader;              /* Number of level-0 PMAs to merge */
88298
88299          nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
88300          rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
88301          if( rc==SQLITE_OK ){
88302            rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
88303          }
88304        }
88305      }
88306
88307      if( rc==SQLITE_OK ){
88308#if SQLITE_MAX_WORKER_THREADS>0
88309        if( pMain!=0 ){
88310          rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
88311        }else
88312#endif
88313        {
88314          assert( pMain==0 );
88315          pMain = pRoot;
88316        }
88317      }else{
88318        vdbeMergeEngineFree(pRoot);
88319      }
88320    }
88321  }
88322
88323  if( rc!=SQLITE_OK ){
88324    vdbeMergeEngineFree(pMain);
88325    pMain = 0;
88326  }
88327  *ppOut = pMain;
88328  return rc;
88329}
88330
88331/*
88332** This function is called as part of an sqlite3VdbeSorterRewind() operation
88333** on a sorter that has written two or more PMAs to temporary files. It sets
88334** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
88335** (for multi-threaded sorters) so that it can be used to iterate through
88336** all records stored in the sorter.
88337**
88338** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
88339*/
88340static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
88341  int rc;                         /* Return code */
88342  SortSubtask *pTask0 = &pSorter->aTask[0];
88343  MergeEngine *pMain = 0;
88344#if SQLITE_MAX_WORKER_THREADS
88345  sqlite3 *db = pTask0->pSorter->db;
88346  int i;
88347  SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
88348  for(i=0; i<pSorter->nTask; i++){
88349    pSorter->aTask[i].xCompare = xCompare;
88350  }
88351#endif
88352
88353  rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
88354  if( rc==SQLITE_OK ){
88355#if SQLITE_MAX_WORKER_THREADS
88356    assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
88357    if( pSorter->bUseThreads ){
88358      int iTask;
88359      PmaReader *pReadr = 0;
88360      SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
88361      rc = vdbeSortAllocUnpacked(pLast);
88362      if( rc==SQLITE_OK ){
88363        pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
88364        pSorter->pReader = pReadr;
88365        if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
88366      }
88367      if( rc==SQLITE_OK ){
88368        rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
88369        if( rc==SQLITE_OK ){
88370          vdbeIncrMergerSetThreads(pReadr->pIncr);
88371          for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
88372            IncrMerger *pIncr;
88373            if( (pIncr = pMain->aReadr[iTask].pIncr) ){
88374              vdbeIncrMergerSetThreads(pIncr);
88375              assert( pIncr->pTask!=pLast );
88376            }
88377          }
88378          for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
88379            /* Check that:
88380            **
88381            **   a) The incremental merge object is configured to use the
88382            **      right task, and
88383            **   b) If it is using task (nTask-1), it is configured to run
88384            **      in single-threaded mode. This is important, as the
88385            **      root merge (INCRINIT_ROOT) will be using the same task
88386            **      object.
88387            */
88388            PmaReader *p = &pMain->aReadr[iTask];
88389            assert( p->pIncr==0 || (
88390                (p->pIncr->pTask==&pSorter->aTask[iTask])             /* a */
88391             && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0)  /* b */
88392            ));
88393            rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
88394          }
88395        }
88396        pMain = 0;
88397      }
88398      if( rc==SQLITE_OK ){
88399        rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
88400      }
88401    }else
88402#endif
88403    {
88404      rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
88405      pSorter->pMerger = pMain;
88406      pMain = 0;
88407    }
88408  }
88409
88410  if( rc!=SQLITE_OK ){
88411    vdbeMergeEngineFree(pMain);
88412  }
88413  return rc;
88414}
88415
88416
88417/*
88418** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
88419** this function is called to prepare for iterating through the records
88420** in sorted order.
88421*/
88422SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
88423  VdbeSorter *pSorter;
88424  int rc = SQLITE_OK;             /* Return code */
88425
88426  assert( pCsr->eCurType==CURTYPE_SORTER );
88427  pSorter = pCsr->uc.pSorter;
88428  assert( pSorter );
88429
88430  /* If no data has been written to disk, then do not do so now. Instead,
88431  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
88432  ** from the in-memory list.  */
88433  if( pSorter->bUsePMA==0 ){
88434    if( pSorter->list.pList ){
88435      *pbEof = 0;
88436      rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
88437    }else{
88438      *pbEof = 1;
88439    }
88440    return rc;
88441  }
88442
88443  /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
88444  ** function flushes the contents of memory to disk, it immediately always
88445  ** creates a new list consisting of a single key immediately afterwards.
88446  ** So the list is never empty at this point.  */
88447  assert( pSorter->list.pList );
88448  rc = vdbeSorterFlushPMA(pSorter);
88449
88450  /* Join all threads */
88451  rc = vdbeSorterJoinAll(pSorter, rc);
88452
88453  vdbeSorterRewindDebug("rewind");
88454
88455  /* Assuming no errors have occurred, set up a merger structure to
88456  ** incrementally read and merge all remaining PMAs.  */
88457  assert( pSorter->pReader==0 );
88458  if( rc==SQLITE_OK ){
88459    rc = vdbeSorterSetupMerge(pSorter);
88460    *pbEof = 0;
88461  }
88462
88463  vdbeSorterRewindDebug("rewinddone");
88464  return rc;
88465}
88466
88467/*
88468** Advance to the next element in the sorter.
88469*/
88470SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
88471  VdbeSorter *pSorter;
88472  int rc;                         /* Return code */
88473
88474  assert( pCsr->eCurType==CURTYPE_SORTER );
88475  pSorter = pCsr->uc.pSorter;
88476  assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
88477  if( pSorter->bUsePMA ){
88478    assert( pSorter->pReader==0 || pSorter->pMerger==0 );
88479    assert( pSorter->bUseThreads==0 || pSorter->pReader );
88480    assert( pSorter->bUseThreads==1 || pSorter->pMerger );
88481#if SQLITE_MAX_WORKER_THREADS>0
88482    if( pSorter->bUseThreads ){
88483      rc = vdbePmaReaderNext(pSorter->pReader);
88484      *pbEof = (pSorter->pReader->pFd==0);
88485    }else
88486#endif
88487    /*if( !pSorter->bUseThreads )*/ {
88488      assert( pSorter->pMerger!=0 );
88489      assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
88490      rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
88491    }
88492  }else{
88493    SorterRecord *pFree = pSorter->list.pList;
88494    pSorter->list.pList = pFree->u.pNext;
88495    pFree->u.pNext = 0;
88496    if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
88497    *pbEof = !pSorter->list.pList;
88498    rc = SQLITE_OK;
88499  }
88500  return rc;
88501}
88502
88503/*
88504** Return a pointer to a buffer owned by the sorter that contains the
88505** current key.
88506*/
88507static void *vdbeSorterRowkey(
88508  const VdbeSorter *pSorter,      /* Sorter object */
88509  int *pnKey                      /* OUT: Size of current key in bytes */
88510){
88511  void *pKey;
88512  if( pSorter->bUsePMA ){
88513    PmaReader *pReader;
88514#if SQLITE_MAX_WORKER_THREADS>0
88515    if( pSorter->bUseThreads ){
88516      pReader = pSorter->pReader;
88517    }else
88518#endif
88519    /*if( !pSorter->bUseThreads )*/{
88520      pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
88521    }
88522    *pnKey = pReader->nKey;
88523    pKey = pReader->aKey;
88524  }else{
88525    *pnKey = pSorter->list.pList->nVal;
88526    pKey = SRVAL(pSorter->list.pList);
88527  }
88528  return pKey;
88529}
88530
88531/*
88532** Copy the current sorter key into the memory cell pOut.
88533*/
88534SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
88535  VdbeSorter *pSorter;
88536  void *pKey; int nKey;           /* Sorter key to copy into pOut */
88537
88538  assert( pCsr->eCurType==CURTYPE_SORTER );
88539  pSorter = pCsr->uc.pSorter;
88540  pKey = vdbeSorterRowkey(pSorter, &nKey);
88541  if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
88542    return SQLITE_NOMEM_BKPT;
88543  }
88544  pOut->n = nKey;
88545  MemSetTypeFlag(pOut, MEM_Blob);
88546  memcpy(pOut->z, pKey, nKey);
88547
88548  return SQLITE_OK;
88549}
88550
88551/*
88552** Compare the key in memory cell pVal with the key that the sorter cursor
88553** passed as the first argument currently points to. For the purposes of
88554** the comparison, ignore the rowid field at the end of each record.
88555**
88556** If the sorter cursor key contains any NULL values, consider it to be
88557** less than pVal. Even if pVal also contains NULL values.
88558**
88559** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
88560** Otherwise, set *pRes to a negative, zero or positive value if the
88561** key in pVal is smaller than, equal to or larger than the current sorter
88562** key.
88563**
88564** This routine forms the core of the OP_SorterCompare opcode, which in
88565** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
88566*/
88567SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
88568  const VdbeCursor *pCsr,         /* Sorter cursor */
88569  Mem *pVal,                      /* Value to compare to current sorter key */
88570  int nKeyCol,                    /* Compare this many columns */
88571  int *pRes                       /* OUT: Result of comparison */
88572){
88573  VdbeSorter *pSorter;
88574  UnpackedRecord *r2;
88575  KeyInfo *pKeyInfo;
88576  int i;
88577  void *pKey; int nKey;           /* Sorter key to compare pVal with */
88578
88579  assert( pCsr->eCurType==CURTYPE_SORTER );
88580  pSorter = pCsr->uc.pSorter;
88581  r2 = pSorter->pUnpacked;
88582  pKeyInfo = pCsr->pKeyInfo;
88583  if( r2==0 ){
88584    r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
88585    if( r2==0 ) return SQLITE_NOMEM_BKPT;
88586    r2->nField = nKeyCol;
88587  }
88588  assert( r2->nField==nKeyCol );
88589
88590  pKey = vdbeSorterRowkey(pSorter, &nKey);
88591  sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
88592  for(i=0; i<nKeyCol; i++){
88593    if( r2->aMem[i].flags & MEM_Null ){
88594      *pRes = -1;
88595      return SQLITE_OK;
88596    }
88597  }
88598
88599  *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
88600  return SQLITE_OK;
88601}
88602
88603/************** End of vdbesort.c ********************************************/
88604/************** Begin file memjournal.c **************************************/
88605/*
88606** 2008 October 7
88607**
88608** The author disclaims copyright to this source code.  In place of
88609** a legal notice, here is a blessing:
88610**
88611**    May you do good and not evil.
88612**    May you find forgiveness for yourself and forgive others.
88613**    May you share freely, never taking more than you give.
88614**
88615*************************************************************************
88616**
88617** This file contains code use to implement an in-memory rollback journal.
88618** The in-memory rollback journal is used to journal transactions for
88619** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
88620**
88621** Update:  The in-memory journal is also used to temporarily cache
88622** smaller journals that are not critical for power-loss recovery.
88623** For example, statement journals that are not too big will be held
88624** entirely in memory, thus reducing the number of file I/O calls, and
88625** more importantly, reducing temporary file creation events.  If these
88626** journals become too large for memory, they are spilled to disk.  But
88627** in the common case, they are usually small and no file I/O needs to
88628** occur.
88629*/
88630/* #include "sqliteInt.h" */
88631
88632/* Forward references to internal structures */
88633typedef struct MemJournal MemJournal;
88634typedef struct FilePoint FilePoint;
88635typedef struct FileChunk FileChunk;
88636
88637/*
88638** The rollback journal is composed of a linked list of these structures.
88639**
88640** The zChunk array is always at least 8 bytes in size - usually much more.
88641** Its actual size is stored in the MemJournal.nChunkSize variable.
88642*/
88643struct FileChunk {
88644  FileChunk *pNext;               /* Next chunk in the journal */
88645  u8 zChunk[8];                   /* Content of this chunk */
88646};
88647
88648/*
88649** By default, allocate this many bytes of memory for each FileChunk object.
88650*/
88651#define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
88652
88653/*
88654** For chunk size nChunkSize, return the number of bytes that should
88655** be allocated for each FileChunk structure.
88656*/
88657#define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
88658
88659/*
88660** An instance of this object serves as a cursor into the rollback journal.
88661** The cursor can be either for reading or writing.
88662*/
88663struct FilePoint {
88664  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
88665  FileChunk *pChunk;              /* Specific chunk into which cursor points */
88666};
88667
88668/*
88669** This structure is a subclass of sqlite3_file. Each open memory-journal
88670** is an instance of this class.
88671*/
88672struct MemJournal {
88673  const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
88674  int nChunkSize;                 /* In-memory chunk-size */
88675
88676  int nSpill;                     /* Bytes of data before flushing */
88677  int nSize;                      /* Bytes of data currently in memory */
88678  FileChunk *pFirst;              /* Head of in-memory chunk-list */
88679  FilePoint endpoint;             /* Pointer to the end of the file */
88680  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
88681
88682  int flags;                      /* xOpen flags */
88683  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
88684  const char *zJournal;           /* Name of the journal file */
88685};
88686
88687/*
88688** Read data from the in-memory journal file.  This is the implementation
88689** of the sqlite3_vfs.xRead method.
88690*/
88691static int memjrnlRead(
88692  sqlite3_file *pJfd,    /* The journal file from which to read */
88693  void *zBuf,            /* Put the results here */
88694  int iAmt,              /* Number of bytes to read */
88695  sqlite_int64 iOfst     /* Begin reading at this offset */
88696){
88697  MemJournal *p = (MemJournal *)pJfd;
88698  u8 *zOut = zBuf;
88699  int nRead = iAmt;
88700  int iChunkOffset;
88701  FileChunk *pChunk;
88702
88703#ifdef SQLITE_ENABLE_ATOMIC_WRITE
88704  if( (iAmt+iOfst)>p->endpoint.iOffset ){
88705    return SQLITE_IOERR_SHORT_READ;
88706  }
88707#endif
88708
88709  assert( (iAmt+iOfst)<=p->endpoint.iOffset );
88710  assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
88711  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
88712    sqlite3_int64 iOff = 0;
88713    for(pChunk=p->pFirst;
88714        ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
88715        pChunk=pChunk->pNext
88716    ){
88717      iOff += p->nChunkSize;
88718    }
88719  }else{
88720    pChunk = p->readpoint.pChunk;
88721    assert( pChunk!=0 );
88722  }
88723
88724  iChunkOffset = (int)(iOfst%p->nChunkSize);
88725  do {
88726    int iSpace = p->nChunkSize - iChunkOffset;
88727    int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
88728    memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
88729    zOut += nCopy;
88730    nRead -= iSpace;
88731    iChunkOffset = 0;
88732  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
88733  p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
88734  p->readpoint.pChunk = pChunk;
88735
88736  return SQLITE_OK;
88737}
88738
88739/*
88740** Free the list of FileChunk structures headed at MemJournal.pFirst.
88741*/
88742static void memjrnlFreeChunks(MemJournal *p){
88743  FileChunk *pIter;
88744  FileChunk *pNext;
88745  for(pIter=p->pFirst; pIter; pIter=pNext){
88746    pNext = pIter->pNext;
88747    sqlite3_free(pIter);
88748  }
88749  p->pFirst = 0;
88750}
88751
88752/*
88753** Flush the contents of memory to a real file on disk.
88754*/
88755static int memjrnlCreateFile(MemJournal *p){
88756  int rc;
88757  sqlite3_file *pReal = (sqlite3_file*)p;
88758  MemJournal copy = *p;
88759
88760  memset(p, 0, sizeof(MemJournal));
88761  rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
88762  if( rc==SQLITE_OK ){
88763    int nChunk = copy.nChunkSize;
88764    i64 iOff = 0;
88765    FileChunk *pIter;
88766    for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
88767      if( iOff + nChunk > copy.endpoint.iOffset ){
88768        nChunk = copy.endpoint.iOffset - iOff;
88769      }
88770      rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
88771      if( rc ) break;
88772      iOff += nChunk;
88773    }
88774    if( rc==SQLITE_OK ){
88775      /* No error has occurred. Free the in-memory buffers. */
88776      memjrnlFreeChunks(&copy);
88777    }
88778  }
88779  if( rc!=SQLITE_OK ){
88780    /* If an error occurred while creating or writing to the file, restore
88781    ** the original before returning. This way, SQLite uses the in-memory
88782    ** journal data to roll back changes made to the internal page-cache
88783    ** before this function was called.  */
88784    sqlite3OsClose(pReal);
88785    *p = copy;
88786  }
88787  return rc;
88788}
88789
88790
88791/*
88792** Write data to the file.
88793*/
88794static int memjrnlWrite(
88795  sqlite3_file *pJfd,    /* The journal file into which to write */
88796  const void *zBuf,      /* Take data to be written from here */
88797  int iAmt,              /* Number of bytes to write */
88798  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
88799){
88800  MemJournal *p = (MemJournal *)pJfd;
88801  int nWrite = iAmt;
88802  u8 *zWrite = (u8 *)zBuf;
88803
88804  /* If the file should be created now, create it and write the new data
88805  ** into the file on disk. */
88806  if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
88807    int rc = memjrnlCreateFile(p);
88808    if( rc==SQLITE_OK ){
88809      rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
88810    }
88811    return rc;
88812  }
88813
88814  /* If the contents of this write should be stored in memory */
88815  else{
88816    /* An in-memory journal file should only ever be appended to. Random
88817    ** access writes are not required. The only exception to this is when
88818    ** the in-memory journal is being used by a connection using the
88819    ** atomic-write optimization. In this case the first 28 bytes of the
88820    ** journal file may be written as part of committing the transaction. */
88821    assert( iOfst==p->endpoint.iOffset || iOfst==0 );
88822#ifdef SQLITE_ENABLE_ATOMIC_WRITE
88823    if( iOfst==0 && p->pFirst ){
88824      assert( p->nChunkSize>iAmt );
88825      memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
88826    }else
88827#else
88828    assert( iOfst>0 || p->pFirst==0 );
88829#endif
88830    {
88831      while( nWrite>0 ){
88832        FileChunk *pChunk = p->endpoint.pChunk;
88833        int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
88834        int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
88835
88836        if( iChunkOffset==0 ){
88837          /* New chunk is required to extend the file. */
88838          FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
88839          if( !pNew ){
88840            return SQLITE_IOERR_NOMEM_BKPT;
88841          }
88842          pNew->pNext = 0;
88843          if( pChunk ){
88844            assert( p->pFirst );
88845            pChunk->pNext = pNew;
88846          }else{
88847            assert( !p->pFirst );
88848            p->pFirst = pNew;
88849          }
88850          p->endpoint.pChunk = pNew;
88851        }
88852
88853        memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
88854        zWrite += iSpace;
88855        nWrite -= iSpace;
88856        p->endpoint.iOffset += iSpace;
88857      }
88858      p->nSize = iAmt + iOfst;
88859    }
88860  }
88861
88862  return SQLITE_OK;
88863}
88864
88865/*
88866** Truncate the file.
88867**
88868** If the journal file is already on disk, truncate it there. Or, if it
88869** is still in main memory but is being truncated to zero bytes in size,
88870** ignore
88871*/
88872static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
88873  MemJournal *p = (MemJournal *)pJfd;
88874  if( ALWAYS(size==0) ){
88875    memjrnlFreeChunks(p);
88876    p->nSize = 0;
88877    p->endpoint.pChunk = 0;
88878    p->endpoint.iOffset = 0;
88879    p->readpoint.pChunk = 0;
88880    p->readpoint.iOffset = 0;
88881  }
88882  return SQLITE_OK;
88883}
88884
88885/*
88886** Close the file.
88887*/
88888static int memjrnlClose(sqlite3_file *pJfd){
88889  MemJournal *p = (MemJournal *)pJfd;
88890  memjrnlFreeChunks(p);
88891  return SQLITE_OK;
88892}
88893
88894/*
88895** Sync the file.
88896**
88897** If the real file has been created, call its xSync method. Otherwise,
88898** syncing an in-memory journal is a no-op.
88899*/
88900static int memjrnlSync(sqlite3_file *pJfd, int flags){
88901  UNUSED_PARAMETER2(pJfd, flags);
88902  return SQLITE_OK;
88903}
88904
88905/*
88906** Query the size of the file in bytes.
88907*/
88908static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
88909  MemJournal *p = (MemJournal *)pJfd;
88910  *pSize = (sqlite_int64) p->endpoint.iOffset;
88911  return SQLITE_OK;
88912}
88913
88914/*
88915** Table of methods for MemJournal sqlite3_file object.
88916*/
88917static const struct sqlite3_io_methods MemJournalMethods = {
88918  1,                /* iVersion */
88919  memjrnlClose,     /* xClose */
88920  memjrnlRead,      /* xRead */
88921  memjrnlWrite,     /* xWrite */
88922  memjrnlTruncate,  /* xTruncate */
88923  memjrnlSync,      /* xSync */
88924  memjrnlFileSize,  /* xFileSize */
88925  0,                /* xLock */
88926  0,                /* xUnlock */
88927  0,                /* xCheckReservedLock */
88928  0,                /* xFileControl */
88929  0,                /* xSectorSize */
88930  0,                /* xDeviceCharacteristics */
88931  0,                /* xShmMap */
88932  0,                /* xShmLock */
88933  0,                /* xShmBarrier */
88934  0,                /* xShmUnmap */
88935  0,                /* xFetch */
88936  0                 /* xUnfetch */
88937};
88938
88939/*
88940** Open a journal file.
88941**
88942** The behaviour of the journal file depends on the value of parameter
88943** nSpill. If nSpill is 0, then the journal file is always create and
88944** accessed using the underlying VFS. If nSpill is less than zero, then
88945** all content is always stored in main-memory. Finally, if nSpill is a
88946** positive value, then the journal file is initially created in-memory
88947** but may be flushed to disk later on. In this case the journal file is
88948** flushed to disk either when it grows larger than nSpill bytes in size,
88949** or when sqlite3JournalCreate() is called.
88950*/
88951SQLITE_PRIVATE int sqlite3JournalOpen(
88952  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
88953  const char *zName,         /* Name of the journal file */
88954  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
88955  int flags,                 /* Opening flags */
88956  int nSpill                 /* Bytes buffered before opening the file */
88957){
88958  MemJournal *p = (MemJournal*)pJfd;
88959
88960  /* Zero the file-handle object. If nSpill was passed zero, initialize
88961  ** it using the sqlite3OsOpen() function of the underlying VFS. In this
88962  ** case none of the code in this module is executed as a result of calls
88963  ** made on the journal file-handle.  */
88964  memset(p, 0, sizeof(MemJournal));
88965  if( nSpill==0 ){
88966    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
88967  }
88968
88969  if( nSpill>0 ){
88970    p->nChunkSize = nSpill;
88971  }else{
88972    p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
88973    assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
88974  }
88975
88976  p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
88977  p->nSpill = nSpill;
88978  p->flags = flags;
88979  p->zJournal = zName;
88980  p->pVfs = pVfs;
88981  return SQLITE_OK;
88982}
88983
88984/*
88985** Open an in-memory journal file.
88986*/
88987SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
88988  sqlite3JournalOpen(0, 0, pJfd, 0, -1);
88989}
88990
88991#ifdef SQLITE_ENABLE_ATOMIC_WRITE
88992/*
88993** If the argument p points to a MemJournal structure that is not an
88994** in-memory-only journal file (i.e. is one that was opened with a +ve
88995** nSpill parameter), and the underlying file has not yet been created,
88996** create it now.
88997*/
88998SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
88999  int rc = SQLITE_OK;
89000  if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){
89001    rc = memjrnlCreateFile((MemJournal*)p);
89002  }
89003  return rc;
89004}
89005#endif
89006
89007/*
89008** The file-handle passed as the only argument is open on a journal file.
89009** Return true if this "journal file" is currently stored in heap memory,
89010** or false otherwise.
89011*/
89012SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
89013  return p->pMethods==&MemJournalMethods;
89014}
89015
89016/*
89017** Return the number of bytes required to store a JournalFile that uses vfs
89018** pVfs to create the underlying on-disk files.
89019*/
89020SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
89021  return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
89022}
89023
89024/************** End of memjournal.c ******************************************/
89025/************** Begin file walker.c ******************************************/
89026/*
89027** 2008 August 16
89028**
89029** The author disclaims copyright to this source code.  In place of
89030** a legal notice, here is a blessing:
89031**
89032**    May you do good and not evil.
89033**    May you find forgiveness for yourself and forgive others.
89034**    May you share freely, never taking more than you give.
89035**
89036*************************************************************************
89037** This file contains routines used for walking the parser tree for
89038** an SQL statement.
89039*/
89040/* #include "sqliteInt.h" */
89041/* #include <stdlib.h> */
89042/* #include <string.h> */
89043
89044
89045/*
89046** Walk an expression tree.  Invoke the callback once for each node
89047** of the expression, while descending.  (In other words, the callback
89048** is invoked before visiting children.)
89049**
89050** The return value from the callback should be one of the WRC_*
89051** constants to specify how to proceed with the walk.
89052**
89053**    WRC_Continue      Continue descending down the tree.
89054**
89055**    WRC_Prune         Do not descend into child nodes, but allow
89056**                      the walk to continue with sibling nodes.
89057**
89058**    WRC_Abort         Do no more callbacks.  Unwind the stack and
89059**                      return from the top-level walk call.
89060**
89061** The return value from this routine is WRC_Abort to abandon the tree walk
89062** and WRC_Continue to continue.
89063*/
89064static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
89065  int rc;
89066  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
89067  testcase( ExprHasProperty(pExpr, EP_Reduced) );
89068  rc = pWalker->xExprCallback(pWalker, pExpr);
89069  if( rc || ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
89070    return rc & WRC_Abort;
89071  }
89072  if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
89073  if( pExpr->pRight && walkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
89074  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
89075    if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
89076  }else if( pExpr->x.pList ){
89077    if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
89078  }
89079  return WRC_Continue;
89080}
89081SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
89082  return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
89083}
89084
89085/*
89086** Call sqlite3WalkExpr() for every expression in list p or until
89087** an abort request is seen.
89088*/
89089SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
89090  int i;
89091  struct ExprList_item *pItem;
89092  if( p ){
89093    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
89094      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
89095    }
89096  }
89097  return WRC_Continue;
89098}
89099
89100/*
89101** Walk all expressions associated with SELECT statement p.  Do
89102** not invoke the SELECT callback on p, but do (of course) invoke
89103** any expr callbacks and SELECT callbacks that come from subqueries.
89104** Return WRC_Abort or WRC_Continue.
89105*/
89106SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
89107  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
89108  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
89109  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
89110  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
89111  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
89112  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
89113  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
89114  return WRC_Continue;
89115}
89116
89117/*
89118** Walk the parse trees associated with all subqueries in the
89119** FROM clause of SELECT statement p.  Do not invoke the select
89120** callback on p, but do invoke it on each FROM clause subquery
89121** and on any subqueries further down in the tree.  Return
89122** WRC_Abort or WRC_Continue;
89123*/
89124SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
89125  SrcList *pSrc;
89126  int i;
89127  struct SrcList_item *pItem;
89128
89129  pSrc = p->pSrc;
89130  if( ALWAYS(pSrc) ){
89131    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
89132      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
89133        return WRC_Abort;
89134      }
89135      if( pItem->fg.isTabFunc
89136       && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
89137      ){
89138        return WRC_Abort;
89139      }
89140    }
89141  }
89142  return WRC_Continue;
89143}
89144
89145/*
89146** Call sqlite3WalkExpr() for every expression in Select statement p.
89147** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
89148** on the compound select chain, p->pPrior.
89149**
89150** If it is not NULL, the xSelectCallback() callback is invoked before
89151** the walk of the expressions and FROM clause. The xSelectCallback2()
89152** method, if it is not NULL, is invoked following the walk of the
89153** expressions and FROM clause.
89154**
89155** Return WRC_Continue under normal conditions.  Return WRC_Abort if
89156** there is an abort request.
89157**
89158** If the Walker does not have an xSelectCallback() then this routine
89159** is a no-op returning WRC_Continue.
89160*/
89161SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
89162  int rc;
89163  if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
89164    return WRC_Continue;
89165  }
89166  rc = WRC_Continue;
89167  pWalker->walkerDepth++;
89168  while( p ){
89169    if( pWalker->xSelectCallback ){
89170       rc = pWalker->xSelectCallback(pWalker, p);
89171       if( rc ) break;
89172    }
89173    if( sqlite3WalkSelectExpr(pWalker, p)
89174     || sqlite3WalkSelectFrom(pWalker, p)
89175    ){
89176      pWalker->walkerDepth--;
89177      return WRC_Abort;
89178    }
89179    if( pWalker->xSelectCallback2 ){
89180      pWalker->xSelectCallback2(pWalker, p);
89181    }
89182    p = p->pPrior;
89183  }
89184  pWalker->walkerDepth--;
89185  return rc & WRC_Abort;
89186}
89187
89188/************** End of walker.c **********************************************/
89189/************** Begin file resolve.c *****************************************/
89190/*
89191** 2008 August 18
89192**
89193** The author disclaims copyright to this source code.  In place of
89194** a legal notice, here is a blessing:
89195**
89196**    May you do good and not evil.
89197**    May you find forgiveness for yourself and forgive others.
89198**    May you share freely, never taking more than you give.
89199**
89200*************************************************************************
89201**
89202** This file contains routines used for walking the parser tree and
89203** resolve all identifiers by associating them with a particular
89204** table and column.
89205*/
89206/* #include "sqliteInt.h" */
89207
89208/*
89209** Walk the expression tree pExpr and increase the aggregate function
89210** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
89211** This needs to occur when copying a TK_AGG_FUNCTION node from an
89212** outer query into an inner subquery.
89213**
89214** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
89215** is a helper function - a callback for the tree walker.
89216*/
89217static int incrAggDepth(Walker *pWalker, Expr *pExpr){
89218  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
89219  return WRC_Continue;
89220}
89221static void incrAggFunctionDepth(Expr *pExpr, int N){
89222  if( N>0 ){
89223    Walker w;
89224    memset(&w, 0, sizeof(w));
89225    w.xExprCallback = incrAggDepth;
89226    w.u.n = N;
89227    sqlite3WalkExpr(&w, pExpr);
89228  }
89229}
89230
89231/*
89232** Turn the pExpr expression into an alias for the iCol-th column of the
89233** result set in pEList.
89234**
89235** If the reference is followed by a COLLATE operator, then make sure
89236** the COLLATE operator is preserved.  For example:
89237**
89238**     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
89239**
89240** Should be transformed into:
89241**
89242**     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
89243**
89244** The nSubquery parameter specifies how many levels of subquery the
89245** alias is removed from the original expression.  The usual value is
89246** zero but it might be more if the alias is contained within a subquery
89247** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
89248** structures must be increased by the nSubquery amount.
89249*/
89250static void resolveAlias(
89251  Parse *pParse,         /* Parsing context */
89252  ExprList *pEList,      /* A result set */
89253  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
89254  Expr *pExpr,           /* Transform this into an alias to the result set */
89255  const char *zType,     /* "GROUP" or "ORDER" or "" */
89256  int nSubquery          /* Number of subqueries that the label is moving */
89257){
89258  Expr *pOrig;           /* The iCol-th column of the result set */
89259  Expr *pDup;            /* Copy of pOrig */
89260  sqlite3 *db;           /* The database connection */
89261
89262  assert( iCol>=0 && iCol<pEList->nExpr );
89263  pOrig = pEList->a[iCol].pExpr;
89264  assert( pOrig!=0 );
89265  db = pParse->db;
89266  pDup = sqlite3ExprDup(db, pOrig, 0);
89267  if( pDup==0 ) return;
89268  if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
89269  if( pExpr->op==TK_COLLATE ){
89270    pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
89271  }
89272  ExprSetProperty(pDup, EP_Alias);
89273
89274  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
89275  ** prevents ExprDelete() from deleting the Expr structure itself,
89276  ** allowing it to be repopulated by the memcpy() on the following line.
89277  ** The pExpr->u.zToken might point into memory that will be freed by the
89278  ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
89279  ** make a copy of the token before doing the sqlite3DbFree().
89280  */
89281  ExprSetProperty(pExpr, EP_Static);
89282  sqlite3ExprDelete(db, pExpr);
89283  memcpy(pExpr, pDup, sizeof(*pExpr));
89284  if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
89285    assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
89286    pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
89287    pExpr->flags |= EP_MemToken;
89288  }
89289  sqlite3DbFree(db, pDup);
89290}
89291
89292
89293/*
89294** Return TRUE if the name zCol occurs anywhere in the USING clause.
89295**
89296** Return FALSE if the USING clause is NULL or if it does not contain
89297** zCol.
89298*/
89299static int nameInUsingClause(IdList *pUsing, const char *zCol){
89300  if( pUsing ){
89301    int k;
89302    for(k=0; k<pUsing->nId; k++){
89303      if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
89304    }
89305  }
89306  return 0;
89307}
89308
89309/*
89310** Subqueries stores the original database, table and column names for their
89311** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
89312** Check to see if the zSpan given to this routine matches the zDb, zTab,
89313** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
89314** match anything.
89315*/
89316SQLITE_PRIVATE int sqlite3MatchSpanName(
89317  const char *zSpan,
89318  const char *zCol,
89319  const char *zTab,
89320  const char *zDb
89321){
89322  int n;
89323  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
89324  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
89325    return 0;
89326  }
89327  zSpan += n+1;
89328  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
89329  if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
89330    return 0;
89331  }
89332  zSpan += n+1;
89333  if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
89334    return 0;
89335  }
89336  return 1;
89337}
89338
89339/*
89340** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
89341** that name in the set of source tables in pSrcList and make the pExpr
89342** expression node refer back to that source column.  The following changes
89343** are made to pExpr:
89344**
89345**    pExpr->iDb           Set the index in db->aDb[] of the database X
89346**                         (even if X is implied).
89347**    pExpr->iTable        Set to the cursor number for the table obtained
89348**                         from pSrcList.
89349**    pExpr->pTab          Points to the Table structure of X.Y (even if
89350**                         X and/or Y are implied.)
89351**    pExpr->iColumn       Set to the column number within the table.
89352**    pExpr->op            Set to TK_COLUMN.
89353**    pExpr->pLeft         Any expression this points to is deleted
89354**    pExpr->pRight        Any expression this points to is deleted.
89355**
89356** The zDb variable is the name of the database (the "X").  This value may be
89357** NULL meaning that name is of the form Y.Z or Z.  Any available database
89358** can be used.  The zTable variable is the name of the table (the "Y").  This
89359** value can be NULL if zDb is also NULL.  If zTable is NULL it
89360** means that the form of the name is Z and that columns from any table
89361** can be used.
89362**
89363** If the name cannot be resolved unambiguously, leave an error message
89364** in pParse and return WRC_Abort.  Return WRC_Prune on success.
89365*/
89366static int lookupName(
89367  Parse *pParse,       /* The parsing context */
89368  const char *zDb,     /* Name of the database containing table, or NULL */
89369  const char *zTab,    /* Name of table containing column, or NULL */
89370  const char *zCol,    /* Name of the column. */
89371  NameContext *pNC,    /* The name context used to resolve the name */
89372  Expr *pExpr          /* Make this EXPR node point to the selected column */
89373){
89374  int i, j;                         /* Loop counters */
89375  int cnt = 0;                      /* Number of matching column names */
89376  int cntTab = 0;                   /* Number of matching table names */
89377  int nSubquery = 0;                /* How many levels of subquery */
89378  sqlite3 *db = pParse->db;         /* The database connection */
89379  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
89380  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
89381  NameContext *pTopNC = pNC;        /* First namecontext in the list */
89382  Schema *pSchema = 0;              /* Schema of the expression */
89383  int isTrigger = 0;                /* True if resolved to a trigger column */
89384  Table *pTab = 0;                  /* Table hold the row */
89385  Column *pCol;                     /* A column of pTab */
89386
89387  assert( pNC );     /* the name context cannot be NULL. */
89388  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
89389  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
89390
89391  /* Initialize the node to no-match */
89392  pExpr->iTable = -1;
89393  pExpr->pTab = 0;
89394  ExprSetVVAProperty(pExpr, EP_NoReduce);
89395
89396  /* Translate the schema name in zDb into a pointer to the corresponding
89397  ** schema.  If not found, pSchema will remain NULL and nothing will match
89398  ** resulting in an appropriate error message toward the end of this routine
89399  */
89400  if( zDb ){
89401    testcase( pNC->ncFlags & NC_PartIdx );
89402    testcase( pNC->ncFlags & NC_IsCheck );
89403    if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
89404      /* Silently ignore database qualifiers inside CHECK constraints and
89405      ** partial indices.  Do not raise errors because that might break
89406      ** legacy and because it does not hurt anything to just ignore the
89407      ** database name. */
89408      zDb = 0;
89409    }else{
89410      for(i=0; i<db->nDb; i++){
89411        assert( db->aDb[i].zDbSName );
89412        if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
89413          pSchema = db->aDb[i].pSchema;
89414          break;
89415        }
89416      }
89417    }
89418  }
89419
89420  /* Start at the inner-most context and move outward until a match is found */
89421  assert( pNC && cnt==0 );
89422  do{
89423    ExprList *pEList;
89424    SrcList *pSrcList = pNC->pSrcList;
89425
89426    if( pSrcList ){
89427      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
89428        pTab = pItem->pTab;
89429        assert( pTab!=0 && pTab->zName!=0 );
89430        assert( pTab->nCol>0 );
89431        if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
89432          int hit = 0;
89433          pEList = pItem->pSelect->pEList;
89434          for(j=0; j<pEList->nExpr; j++){
89435            if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
89436              cnt++;
89437              cntTab = 2;
89438              pMatch = pItem;
89439              pExpr->iColumn = j;
89440              hit = 1;
89441            }
89442          }
89443          if( hit || zTab==0 ) continue;
89444        }
89445        if( zDb && pTab->pSchema!=pSchema ){
89446          continue;
89447        }
89448        if( zTab ){
89449          const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
89450          assert( zTabName!=0 );
89451          if( sqlite3StrICmp(zTabName, zTab)!=0 ){
89452            continue;
89453          }
89454        }
89455        if( 0==(cntTab++) ){
89456          pMatch = pItem;
89457        }
89458        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
89459          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
89460            /* If there has been exactly one prior match and this match
89461            ** is for the right-hand table of a NATURAL JOIN or is in a
89462            ** USING clause, then skip this match.
89463            */
89464            if( cnt==1 ){
89465              if( pItem->fg.jointype & JT_NATURAL ) continue;
89466              if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
89467            }
89468            cnt++;
89469            pMatch = pItem;
89470            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
89471            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
89472            break;
89473          }
89474        }
89475      }
89476      if( pMatch ){
89477        pExpr->iTable = pMatch->iCursor;
89478        pExpr->pTab = pMatch->pTab;
89479        /* RIGHT JOIN not (yet) supported */
89480        assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
89481        if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
89482          ExprSetProperty(pExpr, EP_CanBeNull);
89483        }
89484        pSchema = pExpr->pTab->pSchema;
89485      }
89486    } /* if( pSrcList ) */
89487
89488#ifndef SQLITE_OMIT_TRIGGER
89489    /* If we have not already resolved the name, then maybe
89490    ** it is a new.* or old.* trigger argument reference
89491    */
89492    if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
89493      int op = pParse->eTriggerOp;
89494      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
89495      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
89496        pExpr->iTable = 1;
89497        pTab = pParse->pTriggerTab;
89498      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
89499        pExpr->iTable = 0;
89500        pTab = pParse->pTriggerTab;
89501      }else{
89502        pTab = 0;
89503      }
89504
89505      if( pTab ){
89506        int iCol;
89507        pSchema = pTab->pSchema;
89508        cntTab++;
89509        for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
89510          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
89511            if( iCol==pTab->iPKey ){
89512              iCol = -1;
89513            }
89514            break;
89515          }
89516        }
89517        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
89518          /* IMP: R-51414-32910 */
89519          iCol = -1;
89520        }
89521        if( iCol<pTab->nCol ){
89522          cnt++;
89523          if( iCol<0 ){
89524            pExpr->affinity = SQLITE_AFF_INTEGER;
89525          }else if( pExpr->iTable==0 ){
89526            testcase( iCol==31 );
89527            testcase( iCol==32 );
89528            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
89529          }else{
89530            testcase( iCol==31 );
89531            testcase( iCol==32 );
89532            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
89533          }
89534          pExpr->iColumn = (i16)iCol;
89535          pExpr->pTab = pTab;
89536          isTrigger = 1;
89537        }
89538      }
89539    }
89540#endif /* !defined(SQLITE_OMIT_TRIGGER) */
89541
89542    /*
89543    ** Perhaps the name is a reference to the ROWID
89544    */
89545    if( cnt==0
89546     && cntTab==1
89547     && pMatch
89548     && (pNC->ncFlags & NC_IdxExpr)==0
89549     && sqlite3IsRowid(zCol)
89550     && VisibleRowid(pMatch->pTab)
89551    ){
89552      cnt = 1;
89553      pExpr->iColumn = -1;
89554      pExpr->affinity = SQLITE_AFF_INTEGER;
89555    }
89556
89557    /*
89558    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
89559    ** might refer to an result-set alias.  This happens, for example, when
89560    ** we are resolving names in the WHERE clause of the following command:
89561    **
89562    **     SELECT a+b AS x FROM table WHERE x<10;
89563    **
89564    ** In cases like this, replace pExpr with a copy of the expression that
89565    ** forms the result set entry ("a+b" in the example) and return immediately.
89566    ** Note that the expression in the result set should have already been
89567    ** resolved by the time the WHERE clause is resolved.
89568    **
89569    ** The ability to use an output result-set column in the WHERE, GROUP BY,
89570    ** or HAVING clauses, or as part of a larger expression in the ORDER BY
89571    ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
89572    ** is supported for backwards compatibility only. Hence, we issue a warning
89573    ** on sqlite3_log() whenever the capability is used.
89574    */
89575    if( (pEList = pNC->pEList)!=0
89576     && zTab==0
89577     && cnt==0
89578    ){
89579      for(j=0; j<pEList->nExpr; j++){
89580        char *zAs = pEList->a[j].zName;
89581        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
89582          Expr *pOrig;
89583          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
89584          assert( pExpr->x.pList==0 );
89585          assert( pExpr->x.pSelect==0 );
89586          pOrig = pEList->a[j].pExpr;
89587          if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
89588            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
89589            return WRC_Abort;
89590          }
89591          if( sqlite3ExprVectorSize(pOrig)!=1 ){
89592            sqlite3ErrorMsg(pParse, "row value misused");
89593            return WRC_Abort;
89594          }
89595          resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
89596          cnt = 1;
89597          pMatch = 0;
89598          assert( zTab==0 && zDb==0 );
89599          goto lookupname_end;
89600        }
89601      }
89602    }
89603
89604    /* Advance to the next name context.  The loop will exit when either
89605    ** we have a match (cnt>0) or when we run out of name contexts.
89606    */
89607    if( cnt ) break;
89608    pNC = pNC->pNext;
89609    nSubquery++;
89610  }while( pNC );
89611
89612
89613  /*
89614  ** If X and Y are NULL (in other words if only the column name Z is
89615  ** supplied) and the value of Z is enclosed in double-quotes, then
89616  ** Z is a string literal if it doesn't match any column names.  In that
89617  ** case, we need to return right away and not make any changes to
89618  ** pExpr.
89619  **
89620  ** Because no reference was made to outer contexts, the pNC->nRef
89621  ** fields are not changed in any context.
89622  */
89623  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
89624    pExpr->op = TK_STRING;
89625    pExpr->pTab = 0;
89626    return WRC_Prune;
89627  }
89628
89629  /*
89630  ** cnt==0 means there was not match.  cnt>1 means there were two or
89631  ** more matches.  Either way, we have an error.
89632  */
89633  if( cnt!=1 ){
89634    const char *zErr;
89635    zErr = cnt==0 ? "no such column" : "ambiguous column name";
89636    if( zDb ){
89637      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
89638    }else if( zTab ){
89639      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
89640    }else{
89641      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
89642    }
89643    pParse->checkSchema = 1;
89644    pTopNC->nErr++;
89645  }
89646
89647  /* If a column from a table in pSrcList is referenced, then record
89648  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
89649  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
89650  ** column number is greater than the number of bits in the bitmask
89651  ** then set the high-order bit of the bitmask.
89652  */
89653  if( pExpr->iColumn>=0 && pMatch!=0 ){
89654    int n = pExpr->iColumn;
89655    testcase( n==BMS-1 );
89656    if( n>=BMS ){
89657      n = BMS-1;
89658    }
89659    assert( pMatch->iCursor==pExpr->iTable );
89660    pMatch->colUsed |= ((Bitmask)1)<<n;
89661  }
89662
89663  /* Clean up and return
89664  */
89665  sqlite3ExprDelete(db, pExpr->pLeft);
89666  pExpr->pLeft = 0;
89667  sqlite3ExprDelete(db, pExpr->pRight);
89668  pExpr->pRight = 0;
89669  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
89670lookupname_end:
89671  if( cnt==1 ){
89672    assert( pNC!=0 );
89673    if( !ExprHasProperty(pExpr, EP_Alias) ){
89674      sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
89675    }
89676    /* Increment the nRef value on all name contexts from TopNC up to
89677    ** the point where the name matched. */
89678    for(;;){
89679      assert( pTopNC!=0 );
89680      pTopNC->nRef++;
89681      if( pTopNC==pNC ) break;
89682      pTopNC = pTopNC->pNext;
89683    }
89684    return WRC_Prune;
89685  } else {
89686    return WRC_Abort;
89687  }
89688}
89689
89690/*
89691** Allocate and return a pointer to an expression to load the column iCol
89692** from datasource iSrc in SrcList pSrc.
89693*/
89694SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
89695  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
89696  if( p ){
89697    struct SrcList_item *pItem = &pSrc->a[iSrc];
89698    p->pTab = pItem->pTab;
89699    p->iTable = pItem->iCursor;
89700    if( p->pTab->iPKey==iCol ){
89701      p->iColumn = -1;
89702    }else{
89703      p->iColumn = (ynVar)iCol;
89704      testcase( iCol==BMS );
89705      testcase( iCol==BMS-1 );
89706      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
89707    }
89708    ExprSetProperty(p, EP_Resolved);
89709  }
89710  return p;
89711}
89712
89713/*
89714** Report an error that an expression is not valid for some set of
89715** pNC->ncFlags values determined by validMask.
89716*/
89717static void notValid(
89718  Parse *pParse,       /* Leave error message here */
89719  NameContext *pNC,    /* The name context */
89720  const char *zMsg,    /* Type of error */
89721  int validMask        /* Set of contexts for which prohibited */
89722){
89723  assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
89724  if( (pNC->ncFlags & validMask)!=0 ){
89725    const char *zIn = "partial index WHERE clauses";
89726    if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
89727#ifndef SQLITE_OMIT_CHECK
89728    else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
89729#endif
89730    sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
89731  }
89732}
89733
89734/*
89735** Expression p should encode a floating point value between 1.0 and 0.0.
89736** Return 1024 times this value.  Or return -1 if p is not a floating point
89737** value between 1.0 and 0.0.
89738*/
89739static int exprProbability(Expr *p){
89740  double r = -1.0;
89741  if( p->op!=TK_FLOAT ) return -1;
89742  sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
89743  assert( r>=0.0 );
89744  if( r>1.0 ) return -1;
89745  return (int)(r*134217728.0);
89746}
89747
89748/*
89749** This routine is callback for sqlite3WalkExpr().
89750**
89751** Resolve symbolic names into TK_COLUMN operators for the current
89752** node in the expression tree.  Return 0 to continue the search down
89753** the tree or 2 to abort the tree walk.
89754**
89755** This routine also does error checking and name resolution for
89756** function names.  The operator for aggregate functions is changed
89757** to TK_AGG_FUNCTION.
89758*/
89759static int resolveExprStep(Walker *pWalker, Expr *pExpr){
89760  NameContext *pNC;
89761  Parse *pParse;
89762
89763  pNC = pWalker->u.pNC;
89764  assert( pNC!=0 );
89765  pParse = pNC->pParse;
89766  assert( pParse==pWalker->pParse );
89767
89768  if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
89769  ExprSetProperty(pExpr, EP_Resolved);
89770#ifndef NDEBUG
89771  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
89772    SrcList *pSrcList = pNC->pSrcList;
89773    int i;
89774    for(i=0; i<pNC->pSrcList->nSrc; i++){
89775      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
89776    }
89777  }
89778#endif
89779  switch( pExpr->op ){
89780
89781#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
89782    /* The special operator TK_ROW means use the rowid for the first
89783    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
89784    ** clause processing on UPDATE and DELETE statements.
89785    */
89786    case TK_ROW: {
89787      SrcList *pSrcList = pNC->pSrcList;
89788      struct SrcList_item *pItem;
89789      assert( pSrcList && pSrcList->nSrc==1 );
89790      pItem = pSrcList->a;
89791      pExpr->op = TK_COLUMN;
89792      pExpr->pTab = pItem->pTab;
89793      pExpr->iTable = pItem->iCursor;
89794      pExpr->iColumn = -1;
89795      pExpr->affinity = SQLITE_AFF_INTEGER;
89796      break;
89797    }
89798#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
89799          && !defined(SQLITE_OMIT_SUBQUERY) */
89800
89801    /* A column name:                    ID
89802    ** Or table name and column name:    ID.ID
89803    ** Or a database, table and column:  ID.ID.ID
89804    **
89805    ** The TK_ID and TK_OUT cases are combined so that there will only
89806    ** be one call to lookupName().  Then the compiler will in-line
89807    ** lookupName() for a size reduction and performance increase.
89808    */
89809    case TK_ID:
89810    case TK_DOT: {
89811      const char *zColumn;
89812      const char *zTable;
89813      const char *zDb;
89814      Expr *pRight;
89815
89816      if( pExpr->op==TK_ID ){
89817        zDb = 0;
89818        zTable = 0;
89819        zColumn = pExpr->u.zToken;
89820      }else{
89821        notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
89822        pRight = pExpr->pRight;
89823        if( pRight->op==TK_ID ){
89824          zDb = 0;
89825          zTable = pExpr->pLeft->u.zToken;
89826          zColumn = pRight->u.zToken;
89827        }else{
89828          assert( pRight->op==TK_DOT );
89829          zDb = pExpr->pLeft->u.zToken;
89830          zTable = pRight->pLeft->u.zToken;
89831          zColumn = pRight->pRight->u.zToken;
89832        }
89833      }
89834      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
89835    }
89836
89837    /* Resolve function names
89838    */
89839    case TK_FUNCTION: {
89840      ExprList *pList = pExpr->x.pList;    /* The argument list */
89841      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
89842      int no_such_func = 0;       /* True if no such function exists */
89843      int wrong_num_args = 0;     /* True if wrong number of arguments */
89844      int is_agg = 0;             /* True if is an aggregate function */
89845      int nId;                    /* Number of characters in function name */
89846      const char *zId;            /* The function name. */
89847      FuncDef *pDef;              /* Information about the function */
89848      u8 enc = ENC(pParse->db);   /* The database encoding */
89849
89850      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
89851      zId = pExpr->u.zToken;
89852      nId = sqlite3Strlen30(zId);
89853      pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
89854      if( pDef==0 ){
89855        pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
89856        if( pDef==0 ){
89857          no_such_func = 1;
89858        }else{
89859          wrong_num_args = 1;
89860        }
89861      }else{
89862        is_agg = pDef->xFinalize!=0;
89863        if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
89864          ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
89865          if( n==2 ){
89866            pExpr->iTable = exprProbability(pList->a[1].pExpr);
89867            if( pExpr->iTable<0 ){
89868              sqlite3ErrorMsg(pParse,
89869                "second argument to likelihood() must be a "
89870                "constant between 0.0 and 1.0");
89871              pNC->nErr++;
89872            }
89873          }else{
89874            /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
89875            ** equivalent to likelihood(X, 0.0625).
89876            ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
89877            ** short-hand for likelihood(X,0.0625).
89878            ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
89879            ** for likelihood(X,0.9375).
89880            ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
89881            ** to likelihood(X,0.9375). */
89882            /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
89883            pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
89884          }
89885        }
89886#ifndef SQLITE_OMIT_AUTHORIZATION
89887        {
89888          int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
89889          if( auth!=SQLITE_OK ){
89890            if( auth==SQLITE_DENY ){
89891              sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
89892                                      pDef->zName);
89893              pNC->nErr++;
89894            }
89895            pExpr->op = TK_NULL;
89896            return WRC_Prune;
89897          }
89898        }
89899#endif
89900        if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
89901          /* For the purposes of the EP_ConstFunc flag, date and time
89902          ** functions and other functions that change slowly are considered
89903          ** constant because they are constant for the duration of one query */
89904          ExprSetProperty(pExpr,EP_ConstFunc);
89905        }
89906        if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
89907          /* Date/time functions that use 'now', and other functions like
89908          ** sqlite_version() that might change over time cannot be used
89909          ** in an index. */
89910          notValid(pParse, pNC, "non-deterministic functions",
89911                   NC_IdxExpr|NC_PartIdx);
89912        }
89913      }
89914      if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
89915        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
89916        pNC->nErr++;
89917        is_agg = 0;
89918      }else if( no_such_func && pParse->db->init.busy==0
89919#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
89920                && pParse->explain==0
89921#endif
89922      ){
89923        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
89924        pNC->nErr++;
89925      }else if( wrong_num_args ){
89926        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
89927             nId, zId);
89928        pNC->nErr++;
89929      }
89930      if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
89931      sqlite3WalkExprList(pWalker, pList);
89932      if( is_agg ){
89933        NameContext *pNC2 = pNC;
89934        pExpr->op = TK_AGG_FUNCTION;
89935        pExpr->op2 = 0;
89936        while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
89937          pExpr->op2++;
89938          pNC2 = pNC2->pNext;
89939        }
89940        assert( pDef!=0 );
89941        if( pNC2 ){
89942          assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
89943          testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
89944          pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
89945
89946        }
89947        pNC->ncFlags |= NC_AllowAgg;
89948      }
89949      /* FIX ME:  Compute pExpr->affinity based on the expected return
89950      ** type of the function
89951      */
89952      return WRC_Prune;
89953    }
89954#ifndef SQLITE_OMIT_SUBQUERY
89955    case TK_SELECT:
89956    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
89957#endif
89958    case TK_IN: {
89959      testcase( pExpr->op==TK_IN );
89960      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
89961        int nRef = pNC->nRef;
89962        notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
89963        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
89964        assert( pNC->nRef>=nRef );
89965        if( nRef!=pNC->nRef ){
89966          ExprSetProperty(pExpr, EP_VarSelect);
89967          pNC->ncFlags |= NC_VarSelect;
89968        }
89969      }
89970      break;
89971    }
89972    case TK_VARIABLE: {
89973      notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
89974      break;
89975    }
89976    case TK_BETWEEN:
89977    case TK_EQ:
89978    case TK_NE:
89979    case TK_LT:
89980    case TK_LE:
89981    case TK_GT:
89982    case TK_GE:
89983    case TK_IS:
89984    case TK_ISNOT: {
89985      int nLeft, nRight;
89986      if( pParse->db->mallocFailed ) break;
89987      assert( pExpr->pLeft!=0 );
89988      nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
89989      if( pExpr->op==TK_BETWEEN ){
89990        nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
89991        if( nRight==nLeft ){
89992          nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
89993        }
89994      }else{
89995        assert( pExpr->pRight!=0 );
89996        nRight = sqlite3ExprVectorSize(pExpr->pRight);
89997      }
89998      if( nLeft!=nRight ){
89999        testcase( pExpr->op==TK_EQ );
90000        testcase( pExpr->op==TK_NE );
90001        testcase( pExpr->op==TK_LT );
90002        testcase( pExpr->op==TK_LE );
90003        testcase( pExpr->op==TK_GT );
90004        testcase( pExpr->op==TK_GE );
90005        testcase( pExpr->op==TK_IS );
90006        testcase( pExpr->op==TK_ISNOT );
90007        testcase( pExpr->op==TK_BETWEEN );
90008        sqlite3ErrorMsg(pParse, "row value misused");
90009      }
90010      break;
90011    }
90012  }
90013  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
90014}
90015
90016/*
90017** pEList is a list of expressions which are really the result set of the
90018** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
90019** This routine checks to see if pE is a simple identifier which corresponds
90020** to the AS-name of one of the terms of the expression list.  If it is,
90021** this routine return an integer between 1 and N where N is the number of
90022** elements in pEList, corresponding to the matching entry.  If there is
90023** no match, or if pE is not a simple identifier, then this routine
90024** return 0.
90025**
90026** pEList has been resolved.  pE has not.
90027*/
90028static int resolveAsName(
90029  Parse *pParse,     /* Parsing context for error messages */
90030  ExprList *pEList,  /* List of expressions to scan */
90031  Expr *pE           /* Expression we are trying to match */
90032){
90033  int i;             /* Loop counter */
90034
90035  UNUSED_PARAMETER(pParse);
90036
90037  if( pE->op==TK_ID ){
90038    char *zCol = pE->u.zToken;
90039    for(i=0; i<pEList->nExpr; i++){
90040      char *zAs = pEList->a[i].zName;
90041      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
90042        return i+1;
90043      }
90044    }
90045  }
90046  return 0;
90047}
90048
90049/*
90050** pE is a pointer to an expression which is a single term in the
90051** ORDER BY of a compound SELECT.  The expression has not been
90052** name resolved.
90053**
90054** At the point this routine is called, we already know that the
90055** ORDER BY term is not an integer index into the result set.  That
90056** case is handled by the calling routine.
90057**
90058** Attempt to match pE against result set columns in the left-most
90059** SELECT statement.  Return the index i of the matching column,
90060** as an indication to the caller that it should sort by the i-th column.
90061** The left-most column is 1.  In other words, the value returned is the
90062** same integer value that would be used in the SQL statement to indicate
90063** the column.
90064**
90065** If there is no match, return 0.  Return -1 if an error occurs.
90066*/
90067static int resolveOrderByTermToExprList(
90068  Parse *pParse,     /* Parsing context for error messages */
90069  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
90070  Expr *pE           /* The specific ORDER BY term */
90071){
90072  int i;             /* Loop counter */
90073  ExprList *pEList;  /* The columns of the result set */
90074  NameContext nc;    /* Name context for resolving pE */
90075  sqlite3 *db;       /* Database connection */
90076  int rc;            /* Return code from subprocedures */
90077  u8 savedSuppErr;   /* Saved value of db->suppressErr */
90078
90079  assert( sqlite3ExprIsInteger(pE, &i)==0 );
90080  pEList = pSelect->pEList;
90081
90082  /* Resolve all names in the ORDER BY term expression
90083  */
90084  memset(&nc, 0, sizeof(nc));
90085  nc.pParse = pParse;
90086  nc.pSrcList = pSelect->pSrc;
90087  nc.pEList = pEList;
90088  nc.ncFlags = NC_AllowAgg;
90089  nc.nErr = 0;
90090  db = pParse->db;
90091  savedSuppErr = db->suppressErr;
90092  db->suppressErr = 1;
90093  rc = sqlite3ResolveExprNames(&nc, pE);
90094  db->suppressErr = savedSuppErr;
90095  if( rc ) return 0;
90096
90097  /* Try to match the ORDER BY expression against an expression
90098  ** in the result set.  Return an 1-based index of the matching
90099  ** result-set entry.
90100  */
90101  for(i=0; i<pEList->nExpr; i++){
90102    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
90103      return i+1;
90104    }
90105  }
90106
90107  /* If no match, return 0. */
90108  return 0;
90109}
90110
90111/*
90112** Generate an ORDER BY or GROUP BY term out-of-range error.
90113*/
90114static void resolveOutOfRangeError(
90115  Parse *pParse,         /* The error context into which to write the error */
90116  const char *zType,     /* "ORDER" or "GROUP" */
90117  int i,                 /* The index (1-based) of the term out of range */
90118  int mx                 /* Largest permissible value of i */
90119){
90120  sqlite3ErrorMsg(pParse,
90121    "%r %s BY term out of range - should be "
90122    "between 1 and %d", i, zType, mx);
90123}
90124
90125/*
90126** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
90127** each term of the ORDER BY clause is a constant integer between 1
90128** and N where N is the number of columns in the compound SELECT.
90129**
90130** ORDER BY terms that are already an integer between 1 and N are
90131** unmodified.  ORDER BY terms that are integers outside the range of
90132** 1 through N generate an error.  ORDER BY terms that are expressions
90133** are matched against result set expressions of compound SELECT
90134** beginning with the left-most SELECT and working toward the right.
90135** At the first match, the ORDER BY expression is transformed into
90136** the integer column number.
90137**
90138** Return the number of errors seen.
90139*/
90140static int resolveCompoundOrderBy(
90141  Parse *pParse,        /* Parsing context.  Leave error messages here */
90142  Select *pSelect       /* The SELECT statement containing the ORDER BY */
90143){
90144  int i;
90145  ExprList *pOrderBy;
90146  ExprList *pEList;
90147  sqlite3 *db;
90148  int moreToDo = 1;
90149
90150  pOrderBy = pSelect->pOrderBy;
90151  if( pOrderBy==0 ) return 0;
90152  db = pParse->db;
90153#if SQLITE_MAX_COLUMN
90154  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
90155    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
90156    return 1;
90157  }
90158#endif
90159  for(i=0; i<pOrderBy->nExpr; i++){
90160    pOrderBy->a[i].done = 0;
90161  }
90162  pSelect->pNext = 0;
90163  while( pSelect->pPrior ){
90164    pSelect->pPrior->pNext = pSelect;
90165    pSelect = pSelect->pPrior;
90166  }
90167  while( pSelect && moreToDo ){
90168    struct ExprList_item *pItem;
90169    moreToDo = 0;
90170    pEList = pSelect->pEList;
90171    assert( pEList!=0 );
90172    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
90173      int iCol = -1;
90174      Expr *pE, *pDup;
90175      if( pItem->done ) continue;
90176      pE = sqlite3ExprSkipCollate(pItem->pExpr);
90177      if( sqlite3ExprIsInteger(pE, &iCol) ){
90178        if( iCol<=0 || iCol>pEList->nExpr ){
90179          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
90180          return 1;
90181        }
90182      }else{
90183        iCol = resolveAsName(pParse, pEList, pE);
90184        if( iCol==0 ){
90185          pDup = sqlite3ExprDup(db, pE, 0);
90186          if( !db->mallocFailed ){
90187            assert(pDup);
90188            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
90189          }
90190          sqlite3ExprDelete(db, pDup);
90191        }
90192      }
90193      if( iCol>0 ){
90194        /* Convert the ORDER BY term into an integer column number iCol,
90195        ** taking care to preserve the COLLATE clause if it exists */
90196        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
90197        if( pNew==0 ) return 1;
90198        pNew->flags |= EP_IntValue;
90199        pNew->u.iValue = iCol;
90200        if( pItem->pExpr==pE ){
90201          pItem->pExpr = pNew;
90202        }else{
90203          Expr *pParent = pItem->pExpr;
90204          assert( pParent->op==TK_COLLATE );
90205          while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
90206          assert( pParent->pLeft==pE );
90207          pParent->pLeft = pNew;
90208        }
90209        sqlite3ExprDelete(db, pE);
90210        pItem->u.x.iOrderByCol = (u16)iCol;
90211        pItem->done = 1;
90212      }else{
90213        moreToDo = 1;
90214      }
90215    }
90216    pSelect = pSelect->pNext;
90217  }
90218  for(i=0; i<pOrderBy->nExpr; i++){
90219    if( pOrderBy->a[i].done==0 ){
90220      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
90221            "column in the result set", i+1);
90222      return 1;
90223    }
90224  }
90225  return 0;
90226}
90227
90228/*
90229** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
90230** the SELECT statement pSelect.  If any term is reference to a
90231** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
90232** field) then convert that term into a copy of the corresponding result set
90233** column.
90234**
90235** If any errors are detected, add an error message to pParse and
90236** return non-zero.  Return zero if no errors are seen.
90237*/
90238SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
90239  Parse *pParse,        /* Parsing context.  Leave error messages here */
90240  Select *pSelect,      /* The SELECT statement containing the clause */
90241  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
90242  const char *zType     /* "ORDER" or "GROUP" */
90243){
90244  int i;
90245  sqlite3 *db = pParse->db;
90246  ExprList *pEList;
90247  struct ExprList_item *pItem;
90248
90249  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
90250#if SQLITE_MAX_COLUMN
90251  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
90252    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
90253    return 1;
90254  }
90255#endif
90256  pEList = pSelect->pEList;
90257  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
90258  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
90259    if( pItem->u.x.iOrderByCol ){
90260      if( pItem->u.x.iOrderByCol>pEList->nExpr ){
90261        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
90262        return 1;
90263      }
90264      resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
90265                   zType,0);
90266    }
90267  }
90268  return 0;
90269}
90270
90271/*
90272** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
90273** The Name context of the SELECT statement is pNC.  zType is either
90274** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
90275**
90276** This routine resolves each term of the clause into an expression.
90277** If the order-by term is an integer I between 1 and N (where N is the
90278** number of columns in the result set of the SELECT) then the expression
90279** in the resolution is a copy of the I-th result-set expression.  If
90280** the order-by term is an identifier that corresponds to the AS-name of
90281** a result-set expression, then the term resolves to a copy of the
90282** result-set expression.  Otherwise, the expression is resolved in
90283** the usual way - using sqlite3ResolveExprNames().
90284**
90285** This routine returns the number of errors.  If errors occur, then
90286** an appropriate error message might be left in pParse.  (OOM errors
90287** excepted.)
90288*/
90289static int resolveOrderGroupBy(
90290  NameContext *pNC,     /* The name context of the SELECT statement */
90291  Select *pSelect,      /* The SELECT statement holding pOrderBy */
90292  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
90293  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
90294){
90295  int i, j;                      /* Loop counters */
90296  int iCol;                      /* Column number */
90297  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
90298  Parse *pParse;                 /* Parsing context */
90299  int nResult;                   /* Number of terms in the result set */
90300
90301  if( pOrderBy==0 ) return 0;
90302  nResult = pSelect->pEList->nExpr;
90303  pParse = pNC->pParse;
90304  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
90305    Expr *pE = pItem->pExpr;
90306    Expr *pE2 = sqlite3ExprSkipCollate(pE);
90307    if( zType[0]!='G' ){
90308      iCol = resolveAsName(pParse, pSelect->pEList, pE2);
90309      if( iCol>0 ){
90310        /* If an AS-name match is found, mark this ORDER BY column as being
90311        ** a copy of the iCol-th result-set column.  The subsequent call to
90312        ** sqlite3ResolveOrderGroupBy() will convert the expression to a
90313        ** copy of the iCol-th result-set expression. */
90314        pItem->u.x.iOrderByCol = (u16)iCol;
90315        continue;
90316      }
90317    }
90318    if( sqlite3ExprIsInteger(pE2, &iCol) ){
90319      /* The ORDER BY term is an integer constant.  Again, set the column
90320      ** number so that sqlite3ResolveOrderGroupBy() will convert the
90321      ** order-by term to a copy of the result-set expression */
90322      if( iCol<1 || iCol>0xffff ){
90323        resolveOutOfRangeError(pParse, zType, i+1, nResult);
90324        return 1;
90325      }
90326      pItem->u.x.iOrderByCol = (u16)iCol;
90327      continue;
90328    }
90329
90330    /* Otherwise, treat the ORDER BY term as an ordinary expression */
90331    pItem->u.x.iOrderByCol = 0;
90332    if( sqlite3ResolveExprNames(pNC, pE) ){
90333      return 1;
90334    }
90335    for(j=0; j<pSelect->pEList->nExpr; j++){
90336      if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
90337        pItem->u.x.iOrderByCol = j+1;
90338      }
90339    }
90340  }
90341  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
90342}
90343
90344/*
90345** Resolve names in the SELECT statement p and all of its descendants.
90346*/
90347static int resolveSelectStep(Walker *pWalker, Select *p){
90348  NameContext *pOuterNC;  /* Context that contains this SELECT */
90349  NameContext sNC;        /* Name context of this SELECT */
90350  int isCompound;         /* True if p is a compound select */
90351  int nCompound;          /* Number of compound terms processed so far */
90352  Parse *pParse;          /* Parsing context */
90353  int i;                  /* Loop counter */
90354  ExprList *pGroupBy;     /* The GROUP BY clause */
90355  Select *pLeftmost;      /* Left-most of SELECT of a compound */
90356  sqlite3 *db;            /* Database connection */
90357
90358
90359  assert( p!=0 );
90360  if( p->selFlags & SF_Resolved ){
90361    return WRC_Prune;
90362  }
90363  pOuterNC = pWalker->u.pNC;
90364  pParse = pWalker->pParse;
90365  db = pParse->db;
90366
90367  /* Normally sqlite3SelectExpand() will be called first and will have
90368  ** already expanded this SELECT.  However, if this is a subquery within
90369  ** an expression, sqlite3ResolveExprNames() will be called without a
90370  ** prior call to sqlite3SelectExpand().  When that happens, let
90371  ** sqlite3SelectPrep() do all of the processing for this SELECT.
90372  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
90373  ** this routine in the correct order.
90374  */
90375  if( (p->selFlags & SF_Expanded)==0 ){
90376    sqlite3SelectPrep(pParse, p, pOuterNC);
90377    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
90378  }
90379
90380  isCompound = p->pPrior!=0;
90381  nCompound = 0;
90382  pLeftmost = p;
90383  while( p ){
90384    assert( (p->selFlags & SF_Expanded)!=0 );
90385    assert( (p->selFlags & SF_Resolved)==0 );
90386    p->selFlags |= SF_Resolved;
90387
90388    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
90389    ** are not allowed to refer to any names, so pass an empty NameContext.
90390    */
90391    memset(&sNC, 0, sizeof(sNC));
90392    sNC.pParse = pParse;
90393    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
90394        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
90395      return WRC_Abort;
90396    }
90397
90398    /* If the SF_Converted flags is set, then this Select object was
90399    ** was created by the convertCompoundSelectToSubquery() function.
90400    ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
90401    ** as if it were part of the sub-query, not the parent. This block
90402    ** moves the pOrderBy down to the sub-query. It will be moved back
90403    ** after the names have been resolved.  */
90404    if( p->selFlags & SF_Converted ){
90405      Select *pSub = p->pSrc->a[0].pSelect;
90406      assert( p->pSrc->nSrc==1 && p->pOrderBy );
90407      assert( pSub->pPrior && pSub->pOrderBy==0 );
90408      pSub->pOrderBy = p->pOrderBy;
90409      p->pOrderBy = 0;
90410    }
90411
90412    /* Recursively resolve names in all subqueries
90413    */
90414    for(i=0; i<p->pSrc->nSrc; i++){
90415      struct SrcList_item *pItem = &p->pSrc->a[i];
90416      if( pItem->pSelect ){
90417        NameContext *pNC;         /* Used to iterate name contexts */
90418        int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
90419        const char *zSavedContext = pParse->zAuthContext;
90420
90421        /* Count the total number of references to pOuterNC and all of its
90422        ** parent contexts. After resolving references to expressions in
90423        ** pItem->pSelect, check if this value has changed. If so, then
90424        ** SELECT statement pItem->pSelect must be correlated. Set the
90425        ** pItem->fg.isCorrelated flag if this is the case. */
90426        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
90427
90428        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
90429        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
90430        pParse->zAuthContext = zSavedContext;
90431        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
90432
90433        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
90434        assert( pItem->fg.isCorrelated==0 && nRef<=0 );
90435        pItem->fg.isCorrelated = (nRef!=0);
90436      }
90437    }
90438
90439    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
90440    ** resolve the result-set expression list.
90441    */
90442    sNC.ncFlags = NC_AllowAgg;
90443    sNC.pSrcList = p->pSrc;
90444    sNC.pNext = pOuterNC;
90445
90446    /* Resolve names in the result set. */
90447    if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
90448
90449    /* If there are no aggregate functions in the result-set, and no GROUP BY
90450    ** expression, do not allow aggregates in any of the other expressions.
90451    */
90452    assert( (p->selFlags & SF_Aggregate)==0 );
90453    pGroupBy = p->pGroupBy;
90454    if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
90455      assert( NC_MinMaxAgg==SF_MinMaxAgg );
90456      p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
90457    }else{
90458      sNC.ncFlags &= ~NC_AllowAgg;
90459    }
90460
90461    /* If a HAVING clause is present, then there must be a GROUP BY clause.
90462    */
90463    if( p->pHaving && !pGroupBy ){
90464      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
90465      return WRC_Abort;
90466    }
90467
90468    /* Add the output column list to the name-context before parsing the
90469    ** other expressions in the SELECT statement. This is so that
90470    ** expressions in the WHERE clause (etc.) can refer to expressions by
90471    ** aliases in the result set.
90472    **
90473    ** Minor point: If this is the case, then the expression will be
90474    ** re-evaluated for each reference to it.
90475    */
90476    sNC.pEList = p->pEList;
90477    if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
90478    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
90479
90480    /* Resolve names in table-valued-function arguments */
90481    for(i=0; i<p->pSrc->nSrc; i++){
90482      struct SrcList_item *pItem = &p->pSrc->a[i];
90483      if( pItem->fg.isTabFunc
90484       && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
90485      ){
90486        return WRC_Abort;
90487      }
90488    }
90489
90490    /* The ORDER BY and GROUP BY clauses may not refer to terms in
90491    ** outer queries
90492    */
90493    sNC.pNext = 0;
90494    sNC.ncFlags |= NC_AllowAgg;
90495
90496    /* If this is a converted compound query, move the ORDER BY clause from
90497    ** the sub-query back to the parent query. At this point each term
90498    ** within the ORDER BY clause has been transformed to an integer value.
90499    ** These integers will be replaced by copies of the corresponding result
90500    ** set expressions by the call to resolveOrderGroupBy() below.  */
90501    if( p->selFlags & SF_Converted ){
90502      Select *pSub = p->pSrc->a[0].pSelect;
90503      p->pOrderBy = pSub->pOrderBy;
90504      pSub->pOrderBy = 0;
90505    }
90506
90507    /* Process the ORDER BY clause for singleton SELECT statements.
90508    ** The ORDER BY clause for compounds SELECT statements is handled
90509    ** below, after all of the result-sets for all of the elements of
90510    ** the compound have been resolved.
90511    **
90512    ** If there is an ORDER BY clause on a term of a compound-select other
90513    ** than the right-most term, then that is a syntax error.  But the error
90514    ** is not detected until much later, and so we need to go ahead and
90515    ** resolve those symbols on the incorrect ORDER BY for consistency.
90516    */
90517    if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
90518     && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
90519    ){
90520      return WRC_Abort;
90521    }
90522    if( db->mallocFailed ){
90523      return WRC_Abort;
90524    }
90525
90526    /* Resolve the GROUP BY clause.  At the same time, make sure
90527    ** the GROUP BY clause does not contain aggregate functions.
90528    */
90529    if( pGroupBy ){
90530      struct ExprList_item *pItem;
90531
90532      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
90533        return WRC_Abort;
90534      }
90535      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
90536        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
90537          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
90538              "the GROUP BY clause");
90539          return WRC_Abort;
90540        }
90541      }
90542    }
90543
90544    /* If this is part of a compound SELECT, check that it has the right
90545    ** number of expressions in the select list. */
90546    if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
90547      sqlite3SelectWrongNumTermsError(pParse, p->pNext);
90548      return WRC_Abort;
90549    }
90550
90551    /* Advance to the next term of the compound
90552    */
90553    p = p->pPrior;
90554    nCompound++;
90555  }
90556
90557  /* Resolve the ORDER BY on a compound SELECT after all terms of
90558  ** the compound have been resolved.
90559  */
90560  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
90561    return WRC_Abort;
90562  }
90563
90564  return WRC_Prune;
90565}
90566
90567/*
90568** This routine walks an expression tree and resolves references to
90569** table columns and result-set columns.  At the same time, do error
90570** checking on function usage and set a flag if any aggregate functions
90571** are seen.
90572**
90573** To resolve table columns references we look for nodes (or subtrees) of the
90574** form X.Y.Z or Y.Z or just Z where
90575**
90576**      X:   The name of a database.  Ex:  "main" or "temp" or
90577**           the symbolic name assigned to an ATTACH-ed database.
90578**
90579**      Y:   The name of a table in a FROM clause.  Or in a trigger
90580**           one of the special names "old" or "new".
90581**
90582**      Z:   The name of a column in table Y.
90583**
90584** The node at the root of the subtree is modified as follows:
90585**
90586**    Expr.op        Changed to TK_COLUMN
90587**    Expr.pTab      Points to the Table object for X.Y
90588**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
90589**    Expr.iTable    The VDBE cursor number for X.Y
90590**
90591**
90592** To resolve result-set references, look for expression nodes of the
90593** form Z (with no X and Y prefix) where the Z matches the right-hand
90594** size of an AS clause in the result-set of a SELECT.  The Z expression
90595** is replaced by a copy of the left-hand side of the result-set expression.
90596** Table-name and function resolution occurs on the substituted expression
90597** tree.  For example, in:
90598**
90599**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
90600**
90601** The "x" term of the order by is replaced by "a+b" to render:
90602**
90603**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
90604**
90605** Function calls are checked to make sure that the function is
90606** defined and that the correct number of arguments are specified.
90607** If the function is an aggregate function, then the NC_HasAgg flag is
90608** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
90609** If an expression contains aggregate functions then the EP_Agg
90610** property on the expression is set.
90611**
90612** An error message is left in pParse if anything is amiss.  The number
90613** if errors is returned.
90614*/
90615SQLITE_PRIVATE int sqlite3ResolveExprNames(
90616  NameContext *pNC,       /* Namespace to resolve expressions in. */
90617  Expr *pExpr             /* The expression to be analyzed. */
90618){
90619  u16 savedHasAgg;
90620  Walker w;
90621
90622  if( pExpr==0 ) return 0;
90623#if SQLITE_MAX_EXPR_DEPTH>0
90624  {
90625    Parse *pParse = pNC->pParse;
90626    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
90627      return 1;
90628    }
90629    pParse->nHeight += pExpr->nHeight;
90630  }
90631#endif
90632  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
90633  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
90634  w.pParse = pNC->pParse;
90635  w.xExprCallback = resolveExprStep;
90636  w.xSelectCallback = resolveSelectStep;
90637  w.xSelectCallback2 = 0;
90638  w.walkerDepth = 0;
90639  w.eCode = 0;
90640  w.u.pNC = pNC;
90641  sqlite3WalkExpr(&w, pExpr);
90642#if SQLITE_MAX_EXPR_DEPTH>0
90643  pNC->pParse->nHeight -= pExpr->nHeight;
90644#endif
90645  if( pNC->nErr>0 || w.pParse->nErr>0 ){
90646    ExprSetProperty(pExpr, EP_Error);
90647  }
90648  if( pNC->ncFlags & NC_HasAgg ){
90649    ExprSetProperty(pExpr, EP_Agg);
90650  }
90651  pNC->ncFlags |= savedHasAgg;
90652  return ExprHasProperty(pExpr, EP_Error);
90653}
90654
90655/*
90656** Resolve all names for all expression in an expression list.  This is
90657** just like sqlite3ResolveExprNames() except that it works for an expression
90658** list rather than a single expression.
90659*/
90660SQLITE_PRIVATE int sqlite3ResolveExprListNames(
90661  NameContext *pNC,       /* Namespace to resolve expressions in. */
90662  ExprList *pList         /* The expression list to be analyzed. */
90663){
90664  int i;
90665  if( pList ){
90666    for(i=0; i<pList->nExpr; i++){
90667      if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
90668    }
90669  }
90670  return WRC_Continue;
90671}
90672
90673/*
90674** Resolve all names in all expressions of a SELECT and in all
90675** decendents of the SELECT, including compounds off of p->pPrior,
90676** subqueries in expressions, and subqueries used as FROM clause
90677** terms.
90678**
90679** See sqlite3ResolveExprNames() for a description of the kinds of
90680** transformations that occur.
90681**
90682** All SELECT statements should have been expanded using
90683** sqlite3SelectExpand() prior to invoking this routine.
90684*/
90685SQLITE_PRIVATE void sqlite3ResolveSelectNames(
90686  Parse *pParse,         /* The parser context */
90687  Select *p,             /* The SELECT statement being coded. */
90688  NameContext *pOuterNC  /* Name context for parent SELECT statement */
90689){
90690  Walker w;
90691
90692  assert( p!=0 );
90693  memset(&w, 0, sizeof(w));
90694  w.xExprCallback = resolveExprStep;
90695  w.xSelectCallback = resolveSelectStep;
90696  w.pParse = pParse;
90697  w.u.pNC = pOuterNC;
90698  sqlite3WalkSelect(&w, p);
90699}
90700
90701/*
90702** Resolve names in expressions that can only reference a single table:
90703**
90704**    *   CHECK constraints
90705**    *   WHERE clauses on partial indices
90706**
90707** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
90708** is set to -1 and the Expr.iColumn value is set to the column number.
90709**
90710** Any errors cause an error message to be set in pParse.
90711*/
90712SQLITE_PRIVATE void sqlite3ResolveSelfReference(
90713  Parse *pParse,      /* Parsing context */
90714  Table *pTab,        /* The table being referenced */
90715  int type,           /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
90716  Expr *pExpr,        /* Expression to resolve.  May be NULL. */
90717  ExprList *pList     /* Expression list to resolve.  May be NUL. */
90718){
90719  SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
90720  NameContext sNC;                /* Name context for pParse->pNewTable */
90721
90722  assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
90723  memset(&sNC, 0, sizeof(sNC));
90724  memset(&sSrc, 0, sizeof(sSrc));
90725  sSrc.nSrc = 1;
90726  sSrc.a[0].zName = pTab->zName;
90727  sSrc.a[0].pTab = pTab;
90728  sSrc.a[0].iCursor = -1;
90729  sNC.pParse = pParse;
90730  sNC.pSrcList = &sSrc;
90731  sNC.ncFlags = type;
90732  if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
90733  if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
90734}
90735
90736/************** End of resolve.c *********************************************/
90737/************** Begin file expr.c ********************************************/
90738/*
90739** 2001 September 15
90740**
90741** The author disclaims copyright to this source code.  In place of
90742** a legal notice, here is a blessing:
90743**
90744**    May you do good and not evil.
90745**    May you find forgiveness for yourself and forgive others.
90746**    May you share freely, never taking more than you give.
90747**
90748*************************************************************************
90749** This file contains routines used for analyzing expressions and
90750** for generating VDBE code that evaluates expressions in SQLite.
90751*/
90752/* #include "sqliteInt.h" */
90753
90754/* Forward declarations */
90755static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
90756static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
90757
90758/*
90759** Return the affinity character for a single column of a table.
90760*/
90761SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
90762  assert( iCol<pTab->nCol );
90763  return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
90764}
90765
90766/*
90767** Return the 'affinity' of the expression pExpr if any.
90768**
90769** If pExpr is a column, a reference to a column via an 'AS' alias,
90770** or a sub-select with a column as the return value, then the
90771** affinity of that column is returned. Otherwise, 0x00 is returned,
90772** indicating no affinity for the expression.
90773**
90774** i.e. the WHERE clause expressions in the following statements all
90775** have an affinity:
90776**
90777** CREATE TABLE t1(a);
90778** SELECT * FROM t1 WHERE a;
90779** SELECT a AS b FROM t1 WHERE b;
90780** SELECT * FROM t1 WHERE (select a from t1);
90781*/
90782SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
90783  int op;
90784  pExpr = sqlite3ExprSkipCollate(pExpr);
90785  if( pExpr->flags & EP_Generic ) return 0;
90786  op = pExpr->op;
90787  if( op==TK_SELECT ){
90788    assert( pExpr->flags&EP_xIsSelect );
90789    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
90790  }
90791  if( op==TK_REGISTER ) op = pExpr->op2;
90792#ifndef SQLITE_OMIT_CAST
90793  if( op==TK_CAST ){
90794    assert( !ExprHasProperty(pExpr, EP_IntValue) );
90795    return sqlite3AffinityType(pExpr->u.zToken, 0);
90796  }
90797#endif
90798  if( op==TK_AGG_COLUMN || op==TK_COLUMN ){
90799    return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
90800  }
90801  if( op==TK_SELECT_COLUMN ){
90802    assert( pExpr->pLeft->flags&EP_xIsSelect );
90803    return sqlite3ExprAffinity(
90804        pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
90805    );
90806  }
90807  return pExpr->affinity;
90808}
90809
90810/*
90811** Set the collating sequence for expression pExpr to be the collating
90812** sequence named by pToken.   Return a pointer to a new Expr node that
90813** implements the COLLATE operator.
90814**
90815** If a memory allocation error occurs, that fact is recorded in pParse->db
90816** and the pExpr parameter is returned unchanged.
90817*/
90818SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
90819  Parse *pParse,           /* Parsing context */
90820  Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
90821  const Token *pCollName,  /* Name of collating sequence */
90822  int dequote              /* True to dequote pCollName */
90823){
90824  if( pCollName->n>0 ){
90825    Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
90826    if( pNew ){
90827      pNew->pLeft = pExpr;
90828      pNew->flags |= EP_Collate|EP_Skip;
90829      pExpr = pNew;
90830    }
90831  }
90832  return pExpr;
90833}
90834SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
90835  Token s;
90836  assert( zC!=0 );
90837  sqlite3TokenInit(&s, (char*)zC);
90838  return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
90839}
90840
90841/*
90842** Skip over any TK_COLLATE operators and any unlikely()
90843** or likelihood() function at the root of an expression.
90844*/
90845SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
90846  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
90847    if( ExprHasProperty(pExpr, EP_Unlikely) ){
90848      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
90849      assert( pExpr->x.pList->nExpr>0 );
90850      assert( pExpr->op==TK_FUNCTION );
90851      pExpr = pExpr->x.pList->a[0].pExpr;
90852    }else{
90853      assert( pExpr->op==TK_COLLATE );
90854      pExpr = pExpr->pLeft;
90855    }
90856  }
90857  return pExpr;
90858}
90859
90860/*
90861** Return the collation sequence for the expression pExpr. If
90862** there is no defined collating sequence, return NULL.
90863**
90864** The collating sequence might be determined by a COLLATE operator
90865** or by the presence of a column with a defined collating sequence.
90866** COLLATE operators take first precedence.  Left operands take
90867** precedence over right operands.
90868*/
90869SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
90870  sqlite3 *db = pParse->db;
90871  CollSeq *pColl = 0;
90872  Expr *p = pExpr;
90873  while( p ){
90874    int op = p->op;
90875    if( p->flags & EP_Generic ) break;
90876    if( op==TK_CAST || op==TK_UPLUS ){
90877      p = p->pLeft;
90878      continue;
90879    }
90880    if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
90881      pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
90882      break;
90883    }
90884    if( (op==TK_AGG_COLUMN || op==TK_COLUMN
90885          || op==TK_REGISTER || op==TK_TRIGGER)
90886     && p->pTab!=0
90887    ){
90888      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
90889      ** a TK_COLUMN but was previously evaluated and cached in a register */
90890      int j = p->iColumn;
90891      if( j>=0 ){
90892        const char *zColl = p->pTab->aCol[j].zColl;
90893        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
90894      }
90895      break;
90896    }
90897    if( p->flags & EP_Collate ){
90898      if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
90899        p = p->pLeft;
90900      }else{
90901        Expr *pNext  = p->pRight;
90902        /* The Expr.x union is never used at the same time as Expr.pRight */
90903        assert( p->x.pList==0 || p->pRight==0 );
90904        /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
90905        ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
90906        ** least one EP_Collate. Thus the following two ALWAYS. */
90907        if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
90908          int i;
90909          for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
90910            if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
90911              pNext = p->x.pList->a[i].pExpr;
90912              break;
90913            }
90914          }
90915        }
90916        p = pNext;
90917      }
90918    }else{
90919      break;
90920    }
90921  }
90922  if( sqlite3CheckCollSeq(pParse, pColl) ){
90923    pColl = 0;
90924  }
90925  return pColl;
90926}
90927
90928/*
90929** pExpr is an operand of a comparison operator.  aff2 is the
90930** type affinity of the other operand.  This routine returns the
90931** type affinity that should be used for the comparison operator.
90932*/
90933SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
90934  char aff1 = sqlite3ExprAffinity(pExpr);
90935  if( aff1 && aff2 ){
90936    /* Both sides of the comparison are columns. If one has numeric
90937    ** affinity, use that. Otherwise use no affinity.
90938    */
90939    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
90940      return SQLITE_AFF_NUMERIC;
90941    }else{
90942      return SQLITE_AFF_BLOB;
90943    }
90944  }else if( !aff1 && !aff2 ){
90945    /* Neither side of the comparison is a column.  Compare the
90946    ** results directly.
90947    */
90948    return SQLITE_AFF_BLOB;
90949  }else{
90950    /* One side is a column, the other is not. Use the columns affinity. */
90951    assert( aff1==0 || aff2==0 );
90952    return (aff1 + aff2);
90953  }
90954}
90955
90956/*
90957** pExpr is a comparison operator.  Return the type affinity that should
90958** be applied to both operands prior to doing the comparison.
90959*/
90960static char comparisonAffinity(Expr *pExpr){
90961  char aff;
90962  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
90963          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
90964          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
90965  assert( pExpr->pLeft );
90966  aff = sqlite3ExprAffinity(pExpr->pLeft);
90967  if( pExpr->pRight ){
90968    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
90969  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
90970    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
90971  }else if( aff==0 ){
90972    aff = SQLITE_AFF_BLOB;
90973  }
90974  return aff;
90975}
90976
90977/*
90978** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
90979** idx_affinity is the affinity of an indexed column. Return true
90980** if the index with affinity idx_affinity may be used to implement
90981** the comparison in pExpr.
90982*/
90983SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
90984  char aff = comparisonAffinity(pExpr);
90985  switch( aff ){
90986    case SQLITE_AFF_BLOB:
90987      return 1;
90988    case SQLITE_AFF_TEXT:
90989      return idx_affinity==SQLITE_AFF_TEXT;
90990    default:
90991      return sqlite3IsNumericAffinity(idx_affinity);
90992  }
90993}
90994
90995/*
90996** Return the P5 value that should be used for a binary comparison
90997** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
90998*/
90999static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
91000  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
91001  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
91002  return aff;
91003}
91004
91005/*
91006** Return a pointer to the collation sequence that should be used by
91007** a binary comparison operator comparing pLeft and pRight.
91008**
91009** If the left hand expression has a collating sequence type, then it is
91010** used. Otherwise the collation sequence for the right hand expression
91011** is used, or the default (BINARY) if neither expression has a collating
91012** type.
91013**
91014** Argument pRight (but not pLeft) may be a null pointer. In this case,
91015** it is not considered.
91016*/
91017SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
91018  Parse *pParse,
91019  Expr *pLeft,
91020  Expr *pRight
91021){
91022  CollSeq *pColl;
91023  assert( pLeft );
91024  if( pLeft->flags & EP_Collate ){
91025    pColl = sqlite3ExprCollSeq(pParse, pLeft);
91026  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
91027    pColl = sqlite3ExprCollSeq(pParse, pRight);
91028  }else{
91029    pColl = sqlite3ExprCollSeq(pParse, pLeft);
91030    if( !pColl ){
91031      pColl = sqlite3ExprCollSeq(pParse, pRight);
91032    }
91033  }
91034  return pColl;
91035}
91036
91037/*
91038** Generate code for a comparison operator.
91039*/
91040static int codeCompare(
91041  Parse *pParse,    /* The parsing (and code generating) context */
91042  Expr *pLeft,      /* The left operand */
91043  Expr *pRight,     /* The right operand */
91044  int opcode,       /* The comparison opcode */
91045  int in1, int in2, /* Register holding operands */
91046  int dest,         /* Jump here if true.  */
91047  int jumpIfNull    /* If true, jump if either operand is NULL */
91048){
91049  int p5;
91050  int addr;
91051  CollSeq *p4;
91052
91053  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
91054  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
91055  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
91056                           (void*)p4, P4_COLLSEQ);
91057  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
91058  return addr;
91059}
91060
91061/*
91062** Return true if expression pExpr is a vector, or false otherwise.
91063**
91064** A vector is defined as any expression that results in two or more
91065** columns of result.  Every TK_VECTOR node is an vector because the
91066** parser will not generate a TK_VECTOR with fewer than two entries.
91067** But a TK_SELECT might be either a vector or a scalar. It is only
91068** considered a vector if it has two or more result columns.
91069*/
91070SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
91071  return sqlite3ExprVectorSize(pExpr)>1;
91072}
91073
91074/*
91075** If the expression passed as the only argument is of type TK_VECTOR
91076** return the number of expressions in the vector. Or, if the expression
91077** is a sub-select, return the number of columns in the sub-select. For
91078** any other type of expression, return 1.
91079*/
91080SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
91081  u8 op = pExpr->op;
91082  if( op==TK_REGISTER ) op = pExpr->op2;
91083  if( op==TK_VECTOR ){
91084    return pExpr->x.pList->nExpr;
91085  }else if( op==TK_SELECT ){
91086    return pExpr->x.pSelect->pEList->nExpr;
91087  }else{
91088    return 1;
91089  }
91090}
91091
91092#ifndef SQLITE_OMIT_SUBQUERY
91093/*
91094** Return a pointer to a subexpression of pVector that is the i-th
91095** column of the vector (numbered starting with 0).  The caller must
91096** ensure that i is within range.
91097**
91098** If pVector is really a scalar (and "scalar" here includes subqueries
91099** that return a single column!) then return pVector unmodified.
91100**
91101** pVector retains ownership of the returned subexpression.
91102**
91103** If the vector is a (SELECT ...) then the expression returned is
91104** just the expression for the i-th term of the result set, and may
91105** not be ready for evaluation because the table cursor has not yet
91106** been positioned.
91107*/
91108SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
91109  assert( i<sqlite3ExprVectorSize(pVector) );
91110  if( sqlite3ExprIsVector(pVector) ){
91111    assert( pVector->op2==0 || pVector->op==TK_REGISTER );
91112    if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
91113      return pVector->x.pSelect->pEList->a[i].pExpr;
91114    }else{
91115      return pVector->x.pList->a[i].pExpr;
91116    }
91117  }
91118  return pVector;
91119}
91120#endif /* !defined(SQLITE_OMIT_SUBQUERY) */
91121
91122#ifndef SQLITE_OMIT_SUBQUERY
91123/*
91124** Compute and return a new Expr object which when passed to
91125** sqlite3ExprCode() will generate all necessary code to compute
91126** the iField-th column of the vector expression pVector.
91127**
91128** It is ok for pVector to be a scalar (as long as iField==0).
91129** In that case, this routine works like sqlite3ExprDup().
91130**
91131** The caller owns the returned Expr object and is responsible for
91132** ensuring that the returned value eventually gets freed.
91133**
91134** The caller retains ownership of pVector.  If pVector is a TK_SELECT,
91135** then the returned object will reference pVector and so pVector must remain
91136** valid for the life of the returned object.  If pVector is a TK_VECTOR
91137** or a scalar expression, then it can be deleted as soon as this routine
91138** returns.
91139**
91140** A trick to cause a TK_SELECT pVector to be deleted together with
91141** the returned Expr object is to attach the pVector to the pRight field
91142** of the returned TK_SELECT_COLUMN Expr object.
91143*/
91144SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
91145  Parse *pParse,       /* Parsing context */
91146  Expr *pVector,       /* The vector.  List of expressions or a sub-SELECT */
91147  int iField           /* Which column of the vector to return */
91148){
91149  Expr *pRet;
91150  if( pVector->op==TK_SELECT ){
91151    assert( pVector->flags & EP_xIsSelect );
91152    /* The TK_SELECT_COLUMN Expr node:
91153    **
91154    ** pLeft:           pVector containing TK_SELECT.  Not deleted.
91155    ** pRight:          not used.  But recursively deleted.
91156    ** iColumn:         Index of a column in pVector
91157    ** iTable:          0 or the number of columns on the LHS of an assignment
91158    ** pLeft->iTable:   First in an array of register holding result, or 0
91159    **                  if the result is not yet computed.
91160    **
91161    ** sqlite3ExprDelete() specifically skips the recursive delete of
91162    ** pLeft on TK_SELECT_COLUMN nodes.  But pRight is followed, so pVector
91163    ** can be attached to pRight to cause this node to take ownership of
91164    ** pVector.  Typically there will be multiple TK_SELECT_COLUMN nodes
91165    ** with the same pLeft pointer to the pVector, but only one of them
91166    ** will own the pVector.
91167    */
91168    pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
91169    if( pRet ){
91170      pRet->iColumn = iField;
91171      pRet->pLeft = pVector;
91172    }
91173    assert( pRet==0 || pRet->iTable==0 );
91174  }else{
91175    if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
91176    pRet = sqlite3ExprDup(pParse->db, pVector, 0);
91177  }
91178  return pRet;
91179}
91180#endif /* !define(SQLITE_OMIT_SUBQUERY) */
91181
91182/*
91183** If expression pExpr is of type TK_SELECT, generate code to evaluate
91184** it. Return the register in which the result is stored (or, if the
91185** sub-select returns more than one column, the first in an array
91186** of registers in which the result is stored).
91187**
91188** If pExpr is not a TK_SELECT expression, return 0.
91189*/
91190static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
91191  int reg = 0;
91192#ifndef SQLITE_OMIT_SUBQUERY
91193  if( pExpr->op==TK_SELECT ){
91194    reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
91195  }
91196#endif
91197  return reg;
91198}
91199
91200/*
91201** Argument pVector points to a vector expression - either a TK_VECTOR
91202** or TK_SELECT that returns more than one column. This function returns
91203** the register number of a register that contains the value of
91204** element iField of the vector.
91205**
91206** If pVector is a TK_SELECT expression, then code for it must have
91207** already been generated using the exprCodeSubselect() routine. In this
91208** case parameter regSelect should be the first in an array of registers
91209** containing the results of the sub-select.
91210**
91211** If pVector is of type TK_VECTOR, then code for the requested field
91212** is generated. In this case (*pRegFree) may be set to the number of
91213** a temporary register to be freed by the caller before returning.
91214**
91215** Before returning, output parameter (*ppExpr) is set to point to the
91216** Expr object corresponding to element iElem of the vector.
91217*/
91218static int exprVectorRegister(
91219  Parse *pParse,                  /* Parse context */
91220  Expr *pVector,                  /* Vector to extract element from */
91221  int iField,                     /* Field to extract from pVector */
91222  int regSelect,                  /* First in array of registers */
91223  Expr **ppExpr,                  /* OUT: Expression element */
91224  int *pRegFree                   /* OUT: Temp register to free */
91225){
91226  u8 op = pVector->op;
91227  assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
91228  if( op==TK_REGISTER ){
91229    *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
91230    return pVector->iTable+iField;
91231  }
91232  if( op==TK_SELECT ){
91233    *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
91234     return regSelect+iField;
91235  }
91236  *ppExpr = pVector->x.pList->a[iField].pExpr;
91237  return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
91238}
91239
91240/*
91241** Expression pExpr is a comparison between two vector values. Compute
91242** the result of the comparison (1, 0, or NULL) and write that
91243** result into register dest.
91244**
91245** The caller must satisfy the following preconditions:
91246**
91247**    if pExpr->op==TK_IS:      op==TK_EQ and p5==SQLITE_NULLEQ
91248**    if pExpr->op==TK_ISNOT:   op==TK_NE and p5==SQLITE_NULLEQ
91249**    otherwise:                op==pExpr->op and p5==0
91250*/
91251static void codeVectorCompare(
91252  Parse *pParse,        /* Code generator context */
91253  Expr *pExpr,          /* The comparison operation */
91254  int dest,             /* Write results into this register */
91255  u8 op,                /* Comparison operator */
91256  u8 p5                 /* SQLITE_NULLEQ or zero */
91257){
91258  Vdbe *v = pParse->pVdbe;
91259  Expr *pLeft = pExpr->pLeft;
91260  Expr *pRight = pExpr->pRight;
91261  int nLeft = sqlite3ExprVectorSize(pLeft);
91262  int i;
91263  int regLeft = 0;
91264  int regRight = 0;
91265  u8 opx = op;
91266  int addrDone = sqlite3VdbeMakeLabel(v);
91267
91268  if( nLeft!=sqlite3ExprVectorSize(pRight) ){
91269    sqlite3ErrorMsg(pParse, "row value misused");
91270    return;
91271  }
91272  assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
91273       || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
91274       || pExpr->op==TK_LT || pExpr->op==TK_GT
91275       || pExpr->op==TK_LE || pExpr->op==TK_GE
91276  );
91277  assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
91278            || (pExpr->op==TK_ISNOT && op==TK_NE) );
91279  assert( p5==0 || pExpr->op!=op );
91280  assert( p5==SQLITE_NULLEQ || pExpr->op==op );
91281
91282  p5 |= SQLITE_STOREP2;
91283  if( opx==TK_LE ) opx = TK_LT;
91284  if( opx==TK_GE ) opx = TK_GT;
91285
91286  regLeft = exprCodeSubselect(pParse, pLeft);
91287  regRight = exprCodeSubselect(pParse, pRight);
91288
91289  for(i=0; 1 /*Loop exits by "break"*/; i++){
91290    int regFree1 = 0, regFree2 = 0;
91291    Expr *pL, *pR;
91292    int r1, r2;
91293    assert( i>=0 && i<nLeft );
91294    if( i>0 ) sqlite3ExprCachePush(pParse);
91295    r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
91296    r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
91297    codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
91298    testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
91299    testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
91300    testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
91301    testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
91302    testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
91303    testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
91304    sqlite3ReleaseTempReg(pParse, regFree1);
91305    sqlite3ReleaseTempReg(pParse, regFree2);
91306    if( i>0 ) sqlite3ExprCachePop(pParse);
91307    if( i==nLeft-1 ){
91308      break;
91309    }
91310    if( opx==TK_EQ ){
91311      sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
91312      p5 |= SQLITE_KEEPNULL;
91313    }else if( opx==TK_NE ){
91314      sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
91315      p5 |= SQLITE_KEEPNULL;
91316    }else{
91317      assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
91318      sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
91319      VdbeCoverageIf(v, op==TK_LT);
91320      VdbeCoverageIf(v, op==TK_GT);
91321      VdbeCoverageIf(v, op==TK_LE);
91322      VdbeCoverageIf(v, op==TK_GE);
91323      if( i==nLeft-2 ) opx = op;
91324    }
91325  }
91326  sqlite3VdbeResolveLabel(v, addrDone);
91327}
91328
91329#if SQLITE_MAX_EXPR_DEPTH>0
91330/*
91331** Check that argument nHeight is less than or equal to the maximum
91332** expression depth allowed. If it is not, leave an error message in
91333** pParse.
91334*/
91335SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
91336  int rc = SQLITE_OK;
91337  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
91338  if( nHeight>mxHeight ){
91339    sqlite3ErrorMsg(pParse,
91340       "Expression tree is too large (maximum depth %d)", mxHeight
91341    );
91342    rc = SQLITE_ERROR;
91343  }
91344  return rc;
91345}
91346
91347/* The following three functions, heightOfExpr(), heightOfExprList()
91348** and heightOfSelect(), are used to determine the maximum height
91349** of any expression tree referenced by the structure passed as the
91350** first argument.
91351**
91352** If this maximum height is greater than the current value pointed
91353** to by pnHeight, the second parameter, then set *pnHeight to that
91354** value.
91355*/
91356static void heightOfExpr(Expr *p, int *pnHeight){
91357  if( p ){
91358    if( p->nHeight>*pnHeight ){
91359      *pnHeight = p->nHeight;
91360    }
91361  }
91362}
91363static void heightOfExprList(ExprList *p, int *pnHeight){
91364  if( p ){
91365    int i;
91366    for(i=0; i<p->nExpr; i++){
91367      heightOfExpr(p->a[i].pExpr, pnHeight);
91368    }
91369  }
91370}
91371static void heightOfSelect(Select *p, int *pnHeight){
91372  if( p ){
91373    heightOfExpr(p->pWhere, pnHeight);
91374    heightOfExpr(p->pHaving, pnHeight);
91375    heightOfExpr(p->pLimit, pnHeight);
91376    heightOfExpr(p->pOffset, pnHeight);
91377    heightOfExprList(p->pEList, pnHeight);
91378    heightOfExprList(p->pGroupBy, pnHeight);
91379    heightOfExprList(p->pOrderBy, pnHeight);
91380    heightOfSelect(p->pPrior, pnHeight);
91381  }
91382}
91383
91384/*
91385** Set the Expr.nHeight variable in the structure passed as an
91386** argument. An expression with no children, Expr.pList or
91387** Expr.pSelect member has a height of 1. Any other expression
91388** has a height equal to the maximum height of any other
91389** referenced Expr plus one.
91390**
91391** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
91392** if appropriate.
91393*/
91394static void exprSetHeight(Expr *p){
91395  int nHeight = 0;
91396  heightOfExpr(p->pLeft, &nHeight);
91397  heightOfExpr(p->pRight, &nHeight);
91398  if( ExprHasProperty(p, EP_xIsSelect) ){
91399    heightOfSelect(p->x.pSelect, &nHeight);
91400  }else if( p->x.pList ){
91401    heightOfExprList(p->x.pList, &nHeight);
91402    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
91403  }
91404  p->nHeight = nHeight + 1;
91405}
91406
91407/*
91408** Set the Expr.nHeight variable using the exprSetHeight() function. If
91409** the height is greater than the maximum allowed expression depth,
91410** leave an error in pParse.
91411**
91412** Also propagate all EP_Propagate flags from the Expr.x.pList into
91413** Expr.flags.
91414*/
91415SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
91416  if( pParse->nErr ) return;
91417  exprSetHeight(p);
91418  sqlite3ExprCheckHeight(pParse, p->nHeight);
91419}
91420
91421/*
91422** Return the maximum height of any expression tree referenced
91423** by the select statement passed as an argument.
91424*/
91425SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
91426  int nHeight = 0;
91427  heightOfSelect(p, &nHeight);
91428  return nHeight;
91429}
91430#else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
91431/*
91432** Propagate all EP_Propagate flags from the Expr.x.pList into
91433** Expr.flags.
91434*/
91435SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
91436  if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
91437    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
91438  }
91439}
91440#define exprSetHeight(y)
91441#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
91442
91443/*
91444** This routine is the core allocator for Expr nodes.
91445**
91446** Construct a new expression node and return a pointer to it.  Memory
91447** for this node and for the pToken argument is a single allocation
91448** obtained from sqlite3DbMalloc().  The calling function
91449** is responsible for making sure the node eventually gets freed.
91450**
91451** If dequote is true, then the token (if it exists) is dequoted.
91452** If dequote is false, no dequoting is performed.  The deQuote
91453** parameter is ignored if pToken is NULL or if the token does not
91454** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
91455** then the EP_DblQuoted flag is set on the expression node.
91456**
91457** Special case:  If op==TK_INTEGER and pToken points to a string that
91458** can be translated into a 32-bit integer, then the token is not
91459** stored in u.zToken.  Instead, the integer values is written
91460** into u.iValue and the EP_IntValue flag is set.  No extra storage
91461** is allocated to hold the integer text and the dequote flag is ignored.
91462*/
91463SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
91464  sqlite3 *db,            /* Handle for sqlite3DbMallocRawNN() */
91465  int op,                 /* Expression opcode */
91466  const Token *pToken,    /* Token argument.  Might be NULL */
91467  int dequote             /* True to dequote */
91468){
91469  Expr *pNew;
91470  int nExtra = 0;
91471  int iValue = 0;
91472
91473  assert( db!=0 );
91474  if( pToken ){
91475    if( op!=TK_INTEGER || pToken->z==0
91476          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
91477      nExtra = pToken->n+1;
91478      assert( iValue>=0 );
91479    }
91480  }
91481  pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
91482  if( pNew ){
91483    memset(pNew, 0, sizeof(Expr));
91484    pNew->op = (u8)op;
91485    pNew->iAgg = -1;
91486    if( pToken ){
91487      if( nExtra==0 ){
91488        pNew->flags |= EP_IntValue;
91489        pNew->u.iValue = iValue;
91490      }else{
91491        pNew->u.zToken = (char*)&pNew[1];
91492        assert( pToken->z!=0 || pToken->n==0 );
91493        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
91494        pNew->u.zToken[pToken->n] = 0;
91495        if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
91496          if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
91497          sqlite3Dequote(pNew->u.zToken);
91498        }
91499      }
91500    }
91501#if SQLITE_MAX_EXPR_DEPTH>0
91502    pNew->nHeight = 1;
91503#endif
91504  }
91505  return pNew;
91506}
91507
91508/*
91509** Allocate a new expression node from a zero-terminated token that has
91510** already been dequoted.
91511*/
91512SQLITE_PRIVATE Expr *sqlite3Expr(
91513  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
91514  int op,                 /* Expression opcode */
91515  const char *zToken      /* Token argument.  Might be NULL */
91516){
91517  Token x;
91518  x.z = zToken;
91519  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
91520  return sqlite3ExprAlloc(db, op, &x, 0);
91521}
91522
91523/*
91524** Attach subtrees pLeft and pRight to the Expr node pRoot.
91525**
91526** If pRoot==NULL that means that a memory allocation error has occurred.
91527** In that case, delete the subtrees pLeft and pRight.
91528*/
91529SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
91530  sqlite3 *db,
91531  Expr *pRoot,
91532  Expr *pLeft,
91533  Expr *pRight
91534){
91535  if( pRoot==0 ){
91536    assert( db->mallocFailed );
91537    sqlite3ExprDelete(db, pLeft);
91538    sqlite3ExprDelete(db, pRight);
91539  }else{
91540    if( pRight ){
91541      pRoot->pRight = pRight;
91542      pRoot->flags |= EP_Propagate & pRight->flags;
91543    }
91544    if( pLeft ){
91545      pRoot->pLeft = pLeft;
91546      pRoot->flags |= EP_Propagate & pLeft->flags;
91547    }
91548    exprSetHeight(pRoot);
91549  }
91550}
91551
91552/*
91553** Allocate an Expr node which joins as many as two subtrees.
91554**
91555** One or both of the subtrees can be NULL.  Return a pointer to the new
91556** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
91557** free the subtrees and return NULL.
91558*/
91559SQLITE_PRIVATE Expr *sqlite3PExpr(
91560  Parse *pParse,          /* Parsing context */
91561  int op,                 /* Expression opcode */
91562  Expr *pLeft,            /* Left operand */
91563  Expr *pRight            /* Right operand */
91564){
91565  Expr *p;
91566  if( op==TK_AND && pParse->nErr==0 ){
91567    /* Take advantage of short-circuit false optimization for AND */
91568    p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
91569  }else{
91570    p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
91571    if( p ){
91572      memset(p, 0, sizeof(Expr));
91573      p->op = op & TKFLG_MASK;
91574      p->iAgg = -1;
91575    }
91576    sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
91577  }
91578  if( p ) {
91579    sqlite3ExprCheckHeight(pParse, p->nHeight);
91580  }
91581  return p;
91582}
91583
91584/*
91585** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
91586** do a memory allocation failure) then delete the pSelect object.
91587*/
91588SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
91589  if( pExpr ){
91590    pExpr->x.pSelect = pSelect;
91591    ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
91592    sqlite3ExprSetHeightAndFlags(pParse, pExpr);
91593  }else{
91594    assert( pParse->db->mallocFailed );
91595    sqlite3SelectDelete(pParse->db, pSelect);
91596  }
91597}
91598
91599
91600/*
91601** If the expression is always either TRUE or FALSE (respectively),
91602** then return 1.  If one cannot determine the truth value of the
91603** expression at compile-time return 0.
91604**
91605** This is an optimization.  If is OK to return 0 here even if
91606** the expression really is always false or false (a false negative).
91607** But it is a bug to return 1 if the expression might have different
91608** boolean values in different circumstances (a false positive.)
91609**
91610** Note that if the expression is part of conditional for a
91611** LEFT JOIN, then we cannot determine at compile-time whether or not
91612** is it true or false, so always return 0.
91613*/
91614static int exprAlwaysTrue(Expr *p){
91615  int v = 0;
91616  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
91617  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
91618  return v!=0;
91619}
91620static int exprAlwaysFalse(Expr *p){
91621  int v = 0;
91622  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
91623  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
91624  return v==0;
91625}
91626
91627/*
91628** Join two expressions using an AND operator.  If either expression is
91629** NULL, then just return the other expression.
91630**
91631** If one side or the other of the AND is known to be false, then instead
91632** of returning an AND expression, just return a constant expression with
91633** a value of false.
91634*/
91635SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
91636  if( pLeft==0 ){
91637    return pRight;
91638  }else if( pRight==0 ){
91639    return pLeft;
91640  }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
91641    sqlite3ExprDelete(db, pLeft);
91642    sqlite3ExprDelete(db, pRight);
91643    return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
91644  }else{
91645    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
91646    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
91647    return pNew;
91648  }
91649}
91650
91651/*
91652** Construct a new expression node for a function with multiple
91653** arguments.
91654*/
91655SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
91656  Expr *pNew;
91657  sqlite3 *db = pParse->db;
91658  assert( pToken );
91659  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
91660  if( pNew==0 ){
91661    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
91662    return 0;
91663  }
91664  pNew->x.pList = pList;
91665  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
91666  sqlite3ExprSetHeightAndFlags(pParse, pNew);
91667  return pNew;
91668}
91669
91670/*
91671** Assign a variable number to an expression that encodes a wildcard
91672** in the original SQL statement.
91673**
91674** Wildcards consisting of a single "?" are assigned the next sequential
91675** variable number.
91676**
91677** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
91678** sure "nnn" is not too big to avoid a denial of service attack when
91679** the SQL statement comes from an external source.
91680**
91681** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
91682** as the previous instance of the same wildcard.  Or if this is the first
91683** instance of the wildcard, the next sequential variable number is
91684** assigned.
91685*/
91686SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
91687  sqlite3 *db = pParse->db;
91688  const char *z;
91689  ynVar x;
91690
91691  if( pExpr==0 ) return;
91692  assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
91693  z = pExpr->u.zToken;
91694  assert( z!=0 );
91695  assert( z[0]!=0 );
91696  assert( n==sqlite3Strlen30(z) );
91697  if( z[1]==0 ){
91698    /* Wildcard of the form "?".  Assign the next variable number */
91699    assert( z[0]=='?' );
91700    x = (ynVar)(++pParse->nVar);
91701  }else{
91702    int doAdd = 0;
91703    if( z[0]=='?' ){
91704      /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
91705      ** use it as the variable number */
91706      i64 i;
91707      int bOk;
91708      if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
91709        i = z[1]-'0';  /* The common case of ?N for a single digit N */
91710        bOk = 1;
91711      }else{
91712        bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
91713      }
91714      testcase( i==0 );
91715      testcase( i==1 );
91716      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
91717      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
91718      if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
91719        sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
91720            db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
91721        return;
91722      }
91723      x = (ynVar)i;
91724      if( x>pParse->nVar ){
91725        pParse->nVar = (int)x;
91726        doAdd = 1;
91727      }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
91728        doAdd = 1;
91729      }
91730    }else{
91731      /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
91732      ** number as the prior appearance of the same name, or if the name
91733      ** has never appeared before, reuse the same variable number
91734      */
91735      x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
91736      if( x==0 ){
91737        x = (ynVar)(++pParse->nVar);
91738        doAdd = 1;
91739      }
91740    }
91741    if( doAdd ){
91742      pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
91743    }
91744  }
91745  pExpr->iColumn = x;
91746  if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
91747    sqlite3ErrorMsg(pParse, "too many SQL variables");
91748  }
91749}
91750
91751/*
91752** Recursively delete an expression tree.
91753*/
91754static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
91755  assert( p!=0 );
91756  /* Sanity check: Assert that the IntValue is non-negative if it exists */
91757  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
91758#ifdef SQLITE_DEBUG
91759  if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
91760    assert( p->pLeft==0 );
91761    assert( p->pRight==0 );
91762    assert( p->x.pSelect==0 );
91763  }
91764#endif
91765  if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
91766    /* The Expr.x union is never used at the same time as Expr.pRight */
91767    assert( p->x.pList==0 || p->pRight==0 );
91768    if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
91769    sqlite3ExprDelete(db, p->pRight);
91770    if( ExprHasProperty(p, EP_xIsSelect) ){
91771      sqlite3SelectDelete(db, p->x.pSelect);
91772    }else{
91773      sqlite3ExprListDelete(db, p->x.pList);
91774    }
91775  }
91776  if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
91777  if( !ExprHasProperty(p, EP_Static) ){
91778    sqlite3DbFree(db, p);
91779  }
91780}
91781SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
91782  if( p ) sqlite3ExprDeleteNN(db, p);
91783}
91784
91785/*
91786** Return the number of bytes allocated for the expression structure
91787** passed as the first argument. This is always one of EXPR_FULLSIZE,
91788** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
91789*/
91790static int exprStructSize(Expr *p){
91791  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
91792  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
91793  return EXPR_FULLSIZE;
91794}
91795
91796/*
91797** The dupedExpr*Size() routines each return the number of bytes required
91798** to store a copy of an expression or expression tree.  They differ in
91799** how much of the tree is measured.
91800**
91801**     dupedExprStructSize()     Size of only the Expr structure
91802**     dupedExprNodeSize()       Size of Expr + space for token
91803**     dupedExprSize()           Expr + token + subtree components
91804**
91805***************************************************************************
91806**
91807** The dupedExprStructSize() function returns two values OR-ed together:
91808** (1) the space required for a copy of the Expr structure only and
91809** (2) the EP_xxx flags that indicate what the structure size should be.
91810** The return values is always one of:
91811**
91812**      EXPR_FULLSIZE
91813**      EXPR_REDUCEDSIZE   | EP_Reduced
91814**      EXPR_TOKENONLYSIZE | EP_TokenOnly
91815**
91816** The size of the structure can be found by masking the return value
91817** of this routine with 0xfff.  The flags can be found by masking the
91818** return value with EP_Reduced|EP_TokenOnly.
91819**
91820** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
91821** (unreduced) Expr objects as they or originally constructed by the parser.
91822** During expression analysis, extra information is computed and moved into
91823** later parts of teh Expr object and that extra information might get chopped
91824** off if the expression is reduced.  Note also that it does not work to
91825** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
91826** to reduce a pristine expression tree from the parser.  The implementation
91827** of dupedExprStructSize() contain multiple assert() statements that attempt
91828** to enforce this constraint.
91829*/
91830static int dupedExprStructSize(Expr *p, int flags){
91831  int nSize;
91832  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
91833  assert( EXPR_FULLSIZE<=0xfff );
91834  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
91835  if( 0==flags || p->op==TK_SELECT_COLUMN ){
91836    nSize = EXPR_FULLSIZE;
91837  }else{
91838    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
91839    assert( !ExprHasProperty(p, EP_FromJoin) );
91840    assert( !ExprHasProperty(p, EP_MemToken) );
91841    assert( !ExprHasProperty(p, EP_NoReduce) );
91842    if( p->pLeft || p->x.pList ){
91843      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
91844    }else{
91845      assert( p->pRight==0 );
91846      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
91847    }
91848  }
91849  return nSize;
91850}
91851
91852/*
91853** This function returns the space in bytes required to store the copy
91854** of the Expr structure and a copy of the Expr.u.zToken string (if that
91855** string is defined.)
91856*/
91857static int dupedExprNodeSize(Expr *p, int flags){
91858  int nByte = dupedExprStructSize(p, flags) & 0xfff;
91859  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
91860    nByte += sqlite3Strlen30(p->u.zToken)+1;
91861  }
91862  return ROUND8(nByte);
91863}
91864
91865/*
91866** Return the number of bytes required to create a duplicate of the
91867** expression passed as the first argument. The second argument is a
91868** mask containing EXPRDUP_XXX flags.
91869**
91870** The value returned includes space to create a copy of the Expr struct
91871** itself and the buffer referred to by Expr.u.zToken, if any.
91872**
91873** If the EXPRDUP_REDUCE flag is set, then the return value includes
91874** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
91875** and Expr.pRight variables (but not for any structures pointed to or
91876** descended from the Expr.x.pList or Expr.x.pSelect variables).
91877*/
91878static int dupedExprSize(Expr *p, int flags){
91879  int nByte = 0;
91880  if( p ){
91881    nByte = dupedExprNodeSize(p, flags);
91882    if( flags&EXPRDUP_REDUCE ){
91883      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
91884    }
91885  }
91886  return nByte;
91887}
91888
91889/*
91890** This function is similar to sqlite3ExprDup(), except that if pzBuffer
91891** is not NULL then *pzBuffer is assumed to point to a buffer large enough
91892** to store the copy of expression p, the copies of p->u.zToken
91893** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
91894** if any. Before returning, *pzBuffer is set to the first byte past the
91895** portion of the buffer copied into by this function.
91896*/
91897static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
91898  Expr *pNew;           /* Value to return */
91899  u8 *zAlloc;           /* Memory space from which to build Expr object */
91900  u32 staticFlag;       /* EP_Static if space not obtained from malloc */
91901
91902  assert( db!=0 );
91903  assert( p );
91904  assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
91905  assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
91906
91907  /* Figure out where to write the new Expr structure. */
91908  if( pzBuffer ){
91909    zAlloc = *pzBuffer;
91910    staticFlag = EP_Static;
91911  }else{
91912    zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
91913    staticFlag = 0;
91914  }
91915  pNew = (Expr *)zAlloc;
91916
91917  if( pNew ){
91918    /* Set nNewSize to the size allocated for the structure pointed to
91919    ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
91920    ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
91921    ** by the copy of the p->u.zToken string (if any).
91922    */
91923    const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
91924    const int nNewSize = nStructSize & 0xfff;
91925    int nToken;
91926    if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
91927      nToken = sqlite3Strlen30(p->u.zToken) + 1;
91928    }else{
91929      nToken = 0;
91930    }
91931    if( dupFlags ){
91932      assert( ExprHasProperty(p, EP_Reduced)==0 );
91933      memcpy(zAlloc, p, nNewSize);
91934    }else{
91935      u32 nSize = (u32)exprStructSize(p);
91936      memcpy(zAlloc, p, nSize);
91937      if( nSize<EXPR_FULLSIZE ){
91938        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
91939      }
91940    }
91941
91942    /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
91943    pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
91944    pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
91945    pNew->flags |= staticFlag;
91946
91947    /* Copy the p->u.zToken string, if any. */
91948    if( nToken ){
91949      char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
91950      memcpy(zToken, p->u.zToken, nToken);
91951    }
91952
91953    if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
91954      /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
91955      if( ExprHasProperty(p, EP_xIsSelect) ){
91956        pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
91957      }else{
91958        pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
91959      }
91960    }
91961
91962    /* Fill in pNew->pLeft and pNew->pRight. */
91963    if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
91964      zAlloc += dupedExprNodeSize(p, dupFlags);
91965      if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
91966        pNew->pLeft = p->pLeft ?
91967                      exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
91968        pNew->pRight = p->pRight ?
91969                       exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
91970      }
91971      if( pzBuffer ){
91972        *pzBuffer = zAlloc;
91973      }
91974    }else{
91975      if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
91976        if( pNew->op==TK_SELECT_COLUMN ){
91977          pNew->pLeft = p->pLeft;
91978          assert( p->iColumn==0 || p->pRight==0 );
91979          assert( p->pRight==0  || p->pRight==p->pLeft );
91980        }else{
91981          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
91982        }
91983        pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
91984      }
91985    }
91986  }
91987  return pNew;
91988}
91989
91990/*
91991** Create and return a deep copy of the object passed as the second
91992** argument. If an OOM condition is encountered, NULL is returned
91993** and the db->mallocFailed flag set.
91994*/
91995#ifndef SQLITE_OMIT_CTE
91996static With *withDup(sqlite3 *db, With *p){
91997  With *pRet = 0;
91998  if( p ){
91999    int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
92000    pRet = sqlite3DbMallocZero(db, nByte);
92001    if( pRet ){
92002      int i;
92003      pRet->nCte = p->nCte;
92004      for(i=0; i<p->nCte; i++){
92005        pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
92006        pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
92007        pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
92008      }
92009    }
92010  }
92011  return pRet;
92012}
92013#else
92014# define withDup(x,y) 0
92015#endif
92016
92017/*
92018** The following group of routines make deep copies of expressions,
92019** expression lists, ID lists, and select statements.  The copies can
92020** be deleted (by being passed to their respective ...Delete() routines)
92021** without effecting the originals.
92022**
92023** The expression list, ID, and source lists return by sqlite3ExprListDup(),
92024** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
92025** by subsequent calls to sqlite*ListAppend() routines.
92026**
92027** Any tables that the SrcList might point to are not duplicated.
92028**
92029** The flags parameter contains a combination of the EXPRDUP_XXX flags.
92030** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
92031** truncated version of the usual Expr structure that will be stored as
92032** part of the in-memory representation of the database schema.
92033*/
92034SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
92035  assert( flags==0 || flags==EXPRDUP_REDUCE );
92036  return p ? exprDup(db, p, flags, 0) : 0;
92037}
92038SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
92039  ExprList *pNew;
92040  struct ExprList_item *pItem, *pOldItem;
92041  int i;
92042  Expr *pPriorSelectCol = 0;
92043  assert( db!=0 );
92044  if( p==0 ) return 0;
92045  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
92046  if( pNew==0 ) return 0;
92047  pNew->nExpr = i = p->nExpr;
92048  if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
92049  pNew->a = pItem = sqlite3DbMallocRawNN(db,  i*sizeof(p->a[0]) );
92050  if( pItem==0 ){
92051    sqlite3DbFree(db, pNew);
92052    return 0;
92053  }
92054  pOldItem = p->a;
92055  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
92056    Expr *pOldExpr = pOldItem->pExpr;
92057    Expr *pNewExpr;
92058    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
92059    if( pOldExpr
92060     && pOldExpr->op==TK_SELECT_COLUMN
92061     && (pNewExpr = pItem->pExpr)!=0
92062    ){
92063      assert( pNewExpr->iColumn==0 || i>0 );
92064      if( pNewExpr->iColumn==0 ){
92065        assert( pOldExpr->pLeft==pOldExpr->pRight );
92066        pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
92067      }else{
92068        assert( i>0 );
92069        assert( pItem[-1].pExpr!=0 );
92070        assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
92071        assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
92072        pNewExpr->pLeft = pPriorSelectCol;
92073      }
92074    }
92075    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
92076    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
92077    pItem->sortOrder = pOldItem->sortOrder;
92078    pItem->done = 0;
92079    pItem->bSpanIsTab = pOldItem->bSpanIsTab;
92080    pItem->u = pOldItem->u;
92081  }
92082  return pNew;
92083}
92084
92085/*
92086** If cursors, triggers, views and subqueries are all omitted from
92087** the build, then none of the following routines, except for
92088** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
92089** called with a NULL argument.
92090*/
92091#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
92092 || !defined(SQLITE_OMIT_SUBQUERY)
92093SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
92094  SrcList *pNew;
92095  int i;
92096  int nByte;
92097  assert( db!=0 );
92098  if( p==0 ) return 0;
92099  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
92100  pNew = sqlite3DbMallocRawNN(db, nByte );
92101  if( pNew==0 ) return 0;
92102  pNew->nSrc = pNew->nAlloc = p->nSrc;
92103  for(i=0; i<p->nSrc; i++){
92104    struct SrcList_item *pNewItem = &pNew->a[i];
92105    struct SrcList_item *pOldItem = &p->a[i];
92106    Table *pTab;
92107    pNewItem->pSchema = pOldItem->pSchema;
92108    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
92109    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
92110    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
92111    pNewItem->fg = pOldItem->fg;
92112    pNewItem->iCursor = pOldItem->iCursor;
92113    pNewItem->addrFillSub = pOldItem->addrFillSub;
92114    pNewItem->regReturn = pOldItem->regReturn;
92115    if( pNewItem->fg.isIndexedBy ){
92116      pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
92117    }
92118    pNewItem->pIBIndex = pOldItem->pIBIndex;
92119    if( pNewItem->fg.isTabFunc ){
92120      pNewItem->u1.pFuncArg =
92121          sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
92122    }
92123    pTab = pNewItem->pTab = pOldItem->pTab;
92124    if( pTab ){
92125      pTab->nTabRef++;
92126    }
92127    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
92128    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
92129    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
92130    pNewItem->colUsed = pOldItem->colUsed;
92131  }
92132  return pNew;
92133}
92134SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
92135  IdList *pNew;
92136  int i;
92137  assert( db!=0 );
92138  if( p==0 ) return 0;
92139  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
92140  if( pNew==0 ) return 0;
92141  pNew->nId = p->nId;
92142  pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
92143  if( pNew->a==0 ){
92144    sqlite3DbFree(db, pNew);
92145    return 0;
92146  }
92147  /* Note that because the size of the allocation for p->a[] is not
92148  ** necessarily a power of two, sqlite3IdListAppend() may not be called
92149  ** on the duplicate created by this function. */
92150  for(i=0; i<p->nId; i++){
92151    struct IdList_item *pNewItem = &pNew->a[i];
92152    struct IdList_item *pOldItem = &p->a[i];
92153    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
92154    pNewItem->idx = pOldItem->idx;
92155  }
92156  return pNew;
92157}
92158SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
92159  Select *pRet = 0;
92160  Select *pNext = 0;
92161  Select **pp = &pRet;
92162  Select *p;
92163
92164  assert( db!=0 );
92165  for(p=pDup; p; p=p->pPrior){
92166    Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
92167    if( pNew==0 ) break;
92168    pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
92169    pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
92170    pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
92171    pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
92172    pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
92173    pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
92174    pNew->op = p->op;
92175    pNew->pNext = pNext;
92176    pNew->pPrior = 0;
92177    pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
92178    pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
92179    pNew->iLimit = 0;
92180    pNew->iOffset = 0;
92181    pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
92182    pNew->addrOpenEphm[0] = -1;
92183    pNew->addrOpenEphm[1] = -1;
92184    pNew->nSelectRow = p->nSelectRow;
92185    pNew->pWith = withDup(db, p->pWith);
92186    sqlite3SelectSetName(pNew, p->zSelName);
92187    *pp = pNew;
92188    pp = &pNew->pPrior;
92189    pNext = pNew;
92190  }
92191
92192  return pRet;
92193}
92194#else
92195SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
92196  assert( p==0 );
92197  return 0;
92198}
92199#endif
92200
92201
92202/*
92203** Add a new element to the end of an expression list.  If pList is
92204** initially NULL, then create a new expression list.
92205**
92206** If a memory allocation error occurs, the entire list is freed and
92207** NULL is returned.  If non-NULL is returned, then it is guaranteed
92208** that the new entry was successfully appended.
92209*/
92210SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
92211  Parse *pParse,          /* Parsing context */
92212  ExprList *pList,        /* List to which to append. Might be NULL */
92213  Expr *pExpr             /* Expression to be appended. Might be NULL */
92214){
92215  sqlite3 *db = pParse->db;
92216  assert( db!=0 );
92217  if( pList==0 ){
92218    pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
92219    if( pList==0 ){
92220      goto no_mem;
92221    }
92222    pList->nExpr = 0;
92223    pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
92224    if( pList->a==0 ) goto no_mem;
92225  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
92226    struct ExprList_item *a;
92227    assert( pList->nExpr>0 );
92228    a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
92229    if( a==0 ){
92230      goto no_mem;
92231    }
92232    pList->a = a;
92233  }
92234  assert( pList->a!=0 );
92235  if( 1 ){
92236    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
92237    memset(pItem, 0, sizeof(*pItem));
92238    pItem->pExpr = pExpr;
92239  }
92240  return pList;
92241
92242no_mem:
92243  /* Avoid leaking memory if malloc has failed. */
92244  sqlite3ExprDelete(db, pExpr);
92245  sqlite3ExprListDelete(db, pList);
92246  return 0;
92247}
92248
92249/*
92250** pColumns and pExpr form a vector assignment which is part of the SET
92251** clause of an UPDATE statement.  Like this:
92252**
92253**        (a,b,c) = (expr1,expr2,expr3)
92254** Or:    (a,b,c) = (SELECT x,y,z FROM ....)
92255**
92256** For each term of the vector assignment, append new entries to the
92257** expression list pList.  In the case of a subquery on the RHS, append
92258** TK_SELECT_COLUMN expressions.
92259*/
92260SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
92261  Parse *pParse,         /* Parsing context */
92262  ExprList *pList,       /* List to which to append. Might be NULL */
92263  IdList *pColumns,      /* List of names of LHS of the assignment */
92264  Expr *pExpr            /* Vector expression to be appended. Might be NULL */
92265){
92266  sqlite3 *db = pParse->db;
92267  int n;
92268  int i;
92269  int iFirst = pList ? pList->nExpr : 0;
92270  /* pColumns can only be NULL due to an OOM but an OOM will cause an
92271  ** exit prior to this routine being invoked */
92272  if( NEVER(pColumns==0) ) goto vector_append_error;
92273  if( pExpr==0 ) goto vector_append_error;
92274
92275  /* If the RHS is a vector, then we can immediately check to see that
92276  ** the size of the RHS and LHS match.  But if the RHS is a SELECT,
92277  ** wildcards ("*") in the result set of the SELECT must be expanded before
92278  ** we can do the size check, so defer the size check until code generation.
92279  */
92280  if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
92281    sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
92282                    pColumns->nId, n);
92283    goto vector_append_error;
92284  }
92285
92286  for(i=0; i<pColumns->nId; i++){
92287    Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
92288    pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
92289    if( pList ){
92290      assert( pList->nExpr==iFirst+i+1 );
92291      pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
92292      pColumns->a[i].zName = 0;
92293    }
92294  }
92295
92296  if( pExpr->op==TK_SELECT ){
92297    if( pList && pList->a[iFirst].pExpr ){
92298      Expr *pFirst = pList->a[iFirst].pExpr;
92299      assert( pFirst->op==TK_SELECT_COLUMN );
92300
92301      /* Store the SELECT statement in pRight so it will be deleted when
92302      ** sqlite3ExprListDelete() is called */
92303      pFirst->pRight = pExpr;
92304      pExpr = 0;
92305
92306      /* Remember the size of the LHS in iTable so that we can check that
92307      ** the RHS and LHS sizes match during code generation. */
92308      pFirst->iTable = pColumns->nId;
92309    }
92310  }
92311
92312vector_append_error:
92313  sqlite3ExprDelete(db, pExpr);
92314  sqlite3IdListDelete(db, pColumns);
92315  return pList;
92316}
92317
92318/*
92319** Set the sort order for the last element on the given ExprList.
92320*/
92321SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
92322  if( p==0 ) return;
92323  assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
92324  assert( p->nExpr>0 );
92325  if( iSortOrder<0 ){
92326    assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
92327    return;
92328  }
92329  p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
92330}
92331
92332/*
92333** Set the ExprList.a[].zName element of the most recently added item
92334** on the expression list.
92335**
92336** pList might be NULL following an OOM error.  But pName should never be
92337** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
92338** is set.
92339*/
92340SQLITE_PRIVATE void sqlite3ExprListSetName(
92341  Parse *pParse,          /* Parsing context */
92342  ExprList *pList,        /* List to which to add the span. */
92343  Token *pName,           /* Name to be added */
92344  int dequote             /* True to cause the name to be dequoted */
92345){
92346  assert( pList!=0 || pParse->db->mallocFailed!=0 );
92347  if( pList ){
92348    struct ExprList_item *pItem;
92349    assert( pList->nExpr>0 );
92350    pItem = &pList->a[pList->nExpr-1];
92351    assert( pItem->zName==0 );
92352    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
92353    if( dequote ) sqlite3Dequote(pItem->zName);
92354  }
92355}
92356
92357/*
92358** Set the ExprList.a[].zSpan element of the most recently added item
92359** on the expression list.
92360**
92361** pList might be NULL following an OOM error.  But pSpan should never be
92362** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
92363** is set.
92364*/
92365SQLITE_PRIVATE void sqlite3ExprListSetSpan(
92366  Parse *pParse,          /* Parsing context */
92367  ExprList *pList,        /* List to which to add the span. */
92368  ExprSpan *pSpan         /* The span to be added */
92369){
92370  sqlite3 *db = pParse->db;
92371  assert( pList!=0 || db->mallocFailed!=0 );
92372  if( pList ){
92373    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
92374    assert( pList->nExpr>0 );
92375    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
92376    sqlite3DbFree(db, pItem->zSpan);
92377    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
92378                                    (int)(pSpan->zEnd - pSpan->zStart));
92379  }
92380}
92381
92382/*
92383** If the expression list pEList contains more than iLimit elements,
92384** leave an error message in pParse.
92385*/
92386SQLITE_PRIVATE void sqlite3ExprListCheckLength(
92387  Parse *pParse,
92388  ExprList *pEList,
92389  const char *zObject
92390){
92391  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
92392  testcase( pEList && pEList->nExpr==mx );
92393  testcase( pEList && pEList->nExpr==mx+1 );
92394  if( pEList && pEList->nExpr>mx ){
92395    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
92396  }
92397}
92398
92399/*
92400** Delete an entire expression list.
92401*/
92402static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
92403  int i;
92404  struct ExprList_item *pItem;
92405  assert( pList->a!=0 || pList->nExpr==0 );
92406  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
92407    sqlite3ExprDelete(db, pItem->pExpr);
92408    sqlite3DbFree(db, pItem->zName);
92409    sqlite3DbFree(db, pItem->zSpan);
92410  }
92411  sqlite3DbFree(db, pList->a);
92412  sqlite3DbFree(db, pList);
92413}
92414SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
92415  if( pList ) exprListDeleteNN(db, pList);
92416}
92417
92418/*
92419** Return the bitwise-OR of all Expr.flags fields in the given
92420** ExprList.
92421*/
92422SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
92423  int i;
92424  u32 m = 0;
92425  if( pList ){
92426    for(i=0; i<pList->nExpr; i++){
92427       Expr *pExpr = pList->a[i].pExpr;
92428       assert( pExpr!=0 );
92429       m |= pExpr->flags;
92430    }
92431  }
92432  return m;
92433}
92434
92435/*
92436** These routines are Walker callbacks used to check expressions to
92437** see if they are "constant" for some definition of constant.  The
92438** Walker.eCode value determines the type of "constant" we are looking
92439** for.
92440**
92441** These callback routines are used to implement the following:
92442**
92443**     sqlite3ExprIsConstant()                  pWalker->eCode==1
92444**     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
92445**     sqlite3ExprIsTableConstant()             pWalker->eCode==3
92446**     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
92447**
92448** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
92449** is found to not be a constant.
92450**
92451** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
92452** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
92453** an existing schema and 4 when processing a new statement.  A bound
92454** parameter raises an error for new statements, but is silently converted
92455** to NULL for existing schemas.  This allows sqlite_master tables that
92456** contain a bound parameter because they were generated by older versions
92457** of SQLite to be parsed by newer versions of SQLite without raising a
92458** malformed schema error.
92459*/
92460static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
92461
92462  /* If pWalker->eCode is 2 then any term of the expression that comes from
92463  ** the ON or USING clauses of a left join disqualifies the expression
92464  ** from being considered constant. */
92465  if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
92466    pWalker->eCode = 0;
92467    return WRC_Abort;
92468  }
92469
92470  switch( pExpr->op ){
92471    /* Consider functions to be constant if all their arguments are constant
92472    ** and either pWalker->eCode==4 or 5 or the function has the
92473    ** SQLITE_FUNC_CONST flag. */
92474    case TK_FUNCTION:
92475      if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
92476        return WRC_Continue;
92477      }else{
92478        pWalker->eCode = 0;
92479        return WRC_Abort;
92480      }
92481    case TK_ID:
92482    case TK_COLUMN:
92483    case TK_AGG_FUNCTION:
92484    case TK_AGG_COLUMN:
92485      testcase( pExpr->op==TK_ID );
92486      testcase( pExpr->op==TK_COLUMN );
92487      testcase( pExpr->op==TK_AGG_FUNCTION );
92488      testcase( pExpr->op==TK_AGG_COLUMN );
92489      if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
92490        return WRC_Continue;
92491      }else{
92492        pWalker->eCode = 0;
92493        return WRC_Abort;
92494      }
92495    case TK_VARIABLE:
92496      if( pWalker->eCode==5 ){
92497        /* Silently convert bound parameters that appear inside of CREATE
92498        ** statements into a NULL when parsing the CREATE statement text out
92499        ** of the sqlite_master table */
92500        pExpr->op = TK_NULL;
92501      }else if( pWalker->eCode==4 ){
92502        /* A bound parameter in a CREATE statement that originates from
92503        ** sqlite3_prepare() causes an error */
92504        pWalker->eCode = 0;
92505        return WRC_Abort;
92506      }
92507      /* Fall through */
92508    default:
92509      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
92510      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
92511      return WRC_Continue;
92512  }
92513}
92514static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
92515  UNUSED_PARAMETER(NotUsed);
92516  pWalker->eCode = 0;
92517  return WRC_Abort;
92518}
92519static int exprIsConst(Expr *p, int initFlag, int iCur){
92520  Walker w;
92521  memset(&w, 0, sizeof(w));
92522  w.eCode = initFlag;
92523  w.xExprCallback = exprNodeIsConstant;
92524  w.xSelectCallback = selectNodeIsConstant;
92525  w.u.iCur = iCur;
92526  sqlite3WalkExpr(&w, p);
92527  return w.eCode;
92528}
92529
92530/*
92531** Walk an expression tree.  Return non-zero if the expression is constant
92532** and 0 if it involves variables or function calls.
92533**
92534** For the purposes of this function, a double-quoted string (ex: "abc")
92535** is considered a variable but a single-quoted string (ex: 'abc') is
92536** a constant.
92537*/
92538SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
92539  return exprIsConst(p, 1, 0);
92540}
92541
92542/*
92543** Walk an expression tree.  Return non-zero if the expression is constant
92544** that does no originate from the ON or USING clauses of a join.
92545** Return 0 if it involves variables or function calls or terms from
92546** an ON or USING clause.
92547*/
92548SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
92549  return exprIsConst(p, 2, 0);
92550}
92551
92552/*
92553** Walk an expression tree.  Return non-zero if the expression is constant
92554** for any single row of the table with cursor iCur.  In other words, the
92555** expression must not refer to any non-deterministic function nor any
92556** table other than iCur.
92557*/
92558SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
92559  return exprIsConst(p, 3, iCur);
92560}
92561
92562/*
92563** Walk an expression tree.  Return non-zero if the expression is constant
92564** or a function call with constant arguments.  Return and 0 if there
92565** are any variables.
92566**
92567** For the purposes of this function, a double-quoted string (ex: "abc")
92568** is considered a variable but a single-quoted string (ex: 'abc') is
92569** a constant.
92570*/
92571SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
92572  assert( isInit==0 || isInit==1 );
92573  return exprIsConst(p, 4+isInit, 0);
92574}
92575
92576#ifdef SQLITE_ENABLE_CURSOR_HINTS
92577/*
92578** Walk an expression tree.  Return 1 if the expression contains a
92579** subquery of some kind.  Return 0 if there are no subqueries.
92580*/
92581SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
92582  Walker w;
92583  memset(&w, 0, sizeof(w));
92584  w.eCode = 1;
92585  w.xExprCallback = sqlite3ExprWalkNoop;
92586  w.xSelectCallback = selectNodeIsConstant;
92587  sqlite3WalkExpr(&w, p);
92588  return w.eCode==0;
92589}
92590#endif
92591
92592/*
92593** If the expression p codes a constant integer that is small enough
92594** to fit in a 32-bit integer, return 1 and put the value of the integer
92595** in *pValue.  If the expression is not an integer or if it is too big
92596** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
92597*/
92598SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
92599  int rc = 0;
92600  if( p==0 ) return 0;  /* Can only happen following on OOM */
92601
92602  /* If an expression is an integer literal that fits in a signed 32-bit
92603  ** integer, then the EP_IntValue flag will have already been set */
92604  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
92605           || sqlite3GetInt32(p->u.zToken, &rc)==0 );
92606
92607  if( p->flags & EP_IntValue ){
92608    *pValue = p->u.iValue;
92609    return 1;
92610  }
92611  switch( p->op ){
92612    case TK_UPLUS: {
92613      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
92614      break;
92615    }
92616    case TK_UMINUS: {
92617      int v;
92618      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
92619        assert( v!=(-2147483647-1) );
92620        *pValue = -v;
92621        rc = 1;
92622      }
92623      break;
92624    }
92625    default: break;
92626  }
92627  return rc;
92628}
92629
92630/*
92631** Return FALSE if there is no chance that the expression can be NULL.
92632**
92633** If the expression might be NULL or if the expression is too complex
92634** to tell return TRUE.
92635**
92636** This routine is used as an optimization, to skip OP_IsNull opcodes
92637** when we know that a value cannot be NULL.  Hence, a false positive
92638** (returning TRUE when in fact the expression can never be NULL) might
92639** be a small performance hit but is otherwise harmless.  On the other
92640** hand, a false negative (returning FALSE when the result could be NULL)
92641** will likely result in an incorrect answer.  So when in doubt, return
92642** TRUE.
92643*/
92644SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
92645  u8 op;
92646  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
92647  op = p->op;
92648  if( op==TK_REGISTER ) op = p->op2;
92649  switch( op ){
92650    case TK_INTEGER:
92651    case TK_STRING:
92652    case TK_FLOAT:
92653    case TK_BLOB:
92654      return 0;
92655    case TK_COLUMN:
92656      assert( p->pTab!=0 );
92657      return ExprHasProperty(p, EP_CanBeNull) ||
92658             (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
92659    default:
92660      return 1;
92661  }
92662}
92663
92664/*
92665** Return TRUE if the given expression is a constant which would be
92666** unchanged by OP_Affinity with the affinity given in the second
92667** argument.
92668**
92669** This routine is used to determine if the OP_Affinity operation
92670** can be omitted.  When in doubt return FALSE.  A false negative
92671** is harmless.  A false positive, however, can result in the wrong
92672** answer.
92673*/
92674SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
92675  u8 op;
92676  if( aff==SQLITE_AFF_BLOB ) return 1;
92677  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
92678  op = p->op;
92679  if( op==TK_REGISTER ) op = p->op2;
92680  switch( op ){
92681    case TK_INTEGER: {
92682      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
92683    }
92684    case TK_FLOAT: {
92685      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
92686    }
92687    case TK_STRING: {
92688      return aff==SQLITE_AFF_TEXT;
92689    }
92690    case TK_BLOB: {
92691      return 1;
92692    }
92693    case TK_COLUMN: {
92694      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
92695      return p->iColumn<0
92696          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
92697    }
92698    default: {
92699      return 0;
92700    }
92701  }
92702}
92703
92704/*
92705** Return TRUE if the given string is a row-id column name.
92706*/
92707SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
92708  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
92709  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
92710  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
92711  return 0;
92712}
92713
92714/*
92715** pX is the RHS of an IN operator.  If pX is a SELECT statement
92716** that can be simplified to a direct table access, then return
92717** a pointer to the SELECT statement.  If pX is not a SELECT statement,
92718** or if the SELECT statement needs to be manifested into a transient
92719** table, then return NULL.
92720*/
92721#ifndef SQLITE_OMIT_SUBQUERY
92722static Select *isCandidateForInOpt(Expr *pX){
92723  Select *p;
92724  SrcList *pSrc;
92725  ExprList *pEList;
92726  Table *pTab;
92727  int i;
92728  if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
92729  if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
92730  p = pX->x.pSelect;
92731  if( p->pPrior ) return 0;              /* Not a compound SELECT */
92732  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
92733    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
92734    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
92735    return 0; /* No DISTINCT keyword and no aggregate functions */
92736  }
92737  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
92738  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
92739  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
92740  if( p->pWhere ) return 0;              /* Has no WHERE clause */
92741  pSrc = p->pSrc;
92742  assert( pSrc!=0 );
92743  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
92744  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
92745  pTab = pSrc->a[0].pTab;
92746  assert( pTab!=0 );
92747  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
92748  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
92749  pEList = p->pEList;
92750  assert( pEList!=0 );
92751  /* All SELECT results must be columns. */
92752  for(i=0; i<pEList->nExpr; i++){
92753    Expr *pRes = pEList->a[i].pExpr;
92754    if( pRes->op!=TK_COLUMN ) return 0;
92755    assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
92756  }
92757  return p;
92758}
92759#endif /* SQLITE_OMIT_SUBQUERY */
92760
92761#ifndef SQLITE_OMIT_SUBQUERY
92762/*
92763** Generate code that checks the left-most column of index table iCur to see if
92764** it contains any NULL entries.  Cause the register at regHasNull to be set
92765** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
92766** to be set to NULL if iCur contains one or more NULL values.
92767*/
92768static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
92769  int addr1;
92770  sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
92771  addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
92772  sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
92773  sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
92774  VdbeComment((v, "first_entry_in(%d)", iCur));
92775  sqlite3VdbeJumpHere(v, addr1);
92776}
92777#endif
92778
92779
92780#ifndef SQLITE_OMIT_SUBQUERY
92781/*
92782** The argument is an IN operator with a list (not a subquery) on the
92783** right-hand side.  Return TRUE if that list is constant.
92784*/
92785static int sqlite3InRhsIsConstant(Expr *pIn){
92786  Expr *pLHS;
92787  int res;
92788  assert( !ExprHasProperty(pIn, EP_xIsSelect) );
92789  pLHS = pIn->pLeft;
92790  pIn->pLeft = 0;
92791  res = sqlite3ExprIsConstant(pIn);
92792  pIn->pLeft = pLHS;
92793  return res;
92794}
92795#endif
92796
92797/*
92798** This function is used by the implementation of the IN (...) operator.
92799** The pX parameter is the expression on the RHS of the IN operator, which
92800** might be either a list of expressions or a subquery.
92801**
92802** The job of this routine is to find or create a b-tree object that can
92803** be used either to test for membership in the RHS set or to iterate through
92804** all members of the RHS set, skipping duplicates.
92805**
92806** A cursor is opened on the b-tree object that is the RHS of the IN operator
92807** and pX->iTable is set to the index of that cursor.
92808**
92809** The returned value of this function indicates the b-tree type, as follows:
92810**
92811**   IN_INDEX_ROWID      - The cursor was opened on a database table.
92812**   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
92813**   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
92814**   IN_INDEX_EPH        - The cursor was opened on a specially created and
92815**                         populated epheremal table.
92816**   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
92817**                         implemented as a sequence of comparisons.
92818**
92819** An existing b-tree might be used if the RHS expression pX is a simple
92820** subquery such as:
92821**
92822**     SELECT <column1>, <column2>... FROM <table>
92823**
92824** If the RHS of the IN operator is a list or a more complex subquery, then
92825** an ephemeral table might need to be generated from the RHS and then
92826** pX->iTable made to point to the ephemeral table instead of an
92827** existing table.
92828**
92829** The inFlags parameter must contain exactly one of the bits
92830** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
92831** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
92832** fast membership test.  When the IN_INDEX_LOOP bit is set, the
92833** IN index will be used to loop over all values of the RHS of the
92834** IN operator.
92835**
92836** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
92837** through the set members) then the b-tree must not contain duplicates.
92838** An epheremal table must be used unless the selected columns are guaranteed
92839** to be unique - either because it is an INTEGER PRIMARY KEY or due to
92840** a UNIQUE constraint or index.
92841**
92842** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
92843** for fast set membership tests) then an epheremal table must
92844** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
92845** index can be found with the specified <columns> as its left-most.
92846**
92847** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
92848** if the RHS of the IN operator is a list (not a subquery) then this
92849** routine might decide that creating an ephemeral b-tree for membership
92850** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
92851** calling routine should implement the IN operator using a sequence
92852** of Eq or Ne comparison operations.
92853**
92854** When the b-tree is being used for membership tests, the calling function
92855** might need to know whether or not the RHS side of the IN operator
92856** contains a NULL.  If prRhsHasNull is not a NULL pointer and
92857** if there is any chance that the (...) might contain a NULL value at
92858** runtime, then a register is allocated and the register number written
92859** to *prRhsHasNull. If there is no chance that the (...) contains a
92860** NULL value, then *prRhsHasNull is left unchanged.
92861**
92862** If a register is allocated and its location stored in *prRhsHasNull, then
92863** the value in that register will be NULL if the b-tree contains one or more
92864** NULL values, and it will be some non-NULL value if the b-tree contains no
92865** NULL values.
92866**
92867** If the aiMap parameter is not NULL, it must point to an array containing
92868** one element for each column returned by the SELECT statement on the RHS
92869** of the IN(...) operator. The i'th entry of the array is populated with the
92870** offset of the index column that matches the i'th column returned by the
92871** SELECT. For example, if the expression and selected index are:
92872**
92873**   (?,?,?) IN (SELECT a, b, c FROM t1)
92874**   CREATE INDEX i1 ON t1(b, c, a);
92875**
92876** then aiMap[] is populated with {2, 0, 1}.
92877*/
92878#ifndef SQLITE_OMIT_SUBQUERY
92879SQLITE_PRIVATE int sqlite3FindInIndex(
92880  Parse *pParse,             /* Parsing context */
92881  Expr *pX,                  /* The right-hand side (RHS) of the IN operator */
92882  u32 inFlags,               /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
92883  int *prRhsHasNull,         /* Register holding NULL status.  See notes */
92884  int *aiMap                 /* Mapping from Index fields to RHS fields */
92885){
92886  Select *p;                            /* SELECT to the right of IN operator */
92887  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
92888  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
92889  int mustBeUnique;                     /* True if RHS must be unique */
92890  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
92891
92892  assert( pX->op==TK_IN );
92893  mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
92894
92895  /* If the RHS of this IN(...) operator is a SELECT, and if it matters
92896  ** whether or not the SELECT result contains NULL values, check whether
92897  ** or not NULL is actually possible (it may not be, for example, due
92898  ** to NOT NULL constraints in the schema). If no NULL values are possible,
92899  ** set prRhsHasNull to 0 before continuing.  */
92900  if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
92901    int i;
92902    ExprList *pEList = pX->x.pSelect->pEList;
92903    for(i=0; i<pEList->nExpr; i++){
92904      if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
92905    }
92906    if( i==pEList->nExpr ){
92907      prRhsHasNull = 0;
92908    }
92909  }
92910
92911  /* Check to see if an existing table or index can be used to
92912  ** satisfy the query.  This is preferable to generating a new
92913  ** ephemeral table.  */
92914  if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
92915    sqlite3 *db = pParse->db;              /* Database connection */
92916    Table *pTab;                           /* Table <table>. */
92917    i16 iDb;                               /* Database idx for pTab */
92918    ExprList *pEList = p->pEList;
92919    int nExpr = pEList->nExpr;
92920
92921    assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
92922    assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
92923    assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
92924    pTab = p->pSrc->a[0].pTab;
92925
92926    /* Code an OP_Transaction and OP_TableLock for <table>. */
92927    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
92928    sqlite3CodeVerifySchema(pParse, iDb);
92929    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
92930
92931    assert(v);  /* sqlite3GetVdbe() has always been previously called */
92932    if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
92933      /* The "x IN (SELECT rowid FROM table)" case */
92934      int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
92935      VdbeCoverage(v);
92936
92937      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
92938      eType = IN_INDEX_ROWID;
92939
92940      sqlite3VdbeJumpHere(v, iAddr);
92941    }else{
92942      Index *pIdx;                         /* Iterator variable */
92943      int affinity_ok = 1;
92944      int i;
92945
92946      /* Check that the affinity that will be used to perform each
92947      ** comparison is the same as the affinity of each column in table
92948      ** on the RHS of the IN operator.  If it not, it is not possible to
92949      ** use any index of the RHS table.  */
92950      for(i=0; i<nExpr && affinity_ok; i++){
92951        Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
92952        int iCol = pEList->a[i].pExpr->iColumn;
92953        char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
92954        char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
92955        testcase( cmpaff==SQLITE_AFF_BLOB );
92956        testcase( cmpaff==SQLITE_AFF_TEXT );
92957        switch( cmpaff ){
92958          case SQLITE_AFF_BLOB:
92959            break;
92960          case SQLITE_AFF_TEXT:
92961            /* sqlite3CompareAffinity() only returns TEXT if one side or the
92962            ** other has no affinity and the other side is TEXT.  Hence,
92963            ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
92964            ** and for the term on the LHS of the IN to have no affinity. */
92965            assert( idxaff==SQLITE_AFF_TEXT );
92966            break;
92967          default:
92968            affinity_ok = sqlite3IsNumericAffinity(idxaff);
92969        }
92970      }
92971
92972      if( affinity_ok ){
92973        /* Search for an existing index that will work for this IN operator */
92974        for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
92975          Bitmask colUsed;      /* Columns of the index used */
92976          Bitmask mCol;         /* Mask for the current column */
92977          if( pIdx->nColumn<nExpr ) continue;
92978          /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
92979          ** BITMASK(nExpr) without overflowing */
92980          testcase( pIdx->nColumn==BMS-2 );
92981          testcase( pIdx->nColumn==BMS-1 );
92982          if( pIdx->nColumn>=BMS-1 ) continue;
92983          if( mustBeUnique ){
92984            if( pIdx->nKeyCol>nExpr
92985             ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
92986            ){
92987              continue;  /* This index is not unique over the IN RHS columns */
92988            }
92989          }
92990
92991          colUsed = 0;   /* Columns of index used so far */
92992          for(i=0; i<nExpr; i++){
92993            Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
92994            Expr *pRhs = pEList->a[i].pExpr;
92995            CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
92996            int j;
92997
92998            assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
92999            for(j=0; j<nExpr; j++){
93000              if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
93001              assert( pIdx->azColl[j] );
93002              if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
93003                continue;
93004              }
93005              break;
93006            }
93007            if( j==nExpr ) break;
93008            mCol = MASKBIT(j);
93009            if( mCol & colUsed ) break; /* Each column used only once */
93010            colUsed |= mCol;
93011            if( aiMap ) aiMap[i] = j;
93012          }
93013
93014          assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
93015          if( colUsed==(MASKBIT(nExpr)-1) ){
93016            /* If we reach this point, that means the index pIdx is usable */
93017            int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
93018#ifndef SQLITE_OMIT_EXPLAIN
93019            sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0,
93020              sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName),
93021              P4_DYNAMIC);
93022#endif
93023            sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
93024            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
93025            VdbeComment((v, "%s", pIdx->zName));
93026            assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
93027            eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
93028
93029            if( prRhsHasNull ){
93030#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
93031              i64 mask = (1<<nExpr)-1;
93032              sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
93033                  iTab, 0, 0, (u8*)&mask, P4_INT64);
93034#endif
93035              *prRhsHasNull = ++pParse->nMem;
93036              if( nExpr==1 ){
93037                sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
93038              }
93039            }
93040            sqlite3VdbeJumpHere(v, iAddr);
93041          }
93042        } /* End loop over indexes */
93043      } /* End if( affinity_ok ) */
93044    } /* End if not an rowid index */
93045  } /* End attempt to optimize using an index */
93046
93047  /* If no preexisting index is available for the IN clause
93048  ** and IN_INDEX_NOOP is an allowed reply
93049  ** and the RHS of the IN operator is a list, not a subquery
93050  ** and the RHS is not constant or has two or fewer terms,
93051  ** then it is not worth creating an ephemeral table to evaluate
93052  ** the IN operator so return IN_INDEX_NOOP.
93053  */
93054  if( eType==0
93055   && (inFlags & IN_INDEX_NOOP_OK)
93056   && !ExprHasProperty(pX, EP_xIsSelect)
93057   && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
93058  ){
93059    eType = IN_INDEX_NOOP;
93060  }
93061
93062  if( eType==0 ){
93063    /* Could not find an existing table or index to use as the RHS b-tree.
93064    ** We will have to generate an ephemeral table to do the job.
93065    */
93066    u32 savedNQueryLoop = pParse->nQueryLoop;
93067    int rMayHaveNull = 0;
93068    eType = IN_INDEX_EPH;
93069    if( inFlags & IN_INDEX_LOOP ){
93070      pParse->nQueryLoop = 0;
93071      if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
93072        eType = IN_INDEX_ROWID;
93073      }
93074    }else if( prRhsHasNull ){
93075      *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
93076    }
93077    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
93078    pParse->nQueryLoop = savedNQueryLoop;
93079  }else{
93080    pX->iTable = iTab;
93081  }
93082
93083  if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
93084    int i, n;
93085    n = sqlite3ExprVectorSize(pX->pLeft);
93086    for(i=0; i<n; i++) aiMap[i] = i;
93087  }
93088  return eType;
93089}
93090#endif
93091
93092#ifndef SQLITE_OMIT_SUBQUERY
93093/*
93094** Argument pExpr is an (?, ?...) IN(...) expression. This
93095** function allocates and returns a nul-terminated string containing
93096** the affinities to be used for each column of the comparison.
93097**
93098** It is the responsibility of the caller to ensure that the returned
93099** string is eventually freed using sqlite3DbFree().
93100*/
93101static char *exprINAffinity(Parse *pParse, Expr *pExpr){
93102  Expr *pLeft = pExpr->pLeft;
93103  int nVal = sqlite3ExprVectorSize(pLeft);
93104  Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
93105  char *zRet;
93106
93107  assert( pExpr->op==TK_IN );
93108  zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
93109  if( zRet ){
93110    int i;
93111    for(i=0; i<nVal; i++){
93112      Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
93113      char a = sqlite3ExprAffinity(pA);
93114      if( pSelect ){
93115        zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
93116      }else{
93117        zRet[i] = a;
93118      }
93119    }
93120    zRet[nVal] = '\0';
93121  }
93122  return zRet;
93123}
93124#endif
93125
93126#ifndef SQLITE_OMIT_SUBQUERY
93127/*
93128** Load the Parse object passed as the first argument with an error
93129** message of the form:
93130**
93131**   "sub-select returns N columns - expected M"
93132*/
93133SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
93134  const char *zFmt = "sub-select returns %d columns - expected %d";
93135  sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
93136}
93137#endif
93138
93139/*
93140** Expression pExpr is a vector that has been used in a context where
93141** it is not permitted. If pExpr is a sub-select vector, this routine
93142** loads the Parse object with a message of the form:
93143**
93144**   "sub-select returns N columns - expected 1"
93145**
93146** Or, if it is a regular scalar vector:
93147**
93148**   "row value misused"
93149*/
93150SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
93151#ifndef SQLITE_OMIT_SUBQUERY
93152  if( pExpr->flags & EP_xIsSelect ){
93153    sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
93154  }else
93155#endif
93156  {
93157    sqlite3ErrorMsg(pParse, "row value misused");
93158  }
93159}
93160
93161/*
93162** Generate code for scalar subqueries used as a subquery expression, EXISTS,
93163** or IN operators.  Examples:
93164**
93165**     (SELECT a FROM b)          -- subquery
93166**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
93167**     x IN (4,5,11)              -- IN operator with list on right-hand side
93168**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
93169**
93170** The pExpr parameter describes the expression that contains the IN
93171** operator or subquery.
93172**
93173** If parameter isRowid is non-zero, then expression pExpr is guaranteed
93174** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
93175** to some integer key column of a table B-Tree. In this case, use an
93176** intkey B-Tree to store the set of IN(...) values instead of the usual
93177** (slower) variable length keys B-Tree.
93178**
93179** If rMayHaveNull is non-zero, that means that the operation is an IN
93180** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
93181** All this routine does is initialize the register given by rMayHaveNull
93182** to NULL.  Calling routines will take care of changing this register
93183** value to non-NULL if the RHS is NULL-free.
93184**
93185** For a SELECT or EXISTS operator, return the register that holds the
93186** result.  For a multi-column SELECT, the result is stored in a contiguous
93187** array of registers and the return value is the register of the left-most
93188** result column.  Return 0 for IN operators or if an error occurs.
93189*/
93190#ifndef SQLITE_OMIT_SUBQUERY
93191SQLITE_PRIVATE int sqlite3CodeSubselect(
93192  Parse *pParse,          /* Parsing context */
93193  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
93194  int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
93195  int isRowid             /* If true, LHS of IN operator is a rowid */
93196){
93197  int jmpIfDynamic = -1;                      /* One-time test address */
93198  int rReg = 0;                           /* Register storing resulting */
93199  Vdbe *v = sqlite3GetVdbe(pParse);
93200  if( NEVER(v==0) ) return 0;
93201  sqlite3ExprCachePush(pParse);
93202
93203  /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
93204  ** is encountered if any of the following is true:
93205  **
93206  **    *  The right-hand side is a correlated subquery
93207  **    *  The right-hand side is an expression list containing variables
93208  **    *  We are inside a trigger
93209  **
93210  ** If all of the above are false, then we can run this code just once
93211  ** save the results, and reuse the same result on subsequent invocations.
93212  */
93213  if( !ExprHasProperty(pExpr, EP_VarSelect) ){
93214    jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
93215  }
93216
93217#ifndef SQLITE_OMIT_EXPLAIN
93218  if( pParse->explain==2 ){
93219    char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
93220        jmpIfDynamic>=0?"":"CORRELATED ",
93221        pExpr->op==TK_IN?"LIST":"SCALAR",
93222        pParse->iNextSelectId
93223    );
93224    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
93225  }
93226#endif
93227
93228  switch( pExpr->op ){
93229    case TK_IN: {
93230      int addr;                   /* Address of OP_OpenEphemeral instruction */
93231      Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
93232      KeyInfo *pKeyInfo = 0;      /* Key information */
93233      int nVal;                   /* Size of vector pLeft */
93234
93235      nVal = sqlite3ExprVectorSize(pLeft);
93236      assert( !isRowid || nVal==1 );
93237
93238      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
93239      ** expression it is handled the same way.  An ephemeral table is
93240      ** filled with index keys representing the results from the
93241      ** SELECT or the <exprlist>.
93242      **
93243      ** If the 'x' expression is a column value, or the SELECT...
93244      ** statement returns a column value, then the affinity of that
93245      ** column is used to build the index keys. If both 'x' and the
93246      ** SELECT... statement are columns, then numeric affinity is used
93247      ** if either column has NUMERIC or INTEGER affinity. If neither
93248      ** 'x' nor the SELECT... statement are columns, then numeric affinity
93249      ** is used.
93250      */
93251      pExpr->iTable = pParse->nTab++;
93252      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
93253          pExpr->iTable, (isRowid?0:nVal));
93254      pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
93255
93256      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
93257        /* Case 1:     expr IN (SELECT ...)
93258        **
93259        ** Generate code to write the results of the select into the temporary
93260        ** table allocated and opened above.
93261        */
93262        Select *pSelect = pExpr->x.pSelect;
93263        ExprList *pEList = pSelect->pEList;
93264
93265        assert( !isRowid );
93266        /* If the LHS and RHS of the IN operator do not match, that
93267        ** error will have been caught long before we reach this point. */
93268        if( ALWAYS(pEList->nExpr==nVal) ){
93269          SelectDest dest;
93270          int i;
93271          sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
93272          dest.zAffSdst = exprINAffinity(pParse, pExpr);
93273          pSelect->iLimit = 0;
93274          testcase( pSelect->selFlags & SF_Distinct );
93275          testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
93276          if( sqlite3Select(pParse, pSelect, &dest) ){
93277            sqlite3DbFree(pParse->db, dest.zAffSdst);
93278            sqlite3KeyInfoUnref(pKeyInfo);
93279            return 0;
93280          }
93281          sqlite3DbFree(pParse->db, dest.zAffSdst);
93282          assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
93283          assert( pEList!=0 );
93284          assert( pEList->nExpr>0 );
93285          assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
93286          for(i=0; i<nVal; i++){
93287            Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
93288            pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
93289                pParse, p, pEList->a[i].pExpr
93290            );
93291          }
93292        }
93293      }else if( ALWAYS(pExpr->x.pList!=0) ){
93294        /* Case 2:     expr IN (exprlist)
93295        **
93296        ** For each expression, build an index key from the evaluation and
93297        ** store it in the temporary table. If <expr> is a column, then use
93298        ** that columns affinity when building index keys. If <expr> is not
93299        ** a column, use numeric affinity.
93300        */
93301        char affinity;            /* Affinity of the LHS of the IN */
93302        int i;
93303        ExprList *pList = pExpr->x.pList;
93304        struct ExprList_item *pItem;
93305        int r1, r2, r3;
93306
93307        affinity = sqlite3ExprAffinity(pLeft);
93308        if( !affinity ){
93309          affinity = SQLITE_AFF_BLOB;
93310        }
93311        if( pKeyInfo ){
93312          assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
93313          pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
93314        }
93315
93316        /* Loop through each expression in <exprlist>. */
93317        r1 = sqlite3GetTempReg(pParse);
93318        r2 = sqlite3GetTempReg(pParse);
93319        if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
93320        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
93321          Expr *pE2 = pItem->pExpr;
93322          int iValToIns;
93323
93324          /* If the expression is not constant then we will need to
93325          ** disable the test that was generated above that makes sure
93326          ** this code only executes once.  Because for a non-constant
93327          ** expression we need to rerun this code each time.
93328          */
93329          if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
93330            sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
93331            jmpIfDynamic = -1;
93332          }
93333
93334          /* Evaluate the expression and insert it into the temp table */
93335          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
93336            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
93337          }else{
93338            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
93339            if( isRowid ){
93340              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
93341                                sqlite3VdbeCurrentAddr(v)+2);
93342              VdbeCoverage(v);
93343              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
93344            }else{
93345              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
93346              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
93347              sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
93348            }
93349          }
93350        }
93351        sqlite3ReleaseTempReg(pParse, r1);
93352        sqlite3ReleaseTempReg(pParse, r2);
93353      }
93354      if( pKeyInfo ){
93355        sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
93356      }
93357      break;
93358    }
93359
93360    case TK_EXISTS:
93361    case TK_SELECT:
93362    default: {
93363      /* Case 3:    (SELECT ... FROM ...)
93364      **     or:    EXISTS(SELECT ... FROM ...)
93365      **
93366      ** For a SELECT, generate code to put the values for all columns of
93367      ** the first row into an array of registers and return the index of
93368      ** the first register.
93369      **
93370      ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
93371      ** into a register and return that register number.
93372      **
93373      ** In both cases, the query is augmented with "LIMIT 1".  Any
93374      ** preexisting limit is discarded in place of the new LIMIT 1.
93375      */
93376      Select *pSel;                         /* SELECT statement to encode */
93377      SelectDest dest;                      /* How to deal with SELECT result */
93378      int nReg;                             /* Registers to allocate */
93379
93380      testcase( pExpr->op==TK_EXISTS );
93381      testcase( pExpr->op==TK_SELECT );
93382      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
93383      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
93384
93385      pSel = pExpr->x.pSelect;
93386      nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
93387      sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
93388      pParse->nMem += nReg;
93389      if( pExpr->op==TK_SELECT ){
93390        dest.eDest = SRT_Mem;
93391        dest.iSdst = dest.iSDParm;
93392        dest.nSdst = nReg;
93393        sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
93394        VdbeComment((v, "Init subquery result"));
93395      }else{
93396        dest.eDest = SRT_Exists;
93397        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
93398        VdbeComment((v, "Init EXISTS result"));
93399      }
93400      sqlite3ExprDelete(pParse->db, pSel->pLimit);
93401      pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,
93402                                  &sqlite3IntTokens[1], 0);
93403      pSel->iLimit = 0;
93404      pSel->selFlags &= ~SF_MultiValue;
93405      if( sqlite3Select(pParse, pSel, &dest) ){
93406        return 0;
93407      }
93408      rReg = dest.iSDParm;
93409      ExprSetVVAProperty(pExpr, EP_NoReduce);
93410      break;
93411    }
93412  }
93413
93414  if( rHasNullFlag ){
93415    sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
93416  }
93417
93418  if( jmpIfDynamic>=0 ){
93419    sqlite3VdbeJumpHere(v, jmpIfDynamic);
93420  }
93421  sqlite3ExprCachePop(pParse);
93422
93423  return rReg;
93424}
93425#endif /* SQLITE_OMIT_SUBQUERY */
93426
93427#ifndef SQLITE_OMIT_SUBQUERY
93428/*
93429** Expr pIn is an IN(...) expression. This function checks that the
93430** sub-select on the RHS of the IN() operator has the same number of
93431** columns as the vector on the LHS. Or, if the RHS of the IN() is not
93432** a sub-query, that the LHS is a vector of size 1.
93433*/
93434SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
93435  int nVector = sqlite3ExprVectorSize(pIn->pLeft);
93436  if( (pIn->flags & EP_xIsSelect) ){
93437    if( nVector!=pIn->x.pSelect->pEList->nExpr ){
93438      sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
93439      return 1;
93440    }
93441  }else if( nVector!=1 ){
93442    sqlite3VectorErrorMsg(pParse, pIn->pLeft);
93443    return 1;
93444  }
93445  return 0;
93446}
93447#endif
93448
93449#ifndef SQLITE_OMIT_SUBQUERY
93450/*
93451** Generate code for an IN expression.
93452**
93453**      x IN (SELECT ...)
93454**      x IN (value, value, ...)
93455**
93456** The left-hand side (LHS) is a scalar or vector expression.  The
93457** right-hand side (RHS) is an array of zero or more scalar values, or a
93458** subquery.  If the RHS is a subquery, the number of result columns must
93459** match the number of columns in the vector on the LHS.  If the RHS is
93460** a list of values, the LHS must be a scalar.
93461**
93462** The IN operator is true if the LHS value is contained within the RHS.
93463** The result is false if the LHS is definitely not in the RHS.  The
93464** result is NULL if the presence of the LHS in the RHS cannot be
93465** determined due to NULLs.
93466**
93467** This routine generates code that jumps to destIfFalse if the LHS is not
93468** contained within the RHS.  If due to NULLs we cannot determine if the LHS
93469** is contained in the RHS then jump to destIfNull.  If the LHS is contained
93470** within the RHS then fall through.
93471**
93472** See the separate in-operator.md documentation file in the canonical
93473** SQLite source tree for additional information.
93474*/
93475static void sqlite3ExprCodeIN(
93476  Parse *pParse,        /* Parsing and code generating context */
93477  Expr *pExpr,          /* The IN expression */
93478  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
93479  int destIfNull        /* Jump here if the results are unknown due to NULLs */
93480){
93481  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
93482  int eType;            /* Type of the RHS */
93483  int rLhs;             /* Register(s) holding the LHS values */
93484  int rLhsOrig;         /* LHS values prior to reordering by aiMap[] */
93485  Vdbe *v;              /* Statement under construction */
93486  int *aiMap = 0;       /* Map from vector field to index column */
93487  char *zAff = 0;       /* Affinity string for comparisons */
93488  int nVector;          /* Size of vectors for this IN operator */
93489  int iDummy;           /* Dummy parameter to exprCodeVector() */
93490  Expr *pLeft;          /* The LHS of the IN operator */
93491  int i;                /* loop counter */
93492  int destStep2;        /* Where to jump when NULLs seen in step 2 */
93493  int destStep6 = 0;    /* Start of code for Step 6 */
93494  int addrTruthOp;      /* Address of opcode that determines the IN is true */
93495  int destNotNull;      /* Jump here if a comparison is not true in step 6 */
93496  int addrTop;          /* Top of the step-6 loop */
93497
93498  pLeft = pExpr->pLeft;
93499  if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
93500  zAff = exprINAffinity(pParse, pExpr);
93501  nVector = sqlite3ExprVectorSize(pExpr->pLeft);
93502  aiMap = (int*)sqlite3DbMallocZero(
93503      pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
93504  );
93505  if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
93506
93507  /* Attempt to compute the RHS. After this step, if anything other than
93508  ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
93509  ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
93510  ** the RHS has not yet been coded.  */
93511  v = pParse->pVdbe;
93512  assert( v!=0 );       /* OOM detected prior to this routine */
93513  VdbeNoopComment((v, "begin IN expr"));
93514  eType = sqlite3FindInIndex(pParse, pExpr,
93515                             IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
93516                             destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
93517
93518  assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
93519       || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
93520  );
93521#ifdef SQLITE_DEBUG
93522  /* Confirm that aiMap[] contains nVector integer values between 0 and
93523  ** nVector-1. */
93524  for(i=0; i<nVector; i++){
93525    int j, cnt;
93526    for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
93527    assert( cnt==1 );
93528  }
93529#endif
93530
93531  /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
93532  ** vector, then it is stored in an array of nVector registers starting
93533  ** at r1.
93534  **
93535  ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
93536  ** so that the fields are in the same order as an existing index.   The
93537  ** aiMap[] array contains a mapping from the original LHS field order to
93538  ** the field order that matches the RHS index.
93539  */
93540  sqlite3ExprCachePush(pParse);
93541  rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
93542  for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
93543  if( i==nVector ){
93544    /* LHS fields are not reordered */
93545    rLhs = rLhsOrig;
93546  }else{
93547    /* Need to reorder the LHS fields according to aiMap */
93548    rLhs = sqlite3GetTempRange(pParse, nVector);
93549    for(i=0; i<nVector; i++){
93550      sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
93551    }
93552  }
93553
93554  /* If sqlite3FindInIndex() did not find or create an index that is
93555  ** suitable for evaluating the IN operator, then evaluate using a
93556  ** sequence of comparisons.
93557  **
93558  ** This is step (1) in the in-operator.md optimized algorithm.
93559  */
93560  if( eType==IN_INDEX_NOOP ){
93561    ExprList *pList = pExpr->x.pList;
93562    CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
93563    int labelOk = sqlite3VdbeMakeLabel(v);
93564    int r2, regToFree;
93565    int regCkNull = 0;
93566    int ii;
93567    assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
93568    if( destIfNull!=destIfFalse ){
93569      regCkNull = sqlite3GetTempReg(pParse);
93570      sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
93571    }
93572    for(ii=0; ii<pList->nExpr; ii++){
93573      r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
93574      if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
93575        sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
93576      }
93577      if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
93578        sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
93579                          (void*)pColl, P4_COLLSEQ);
93580        VdbeCoverageIf(v, ii<pList->nExpr-1);
93581        VdbeCoverageIf(v, ii==pList->nExpr-1);
93582        sqlite3VdbeChangeP5(v, zAff[0]);
93583      }else{
93584        assert( destIfNull==destIfFalse );
93585        sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
93586                          (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
93587        sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
93588      }
93589      sqlite3ReleaseTempReg(pParse, regToFree);
93590    }
93591    if( regCkNull ){
93592      sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
93593      sqlite3VdbeGoto(v, destIfFalse);
93594    }
93595    sqlite3VdbeResolveLabel(v, labelOk);
93596    sqlite3ReleaseTempReg(pParse, regCkNull);
93597    goto sqlite3ExprCodeIN_finished;
93598  }
93599
93600  /* Step 2: Check to see if the LHS contains any NULL columns.  If the
93601  ** LHS does contain NULLs then the result must be either FALSE or NULL.
93602  ** We will then skip the binary search of the RHS.
93603  */
93604  if( destIfNull==destIfFalse ){
93605    destStep2 = destIfFalse;
93606  }else{
93607    destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
93608  }
93609  for(i=0; i<nVector; i++){
93610    Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
93611    if( sqlite3ExprCanBeNull(p) ){
93612      sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
93613      VdbeCoverage(v);
93614    }
93615  }
93616
93617  /* Step 3.  The LHS is now known to be non-NULL.  Do the binary search
93618  ** of the RHS using the LHS as a probe.  If found, the result is
93619  ** true.
93620  */
93621  if( eType==IN_INDEX_ROWID ){
93622    /* In this case, the RHS is the ROWID of table b-tree and so we also
93623    ** know that the RHS is non-NULL.  Hence, we combine steps 3 and 4
93624    ** into a single opcode. */
93625    sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
93626    VdbeCoverage(v);
93627    addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto);  /* Return True */
93628  }else{
93629    sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
93630    if( destIfFalse==destIfNull ){
93631      /* Combine Step 3 and Step 5 into a single opcode */
93632      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
93633                           rLhs, nVector); VdbeCoverage(v);
93634      goto sqlite3ExprCodeIN_finished;
93635    }
93636    /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
93637    addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
93638                                      rLhs, nVector); VdbeCoverage(v);
93639  }
93640
93641  /* Step 4.  If the RHS is known to be non-NULL and we did not find
93642  ** an match on the search above, then the result must be FALSE.
93643  */
93644  if( rRhsHasNull && nVector==1 ){
93645    sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
93646    VdbeCoverage(v);
93647  }
93648
93649  /* Step 5.  If we do not care about the difference between NULL and
93650  ** FALSE, then just return false.
93651  */
93652  if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
93653
93654  /* Step 6: Loop through rows of the RHS.  Compare each row to the LHS.
93655  ** If any comparison is NULL, then the result is NULL.  If all
93656  ** comparisons are FALSE then the final result is FALSE.
93657  **
93658  ** For a scalar LHS, it is sufficient to check just the first row
93659  ** of the RHS.
93660  */
93661  if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
93662  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
93663  VdbeCoverage(v);
93664  if( nVector>1 ){
93665    destNotNull = sqlite3VdbeMakeLabel(v);
93666  }else{
93667    /* For nVector==1, combine steps 6 and 7 by immediately returning
93668    ** FALSE if the first comparison is not NULL */
93669    destNotNull = destIfFalse;
93670  }
93671  for(i=0; i<nVector; i++){
93672    Expr *p;
93673    CollSeq *pColl;
93674    int r3 = sqlite3GetTempReg(pParse);
93675    p = sqlite3VectorFieldSubexpr(pLeft, i);
93676    pColl = sqlite3ExprCollSeq(pParse, p);
93677    sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
93678    sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
93679                      (void*)pColl, P4_COLLSEQ);
93680    VdbeCoverage(v);
93681    sqlite3ReleaseTempReg(pParse, r3);
93682  }
93683  sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
93684  if( nVector>1 ){
93685    sqlite3VdbeResolveLabel(v, destNotNull);
93686    sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
93687    VdbeCoverage(v);
93688
93689    /* Step 7:  If we reach this point, we know that the result must
93690    ** be false. */
93691    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
93692  }
93693
93694  /* Jumps here in order to return true. */
93695  sqlite3VdbeJumpHere(v, addrTruthOp);
93696
93697sqlite3ExprCodeIN_finished:
93698  if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
93699  sqlite3ExprCachePop(pParse);
93700  VdbeComment((v, "end IN expr"));
93701sqlite3ExprCodeIN_oom_error:
93702  sqlite3DbFree(pParse->db, aiMap);
93703  sqlite3DbFree(pParse->db, zAff);
93704}
93705#endif /* SQLITE_OMIT_SUBQUERY */
93706
93707#ifndef SQLITE_OMIT_FLOATING_POINT
93708/*
93709** Generate an instruction that will put the floating point
93710** value described by z[0..n-1] into register iMem.
93711**
93712** The z[] string will probably not be zero-terminated.  But the
93713** z[n] character is guaranteed to be something that does not look
93714** like the continuation of the number.
93715*/
93716static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
93717  if( ALWAYS(z!=0) ){
93718    double value;
93719    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
93720    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
93721    if( negateFlag ) value = -value;
93722    sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
93723  }
93724}
93725#endif
93726
93727
93728/*
93729** Generate an instruction that will put the integer describe by
93730** text z[0..n-1] into register iMem.
93731**
93732** Expr.u.zToken is always UTF8 and zero-terminated.
93733*/
93734static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
93735  Vdbe *v = pParse->pVdbe;
93736  if( pExpr->flags & EP_IntValue ){
93737    int i = pExpr->u.iValue;
93738    assert( i>=0 );
93739    if( negFlag ) i = -i;
93740    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
93741  }else{
93742    int c;
93743    i64 value;
93744    const char *z = pExpr->u.zToken;
93745    assert( z!=0 );
93746    c = sqlite3DecOrHexToI64(z, &value);
93747    if( c==1 || (c==2 && !negFlag) || (negFlag && value==SMALLEST_INT64)){
93748#ifdef SQLITE_OMIT_FLOATING_POINT
93749      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
93750#else
93751#ifndef SQLITE_OMIT_HEX_INTEGER
93752      if( sqlite3_strnicmp(z,"0x",2)==0 ){
93753        sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
93754      }else
93755#endif
93756      {
93757        codeReal(v, z, negFlag, iMem);
93758      }
93759#endif
93760    }else{
93761      if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
93762      sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
93763    }
93764  }
93765}
93766
93767/*
93768** Erase column-cache entry number i
93769*/
93770static void cacheEntryClear(Parse *pParse, int i){
93771  if( pParse->aColCache[i].tempReg ){
93772    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
93773      pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
93774    }
93775  }
93776  pParse->nColCache--;
93777  if( i<pParse->nColCache ){
93778    pParse->aColCache[i] = pParse->aColCache[pParse->nColCache];
93779  }
93780}
93781
93782
93783/*
93784** Record in the column cache that a particular column from a
93785** particular table is stored in a particular register.
93786*/
93787SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
93788  int i;
93789  int minLru;
93790  int idxLru;
93791  struct yColCache *p;
93792
93793  /* Unless an error has occurred, register numbers are always positive. */
93794  assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
93795  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
93796
93797  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
93798  ** for testing only - to verify that SQLite always gets the same answer
93799  ** with and without the column cache.
93800  */
93801  if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
93802
93803  /* First replace any existing entry.
93804  **
93805  ** Actually, the way the column cache is currently used, we are guaranteed
93806  ** that the object will never already be in cache.  Verify this guarantee.
93807  */
93808#ifndef NDEBUG
93809  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
93810    assert( p->iTable!=iTab || p->iColumn!=iCol );
93811  }
93812#endif
93813
93814  /* If the cache is already full, delete the least recently used entry */
93815  if( pParse->nColCache>=SQLITE_N_COLCACHE ){
93816    minLru = 0x7fffffff;
93817    idxLru = -1;
93818    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
93819      if( p->lru<minLru ){
93820        idxLru = i;
93821        minLru = p->lru;
93822      }
93823    }
93824    p = &pParse->aColCache[idxLru];
93825  }else{
93826    p = &pParse->aColCache[pParse->nColCache++];
93827  }
93828
93829  /* Add the new entry to the end of the cache */
93830  p->iLevel = pParse->iCacheLevel;
93831  p->iTable = iTab;
93832  p->iColumn = iCol;
93833  p->iReg = iReg;
93834  p->tempReg = 0;
93835  p->lru = pParse->iCacheCnt++;
93836}
93837
93838/*
93839** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
93840** Purge the range of registers from the column cache.
93841*/
93842SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
93843  int i = 0;
93844  while( i<pParse->nColCache ){
93845    struct yColCache *p = &pParse->aColCache[i];
93846    if( p->iReg >= iReg && p->iReg < iReg+nReg ){
93847      cacheEntryClear(pParse, i);
93848    }else{
93849      i++;
93850    }
93851  }
93852}
93853
93854/*
93855** Remember the current column cache context.  Any new entries added
93856** added to the column cache after this call are removed when the
93857** corresponding pop occurs.
93858*/
93859SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
93860  pParse->iCacheLevel++;
93861#ifdef SQLITE_DEBUG
93862  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
93863    printf("PUSH to %d\n", pParse->iCacheLevel);
93864  }
93865#endif
93866}
93867
93868/*
93869** Remove from the column cache any entries that were added since the
93870** the previous sqlite3ExprCachePush operation.  In other words, restore
93871** the cache to the state it was in prior the most recent Push.
93872*/
93873SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
93874  int i = 0;
93875  assert( pParse->iCacheLevel>=1 );
93876  pParse->iCacheLevel--;
93877#ifdef SQLITE_DEBUG
93878  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
93879    printf("POP  to %d\n", pParse->iCacheLevel);
93880  }
93881#endif
93882  while( i<pParse->nColCache ){
93883    if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){
93884      cacheEntryClear(pParse, i);
93885    }else{
93886      i++;
93887    }
93888  }
93889}
93890
93891/*
93892** When a cached column is reused, make sure that its register is
93893** no longer available as a temp register.  ticket #3879:  that same
93894** register might be in the cache in multiple places, so be sure to
93895** get them all.
93896*/
93897static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
93898  int i;
93899  struct yColCache *p;
93900  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
93901    if( p->iReg==iReg ){
93902      p->tempReg = 0;
93903    }
93904  }
93905}
93906
93907/* Generate code that will load into register regOut a value that is
93908** appropriate for the iIdxCol-th column of index pIdx.
93909*/
93910SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
93911  Parse *pParse,  /* The parsing context */
93912  Index *pIdx,    /* The index whose column is to be loaded */
93913  int iTabCur,    /* Cursor pointing to a table row */
93914  int iIdxCol,    /* The column of the index to be loaded */
93915  int regOut      /* Store the index column value in this register */
93916){
93917  i16 iTabCol = pIdx->aiColumn[iIdxCol];
93918  if( iTabCol==XN_EXPR ){
93919    assert( pIdx->aColExpr );
93920    assert( pIdx->aColExpr->nExpr>iIdxCol );
93921    pParse->iSelfTab = iTabCur;
93922    sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
93923  }else{
93924    sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
93925                                    iTabCol, regOut);
93926  }
93927}
93928
93929/*
93930** Generate code to extract the value of the iCol-th column of a table.
93931*/
93932SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
93933  Vdbe *v,        /* The VDBE under construction */
93934  Table *pTab,    /* The table containing the value */
93935  int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
93936  int iCol,       /* Index of the column to extract */
93937  int regOut      /* Extract the value into this register */
93938){
93939  if( iCol<0 || iCol==pTab->iPKey ){
93940    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
93941  }else{
93942    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
93943    int x = iCol;
93944    if( !HasRowid(pTab) && !IsVirtual(pTab) ){
93945      x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
93946    }
93947    sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
93948  }
93949  if( iCol>=0 ){
93950    sqlite3ColumnDefault(v, pTab, iCol, regOut);
93951  }
93952}
93953
93954/*
93955** Generate code that will extract the iColumn-th column from
93956** table pTab and store the column value in a register.
93957**
93958** An effort is made to store the column value in register iReg.  This
93959** is not garanteeed for GetColumn() - the result can be stored in
93960** any register.  But the result is guaranteed to land in register iReg
93961** for GetColumnToReg().
93962**
93963** There must be an open cursor to pTab in iTable when this routine
93964** is called.  If iColumn<0 then code is generated that extracts the rowid.
93965*/
93966SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
93967  Parse *pParse,   /* Parsing and code generating context */
93968  Table *pTab,     /* Description of the table we are reading from */
93969  int iColumn,     /* Index of the table column */
93970  int iTable,      /* The cursor pointing to the table */
93971  int iReg,        /* Store results here */
93972  u8 p5            /* P5 value for OP_Column + FLAGS */
93973){
93974  Vdbe *v = pParse->pVdbe;
93975  int i;
93976  struct yColCache *p;
93977
93978  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
93979    if( p->iTable==iTable && p->iColumn==iColumn ){
93980      p->lru = pParse->iCacheCnt++;
93981      sqlite3ExprCachePinRegister(pParse, p->iReg);
93982      return p->iReg;
93983    }
93984  }
93985  assert( v!=0 );
93986  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
93987  if( p5 ){
93988    sqlite3VdbeChangeP5(v, p5);
93989  }else{
93990    sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
93991  }
93992  return iReg;
93993}
93994SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
93995  Parse *pParse,   /* Parsing and code generating context */
93996  Table *pTab,     /* Description of the table we are reading from */
93997  int iColumn,     /* Index of the table column */
93998  int iTable,      /* The cursor pointing to the table */
93999  int iReg         /* Store results here */
94000){
94001  int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
94002  if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
94003}
94004
94005
94006/*
94007** Clear all column cache entries.
94008*/
94009SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
94010  int i;
94011
94012#ifdef SQLITE_DEBUG
94013  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
94014    printf("CLEAR\n");
94015  }
94016#endif
94017  for(i=0; i<pParse->nColCache; i++){
94018    if( pParse->aColCache[i].tempReg
94019     && pParse->nTempReg<ArraySize(pParse->aTempReg)
94020    ){
94021       pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
94022    }
94023  }
94024  pParse->nColCache = 0;
94025}
94026
94027/*
94028** Record the fact that an affinity change has occurred on iCount
94029** registers starting with iStart.
94030*/
94031SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
94032  sqlite3ExprCacheRemove(pParse, iStart, iCount);
94033}
94034
94035/*
94036** Generate code to move content from registers iFrom...iFrom+nReg-1
94037** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
94038*/
94039SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
94040  assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
94041  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
94042  sqlite3ExprCacheRemove(pParse, iFrom, nReg);
94043}
94044
94045#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
94046/*
94047** Return true if any register in the range iFrom..iTo (inclusive)
94048** is used as part of the column cache.
94049**
94050** This routine is used within assert() and testcase() macros only
94051** and does not appear in a normal build.
94052*/
94053static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
94054  int i;
94055  struct yColCache *p;
94056  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
94057    int r = p->iReg;
94058    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
94059  }
94060  return 0;
94061}
94062#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
94063
94064
94065/*
94066** Convert a scalar expression node to a TK_REGISTER referencing
94067** register iReg.  The caller must ensure that iReg already contains
94068** the correct value for the expression.
94069*/
94070static void exprToRegister(Expr *p, int iReg){
94071  p->op2 = p->op;
94072  p->op = TK_REGISTER;
94073  p->iTable = iReg;
94074  ExprClearProperty(p, EP_Skip);
94075}
94076
94077/*
94078** Evaluate an expression (either a vector or a scalar expression) and store
94079** the result in continguous temporary registers.  Return the index of
94080** the first register used to store the result.
94081**
94082** If the returned result register is a temporary scalar, then also write
94083** that register number into *piFreeable.  If the returned result register
94084** is not a temporary or if the expression is a vector set *piFreeable
94085** to 0.
94086*/
94087static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
94088  int iResult;
94089  int nResult = sqlite3ExprVectorSize(p);
94090  if( nResult==1 ){
94091    iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
94092  }else{
94093    *piFreeable = 0;
94094    if( p->op==TK_SELECT ){
94095      iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
94096    }else{
94097      int i;
94098      iResult = pParse->nMem+1;
94099      pParse->nMem += nResult;
94100      for(i=0; i<nResult; i++){
94101        sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
94102      }
94103    }
94104  }
94105  return iResult;
94106}
94107
94108
94109/*
94110** Generate code into the current Vdbe to evaluate the given
94111** expression.  Attempt to store the results in register "target".
94112** Return the register where results are stored.
94113**
94114** With this routine, there is no guarantee that results will
94115** be stored in target.  The result might be stored in some other
94116** register if it is convenient to do so.  The calling function
94117** must check the return code and move the results to the desired
94118** register.
94119*/
94120SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
94121  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
94122  int op;                   /* The opcode being coded */
94123  int inReg = target;       /* Results stored in register inReg */
94124  int regFree1 = 0;         /* If non-zero free this temporary register */
94125  int regFree2 = 0;         /* If non-zero free this temporary register */
94126  int r1, r2;               /* Various register numbers */
94127  Expr tempX;               /* Temporary expression node */
94128  int p5 = 0;
94129
94130  assert( target>0 && target<=pParse->nMem );
94131  if( v==0 ){
94132    assert( pParse->db->mallocFailed );
94133    return 0;
94134  }
94135
94136  if( pExpr==0 ){
94137    op = TK_NULL;
94138  }else{
94139    op = pExpr->op;
94140  }
94141  switch( op ){
94142    case TK_AGG_COLUMN: {
94143      AggInfo *pAggInfo = pExpr->pAggInfo;
94144      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
94145      if( !pAggInfo->directMode ){
94146        assert( pCol->iMem>0 );
94147        return pCol->iMem;
94148      }else if( pAggInfo->useSortingIdx ){
94149        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
94150                              pCol->iSorterColumn, target);
94151        return target;
94152      }
94153      /* Otherwise, fall thru into the TK_COLUMN case */
94154    }
94155    case TK_COLUMN: {
94156      int iTab = pExpr->iTable;
94157      if( iTab<0 ){
94158        if( pParse->ckBase>0 ){
94159          /* Generating CHECK constraints or inserting into partial index */
94160          return pExpr->iColumn + pParse->ckBase;
94161        }else{
94162          /* Coding an expression that is part of an index where column names
94163          ** in the index refer to the table to which the index belongs */
94164          iTab = pParse->iSelfTab;
94165        }
94166      }
94167      return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
94168                               pExpr->iColumn, iTab, target,
94169                               pExpr->op2);
94170    }
94171    case TK_INTEGER: {
94172      codeInteger(pParse, pExpr, 0, target);
94173      return target;
94174    }
94175#ifndef SQLITE_OMIT_FLOATING_POINT
94176    case TK_FLOAT: {
94177      assert( !ExprHasProperty(pExpr, EP_IntValue) );
94178      codeReal(v, pExpr->u.zToken, 0, target);
94179      return target;
94180    }
94181#endif
94182    case TK_STRING: {
94183      assert( !ExprHasProperty(pExpr, EP_IntValue) );
94184      sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
94185      return target;
94186    }
94187    case TK_NULL: {
94188      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
94189      return target;
94190    }
94191#ifndef SQLITE_OMIT_BLOB_LITERAL
94192    case TK_BLOB: {
94193      int n;
94194      const char *z;
94195      char *zBlob;
94196      assert( !ExprHasProperty(pExpr, EP_IntValue) );
94197      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
94198      assert( pExpr->u.zToken[1]=='\'' );
94199      z = &pExpr->u.zToken[2];
94200      n = sqlite3Strlen30(z) - 1;
94201      assert( z[n]=='\'' );
94202      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
94203      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
94204      return target;
94205    }
94206#endif
94207    case TK_VARIABLE: {
94208      assert( !ExprHasProperty(pExpr, EP_IntValue) );
94209      assert( pExpr->u.zToken!=0 );
94210      assert( pExpr->u.zToken[0]!=0 );
94211      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
94212      if( pExpr->u.zToken[1]!=0 ){
94213        const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
94214        assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
94215        pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
94216        sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
94217      }
94218      return target;
94219    }
94220    case TK_REGISTER: {
94221      return pExpr->iTable;
94222    }
94223#ifndef SQLITE_OMIT_CAST
94224    case TK_CAST: {
94225      /* Expressions of the form:   CAST(pLeft AS token) */
94226      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
94227      if( inReg!=target ){
94228        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
94229        inReg = target;
94230      }
94231      sqlite3VdbeAddOp2(v, OP_Cast, target,
94232                        sqlite3AffinityType(pExpr->u.zToken, 0));
94233      testcase( usedAsColumnCache(pParse, inReg, inReg) );
94234      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
94235      return inReg;
94236    }
94237#endif /* SQLITE_OMIT_CAST */
94238    case TK_IS:
94239    case TK_ISNOT:
94240      op = (op==TK_IS) ? TK_EQ : TK_NE;
94241      p5 = SQLITE_NULLEQ;
94242      /* fall-through */
94243    case TK_LT:
94244    case TK_LE:
94245    case TK_GT:
94246    case TK_GE:
94247    case TK_NE:
94248    case TK_EQ: {
94249      Expr *pLeft = pExpr->pLeft;
94250      if( sqlite3ExprIsVector(pLeft) ){
94251        codeVectorCompare(pParse, pExpr, target, op, p5);
94252      }else{
94253        r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
94254        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
94255        codeCompare(pParse, pLeft, pExpr->pRight, op,
94256            r1, r2, inReg, SQLITE_STOREP2 | p5);
94257        assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
94258        assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
94259        assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
94260        assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
94261        assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
94262        assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
94263        testcase( regFree1==0 );
94264        testcase( regFree2==0 );
94265      }
94266      break;
94267    }
94268    case TK_AND:
94269    case TK_OR:
94270    case TK_PLUS:
94271    case TK_STAR:
94272    case TK_MINUS:
94273    case TK_REM:
94274    case TK_BITAND:
94275    case TK_BITOR:
94276    case TK_SLASH:
94277    case TK_LSHIFT:
94278    case TK_RSHIFT:
94279    case TK_CONCAT: {
94280      assert( TK_AND==OP_And );            testcase( op==TK_AND );
94281      assert( TK_OR==OP_Or );              testcase( op==TK_OR );
94282      assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
94283      assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
94284      assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
94285      assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
94286      assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
94287      assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
94288      assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
94289      assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
94290      assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
94291      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
94292      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
94293      sqlite3VdbeAddOp3(v, op, r2, r1, target);
94294      testcase( regFree1==0 );
94295      testcase( regFree2==0 );
94296      break;
94297    }
94298    case TK_UMINUS: {
94299      Expr *pLeft = pExpr->pLeft;
94300      assert( pLeft );
94301      if( pLeft->op==TK_INTEGER ){
94302        codeInteger(pParse, pLeft, 1, target);
94303        return target;
94304#ifndef SQLITE_OMIT_FLOATING_POINT
94305      }else if( pLeft->op==TK_FLOAT ){
94306        assert( !ExprHasProperty(pExpr, EP_IntValue) );
94307        codeReal(v, pLeft->u.zToken, 1, target);
94308        return target;
94309#endif
94310      }else{
94311        tempX.op = TK_INTEGER;
94312        tempX.flags = EP_IntValue|EP_TokenOnly;
94313        tempX.u.iValue = 0;
94314        r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
94315        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
94316        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
94317        testcase( regFree2==0 );
94318      }
94319      break;
94320    }
94321    case TK_BITNOT:
94322    case TK_NOT: {
94323      assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
94324      assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
94325      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
94326      testcase( regFree1==0 );
94327      sqlite3VdbeAddOp2(v, op, r1, inReg);
94328      break;
94329    }
94330    case TK_ISNULL:
94331    case TK_NOTNULL: {
94332      int addr;
94333      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
94334      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
94335      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
94336      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
94337      testcase( regFree1==0 );
94338      addr = sqlite3VdbeAddOp1(v, op, r1);
94339      VdbeCoverageIf(v, op==TK_ISNULL);
94340      VdbeCoverageIf(v, op==TK_NOTNULL);
94341      sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
94342      sqlite3VdbeJumpHere(v, addr);
94343      break;
94344    }
94345    case TK_AGG_FUNCTION: {
94346      AggInfo *pInfo = pExpr->pAggInfo;
94347      if( pInfo==0 ){
94348        assert( !ExprHasProperty(pExpr, EP_IntValue) );
94349        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
94350      }else{
94351        return pInfo->aFunc[pExpr->iAgg].iMem;
94352      }
94353      break;
94354    }
94355    case TK_FUNCTION: {
94356      ExprList *pFarg;       /* List of function arguments */
94357      int nFarg;             /* Number of function arguments */
94358      FuncDef *pDef;         /* The function definition object */
94359      const char *zId;       /* The function name */
94360      u32 constMask = 0;     /* Mask of function arguments that are constant */
94361      int i;                 /* Loop counter */
94362      sqlite3 *db = pParse->db;  /* The database connection */
94363      u8 enc = ENC(db);      /* The text encoding used by this database */
94364      CollSeq *pColl = 0;    /* A collating sequence */
94365
94366      if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
94367        /* SQL functions can be expensive. So try to move constant functions
94368        ** out of the inner loop, even if that means an extra OP_Copy. */
94369        return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
94370      }
94371      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
94372      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
94373        pFarg = 0;
94374      }else{
94375        pFarg = pExpr->x.pList;
94376      }
94377      nFarg = pFarg ? pFarg->nExpr : 0;
94378      assert( !ExprHasProperty(pExpr, EP_IntValue) );
94379      zId = pExpr->u.zToken;
94380      pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
94381#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
94382      if( pDef==0 && pParse->explain ){
94383        pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
94384      }
94385#endif
94386      if( pDef==0 || pDef->xFinalize!=0 ){
94387        sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
94388        break;
94389      }
94390
94391      /* Attempt a direct implementation of the built-in COALESCE() and
94392      ** IFNULL() functions.  This avoids unnecessary evaluation of
94393      ** arguments past the first non-NULL argument.
94394      */
94395      if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
94396        int endCoalesce = sqlite3VdbeMakeLabel(v);
94397        assert( nFarg>=2 );
94398        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
94399        for(i=1; i<nFarg; i++){
94400          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
94401          VdbeCoverage(v);
94402          sqlite3ExprCacheRemove(pParse, target, 1);
94403          sqlite3ExprCachePush(pParse);
94404          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
94405          sqlite3ExprCachePop(pParse);
94406        }
94407        sqlite3VdbeResolveLabel(v, endCoalesce);
94408        break;
94409      }
94410
94411      /* The UNLIKELY() function is a no-op.  The result is the value
94412      ** of the first argument.
94413      */
94414      if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
94415        assert( nFarg>=1 );
94416        return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
94417      }
94418
94419#ifdef SQLITE_DEBUG
94420      /* The AFFINITY() function evaluates to a string that describes
94421      ** the type affinity of the argument.  This is used for testing of
94422      ** the SQLite type logic.
94423      */
94424      if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
94425        const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
94426        char aff;
94427        assert( nFarg==1 );
94428        aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
94429        sqlite3VdbeLoadString(v, target,
94430                              aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
94431        return target;
94432      }
94433#endif
94434
94435      for(i=0; i<nFarg; i++){
94436        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
94437          testcase( i==31 );
94438          constMask |= MASKBIT32(i);
94439        }
94440        if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
94441          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
94442        }
94443      }
94444      if( pFarg ){
94445        if( constMask ){
94446          r1 = pParse->nMem+1;
94447          pParse->nMem += nFarg;
94448        }else{
94449          r1 = sqlite3GetTempRange(pParse, nFarg);
94450        }
94451
94452        /* For length() and typeof() functions with a column argument,
94453        ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
94454        ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
94455        ** loading.
94456        */
94457        if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
94458          u8 exprOp;
94459          assert( nFarg==1 );
94460          assert( pFarg->a[0].pExpr!=0 );
94461          exprOp = pFarg->a[0].pExpr->op;
94462          if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
94463            assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
94464            assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
94465            testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
94466            pFarg->a[0].pExpr->op2 =
94467                  pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
94468          }
94469        }
94470
94471        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
94472        sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
94473                                SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
94474        sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
94475      }else{
94476        r1 = 0;
94477      }
94478#ifndef SQLITE_OMIT_VIRTUALTABLE
94479      /* Possibly overload the function if the first argument is
94480      ** a virtual table column.
94481      **
94482      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
94483      ** second argument, not the first, as the argument to test to
94484      ** see if it is a column in a virtual table.  This is done because
94485      ** the left operand of infix functions (the operand we want to
94486      ** control overloading) ends up as the second argument to the
94487      ** function.  The expression "A glob B" is equivalent to
94488      ** "glob(B,A).  We want to use the A in "A glob B" to test
94489      ** for function overloading.  But we use the B term in "glob(B,A)".
94490      */
94491      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
94492        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
94493      }else if( nFarg>0 ){
94494        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
94495      }
94496#endif
94497      if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
94498        if( !pColl ) pColl = db->pDfltColl;
94499        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
94500      }
94501      sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
94502                        (char*)pDef, P4_FUNCDEF);
94503      sqlite3VdbeChangeP5(v, (u8)nFarg);
94504      if( nFarg && constMask==0 ){
94505        sqlite3ReleaseTempRange(pParse, r1, nFarg);
94506      }
94507      return target;
94508    }
94509#ifndef SQLITE_OMIT_SUBQUERY
94510    case TK_EXISTS:
94511    case TK_SELECT: {
94512      int nCol;
94513      testcase( op==TK_EXISTS );
94514      testcase( op==TK_SELECT );
94515      if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
94516        sqlite3SubselectError(pParse, nCol, 1);
94517      }else{
94518        return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
94519      }
94520      break;
94521    }
94522    case TK_SELECT_COLUMN: {
94523      int n;
94524      if( pExpr->pLeft->iTable==0 ){
94525        pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
94526      }
94527      assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
94528      if( pExpr->iTable
94529       && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
94530      ){
94531        sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
94532                                pExpr->iTable, n);
94533      }
94534      return pExpr->pLeft->iTable + pExpr->iColumn;
94535    }
94536    case TK_IN: {
94537      int destIfFalse = sqlite3VdbeMakeLabel(v);
94538      int destIfNull = sqlite3VdbeMakeLabel(v);
94539      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
94540      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
94541      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
94542      sqlite3VdbeResolveLabel(v, destIfFalse);
94543      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
94544      sqlite3VdbeResolveLabel(v, destIfNull);
94545      return target;
94546    }
94547#endif /* SQLITE_OMIT_SUBQUERY */
94548
94549
94550    /*
94551    **    x BETWEEN y AND z
94552    **
94553    ** This is equivalent to
94554    **
94555    **    x>=y AND x<=z
94556    **
94557    ** X is stored in pExpr->pLeft.
94558    ** Y is stored in pExpr->pList->a[0].pExpr.
94559    ** Z is stored in pExpr->pList->a[1].pExpr.
94560    */
94561    case TK_BETWEEN: {
94562      exprCodeBetween(pParse, pExpr, target, 0, 0);
94563      return target;
94564    }
94565    case TK_SPAN:
94566    case TK_COLLATE:
94567    case TK_UPLUS: {
94568      return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
94569    }
94570
94571    case TK_TRIGGER: {
94572      /* If the opcode is TK_TRIGGER, then the expression is a reference
94573      ** to a column in the new.* or old.* pseudo-tables available to
94574      ** trigger programs. In this case Expr.iTable is set to 1 for the
94575      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
94576      ** is set to the column of the pseudo-table to read, or to -1 to
94577      ** read the rowid field.
94578      **
94579      ** The expression is implemented using an OP_Param opcode. The p1
94580      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
94581      ** to reference another column of the old.* pseudo-table, where
94582      ** i is the index of the column. For a new.rowid reference, p1 is
94583      ** set to (n+1), where n is the number of columns in each pseudo-table.
94584      ** For a reference to any other column in the new.* pseudo-table, p1
94585      ** is set to (n+2+i), where n and i are as defined previously. For
94586      ** example, if the table on which triggers are being fired is
94587      ** declared as:
94588      **
94589      **   CREATE TABLE t1(a, b);
94590      **
94591      ** Then p1 is interpreted as follows:
94592      **
94593      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
94594      **   p1==1   ->    old.a         p1==4   ->    new.a
94595      **   p1==2   ->    old.b         p1==5   ->    new.b
94596      */
94597      Table *pTab = pExpr->pTab;
94598      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
94599
94600      assert( pExpr->iTable==0 || pExpr->iTable==1 );
94601      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
94602      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
94603      assert( p1>=0 && p1<(pTab->nCol*2+2) );
94604
94605      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
94606      VdbeComment((v, "%s.%s -> $%d",
94607        (pExpr->iTable ? "new" : "old"),
94608        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
94609        target
94610      ));
94611
94612#ifndef SQLITE_OMIT_FLOATING_POINT
94613      /* If the column has REAL affinity, it may currently be stored as an
94614      ** integer. Use OP_RealAffinity to make sure it is really real.
94615      **
94616      ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
94617      ** floating point when extracting it from the record.  */
94618      if( pExpr->iColumn>=0
94619       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
94620      ){
94621        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
94622      }
94623#endif
94624      break;
94625    }
94626
94627    case TK_VECTOR: {
94628      sqlite3ErrorMsg(pParse, "row value misused");
94629      break;
94630    }
94631
94632    /*
94633    ** Form A:
94634    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
94635    **
94636    ** Form B:
94637    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
94638    **
94639    ** Form A is can be transformed into the equivalent form B as follows:
94640    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
94641    **        WHEN x=eN THEN rN ELSE y END
94642    **
94643    ** X (if it exists) is in pExpr->pLeft.
94644    ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
94645    ** odd.  The Y is also optional.  If the number of elements in x.pList
94646    ** is even, then Y is omitted and the "otherwise" result is NULL.
94647    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
94648    **
94649    ** The result of the expression is the Ri for the first matching Ei,
94650    ** or if there is no matching Ei, the ELSE term Y, or if there is
94651    ** no ELSE term, NULL.
94652    */
94653    default: assert( op==TK_CASE ); {
94654      int endLabel;                     /* GOTO label for end of CASE stmt */
94655      int nextCase;                     /* GOTO label for next WHEN clause */
94656      int nExpr;                        /* 2x number of WHEN terms */
94657      int i;                            /* Loop counter */
94658      ExprList *pEList;                 /* List of WHEN terms */
94659      struct ExprList_item *aListelem;  /* Array of WHEN terms */
94660      Expr opCompare;                   /* The X==Ei expression */
94661      Expr *pX;                         /* The X expression */
94662      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
94663      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
94664
94665      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
94666      assert(pExpr->x.pList->nExpr > 0);
94667      pEList = pExpr->x.pList;
94668      aListelem = pEList->a;
94669      nExpr = pEList->nExpr;
94670      endLabel = sqlite3VdbeMakeLabel(v);
94671      if( (pX = pExpr->pLeft)!=0 ){
94672        tempX = *pX;
94673        testcase( pX->op==TK_COLUMN );
94674        exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
94675        testcase( regFree1==0 );
94676        memset(&opCompare, 0, sizeof(opCompare));
94677        opCompare.op = TK_EQ;
94678        opCompare.pLeft = &tempX;
94679        pTest = &opCompare;
94680        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
94681        ** The value in regFree1 might get SCopy-ed into the file result.
94682        ** So make sure that the regFree1 register is not reused for other
94683        ** purposes and possibly overwritten.  */
94684        regFree1 = 0;
94685      }
94686      for(i=0; i<nExpr-1; i=i+2){
94687        sqlite3ExprCachePush(pParse);
94688        if( pX ){
94689          assert( pTest!=0 );
94690          opCompare.pRight = aListelem[i].pExpr;
94691        }else{
94692          pTest = aListelem[i].pExpr;
94693        }
94694        nextCase = sqlite3VdbeMakeLabel(v);
94695        testcase( pTest->op==TK_COLUMN );
94696        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
94697        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
94698        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
94699        sqlite3VdbeGoto(v, endLabel);
94700        sqlite3ExprCachePop(pParse);
94701        sqlite3VdbeResolveLabel(v, nextCase);
94702      }
94703      if( (nExpr&1)!=0 ){
94704        sqlite3ExprCachePush(pParse);
94705        sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
94706        sqlite3ExprCachePop(pParse);
94707      }else{
94708        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
94709      }
94710      assert( pParse->db->mallocFailed || pParse->nErr>0
94711           || pParse->iCacheLevel==iCacheLevel );
94712      sqlite3VdbeResolveLabel(v, endLabel);
94713      break;
94714    }
94715#ifndef SQLITE_OMIT_TRIGGER
94716    case TK_RAISE: {
94717      assert( pExpr->affinity==OE_Rollback
94718           || pExpr->affinity==OE_Abort
94719           || pExpr->affinity==OE_Fail
94720           || pExpr->affinity==OE_Ignore
94721      );
94722      if( !pParse->pTriggerTab ){
94723        sqlite3ErrorMsg(pParse,
94724                       "RAISE() may only be used within a trigger-program");
94725        return 0;
94726      }
94727      if( pExpr->affinity==OE_Abort ){
94728        sqlite3MayAbort(pParse);
94729      }
94730      assert( !ExprHasProperty(pExpr, EP_IntValue) );
94731      if( pExpr->affinity==OE_Ignore ){
94732        sqlite3VdbeAddOp4(
94733            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
94734        VdbeCoverage(v);
94735      }else{
94736        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
94737                              pExpr->affinity, pExpr->u.zToken, 0, 0);
94738      }
94739
94740      break;
94741    }
94742#endif
94743  }
94744  sqlite3ReleaseTempReg(pParse, regFree1);
94745  sqlite3ReleaseTempReg(pParse, regFree2);
94746  return inReg;
94747}
94748
94749/*
94750** Factor out the code of the given expression to initialization time.
94751**
94752** If regDest>=0 then the result is always stored in that register and the
94753** result is not reusable.  If regDest<0 then this routine is free to
94754** store the value whereever it wants.  The register where the expression
94755** is stored is returned.  When regDest<0, two identical expressions will
94756** code to the same register.
94757*/
94758SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
94759  Parse *pParse,    /* Parsing context */
94760  Expr *pExpr,      /* The expression to code when the VDBE initializes */
94761  int regDest       /* Store the value in this register */
94762){
94763  ExprList *p;
94764  assert( ConstFactorOk(pParse) );
94765  p = pParse->pConstExpr;
94766  if( regDest<0 && p ){
94767    struct ExprList_item *pItem;
94768    int i;
94769    for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
94770      if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
94771        return pItem->u.iConstExprReg;
94772      }
94773    }
94774  }
94775  pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
94776  p = sqlite3ExprListAppend(pParse, p, pExpr);
94777  if( p ){
94778     struct ExprList_item *pItem = &p->a[p->nExpr-1];
94779     pItem->reusable = regDest<0;
94780     if( regDest<0 ) regDest = ++pParse->nMem;
94781     pItem->u.iConstExprReg = regDest;
94782  }
94783  pParse->pConstExpr = p;
94784  return regDest;
94785}
94786
94787/*
94788** Generate code to evaluate an expression and store the results
94789** into a register.  Return the register number where the results
94790** are stored.
94791**
94792** If the register is a temporary register that can be deallocated,
94793** then write its number into *pReg.  If the result register is not
94794** a temporary, then set *pReg to zero.
94795**
94796** If pExpr is a constant, then this routine might generate this
94797** code to fill the register in the initialization section of the
94798** VDBE program, in order to factor it out of the evaluation loop.
94799*/
94800SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
94801  int r2;
94802  pExpr = sqlite3ExprSkipCollate(pExpr);
94803  if( ConstFactorOk(pParse)
94804   && pExpr->op!=TK_REGISTER
94805   && sqlite3ExprIsConstantNotJoin(pExpr)
94806  ){
94807    *pReg  = 0;
94808    r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
94809  }else{
94810    int r1 = sqlite3GetTempReg(pParse);
94811    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
94812    if( r2==r1 ){
94813      *pReg = r1;
94814    }else{
94815      sqlite3ReleaseTempReg(pParse, r1);
94816      *pReg = 0;
94817    }
94818  }
94819  return r2;
94820}
94821
94822/*
94823** Generate code that will evaluate expression pExpr and store the
94824** results in register target.  The results are guaranteed to appear
94825** in register target.
94826*/
94827SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
94828  int inReg;
94829
94830  assert( target>0 && target<=pParse->nMem );
94831  if( pExpr && pExpr->op==TK_REGISTER ){
94832    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
94833  }else{
94834    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
94835    assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
94836    if( inReg!=target && pParse->pVdbe ){
94837      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
94838    }
94839  }
94840}
94841
94842/*
94843** Make a transient copy of expression pExpr and then code it using
94844** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
94845** except that the input expression is guaranteed to be unchanged.
94846*/
94847SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
94848  sqlite3 *db = pParse->db;
94849  pExpr = sqlite3ExprDup(db, pExpr, 0);
94850  if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
94851  sqlite3ExprDelete(db, pExpr);
94852}
94853
94854/*
94855** Generate code that will evaluate expression pExpr and store the
94856** results in register target.  The results are guaranteed to appear
94857** in register target.  If the expression is constant, then this routine
94858** might choose to code the expression at initialization time.
94859*/
94860SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
94861  if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
94862    sqlite3ExprCodeAtInit(pParse, pExpr, target);
94863  }else{
94864    sqlite3ExprCode(pParse, pExpr, target);
94865  }
94866}
94867
94868/*
94869** Generate code that evaluates the given expression and puts the result
94870** in register target.
94871**
94872** Also make a copy of the expression results into another "cache" register
94873** and modify the expression so that the next time it is evaluated,
94874** the result is a copy of the cache register.
94875**
94876** This routine is used for expressions that are used multiple
94877** times.  They are evaluated once and the results of the expression
94878** are reused.
94879*/
94880SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
94881  Vdbe *v = pParse->pVdbe;
94882  int iMem;
94883
94884  assert( target>0 );
94885  assert( pExpr->op!=TK_REGISTER );
94886  sqlite3ExprCode(pParse, pExpr, target);
94887  iMem = ++pParse->nMem;
94888  sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
94889  exprToRegister(pExpr, iMem);
94890}
94891
94892/*
94893** Generate code that pushes the value of every element of the given
94894** expression list into a sequence of registers beginning at target.
94895**
94896** Return the number of elements evaluated.
94897**
94898** The SQLITE_ECEL_DUP flag prevents the arguments from being
94899** filled using OP_SCopy.  OP_Copy must be used instead.
94900**
94901** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
94902** factored out into initialization code.
94903**
94904** The SQLITE_ECEL_REF flag means that expressions in the list with
94905** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
94906** in registers at srcReg, and so the value can be copied from there.
94907*/
94908SQLITE_PRIVATE int sqlite3ExprCodeExprList(
94909  Parse *pParse,     /* Parsing context */
94910  ExprList *pList,   /* The expression list to be coded */
94911  int target,        /* Where to write results */
94912  int srcReg,        /* Source registers if SQLITE_ECEL_REF */
94913  u8 flags           /* SQLITE_ECEL_* flags */
94914){
94915  struct ExprList_item *pItem;
94916  int i, j, n;
94917  u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
94918  Vdbe *v = pParse->pVdbe;
94919  assert( pList!=0 );
94920  assert( target>0 );
94921  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
94922  n = pList->nExpr;
94923  if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
94924  for(pItem=pList->a, i=0; i<n; i++, pItem++){
94925    Expr *pExpr = pItem->pExpr;
94926    if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
94927      if( flags & SQLITE_ECEL_OMITREF ){
94928        i--;
94929        n--;
94930      }else{
94931        sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
94932      }
94933    }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
94934      sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
94935    }else{
94936      int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
94937      if( inReg!=target+i ){
94938        VdbeOp *pOp;
94939        if( copyOp==OP_Copy
94940         && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
94941         && pOp->p1+pOp->p3+1==inReg
94942         && pOp->p2+pOp->p3+1==target+i
94943        ){
94944          pOp->p3++;
94945        }else{
94946          sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
94947        }
94948      }
94949    }
94950  }
94951  return n;
94952}
94953
94954/*
94955** Generate code for a BETWEEN operator.
94956**
94957**    x BETWEEN y AND z
94958**
94959** The above is equivalent to
94960**
94961**    x>=y AND x<=z
94962**
94963** Code it as such, taking care to do the common subexpression
94964** elimination of x.
94965**
94966** The xJumpIf parameter determines details:
94967**
94968**    NULL:                   Store the boolean result in reg[dest]
94969**    sqlite3ExprIfTrue:      Jump to dest if true
94970**    sqlite3ExprIfFalse:     Jump to dest if false
94971**
94972** The jumpIfNull parameter is ignored if xJumpIf is NULL.
94973*/
94974static void exprCodeBetween(
94975  Parse *pParse,    /* Parsing and code generating context */
94976  Expr *pExpr,      /* The BETWEEN expression */
94977  int dest,         /* Jump destination or storage location */
94978  void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
94979  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
94980){
94981 Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
94982  Expr compLeft;    /* The  x>=y  term */
94983  Expr compRight;   /* The  x<=z  term */
94984  Expr exprX;       /* The  x  subexpression */
94985  int regFree1 = 0; /* Temporary use register */
94986
94987
94988  memset(&compLeft, 0, sizeof(Expr));
94989  memset(&compRight, 0, sizeof(Expr));
94990  memset(&exprAnd, 0, sizeof(Expr));
94991
94992  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
94993  exprX = *pExpr->pLeft;
94994  exprAnd.op = TK_AND;
94995  exprAnd.pLeft = &compLeft;
94996  exprAnd.pRight = &compRight;
94997  compLeft.op = TK_GE;
94998  compLeft.pLeft = &exprX;
94999  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
95000  compRight.op = TK_LE;
95001  compRight.pLeft = &exprX;
95002  compRight.pRight = pExpr->x.pList->a[1].pExpr;
95003  exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
95004  if( xJump ){
95005    xJump(pParse, &exprAnd, dest, jumpIfNull);
95006  }else{
95007    /* Mark the expression is being from the ON or USING clause of a join
95008    ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
95009    ** it into the Parse.pConstExpr list.  We should use a new bit for this,
95010    ** for clarity, but we are out of bits in the Expr.flags field so we
95011    ** have to reuse the EP_FromJoin bit.  Bummer. */
95012    exprX.flags |= EP_FromJoin;
95013    sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
95014  }
95015  sqlite3ReleaseTempReg(pParse, regFree1);
95016
95017  /* Ensure adequate test coverage */
95018  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1==0 );
95019  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1!=0 );
95020  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1==0 );
95021  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1!=0 );
95022  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
95023  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
95024  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
95025  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
95026  testcase( xJump==0 );
95027}
95028
95029/*
95030** Generate code for a boolean expression such that a jump is made
95031** to the label "dest" if the expression is true but execution
95032** continues straight thru if the expression is false.
95033**
95034** If the expression evaluates to NULL (neither true nor false), then
95035** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
95036**
95037** This code depends on the fact that certain token values (ex: TK_EQ)
95038** are the same as opcode values (ex: OP_Eq) that implement the corresponding
95039** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
95040** the make process cause these values to align.  Assert()s in the code
95041** below verify that the numbers are aligned correctly.
95042*/
95043SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
95044  Vdbe *v = pParse->pVdbe;
95045  int op = 0;
95046  int regFree1 = 0;
95047  int regFree2 = 0;
95048  int r1, r2;
95049
95050  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
95051  if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
95052  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
95053  op = pExpr->op;
95054  switch( op ){
95055    case TK_AND: {
95056      int d2 = sqlite3VdbeMakeLabel(v);
95057      testcase( jumpIfNull==0 );
95058      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
95059      sqlite3ExprCachePush(pParse);
95060      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
95061      sqlite3VdbeResolveLabel(v, d2);
95062      sqlite3ExprCachePop(pParse);
95063      break;
95064    }
95065    case TK_OR: {
95066      testcase( jumpIfNull==0 );
95067      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
95068      sqlite3ExprCachePush(pParse);
95069      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
95070      sqlite3ExprCachePop(pParse);
95071      break;
95072    }
95073    case TK_NOT: {
95074      testcase( jumpIfNull==0 );
95075      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
95076      break;
95077    }
95078    case TK_IS:
95079    case TK_ISNOT:
95080      testcase( op==TK_IS );
95081      testcase( op==TK_ISNOT );
95082      op = (op==TK_IS) ? TK_EQ : TK_NE;
95083      jumpIfNull = SQLITE_NULLEQ;
95084      /* Fall thru */
95085    case TK_LT:
95086    case TK_LE:
95087    case TK_GT:
95088    case TK_GE:
95089    case TK_NE:
95090    case TK_EQ: {
95091      if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
95092      testcase( jumpIfNull==0 );
95093      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
95094      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
95095      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
95096                  r1, r2, dest, jumpIfNull);
95097      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
95098      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
95099      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
95100      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
95101      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
95102      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
95103      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
95104      assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
95105      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
95106      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
95107      testcase( regFree1==0 );
95108      testcase( regFree2==0 );
95109      break;
95110    }
95111    case TK_ISNULL:
95112    case TK_NOTNULL: {
95113      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
95114      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
95115      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
95116      sqlite3VdbeAddOp2(v, op, r1, dest);
95117      VdbeCoverageIf(v, op==TK_ISNULL);
95118      VdbeCoverageIf(v, op==TK_NOTNULL);
95119      testcase( regFree1==0 );
95120      break;
95121    }
95122    case TK_BETWEEN: {
95123      testcase( jumpIfNull==0 );
95124      exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
95125      break;
95126    }
95127#ifndef SQLITE_OMIT_SUBQUERY
95128    case TK_IN: {
95129      int destIfFalse = sqlite3VdbeMakeLabel(v);
95130      int destIfNull = jumpIfNull ? dest : destIfFalse;
95131      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
95132      sqlite3VdbeGoto(v, dest);
95133      sqlite3VdbeResolveLabel(v, destIfFalse);
95134      break;
95135    }
95136#endif
95137    default: {
95138    default_expr:
95139      if( exprAlwaysTrue(pExpr) ){
95140        sqlite3VdbeGoto(v, dest);
95141      }else if( exprAlwaysFalse(pExpr) ){
95142        /* No-op */
95143      }else{
95144        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
95145        sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
95146        VdbeCoverage(v);
95147        testcase( regFree1==0 );
95148        testcase( jumpIfNull==0 );
95149      }
95150      break;
95151    }
95152  }
95153  sqlite3ReleaseTempReg(pParse, regFree1);
95154  sqlite3ReleaseTempReg(pParse, regFree2);
95155}
95156
95157/*
95158** Generate code for a boolean expression such that a jump is made
95159** to the label "dest" if the expression is false but execution
95160** continues straight thru if the expression is true.
95161**
95162** If the expression evaluates to NULL (neither true nor false) then
95163** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
95164** is 0.
95165*/
95166SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
95167  Vdbe *v = pParse->pVdbe;
95168  int op = 0;
95169  int regFree1 = 0;
95170  int regFree2 = 0;
95171  int r1, r2;
95172
95173  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
95174  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
95175  if( pExpr==0 )    return;
95176
95177  /* The value of pExpr->op and op are related as follows:
95178  **
95179  **       pExpr->op            op
95180  **       ---------          ----------
95181  **       TK_ISNULL          OP_NotNull
95182  **       TK_NOTNULL         OP_IsNull
95183  **       TK_NE              OP_Eq
95184  **       TK_EQ              OP_Ne
95185  **       TK_GT              OP_Le
95186  **       TK_LE              OP_Gt
95187  **       TK_GE              OP_Lt
95188  **       TK_LT              OP_Ge
95189  **
95190  ** For other values of pExpr->op, op is undefined and unused.
95191  ** The value of TK_ and OP_ constants are arranged such that we
95192  ** can compute the mapping above using the following expression.
95193  ** Assert()s verify that the computation is correct.
95194  */
95195  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
95196
95197  /* Verify correct alignment of TK_ and OP_ constants
95198  */
95199  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
95200  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
95201  assert( pExpr->op!=TK_NE || op==OP_Eq );
95202  assert( pExpr->op!=TK_EQ || op==OP_Ne );
95203  assert( pExpr->op!=TK_LT || op==OP_Ge );
95204  assert( pExpr->op!=TK_LE || op==OP_Gt );
95205  assert( pExpr->op!=TK_GT || op==OP_Le );
95206  assert( pExpr->op!=TK_GE || op==OP_Lt );
95207
95208  switch( pExpr->op ){
95209    case TK_AND: {
95210      testcase( jumpIfNull==0 );
95211      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
95212      sqlite3ExprCachePush(pParse);
95213      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
95214      sqlite3ExprCachePop(pParse);
95215      break;
95216    }
95217    case TK_OR: {
95218      int d2 = sqlite3VdbeMakeLabel(v);
95219      testcase( jumpIfNull==0 );
95220      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
95221      sqlite3ExprCachePush(pParse);
95222      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
95223      sqlite3VdbeResolveLabel(v, d2);
95224      sqlite3ExprCachePop(pParse);
95225      break;
95226    }
95227    case TK_NOT: {
95228      testcase( jumpIfNull==0 );
95229      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
95230      break;
95231    }
95232    case TK_IS:
95233    case TK_ISNOT:
95234      testcase( pExpr->op==TK_IS );
95235      testcase( pExpr->op==TK_ISNOT );
95236      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
95237      jumpIfNull = SQLITE_NULLEQ;
95238      /* Fall thru */
95239    case TK_LT:
95240    case TK_LE:
95241    case TK_GT:
95242    case TK_GE:
95243    case TK_NE:
95244    case TK_EQ: {
95245      if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
95246      testcase( jumpIfNull==0 );
95247      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
95248      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
95249      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
95250                  r1, r2, dest, jumpIfNull);
95251      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
95252      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
95253      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
95254      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
95255      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
95256      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
95257      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
95258      assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
95259      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
95260      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
95261      testcase( regFree1==0 );
95262      testcase( regFree2==0 );
95263      break;
95264    }
95265    case TK_ISNULL:
95266    case TK_NOTNULL: {
95267      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
95268      sqlite3VdbeAddOp2(v, op, r1, dest);
95269      testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
95270      testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
95271      testcase( regFree1==0 );
95272      break;
95273    }
95274    case TK_BETWEEN: {
95275      testcase( jumpIfNull==0 );
95276      exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
95277      break;
95278    }
95279#ifndef SQLITE_OMIT_SUBQUERY
95280    case TK_IN: {
95281      if( jumpIfNull ){
95282        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
95283      }else{
95284        int destIfNull = sqlite3VdbeMakeLabel(v);
95285        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
95286        sqlite3VdbeResolveLabel(v, destIfNull);
95287      }
95288      break;
95289    }
95290#endif
95291    default: {
95292    default_expr:
95293      if( exprAlwaysFalse(pExpr) ){
95294        sqlite3VdbeGoto(v, dest);
95295      }else if( exprAlwaysTrue(pExpr) ){
95296        /* no-op */
95297      }else{
95298        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
95299        sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
95300        VdbeCoverage(v);
95301        testcase( regFree1==0 );
95302        testcase( jumpIfNull==0 );
95303      }
95304      break;
95305    }
95306  }
95307  sqlite3ReleaseTempReg(pParse, regFree1);
95308  sqlite3ReleaseTempReg(pParse, regFree2);
95309}
95310
95311/*
95312** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
95313** code generation, and that copy is deleted after code generation. This
95314** ensures that the original pExpr is unchanged.
95315*/
95316SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
95317  sqlite3 *db = pParse->db;
95318  Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
95319  if( db->mallocFailed==0 ){
95320    sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
95321  }
95322  sqlite3ExprDelete(db, pCopy);
95323}
95324
95325
95326/*
95327** Do a deep comparison of two expression trees.  Return 0 if the two
95328** expressions are completely identical.  Return 1 if they differ only
95329** by a COLLATE operator at the top level.  Return 2 if there are differences
95330** other than the top-level COLLATE operator.
95331**
95332** If any subelement of pB has Expr.iTable==(-1) then it is allowed
95333** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
95334**
95335** The pA side might be using TK_REGISTER.  If that is the case and pB is
95336** not using TK_REGISTER but is otherwise equivalent, then still return 0.
95337**
95338** Sometimes this routine will return 2 even if the two expressions
95339** really are equivalent.  If we cannot prove that the expressions are
95340** identical, we return 2 just to be safe.  So if this routine
95341** returns 2, then you do not really know for certain if the two
95342** expressions are the same.  But if you get a 0 or 1 return, then you
95343** can be sure the expressions are the same.  In the places where
95344** this routine is used, it does not hurt to get an extra 2 - that
95345** just might result in some slightly slower code.  But returning
95346** an incorrect 0 or 1 could lead to a malfunction.
95347*/
95348SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
95349  u32 combinedFlags;
95350  if( pA==0 || pB==0 ){
95351    return pB==pA ? 0 : 2;
95352  }
95353  combinedFlags = pA->flags | pB->flags;
95354  if( combinedFlags & EP_IntValue ){
95355    if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
95356      return 0;
95357    }
95358    return 2;
95359  }
95360  if( pA->op!=pB->op ){
95361    if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
95362      return 1;
95363    }
95364    if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
95365      return 1;
95366    }
95367    return 2;
95368  }
95369  if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
95370    if( pA->op==TK_FUNCTION ){
95371      if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
95372    }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
95373      return pA->op==TK_COLLATE ? 1 : 2;
95374    }
95375  }
95376  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
95377  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
95378    if( combinedFlags & EP_xIsSelect ) return 2;
95379    if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
95380    if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
95381    if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
95382    if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
95383      if( pA->iColumn!=pB->iColumn ) return 2;
95384      if( pA->iTable!=pB->iTable
95385       && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
95386    }
95387  }
95388  return 0;
95389}
95390
95391/*
95392** Compare two ExprList objects.  Return 0 if they are identical and
95393** non-zero if they differ in any way.
95394**
95395** If any subelement of pB has Expr.iTable==(-1) then it is allowed
95396** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
95397**
95398** This routine might return non-zero for equivalent ExprLists.  The
95399** only consequence will be disabled optimizations.  But this routine
95400** must never return 0 if the two ExprList objects are different, or
95401** a malfunction will result.
95402**
95403** Two NULL pointers are considered to be the same.  But a NULL pointer
95404** always differs from a non-NULL pointer.
95405*/
95406SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
95407  int i;
95408  if( pA==0 && pB==0 ) return 0;
95409  if( pA==0 || pB==0 ) return 1;
95410  if( pA->nExpr!=pB->nExpr ) return 1;
95411  for(i=0; i<pA->nExpr; i++){
95412    Expr *pExprA = pA->a[i].pExpr;
95413    Expr *pExprB = pB->a[i].pExpr;
95414    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
95415    if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
95416  }
95417  return 0;
95418}
95419
95420/*
95421** Like sqlite3ExprCompare() except COLLATE operators at the top-level
95422** are ignored.
95423*/
95424SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
95425  return sqlite3ExprCompare(
95426             sqlite3ExprSkipCollate(pA),
95427             sqlite3ExprSkipCollate(pB),
95428             iTab);
95429}
95430
95431/*
95432** Return true if we can prove the pE2 will always be true if pE1 is
95433** true.  Return false if we cannot complete the proof or if pE2 might
95434** be false.  Examples:
95435**
95436**     pE1: x==5       pE2: x==5             Result: true
95437**     pE1: x>0        pE2: x==5             Result: false
95438**     pE1: x=21       pE2: x=21 OR y=43     Result: true
95439**     pE1: x!=123     pE2: x IS NOT NULL    Result: true
95440**     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
95441**     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
95442**     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
95443**
95444** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
95445** Expr.iTable<0 then assume a table number given by iTab.
95446**
95447** When in doubt, return false.  Returning true might give a performance
95448** improvement.  Returning false might cause a performance reduction, but
95449** it will always give the correct answer and is hence always safe.
95450*/
95451SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
95452  if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
95453    return 1;
95454  }
95455  if( pE2->op==TK_OR
95456   && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
95457             || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
95458  ){
95459    return 1;
95460  }
95461  if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
95462    Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
95463    testcase( pX!=pE1->pLeft );
95464    if( sqlite3ExprCompare(pX, pE2->pLeft, iTab)==0 ) return 1;
95465  }
95466  return 0;
95467}
95468
95469/*
95470** An instance of the following structure is used by the tree walker
95471** to determine if an expression can be evaluated by reference to the
95472** index only, without having to do a search for the corresponding
95473** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur
95474** is the cursor for the table.
95475*/
95476struct IdxCover {
95477  Index *pIdx;     /* The index to be tested for coverage */
95478  int iCur;        /* Cursor number for the table corresponding to the index */
95479};
95480
95481/*
95482** Check to see if there are references to columns in table
95483** pWalker->u.pIdxCover->iCur can be satisfied using the index
95484** pWalker->u.pIdxCover->pIdx.
95485*/
95486static int exprIdxCover(Walker *pWalker, Expr *pExpr){
95487  if( pExpr->op==TK_COLUMN
95488   && pExpr->iTable==pWalker->u.pIdxCover->iCur
95489   && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
95490  ){
95491    pWalker->eCode = 1;
95492    return WRC_Abort;
95493  }
95494  return WRC_Continue;
95495}
95496
95497/*
95498** Determine if an index pIdx on table with cursor iCur contains will
95499** the expression pExpr.  Return true if the index does cover the
95500** expression and false if the pExpr expression references table columns
95501** that are not found in the index pIdx.
95502**
95503** An index covering an expression means that the expression can be
95504** evaluated using only the index and without having to lookup the
95505** corresponding table entry.
95506*/
95507SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
95508  Expr *pExpr,        /* The index to be tested */
95509  int iCur,           /* The cursor number for the corresponding table */
95510  Index *pIdx         /* The index that might be used for coverage */
95511){
95512  Walker w;
95513  struct IdxCover xcov;
95514  memset(&w, 0, sizeof(w));
95515  xcov.iCur = iCur;
95516  xcov.pIdx = pIdx;
95517  w.xExprCallback = exprIdxCover;
95518  w.u.pIdxCover = &xcov;
95519  sqlite3WalkExpr(&w, pExpr);
95520  return !w.eCode;
95521}
95522
95523
95524/*
95525** An instance of the following structure is used by the tree walker
95526** to count references to table columns in the arguments of an
95527** aggregate function, in order to implement the
95528** sqlite3FunctionThisSrc() routine.
95529*/
95530struct SrcCount {
95531  SrcList *pSrc;   /* One particular FROM clause in a nested query */
95532  int nThis;       /* Number of references to columns in pSrcList */
95533  int nOther;      /* Number of references to columns in other FROM clauses */
95534};
95535
95536/*
95537** Count the number of references to columns.
95538*/
95539static int exprSrcCount(Walker *pWalker, Expr *pExpr){
95540  /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
95541  ** is always called before sqlite3ExprAnalyzeAggregates() and so the
95542  ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
95543  ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
95544  ** NEVER() will need to be removed. */
95545  if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
95546    int i;
95547    struct SrcCount *p = pWalker->u.pSrcCount;
95548    SrcList *pSrc = p->pSrc;
95549    int nSrc = pSrc ? pSrc->nSrc : 0;
95550    for(i=0; i<nSrc; i++){
95551      if( pExpr->iTable==pSrc->a[i].iCursor ) break;
95552    }
95553    if( i<nSrc ){
95554      p->nThis++;
95555    }else{
95556      p->nOther++;
95557    }
95558  }
95559  return WRC_Continue;
95560}
95561
95562/*
95563** Determine if any of the arguments to the pExpr Function reference
95564** pSrcList.  Return true if they do.  Also return true if the function
95565** has no arguments or has only constant arguments.  Return false if pExpr
95566** references columns but not columns of tables found in pSrcList.
95567*/
95568SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
95569  Walker w;
95570  struct SrcCount cnt;
95571  assert( pExpr->op==TK_AGG_FUNCTION );
95572  memset(&w, 0, sizeof(w));
95573  w.xExprCallback = exprSrcCount;
95574  w.u.pSrcCount = &cnt;
95575  cnt.pSrc = pSrcList;
95576  cnt.nThis = 0;
95577  cnt.nOther = 0;
95578  sqlite3WalkExprList(&w, pExpr->x.pList);
95579  return cnt.nThis>0 || cnt.nOther==0;
95580}
95581
95582/*
95583** Add a new element to the pAggInfo->aCol[] array.  Return the index of
95584** the new element.  Return a negative number if malloc fails.
95585*/
95586static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
95587  int i;
95588  pInfo->aCol = sqlite3ArrayAllocate(
95589       db,
95590       pInfo->aCol,
95591       sizeof(pInfo->aCol[0]),
95592       &pInfo->nColumn,
95593       &i
95594  );
95595  return i;
95596}
95597
95598/*
95599** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
95600** the new element.  Return a negative number if malloc fails.
95601*/
95602static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
95603  int i;
95604  pInfo->aFunc = sqlite3ArrayAllocate(
95605       db,
95606       pInfo->aFunc,
95607       sizeof(pInfo->aFunc[0]),
95608       &pInfo->nFunc,
95609       &i
95610  );
95611  return i;
95612}
95613
95614/*
95615** This is the xExprCallback for a tree walker.  It is used to
95616** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
95617** for additional information.
95618*/
95619static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
95620  int i;
95621  NameContext *pNC = pWalker->u.pNC;
95622  Parse *pParse = pNC->pParse;
95623  SrcList *pSrcList = pNC->pSrcList;
95624  AggInfo *pAggInfo = pNC->pAggInfo;
95625
95626  switch( pExpr->op ){
95627    case TK_AGG_COLUMN:
95628    case TK_COLUMN: {
95629      testcase( pExpr->op==TK_AGG_COLUMN );
95630      testcase( pExpr->op==TK_COLUMN );
95631      /* Check to see if the column is in one of the tables in the FROM
95632      ** clause of the aggregate query */
95633      if( ALWAYS(pSrcList!=0) ){
95634        struct SrcList_item *pItem = pSrcList->a;
95635        for(i=0; i<pSrcList->nSrc; i++, pItem++){
95636          struct AggInfo_col *pCol;
95637          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
95638          if( pExpr->iTable==pItem->iCursor ){
95639            /* If we reach this point, it means that pExpr refers to a table
95640            ** that is in the FROM clause of the aggregate query.
95641            **
95642            ** Make an entry for the column in pAggInfo->aCol[] if there
95643            ** is not an entry there already.
95644            */
95645            int k;
95646            pCol = pAggInfo->aCol;
95647            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
95648              if( pCol->iTable==pExpr->iTable &&
95649                  pCol->iColumn==pExpr->iColumn ){
95650                break;
95651              }
95652            }
95653            if( (k>=pAggInfo->nColumn)
95654             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
95655            ){
95656              pCol = &pAggInfo->aCol[k];
95657              pCol->pTab = pExpr->pTab;
95658              pCol->iTable = pExpr->iTable;
95659              pCol->iColumn = pExpr->iColumn;
95660              pCol->iMem = ++pParse->nMem;
95661              pCol->iSorterColumn = -1;
95662              pCol->pExpr = pExpr;
95663              if( pAggInfo->pGroupBy ){
95664                int j, n;
95665                ExprList *pGB = pAggInfo->pGroupBy;
95666                struct ExprList_item *pTerm = pGB->a;
95667                n = pGB->nExpr;
95668                for(j=0; j<n; j++, pTerm++){
95669                  Expr *pE = pTerm->pExpr;
95670                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
95671                      pE->iColumn==pExpr->iColumn ){
95672                    pCol->iSorterColumn = j;
95673                    break;
95674                  }
95675                }
95676              }
95677              if( pCol->iSorterColumn<0 ){
95678                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
95679              }
95680            }
95681            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
95682            ** because it was there before or because we just created it).
95683            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
95684            ** pAggInfo->aCol[] entry.
95685            */
95686            ExprSetVVAProperty(pExpr, EP_NoReduce);
95687            pExpr->pAggInfo = pAggInfo;
95688            pExpr->op = TK_AGG_COLUMN;
95689            pExpr->iAgg = (i16)k;
95690            break;
95691          } /* endif pExpr->iTable==pItem->iCursor */
95692        } /* end loop over pSrcList */
95693      }
95694      return WRC_Prune;
95695    }
95696    case TK_AGG_FUNCTION: {
95697      if( (pNC->ncFlags & NC_InAggFunc)==0
95698       && pWalker->walkerDepth==pExpr->op2
95699      ){
95700        /* Check to see if pExpr is a duplicate of another aggregate
95701        ** function that is already in the pAggInfo structure
95702        */
95703        struct AggInfo_func *pItem = pAggInfo->aFunc;
95704        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
95705          if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
95706            break;
95707          }
95708        }
95709        if( i>=pAggInfo->nFunc ){
95710          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
95711          */
95712          u8 enc = ENC(pParse->db);
95713          i = addAggInfoFunc(pParse->db, pAggInfo);
95714          if( i>=0 ){
95715            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
95716            pItem = &pAggInfo->aFunc[i];
95717            pItem->pExpr = pExpr;
95718            pItem->iMem = ++pParse->nMem;
95719            assert( !ExprHasProperty(pExpr, EP_IntValue) );
95720            pItem->pFunc = sqlite3FindFunction(pParse->db,
95721                   pExpr->u.zToken,
95722                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
95723            if( pExpr->flags & EP_Distinct ){
95724              pItem->iDistinct = pParse->nTab++;
95725            }else{
95726              pItem->iDistinct = -1;
95727            }
95728          }
95729        }
95730        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
95731        */
95732        assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
95733        ExprSetVVAProperty(pExpr, EP_NoReduce);
95734        pExpr->iAgg = (i16)i;
95735        pExpr->pAggInfo = pAggInfo;
95736        return WRC_Prune;
95737      }else{
95738        return WRC_Continue;
95739      }
95740    }
95741  }
95742  return WRC_Continue;
95743}
95744static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
95745  UNUSED_PARAMETER(pWalker);
95746  UNUSED_PARAMETER(pSelect);
95747  return WRC_Continue;
95748}
95749
95750/*
95751** Analyze the pExpr expression looking for aggregate functions and
95752** for variables that need to be added to AggInfo object that pNC->pAggInfo
95753** points to.  Additional entries are made on the AggInfo object as
95754** necessary.
95755**
95756** This routine should only be called after the expression has been
95757** analyzed by sqlite3ResolveExprNames().
95758*/
95759SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
95760  Walker w;
95761  memset(&w, 0, sizeof(w));
95762  w.xExprCallback = analyzeAggregate;
95763  w.xSelectCallback = analyzeAggregatesInSelect;
95764  w.u.pNC = pNC;
95765  assert( pNC->pSrcList!=0 );
95766  sqlite3WalkExpr(&w, pExpr);
95767}
95768
95769/*
95770** Call sqlite3ExprAnalyzeAggregates() for every expression in an
95771** expression list.  Return the number of errors.
95772**
95773** If an error is found, the analysis is cut short.
95774*/
95775SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
95776  struct ExprList_item *pItem;
95777  int i;
95778  if( pList ){
95779    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
95780      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
95781    }
95782  }
95783}
95784
95785/*
95786** Allocate a single new register for use to hold some intermediate result.
95787*/
95788SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
95789  if( pParse->nTempReg==0 ){
95790    return ++pParse->nMem;
95791  }
95792  return pParse->aTempReg[--pParse->nTempReg];
95793}
95794
95795/*
95796** Deallocate a register, making available for reuse for some other
95797** purpose.
95798**
95799** If a register is currently being used by the column cache, then
95800** the deallocation is deferred until the column cache line that uses
95801** the register becomes stale.
95802*/
95803SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
95804  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
95805    int i;
95806    struct yColCache *p;
95807    for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
95808      if( p->iReg==iReg ){
95809        p->tempReg = 1;
95810        return;
95811      }
95812    }
95813    pParse->aTempReg[pParse->nTempReg++] = iReg;
95814  }
95815}
95816
95817/*
95818** Allocate or deallocate a block of nReg consecutive registers.
95819*/
95820SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
95821  int i, n;
95822  if( nReg==1 ) return sqlite3GetTempReg(pParse);
95823  i = pParse->iRangeReg;
95824  n = pParse->nRangeReg;
95825  if( nReg<=n ){
95826    assert( !usedAsColumnCache(pParse, i, i+n-1) );
95827    pParse->iRangeReg += nReg;
95828    pParse->nRangeReg -= nReg;
95829  }else{
95830    i = pParse->nMem+1;
95831    pParse->nMem += nReg;
95832  }
95833  return i;
95834}
95835SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
95836  if( nReg==1 ){
95837    sqlite3ReleaseTempReg(pParse, iReg);
95838    return;
95839  }
95840  sqlite3ExprCacheRemove(pParse, iReg, nReg);
95841  if( nReg>pParse->nRangeReg ){
95842    pParse->nRangeReg = nReg;
95843    pParse->iRangeReg = iReg;
95844  }
95845}
95846
95847/*
95848** Mark all temporary registers as being unavailable for reuse.
95849*/
95850SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
95851  pParse->nTempReg = 0;
95852  pParse->nRangeReg = 0;
95853}
95854
95855/*
95856** Validate that no temporary register falls within the range of
95857** iFirst..iLast, inclusive.  This routine is only call from within assert()
95858** statements.
95859*/
95860#ifdef SQLITE_DEBUG
95861SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
95862  int i;
95863  if( pParse->nRangeReg>0
95864   && pParse->iRangeReg+pParse->nRangeReg<iLast
95865   && pParse->iRangeReg>=iFirst
95866  ){
95867     return 0;
95868  }
95869  for(i=0; i<pParse->nTempReg; i++){
95870    if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
95871      return 0;
95872    }
95873  }
95874  return 1;
95875}
95876#endif /* SQLITE_DEBUG */
95877
95878/************** End of expr.c ************************************************/
95879/************** Begin file alter.c *******************************************/
95880/*
95881** 2005 February 15
95882**
95883** The author disclaims copyright to this source code.  In place of
95884** a legal notice, here is a blessing:
95885**
95886**    May you do good and not evil.
95887**    May you find forgiveness for yourself and forgive others.
95888**    May you share freely, never taking more than you give.
95889**
95890*************************************************************************
95891** This file contains C code routines that used to generate VDBE code
95892** that implements the ALTER TABLE command.
95893*/
95894/* #include "sqliteInt.h" */
95895
95896/*
95897** The code in this file only exists if we are not omitting the
95898** ALTER TABLE logic from the build.
95899*/
95900#ifndef SQLITE_OMIT_ALTERTABLE
95901
95902
95903/*
95904** This function is used by SQL generated to implement the
95905** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
95906** CREATE INDEX command. The second is a table name. The table name in
95907** the CREATE TABLE or CREATE INDEX statement is replaced with the third
95908** argument and the result returned. Examples:
95909**
95910** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
95911**     -> 'CREATE TABLE def(a, b, c)'
95912**
95913** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
95914**     -> 'CREATE INDEX i ON def(a, b, c)'
95915*/
95916static void renameTableFunc(
95917  sqlite3_context *context,
95918  int NotUsed,
95919  sqlite3_value **argv
95920){
95921  unsigned char const *zSql = sqlite3_value_text(argv[0]);
95922  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
95923
95924  int token;
95925  Token tname;
95926  unsigned char const *zCsr = zSql;
95927  int len = 0;
95928  char *zRet;
95929
95930  sqlite3 *db = sqlite3_context_db_handle(context);
95931
95932  UNUSED_PARAMETER(NotUsed);
95933
95934  /* The principle used to locate the table name in the CREATE TABLE
95935  ** statement is that the table name is the first non-space token that
95936  ** is immediately followed by a TK_LP or TK_USING token.
95937  */
95938  if( zSql ){
95939    do {
95940      if( !*zCsr ){
95941        /* Ran out of input before finding an opening bracket. Return NULL. */
95942        return;
95943      }
95944
95945      /* Store the token that zCsr points to in tname. */
95946      tname.z = (char*)zCsr;
95947      tname.n = len;
95948
95949      /* Advance zCsr to the next token. Store that token type in 'token',
95950      ** and its length in 'len' (to be used next iteration of this loop).
95951      */
95952      do {
95953        zCsr += len;
95954        len = sqlite3GetToken(zCsr, &token);
95955      } while( token==TK_SPACE );
95956      assert( len>0 );
95957    } while( token!=TK_LP && token!=TK_USING );
95958
95959    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
95960       zSql, zTableName, tname.z+tname.n);
95961    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
95962  }
95963}
95964
95965/*
95966** This C function implements an SQL user function that is used by SQL code
95967** generated by the ALTER TABLE ... RENAME command to modify the definition
95968** of any foreign key constraints that use the table being renamed as the
95969** parent table. It is passed three arguments:
95970**
95971**   1) The complete text of the CREATE TABLE statement being modified,
95972**   2) The old name of the table being renamed, and
95973**   3) The new name of the table being renamed.
95974**
95975** It returns the new CREATE TABLE statement. For example:
95976**
95977**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
95978**       -> 'CREATE TABLE t1(a REFERENCES t3)'
95979*/
95980#ifndef SQLITE_OMIT_FOREIGN_KEY
95981static void renameParentFunc(
95982  sqlite3_context *context,
95983  int NotUsed,
95984  sqlite3_value **argv
95985){
95986  sqlite3 *db = sqlite3_context_db_handle(context);
95987  char *zOutput = 0;
95988  char *zResult;
95989  unsigned char const *zInput = sqlite3_value_text(argv[0]);
95990  unsigned char const *zOld = sqlite3_value_text(argv[1]);
95991  unsigned char const *zNew = sqlite3_value_text(argv[2]);
95992
95993  unsigned const char *z;         /* Pointer to token */
95994  int n;                          /* Length of token z */
95995  int token;                      /* Type of token */
95996
95997  UNUSED_PARAMETER(NotUsed);
95998  if( zInput==0 || zOld==0 ) return;
95999  for(z=zInput; *z; z=z+n){
96000    n = sqlite3GetToken(z, &token);
96001    if( token==TK_REFERENCES ){
96002      char *zParent;
96003      do {
96004        z += n;
96005        n = sqlite3GetToken(z, &token);
96006      }while( token==TK_SPACE );
96007
96008      if( token==TK_ILLEGAL ) break;
96009      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
96010      if( zParent==0 ) break;
96011      sqlite3Dequote(zParent);
96012      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
96013        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
96014            (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
96015        );
96016        sqlite3DbFree(db, zOutput);
96017        zOutput = zOut;
96018        zInput = &z[n];
96019      }
96020      sqlite3DbFree(db, zParent);
96021    }
96022  }
96023
96024  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
96025  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
96026  sqlite3DbFree(db, zOutput);
96027}
96028#endif
96029
96030#ifndef SQLITE_OMIT_TRIGGER
96031/* This function is used by SQL generated to implement the
96032** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
96033** statement. The second is a table name. The table name in the CREATE
96034** TRIGGER statement is replaced with the third argument and the result
96035** returned. This is analagous to renameTableFunc() above, except for CREATE
96036** TRIGGER, not CREATE INDEX and CREATE TABLE.
96037*/
96038static void renameTriggerFunc(
96039  sqlite3_context *context,
96040  int NotUsed,
96041  sqlite3_value **argv
96042){
96043  unsigned char const *zSql = sqlite3_value_text(argv[0]);
96044  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
96045
96046  int token;
96047  Token tname;
96048  int dist = 3;
96049  unsigned char const *zCsr = zSql;
96050  int len = 0;
96051  char *zRet;
96052  sqlite3 *db = sqlite3_context_db_handle(context);
96053
96054  UNUSED_PARAMETER(NotUsed);
96055
96056  /* The principle used to locate the table name in the CREATE TRIGGER
96057  ** statement is that the table name is the first token that is immediately
96058  ** preceded by either TK_ON or TK_DOT and immediately followed by one
96059  ** of TK_WHEN, TK_BEGIN or TK_FOR.
96060  */
96061  if( zSql ){
96062    do {
96063
96064      if( !*zCsr ){
96065        /* Ran out of input before finding the table name. Return NULL. */
96066        return;
96067      }
96068
96069      /* Store the token that zCsr points to in tname. */
96070      tname.z = (char*)zCsr;
96071      tname.n = len;
96072
96073      /* Advance zCsr to the next token. Store that token type in 'token',
96074      ** and its length in 'len' (to be used next iteration of this loop).
96075      */
96076      do {
96077        zCsr += len;
96078        len = sqlite3GetToken(zCsr, &token);
96079      }while( token==TK_SPACE );
96080      assert( len>0 );
96081
96082      /* Variable 'dist' stores the number of tokens read since the most
96083      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
96084      ** token is read and 'dist' equals 2, the condition stated above
96085      ** to be met.
96086      **
96087      ** Note that ON cannot be a database, table or column name, so
96088      ** there is no need to worry about syntax like
96089      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
96090      */
96091      dist++;
96092      if( token==TK_DOT || token==TK_ON ){
96093        dist = 0;
96094      }
96095    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
96096
96097    /* Variable tname now contains the token that is the old table-name
96098    ** in the CREATE TRIGGER statement.
96099    */
96100    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
96101       zSql, zTableName, tname.z+tname.n);
96102    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
96103  }
96104}
96105#endif   /* !SQLITE_OMIT_TRIGGER */
96106
96107/*
96108** Register built-in functions used to help implement ALTER TABLE
96109*/
96110SQLITE_PRIVATE void sqlite3AlterFunctions(void){
96111  static FuncDef aAlterTableFuncs[] = {
96112    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
96113#ifndef SQLITE_OMIT_TRIGGER
96114    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
96115#endif
96116#ifndef SQLITE_OMIT_FOREIGN_KEY
96117    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
96118#endif
96119  };
96120  sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
96121}
96122
96123/*
96124** This function is used to create the text of expressions of the form:
96125**
96126**   name=<constant1> OR name=<constant2> OR ...
96127**
96128** If argument zWhere is NULL, then a pointer string containing the text
96129** "name=<constant>" is returned, where <constant> is the quoted version
96130** of the string passed as argument zConstant. The returned buffer is
96131** allocated using sqlite3DbMalloc(). It is the responsibility of the
96132** caller to ensure that it is eventually freed.
96133**
96134** If argument zWhere is not NULL, then the string returned is
96135** "<where> OR name=<constant>", where <where> is the contents of zWhere.
96136** In this case zWhere is passed to sqlite3DbFree() before returning.
96137**
96138*/
96139static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
96140  char *zNew;
96141  if( !zWhere ){
96142    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
96143  }else{
96144    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
96145    sqlite3DbFree(db, zWhere);
96146  }
96147  return zNew;
96148}
96149
96150#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
96151/*
96152** Generate the text of a WHERE expression which can be used to select all
96153** tables that have foreign key constraints that refer to table pTab (i.e.
96154** constraints for which pTab is the parent table) from the sqlite_master
96155** table.
96156*/
96157static char *whereForeignKeys(Parse *pParse, Table *pTab){
96158  FKey *p;
96159  char *zWhere = 0;
96160  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
96161    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
96162  }
96163  return zWhere;
96164}
96165#endif
96166
96167/*
96168** Generate the text of a WHERE expression which can be used to select all
96169** temporary triggers on table pTab from the sqlite_temp_master table. If
96170** table pTab has no temporary triggers, or is itself stored in the
96171** temporary database, NULL is returned.
96172*/
96173static char *whereTempTriggers(Parse *pParse, Table *pTab){
96174  Trigger *pTrig;
96175  char *zWhere = 0;
96176  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
96177
96178  /* If the table is not located in the temp-db (in which case NULL is
96179  ** returned, loop through the tables list of triggers. For each trigger
96180  ** that is not part of the temp-db schema, add a clause to the WHERE
96181  ** expression being built up in zWhere.
96182  */
96183  if( pTab->pSchema!=pTempSchema ){
96184    sqlite3 *db = pParse->db;
96185    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
96186      if( pTrig->pSchema==pTempSchema ){
96187        zWhere = whereOrName(db, zWhere, pTrig->zName);
96188      }
96189    }
96190  }
96191  if( zWhere ){
96192    char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
96193    sqlite3DbFree(pParse->db, zWhere);
96194    zWhere = zNew;
96195  }
96196  return zWhere;
96197}
96198
96199/*
96200** Generate code to drop and reload the internal representation of table
96201** pTab from the database, including triggers and temporary triggers.
96202** Argument zName is the name of the table in the database schema at
96203** the time the generated code is executed. This can be different from
96204** pTab->zName if this function is being called to code part of an
96205** "ALTER TABLE RENAME TO" statement.
96206*/
96207static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
96208  Vdbe *v;
96209  char *zWhere;
96210  int iDb;                   /* Index of database containing pTab */
96211#ifndef SQLITE_OMIT_TRIGGER
96212  Trigger *pTrig;
96213#endif
96214
96215  v = sqlite3GetVdbe(pParse);
96216  if( NEVER(v==0) ) return;
96217  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
96218  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
96219  assert( iDb>=0 );
96220
96221#ifndef SQLITE_OMIT_TRIGGER
96222  /* Drop any table triggers from the internal schema. */
96223  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
96224    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
96225    assert( iTrigDb==iDb || iTrigDb==1 );
96226    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
96227  }
96228#endif
96229
96230  /* Drop the table and index from the internal schema.  */
96231  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
96232
96233  /* Reload the table, index and permanent trigger schemas. */
96234  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
96235  if( !zWhere ) return;
96236  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
96237
96238#ifndef SQLITE_OMIT_TRIGGER
96239  /* Now, if the table is not stored in the temp database, reload any temp
96240  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
96241  */
96242  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
96243    sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
96244  }
96245#endif
96246}
96247
96248/*
96249** Parameter zName is the name of a table that is about to be altered
96250** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
96251** If the table is a system table, this function leaves an error message
96252** in pParse->zErr (system tables may not be altered) and returns non-zero.
96253**
96254** Or, if zName is not a system table, zero is returned.
96255*/
96256static int isSystemTable(Parse *pParse, const char *zName){
96257  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
96258    sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
96259    return 1;
96260  }
96261  return 0;
96262}
96263
96264/*
96265** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
96266** command.
96267*/
96268SQLITE_PRIVATE void sqlite3AlterRenameTable(
96269  Parse *pParse,            /* Parser context. */
96270  SrcList *pSrc,            /* The table to rename. */
96271  Token *pName              /* The new table name. */
96272){
96273  int iDb;                  /* Database that contains the table */
96274  char *zDb;                /* Name of database iDb */
96275  Table *pTab;              /* Table being renamed */
96276  char *zName = 0;          /* NULL-terminated version of pName */
96277  sqlite3 *db = pParse->db; /* Database connection */
96278  int nTabName;             /* Number of UTF-8 characters in zTabName */
96279  const char *zTabName;     /* Original name of the table */
96280  Vdbe *v;
96281#ifndef SQLITE_OMIT_TRIGGER
96282  char *zWhere = 0;         /* Where clause to locate temp triggers */
96283#endif
96284  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
96285  int savedDbFlags;         /* Saved value of db->flags */
96286
96287  savedDbFlags = db->flags;
96288  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
96289  assert( pSrc->nSrc==1 );
96290  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
96291
96292  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
96293  if( !pTab ) goto exit_rename_table;
96294  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
96295  zDb = db->aDb[iDb].zDbSName;
96296  db->flags |= SQLITE_PreferBuiltin;
96297
96298  /* Get a NULL terminated version of the new table name. */
96299  zName = sqlite3NameFromToken(db, pName);
96300  if( !zName ) goto exit_rename_table;
96301
96302  /* Check that a table or index named 'zName' does not already exist
96303  ** in database iDb. If so, this is an error.
96304  */
96305  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
96306    sqlite3ErrorMsg(pParse,
96307        "there is already another table or index with this name: %s", zName);
96308    goto exit_rename_table;
96309  }
96310
96311  /* Make sure it is not a system table being altered, or a reserved name
96312  ** that the table is being renamed to.
96313  */
96314  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
96315    goto exit_rename_table;
96316  }
96317  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
96318    exit_rename_table;
96319  }
96320
96321#ifndef SQLITE_OMIT_VIEW
96322  if( pTab->pSelect ){
96323    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
96324    goto exit_rename_table;
96325  }
96326#endif
96327
96328#ifndef SQLITE_OMIT_AUTHORIZATION
96329  /* Invoke the authorization callback. */
96330  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
96331    goto exit_rename_table;
96332  }
96333#endif
96334
96335#ifndef SQLITE_OMIT_VIRTUALTABLE
96336  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
96337    goto exit_rename_table;
96338  }
96339  if( IsVirtual(pTab) ){
96340    pVTab = sqlite3GetVTable(db, pTab);
96341    if( pVTab->pVtab->pModule->xRename==0 ){
96342      pVTab = 0;
96343    }
96344  }
96345#endif
96346
96347  /* Begin a transaction for database iDb.
96348  ** Then modify the schema cookie (since the ALTER TABLE modifies the
96349  ** schema). Open a statement transaction if the table is a virtual
96350  ** table.
96351  */
96352  v = sqlite3GetVdbe(pParse);
96353  if( v==0 ){
96354    goto exit_rename_table;
96355  }
96356  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
96357  sqlite3ChangeCookie(pParse, iDb);
96358
96359  /* If this is a virtual table, invoke the xRename() function if
96360  ** one is defined. The xRename() callback will modify the names
96361  ** of any resources used by the v-table implementation (including other
96362  ** SQLite tables) that are identified by the name of the virtual table.
96363  */
96364#ifndef SQLITE_OMIT_VIRTUALTABLE
96365  if( pVTab ){
96366    int i = ++pParse->nMem;
96367    sqlite3VdbeLoadString(v, i, zName);
96368    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
96369    sqlite3MayAbort(pParse);
96370  }
96371#endif
96372
96373  /* figure out how many UTF-8 characters are in zName */
96374  zTabName = pTab->zName;
96375  nTabName = sqlite3Utf8CharLen(zTabName, -1);
96376
96377#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
96378  if( db->flags&SQLITE_ForeignKeys ){
96379    /* If foreign-key support is enabled, rewrite the CREATE TABLE
96380    ** statements corresponding to all child tables of foreign key constraints
96381    ** for which the renamed table is the parent table.  */
96382    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
96383      sqlite3NestedParse(pParse,
96384          "UPDATE \"%w\".%s SET "
96385              "sql = sqlite_rename_parent(sql, %Q, %Q) "
96386              "WHERE %s;", zDb, MASTER_NAME, zTabName, zName, zWhere);
96387      sqlite3DbFree(db, zWhere);
96388    }
96389  }
96390#endif
96391
96392  /* Modify the sqlite_master table to use the new table name. */
96393  sqlite3NestedParse(pParse,
96394      "UPDATE %Q.%s SET "
96395#ifdef SQLITE_OMIT_TRIGGER
96396          "sql = sqlite_rename_table(sql, %Q), "
96397#else
96398          "sql = CASE "
96399            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
96400            "ELSE sqlite_rename_table(sql, %Q) END, "
96401#endif
96402          "tbl_name = %Q, "
96403          "name = CASE "
96404            "WHEN type='table' THEN %Q "
96405            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
96406             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
96407            "ELSE name END "
96408      "WHERE tbl_name=%Q COLLATE nocase AND "
96409          "(type='table' OR type='index' OR type='trigger');",
96410      zDb, MASTER_NAME, zName, zName, zName,
96411#ifndef SQLITE_OMIT_TRIGGER
96412      zName,
96413#endif
96414      zName, nTabName, zTabName
96415  );
96416
96417#ifndef SQLITE_OMIT_AUTOINCREMENT
96418  /* If the sqlite_sequence table exists in this database, then update
96419  ** it with the new table name.
96420  */
96421  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
96422    sqlite3NestedParse(pParse,
96423        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
96424        zDb, zName, pTab->zName);
96425  }
96426#endif
96427
96428#ifndef SQLITE_OMIT_TRIGGER
96429  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
96430  ** table. Don't do this if the table being ALTERed is itself located in
96431  ** the temp database.
96432  */
96433  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
96434    sqlite3NestedParse(pParse,
96435        "UPDATE sqlite_temp_master SET "
96436            "sql = sqlite_rename_trigger(sql, %Q), "
96437            "tbl_name = %Q "
96438            "WHERE %s;", zName, zName, zWhere);
96439    sqlite3DbFree(db, zWhere);
96440  }
96441#endif
96442
96443#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
96444  if( db->flags&SQLITE_ForeignKeys ){
96445    FKey *p;
96446    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
96447      Table *pFrom = p->pFrom;
96448      if( pFrom!=pTab ){
96449        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
96450      }
96451    }
96452  }
96453#endif
96454
96455  /* Drop and reload the internal table schema. */
96456  reloadTableSchema(pParse, pTab, zName);
96457
96458exit_rename_table:
96459  sqlite3SrcListDelete(db, pSrc);
96460  sqlite3DbFree(db, zName);
96461  db->flags = savedDbFlags;
96462}
96463
96464/*
96465** This function is called after an "ALTER TABLE ... ADD" statement
96466** has been parsed. Argument pColDef contains the text of the new
96467** column definition.
96468**
96469** The Table structure pParse->pNewTable was extended to include
96470** the new column during parsing.
96471*/
96472SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
96473  Table *pNew;              /* Copy of pParse->pNewTable */
96474  Table *pTab;              /* Table being altered */
96475  int iDb;                  /* Database number */
96476  const char *zDb;          /* Database name */
96477  const char *zTab;         /* Table name */
96478  char *zCol;               /* Null-terminated column definition */
96479  Column *pCol;             /* The new column */
96480  Expr *pDflt;              /* Default value for the new column */
96481  sqlite3 *db;              /* The database connection; */
96482  Vdbe *v = pParse->pVdbe;  /* The prepared statement under construction */
96483  int r1;                   /* Temporary registers */
96484
96485  db = pParse->db;
96486  if( pParse->nErr || db->mallocFailed ) return;
96487  assert( v!=0 );
96488  pNew = pParse->pNewTable;
96489  assert( pNew );
96490
96491  assert( sqlite3BtreeHoldsAllMutexes(db) );
96492  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
96493  zDb = db->aDb[iDb].zDbSName;
96494  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
96495  pCol = &pNew->aCol[pNew->nCol-1];
96496  pDflt = pCol->pDflt;
96497  pTab = sqlite3FindTable(db, zTab, zDb);
96498  assert( pTab );
96499
96500#ifndef SQLITE_OMIT_AUTHORIZATION
96501  /* Invoke the authorization callback. */
96502  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
96503    return;
96504  }
96505#endif
96506
96507  /* If the default value for the new column was specified with a
96508  ** literal NULL, then set pDflt to 0. This simplifies checking
96509  ** for an SQL NULL default below.
96510  */
96511  assert( pDflt==0 || pDflt->op==TK_SPAN );
96512  if( pDflt && pDflt->pLeft->op==TK_NULL ){
96513    pDflt = 0;
96514  }
96515
96516  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
96517  ** If there is a NOT NULL constraint, then the default value for the
96518  ** column must not be NULL.
96519  */
96520  if( pCol->colFlags & COLFLAG_PRIMKEY ){
96521    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
96522    return;
96523  }
96524  if( pNew->pIndex ){
96525    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
96526    return;
96527  }
96528  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
96529    sqlite3ErrorMsg(pParse,
96530        "Cannot add a REFERENCES column with non-NULL default value");
96531    return;
96532  }
96533  if( pCol->notNull && !pDflt ){
96534    sqlite3ErrorMsg(pParse,
96535        "Cannot add a NOT NULL column with default value NULL");
96536    return;
96537  }
96538
96539  /* Ensure the default expression is something that sqlite3ValueFromExpr()
96540  ** can handle (i.e. not CURRENT_TIME etc.)
96541  */
96542  if( pDflt ){
96543    sqlite3_value *pVal = 0;
96544    int rc;
96545    rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
96546    assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
96547    if( rc!=SQLITE_OK ){
96548      assert( db->mallocFailed == 1 );
96549      return;
96550    }
96551    if( !pVal ){
96552      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
96553      return;
96554    }
96555    sqlite3ValueFree(pVal);
96556  }
96557
96558  /* Modify the CREATE TABLE statement. */
96559  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
96560  if( zCol ){
96561    char *zEnd = &zCol[pColDef->n-1];
96562    int savedDbFlags = db->flags;
96563    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
96564      *zEnd-- = '\0';
96565    }
96566    db->flags |= SQLITE_PreferBuiltin;
96567    sqlite3NestedParse(pParse,
96568        "UPDATE \"%w\".%s SET "
96569          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
96570        "WHERE type = 'table' AND name = %Q",
96571      zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
96572      zTab
96573    );
96574    sqlite3DbFree(db, zCol);
96575    db->flags = savedDbFlags;
96576  }
96577
96578  /* Make sure the schema version is at least 3.  But do not upgrade
96579  ** from less than 3 to 4, as that will corrupt any preexisting DESC
96580  ** index.
96581  */
96582  r1 = sqlite3GetTempReg(pParse);
96583  sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
96584  sqlite3VdbeUsesBtree(v, iDb);
96585  sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
96586  sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
96587  VdbeCoverage(v);
96588  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
96589  sqlite3ReleaseTempReg(pParse, r1);
96590
96591  /* Reload the schema of the modified table. */
96592  reloadTableSchema(pParse, pTab, pTab->zName);
96593}
96594
96595/*
96596** This function is called by the parser after the table-name in
96597** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
96598** pSrc is the full-name of the table being altered.
96599**
96600** This routine makes a (partial) copy of the Table structure
96601** for the table being altered and sets Parse.pNewTable to point
96602** to it. Routines called by the parser as the column definition
96603** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
96604** the copy. The copy of the Table structure is deleted by tokenize.c
96605** after parsing is finished.
96606**
96607** Routine sqlite3AlterFinishAddColumn() will be called to complete
96608** coding the "ALTER TABLE ... ADD" statement.
96609*/
96610SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
96611  Table *pNew;
96612  Table *pTab;
96613  Vdbe *v;
96614  int iDb;
96615  int i;
96616  int nAlloc;
96617  sqlite3 *db = pParse->db;
96618
96619  /* Look up the table being altered. */
96620  assert( pParse->pNewTable==0 );
96621  assert( sqlite3BtreeHoldsAllMutexes(db) );
96622  if( db->mallocFailed ) goto exit_begin_add_column;
96623  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
96624  if( !pTab ) goto exit_begin_add_column;
96625
96626#ifndef SQLITE_OMIT_VIRTUALTABLE
96627  if( IsVirtual(pTab) ){
96628    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
96629    goto exit_begin_add_column;
96630  }
96631#endif
96632
96633  /* Make sure this is not an attempt to ALTER a view. */
96634  if( pTab->pSelect ){
96635    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
96636    goto exit_begin_add_column;
96637  }
96638  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
96639    goto exit_begin_add_column;
96640  }
96641
96642  assert( pTab->addColOffset>0 );
96643  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
96644
96645  /* Put a copy of the Table struct in Parse.pNewTable for the
96646  ** sqlite3AddColumn() function and friends to modify.  But modify
96647  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
96648  ** prefix, we insure that the name will not collide with an existing
96649  ** table because user table are not allowed to have the "sqlite_"
96650  ** prefix on their name.
96651  */
96652  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
96653  if( !pNew ) goto exit_begin_add_column;
96654  pParse->pNewTable = pNew;
96655  pNew->nTabRef = 1;
96656  pNew->nCol = pTab->nCol;
96657  assert( pNew->nCol>0 );
96658  nAlloc = (((pNew->nCol-1)/8)*8)+8;
96659  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
96660  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
96661  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
96662  if( !pNew->aCol || !pNew->zName ){
96663    assert( db->mallocFailed );
96664    goto exit_begin_add_column;
96665  }
96666  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
96667  for(i=0; i<pNew->nCol; i++){
96668    Column *pCol = &pNew->aCol[i];
96669    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
96670    pCol->zColl = 0;
96671    pCol->pDflt = 0;
96672  }
96673  pNew->pSchema = db->aDb[iDb].pSchema;
96674  pNew->addColOffset = pTab->addColOffset;
96675  pNew->nTabRef = 1;
96676
96677  /* Begin a transaction and increment the schema cookie.  */
96678  sqlite3BeginWriteOperation(pParse, 0, iDb);
96679  v = sqlite3GetVdbe(pParse);
96680  if( !v ) goto exit_begin_add_column;
96681  sqlite3ChangeCookie(pParse, iDb);
96682
96683exit_begin_add_column:
96684  sqlite3SrcListDelete(db, pSrc);
96685  return;
96686}
96687#endif  /* SQLITE_ALTER_TABLE */
96688
96689/************** End of alter.c ***********************************************/
96690/************** Begin file analyze.c *****************************************/
96691/*
96692** 2005-07-08
96693**
96694** The author disclaims copyright to this source code.  In place of
96695** a legal notice, here is a blessing:
96696**
96697**    May you do good and not evil.
96698**    May you find forgiveness for yourself and forgive others.
96699**    May you share freely, never taking more than you give.
96700**
96701*************************************************************************
96702** This file contains code associated with the ANALYZE command.
96703**
96704** The ANALYZE command gather statistics about the content of tables
96705** and indices.  These statistics are made available to the query planner
96706** to help it make better decisions about how to perform queries.
96707**
96708** The following system tables are or have been supported:
96709**
96710**    CREATE TABLE sqlite_stat1(tbl, idx, stat);
96711**    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
96712**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
96713**    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
96714**
96715** Additional tables might be added in future releases of SQLite.
96716** The sqlite_stat2 table is not created or used unless the SQLite version
96717** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
96718** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
96719** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
96720** created and used by SQLite versions 3.7.9 and later and with
96721** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
96722** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
96723** version of sqlite_stat3 and is only available when compiled with
96724** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
96725** not possible to enable both STAT3 and STAT4 at the same time.  If they
96726** are both enabled, then STAT4 takes precedence.
96727**
96728** For most applications, sqlite_stat1 provides all the statistics required
96729** for the query planner to make good choices.
96730**
96731** Format of sqlite_stat1:
96732**
96733** There is normally one row per index, with the index identified by the
96734** name in the idx column.  The tbl column is the name of the table to
96735** which the index belongs.  In each such row, the stat column will be
96736** a string consisting of a list of integers.  The first integer in this
96737** list is the number of rows in the index.  (This is the same as the
96738** number of rows in the table, except for partial indices.)  The second
96739** integer is the average number of rows in the index that have the same
96740** value in the first column of the index.  The third integer is the average
96741** number of rows in the index that have the same value for the first two
96742** columns.  The N-th integer (for N>1) is the average number of rows in
96743** the index which have the same value for the first N-1 columns.  For
96744** a K-column index, there will be K+1 integers in the stat column.  If
96745** the index is unique, then the last integer will be 1.
96746**
96747** The list of integers in the stat column can optionally be followed
96748** by the keyword "unordered".  The "unordered" keyword, if it is present,
96749** must be separated from the last integer by a single space.  If the
96750** "unordered" keyword is present, then the query planner assumes that
96751** the index is unordered and will not use the index for a range query.
96752**
96753** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
96754** column contains a single integer which is the (estimated) number of
96755** rows in the table identified by sqlite_stat1.tbl.
96756**
96757** Format of sqlite_stat2:
96758**
96759** The sqlite_stat2 is only created and is only used if SQLite is compiled
96760** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
96761** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
96762** about the distribution of keys within an index.  The index is identified by
96763** the "idx" column and the "tbl" column is the name of the table to which
96764** the index belongs.  There are usually 10 rows in the sqlite_stat2
96765** table for each index.
96766**
96767** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
96768** inclusive are samples of the left-most key value in the index taken at
96769** evenly spaced points along the index.  Let the number of samples be S
96770** (10 in the standard build) and let C be the number of rows in the index.
96771** Then the sampled rows are given by:
96772**
96773**     rownumber = (i*C*2 + C)/(S*2)
96774**
96775** For i between 0 and S-1.  Conceptually, the index space is divided into
96776** S uniform buckets and the samples are the middle row from each bucket.
96777**
96778** The format for sqlite_stat2 is recorded here for legacy reference.  This
96779** version of SQLite does not support sqlite_stat2.  It neither reads nor
96780** writes the sqlite_stat2 table.  This version of SQLite only supports
96781** sqlite_stat3.
96782**
96783** Format for sqlite_stat3:
96784**
96785** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
96786** sqlite_stat4 format will be described first.  Further information
96787** about sqlite_stat3 follows the sqlite_stat4 description.
96788**
96789** Format for sqlite_stat4:
96790**
96791** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
96792** to aid the query planner in choosing good indices based on the values
96793** that indexed columns are compared against in the WHERE clauses of
96794** queries.
96795**
96796** The sqlite_stat4 table contains multiple entries for each index.
96797** The idx column names the index and the tbl column is the table of the
96798** index.  If the idx and tbl columns are the same, then the sample is
96799** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
96800** binary encoding of a key from the index.  The nEq column is a
96801** list of integers.  The first integer is the approximate number
96802** of entries in the index whose left-most column exactly matches
96803** the left-most column of the sample.  The second integer in nEq
96804** is the approximate number of entries in the index where the
96805** first two columns match the first two columns of the sample.
96806** And so forth.  nLt is another list of integers that show the approximate
96807** number of entries that are strictly less than the sample.  The first
96808** integer in nLt contains the number of entries in the index where the
96809** left-most column is less than the left-most column of the sample.
96810** The K-th integer in the nLt entry is the number of index entries
96811** where the first K columns are less than the first K columns of the
96812** sample.  The nDLt column is like nLt except that it contains the
96813** number of distinct entries in the index that are less than the
96814** sample.
96815**
96816** There can be an arbitrary number of sqlite_stat4 entries per index.
96817** The ANALYZE command will typically generate sqlite_stat4 tables
96818** that contain between 10 and 40 samples which are distributed across
96819** the key space, though not uniformly, and which include samples with
96820** large nEq values.
96821**
96822** Format for sqlite_stat3 redux:
96823**
96824** The sqlite_stat3 table is like sqlite_stat4 except that it only
96825** looks at the left-most column of the index.  The sqlite_stat3.sample
96826** column contains the actual value of the left-most column instead
96827** of a blob encoding of the complete index key as is found in
96828** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
96829** all contain just a single integer which is the same as the first
96830** integer in the equivalent columns in sqlite_stat4.
96831*/
96832#ifndef SQLITE_OMIT_ANALYZE
96833/* #include "sqliteInt.h" */
96834
96835#if defined(SQLITE_ENABLE_STAT4)
96836# define IsStat4     1
96837# define IsStat3     0
96838#elif defined(SQLITE_ENABLE_STAT3)
96839# define IsStat4     0
96840# define IsStat3     1
96841#else
96842# define IsStat4     0
96843# define IsStat3     0
96844# undef SQLITE_STAT4_SAMPLES
96845# define SQLITE_STAT4_SAMPLES 1
96846#endif
96847#define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
96848
96849/*
96850** This routine generates code that opens the sqlite_statN tables.
96851** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
96852** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
96853** appropriate compile-time options are provided.
96854**
96855** If the sqlite_statN tables do not previously exist, it is created.
96856**
96857** Argument zWhere may be a pointer to a buffer containing a table name,
96858** or it may be a NULL pointer. If it is not NULL, then all entries in
96859** the sqlite_statN tables associated with the named table are deleted.
96860** If zWhere==0, then code is generated to delete all stat table entries.
96861*/
96862static void openStatTable(
96863  Parse *pParse,          /* Parsing context */
96864  int iDb,                /* The database we are looking in */
96865  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
96866  const char *zWhere,     /* Delete entries for this table or index */
96867  const char *zWhereType  /* Either "tbl" or "idx" */
96868){
96869  static const struct {
96870    const char *zName;
96871    const char *zCols;
96872  } aTable[] = {
96873    { "sqlite_stat1", "tbl,idx,stat" },
96874#if defined(SQLITE_ENABLE_STAT4)
96875    { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
96876    { "sqlite_stat3", 0 },
96877#elif defined(SQLITE_ENABLE_STAT3)
96878    { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
96879    { "sqlite_stat4", 0 },
96880#else
96881    { "sqlite_stat3", 0 },
96882    { "sqlite_stat4", 0 },
96883#endif
96884  };
96885  int i;
96886  sqlite3 *db = pParse->db;
96887  Db *pDb;
96888  Vdbe *v = sqlite3GetVdbe(pParse);
96889  int aRoot[ArraySize(aTable)];
96890  u8 aCreateTbl[ArraySize(aTable)];
96891
96892  if( v==0 ) return;
96893  assert( sqlite3BtreeHoldsAllMutexes(db) );
96894  assert( sqlite3VdbeDb(v)==db );
96895  pDb = &db->aDb[iDb];
96896
96897  /* Create new statistic tables if they do not exist, or clear them
96898  ** if they do already exist.
96899  */
96900  for(i=0; i<ArraySize(aTable); i++){
96901    const char *zTab = aTable[i].zName;
96902    Table *pStat;
96903    if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
96904      if( aTable[i].zCols ){
96905        /* The sqlite_statN table does not exist. Create it. Note that a
96906        ** side-effect of the CREATE TABLE statement is to leave the rootpage
96907        ** of the new table in register pParse->regRoot. This is important
96908        ** because the OpenWrite opcode below will be needing it. */
96909        sqlite3NestedParse(pParse,
96910            "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
96911        );
96912        aRoot[i] = pParse->regRoot;
96913        aCreateTbl[i] = OPFLAG_P2ISREG;
96914      }
96915    }else{
96916      /* The table already exists. If zWhere is not NULL, delete all entries
96917      ** associated with the table zWhere. If zWhere is NULL, delete the
96918      ** entire contents of the table. */
96919      aRoot[i] = pStat->tnum;
96920      aCreateTbl[i] = 0;
96921      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
96922      if( zWhere ){
96923        sqlite3NestedParse(pParse,
96924           "DELETE FROM %Q.%s WHERE %s=%Q",
96925           pDb->zDbSName, zTab, zWhereType, zWhere
96926        );
96927      }else{
96928        /* The sqlite_stat[134] table already exists.  Delete all rows. */
96929        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
96930      }
96931    }
96932  }
96933
96934  /* Open the sqlite_stat[134] tables for writing. */
96935  for(i=0; aTable[i].zCols; i++){
96936    assert( i<ArraySize(aTable) );
96937    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
96938    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
96939    VdbeComment((v, aTable[i].zName));
96940  }
96941}
96942
96943/*
96944** Recommended number of samples for sqlite_stat4
96945*/
96946#ifndef SQLITE_STAT4_SAMPLES
96947# define SQLITE_STAT4_SAMPLES 24
96948#endif
96949
96950/*
96951** Three SQL functions - stat_init(), stat_push(), and stat_get() -
96952** share an instance of the following structure to hold their state
96953** information.
96954*/
96955typedef struct Stat4Accum Stat4Accum;
96956typedef struct Stat4Sample Stat4Sample;
96957struct Stat4Sample {
96958  tRowcnt *anEq;                  /* sqlite_stat4.nEq */
96959  tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
96960#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96961  tRowcnt *anLt;                  /* sqlite_stat4.nLt */
96962  union {
96963    i64 iRowid;                     /* Rowid in main table of the key */
96964    u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
96965  } u;
96966  u32 nRowid;                     /* Sizeof aRowid[] */
96967  u8 isPSample;                   /* True if a periodic sample */
96968  int iCol;                       /* If !isPSample, the reason for inclusion */
96969  u32 iHash;                      /* Tiebreaker hash */
96970#endif
96971};
96972struct Stat4Accum {
96973  tRowcnt nRow;             /* Number of rows in the entire table */
96974  tRowcnt nPSample;         /* How often to do a periodic sample */
96975  int nCol;                 /* Number of columns in index + pk/rowid */
96976  int nKeyCol;              /* Number of index columns w/o the pk/rowid */
96977  int mxSample;             /* Maximum number of samples to accumulate */
96978  Stat4Sample current;      /* Current row as a Stat4Sample */
96979  u32 iPrn;                 /* Pseudo-random number used for sampling */
96980  Stat4Sample *aBest;       /* Array of nCol best samples */
96981  int iMin;                 /* Index in a[] of entry with minimum score */
96982  int nSample;              /* Current number of samples */
96983  int nMaxEqZero;           /* Max leading 0 in anEq[] for any a[] entry */
96984  int iGet;                 /* Index of current sample accessed by stat_get() */
96985  Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
96986  sqlite3 *db;              /* Database connection, for malloc() */
96987};
96988
96989/* Reclaim memory used by a Stat4Sample
96990*/
96991#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96992static void sampleClear(sqlite3 *db, Stat4Sample *p){
96993  assert( db!=0 );
96994  if( p->nRowid ){
96995    sqlite3DbFree(db, p->u.aRowid);
96996    p->nRowid = 0;
96997  }
96998}
96999#endif
97000
97001/* Initialize the BLOB value of a ROWID
97002*/
97003#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97004static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
97005  assert( db!=0 );
97006  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
97007  p->u.aRowid = sqlite3DbMallocRawNN(db, n);
97008  if( p->u.aRowid ){
97009    p->nRowid = n;
97010    memcpy(p->u.aRowid, pData, n);
97011  }else{
97012    p->nRowid = 0;
97013  }
97014}
97015#endif
97016
97017/* Initialize the INTEGER value of a ROWID.
97018*/
97019#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97020static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
97021  assert( db!=0 );
97022  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
97023  p->nRowid = 0;
97024  p->u.iRowid = iRowid;
97025}
97026#endif
97027
97028
97029/*
97030** Copy the contents of object (*pFrom) into (*pTo).
97031*/
97032#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97033static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
97034  pTo->isPSample = pFrom->isPSample;
97035  pTo->iCol = pFrom->iCol;
97036  pTo->iHash = pFrom->iHash;
97037  memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
97038  memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
97039  memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
97040  if( pFrom->nRowid ){
97041    sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
97042  }else{
97043    sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
97044  }
97045}
97046#endif
97047
97048/*
97049** Reclaim all memory of a Stat4Accum structure.
97050*/
97051static void stat4Destructor(void *pOld){
97052  Stat4Accum *p = (Stat4Accum*)pOld;
97053#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97054  int i;
97055  for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
97056  for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
97057  sampleClear(p->db, &p->current);
97058#endif
97059  sqlite3DbFree(p->db, p);
97060}
97061
97062/*
97063** Implementation of the stat_init(N,K,C) SQL function. The three parameters
97064** are:
97065**     N:    The number of columns in the index including the rowid/pk (note 1)
97066**     K:    The number of columns in the index excluding the rowid/pk.
97067**     C:    The number of rows in the index (note 2)
97068**
97069** Note 1:  In the special case of the covering index that implements a
97070** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
97071** total number of columns in the table.
97072**
97073** Note 2:  C is only used for STAT3 and STAT4.
97074**
97075** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
97076** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
97077** PRIMARY KEY of the table.  The covering index that implements the
97078** original WITHOUT ROWID table as N==K as a special case.
97079**
97080** This routine allocates the Stat4Accum object in heap memory. The return
97081** value is a pointer to the Stat4Accum object.  The datatype of the
97082** return value is BLOB, but it is really just a pointer to the Stat4Accum
97083** object.
97084*/
97085static void statInit(
97086  sqlite3_context *context,
97087  int argc,
97088  sqlite3_value **argv
97089){
97090  Stat4Accum *p;
97091  int nCol;                       /* Number of columns in index being sampled */
97092  int nKeyCol;                    /* Number of key columns */
97093  int nColUp;                     /* nCol rounded up for alignment */
97094  int n;                          /* Bytes of space to allocate */
97095  sqlite3 *db;                    /* Database connection */
97096#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97097  int mxSample = SQLITE_STAT4_SAMPLES;
97098#endif
97099
97100  /* Decode the three function arguments */
97101  UNUSED_PARAMETER(argc);
97102  nCol = sqlite3_value_int(argv[0]);
97103  assert( nCol>0 );
97104  nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
97105  nKeyCol = sqlite3_value_int(argv[1]);
97106  assert( nKeyCol<=nCol );
97107  assert( nKeyCol>0 );
97108
97109  /* Allocate the space required for the Stat4Accum object */
97110  n = sizeof(*p)
97111    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
97112    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
97113#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97114    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
97115    + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
97116    + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
97117#endif
97118  ;
97119  db = sqlite3_context_db_handle(context);
97120  p = sqlite3DbMallocZero(db, n);
97121  if( p==0 ){
97122    sqlite3_result_error_nomem(context);
97123    return;
97124  }
97125
97126  p->db = db;
97127  p->nRow = 0;
97128  p->nCol = nCol;
97129  p->nKeyCol = nKeyCol;
97130  p->current.anDLt = (tRowcnt*)&p[1];
97131  p->current.anEq = &p->current.anDLt[nColUp];
97132
97133#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97134  {
97135    u8 *pSpace;                     /* Allocated space not yet assigned */
97136    int i;                          /* Used to iterate through p->aSample[] */
97137
97138    p->iGet = -1;
97139    p->mxSample = mxSample;
97140    p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
97141    p->current.anLt = &p->current.anEq[nColUp];
97142    p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
97143
97144    /* Set up the Stat4Accum.a[] and aBest[] arrays */
97145    p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
97146    p->aBest = &p->a[mxSample];
97147    pSpace = (u8*)(&p->a[mxSample+nCol]);
97148    for(i=0; i<(mxSample+nCol); i++){
97149      p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
97150      p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
97151      p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
97152    }
97153    assert( (pSpace - (u8*)p)==n );
97154
97155    for(i=0; i<nCol; i++){
97156      p->aBest[i].iCol = i;
97157    }
97158  }
97159#endif
97160
97161  /* Return a pointer to the allocated object to the caller.  Note that
97162  ** only the pointer (the 2nd parameter) matters.  The size of the object
97163  ** (given by the 3rd parameter) is never used and can be any positive
97164  ** value. */
97165  sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
97166}
97167static const FuncDef statInitFuncdef = {
97168  2+IsStat34,      /* nArg */
97169  SQLITE_UTF8,     /* funcFlags */
97170  0,               /* pUserData */
97171  0,               /* pNext */
97172  statInit,        /* xSFunc */
97173  0,               /* xFinalize */
97174  "stat_init",     /* zName */
97175  {0}
97176};
97177
97178#ifdef SQLITE_ENABLE_STAT4
97179/*
97180** pNew and pOld are both candidate non-periodic samples selected for
97181** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
97182** considering only any trailing columns and the sample hash value, this
97183** function returns true if sample pNew is to be preferred over pOld.
97184** In other words, if we assume that the cardinalities of the selected
97185** column for pNew and pOld are equal, is pNew to be preferred over pOld.
97186**
97187** This function assumes that for each argument sample, the contents of
97188** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
97189*/
97190static int sampleIsBetterPost(
97191  Stat4Accum *pAccum,
97192  Stat4Sample *pNew,
97193  Stat4Sample *pOld
97194){
97195  int nCol = pAccum->nCol;
97196  int i;
97197  assert( pNew->iCol==pOld->iCol );
97198  for(i=pNew->iCol+1; i<nCol; i++){
97199    if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
97200    if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
97201  }
97202  if( pNew->iHash>pOld->iHash ) return 1;
97203  return 0;
97204}
97205#endif
97206
97207#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97208/*
97209** Return true if pNew is to be preferred over pOld.
97210**
97211** This function assumes that for each argument sample, the contents of
97212** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
97213*/
97214static int sampleIsBetter(
97215  Stat4Accum *pAccum,
97216  Stat4Sample *pNew,
97217  Stat4Sample *pOld
97218){
97219  tRowcnt nEqNew = pNew->anEq[pNew->iCol];
97220  tRowcnt nEqOld = pOld->anEq[pOld->iCol];
97221
97222  assert( pOld->isPSample==0 && pNew->isPSample==0 );
97223  assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
97224
97225  if( (nEqNew>nEqOld) ) return 1;
97226#ifdef SQLITE_ENABLE_STAT4
97227  if( nEqNew==nEqOld ){
97228    if( pNew->iCol<pOld->iCol ) return 1;
97229    return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
97230  }
97231  return 0;
97232#else
97233  return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
97234#endif
97235}
97236
97237/*
97238** Copy the contents of sample *pNew into the p->a[] array. If necessary,
97239** remove the least desirable sample from p->a[] to make room.
97240*/
97241static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
97242  Stat4Sample *pSample = 0;
97243  int i;
97244
97245  assert( IsStat4 || nEqZero==0 );
97246
97247#ifdef SQLITE_ENABLE_STAT4
97248  /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
97249  ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
97250  ** other words, if nMaxEqZero is n, then it is guaranteed that there
97251  ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
97252  if( nEqZero>p->nMaxEqZero ){
97253    p->nMaxEqZero = nEqZero;
97254  }
97255  if( pNew->isPSample==0 ){
97256    Stat4Sample *pUpgrade = 0;
97257    assert( pNew->anEq[pNew->iCol]>0 );
97258
97259    /* This sample is being added because the prefix that ends in column
97260    ** iCol occurs many times in the table. However, if we have already
97261    ** added a sample that shares this prefix, there is no need to add
97262    ** this one. Instead, upgrade the priority of the highest priority
97263    ** existing sample that shares this prefix.  */
97264    for(i=p->nSample-1; i>=0; i--){
97265      Stat4Sample *pOld = &p->a[i];
97266      if( pOld->anEq[pNew->iCol]==0 ){
97267        if( pOld->isPSample ) return;
97268        assert( pOld->iCol>pNew->iCol );
97269        assert( sampleIsBetter(p, pNew, pOld) );
97270        if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
97271          pUpgrade = pOld;
97272        }
97273      }
97274    }
97275    if( pUpgrade ){
97276      pUpgrade->iCol = pNew->iCol;
97277      pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
97278      goto find_new_min;
97279    }
97280  }
97281#endif
97282
97283  /* If necessary, remove sample iMin to make room for the new sample. */
97284  if( p->nSample>=p->mxSample ){
97285    Stat4Sample *pMin = &p->a[p->iMin];
97286    tRowcnt *anEq = pMin->anEq;
97287    tRowcnt *anLt = pMin->anLt;
97288    tRowcnt *anDLt = pMin->anDLt;
97289    sampleClear(p->db, pMin);
97290    memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
97291    pSample = &p->a[p->nSample-1];
97292    pSample->nRowid = 0;
97293    pSample->anEq = anEq;
97294    pSample->anDLt = anDLt;
97295    pSample->anLt = anLt;
97296    p->nSample = p->mxSample-1;
97297  }
97298
97299  /* The "rows less-than" for the rowid column must be greater than that
97300  ** for the last sample in the p->a[] array. Otherwise, the samples would
97301  ** be out of order. */
97302#ifdef SQLITE_ENABLE_STAT4
97303  assert( p->nSample==0
97304       || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
97305#endif
97306
97307  /* Insert the new sample */
97308  pSample = &p->a[p->nSample];
97309  sampleCopy(p, pSample, pNew);
97310  p->nSample++;
97311
97312  /* Zero the first nEqZero entries in the anEq[] array. */
97313  memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
97314
97315#ifdef SQLITE_ENABLE_STAT4
97316 find_new_min:
97317#endif
97318  if( p->nSample>=p->mxSample ){
97319    int iMin = -1;
97320    for(i=0; i<p->mxSample; i++){
97321      if( p->a[i].isPSample ) continue;
97322      if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
97323        iMin = i;
97324      }
97325    }
97326    assert( iMin>=0 );
97327    p->iMin = iMin;
97328  }
97329}
97330#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
97331
97332/*
97333** Field iChng of the index being scanned has changed. So at this point
97334** p->current contains a sample that reflects the previous row of the
97335** index. The value of anEq[iChng] and subsequent anEq[] elements are
97336** correct at this point.
97337*/
97338static void samplePushPrevious(Stat4Accum *p, int iChng){
97339#ifdef SQLITE_ENABLE_STAT4
97340  int i;
97341
97342  /* Check if any samples from the aBest[] array should be pushed
97343  ** into IndexSample.a[] at this point.  */
97344  for(i=(p->nCol-2); i>=iChng; i--){
97345    Stat4Sample *pBest = &p->aBest[i];
97346    pBest->anEq[i] = p->current.anEq[i];
97347    if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
97348      sampleInsert(p, pBest, i);
97349    }
97350  }
97351
97352  /* Check that no sample contains an anEq[] entry with an index of
97353  ** p->nMaxEqZero or greater set to zero. */
97354  for(i=p->nSample-1; i>=0; i--){
97355    int j;
97356    for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
97357  }
97358
97359  /* Update the anEq[] fields of any samples already collected. */
97360  if( iChng<p->nMaxEqZero ){
97361    for(i=p->nSample-1; i>=0; i--){
97362      int j;
97363      for(j=iChng; j<p->nCol; j++){
97364        if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
97365      }
97366    }
97367    p->nMaxEqZero = iChng;
97368  }
97369#endif
97370
97371#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
97372  if( iChng==0 ){
97373    tRowcnt nLt = p->current.anLt[0];
97374    tRowcnt nEq = p->current.anEq[0];
97375
97376    /* Check if this is to be a periodic sample. If so, add it. */
97377    if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
97378      p->current.isPSample = 1;
97379      sampleInsert(p, &p->current, 0);
97380      p->current.isPSample = 0;
97381    }else
97382
97383    /* Or if it is a non-periodic sample. Add it in this case too. */
97384    if( p->nSample<p->mxSample
97385     || sampleIsBetter(p, &p->current, &p->a[p->iMin])
97386    ){
97387      sampleInsert(p, &p->current, 0);
97388    }
97389  }
97390#endif
97391
97392#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
97393  UNUSED_PARAMETER( p );
97394  UNUSED_PARAMETER( iChng );
97395#endif
97396}
97397
97398/*
97399** Implementation of the stat_push SQL function:  stat_push(P,C,R)
97400** Arguments:
97401**
97402**    P     Pointer to the Stat4Accum object created by stat_init()
97403**    C     Index of left-most column to differ from previous row
97404**    R     Rowid for the current row.  Might be a key record for
97405**          WITHOUT ROWID tables.
97406**
97407** This SQL function always returns NULL.  It's purpose it to accumulate
97408** statistical data and/or samples in the Stat4Accum object about the
97409** index being analyzed.  The stat_get() SQL function will later be used to
97410** extract relevant information for constructing the sqlite_statN tables.
97411**
97412** The R parameter is only used for STAT3 and STAT4
97413*/
97414static void statPush(
97415  sqlite3_context *context,
97416  int argc,
97417  sqlite3_value **argv
97418){
97419  int i;
97420
97421  /* The three function arguments */
97422  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
97423  int iChng = sqlite3_value_int(argv[1]);
97424
97425  UNUSED_PARAMETER( argc );
97426  UNUSED_PARAMETER( context );
97427  assert( p->nCol>0 );
97428  assert( iChng<p->nCol );
97429
97430  if( p->nRow==0 ){
97431    /* This is the first call to this function. Do initialization. */
97432    for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
97433  }else{
97434    /* Second and subsequent calls get processed here */
97435    samplePushPrevious(p, iChng);
97436
97437    /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
97438    ** to the current row of the index. */
97439    for(i=0; i<iChng; i++){
97440      p->current.anEq[i]++;
97441    }
97442    for(i=iChng; i<p->nCol; i++){
97443      p->current.anDLt[i]++;
97444#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97445      p->current.anLt[i] += p->current.anEq[i];
97446#endif
97447      p->current.anEq[i] = 1;
97448    }
97449  }
97450  p->nRow++;
97451#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97452  if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
97453    sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
97454  }else{
97455    sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
97456                                       sqlite3_value_blob(argv[2]));
97457  }
97458  p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
97459#endif
97460
97461#ifdef SQLITE_ENABLE_STAT4
97462  {
97463    tRowcnt nLt = p->current.anLt[p->nCol-1];
97464
97465    /* Check if this is to be a periodic sample. If so, add it. */
97466    if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
97467      p->current.isPSample = 1;
97468      p->current.iCol = 0;
97469      sampleInsert(p, &p->current, p->nCol-1);
97470      p->current.isPSample = 0;
97471    }
97472
97473    /* Update the aBest[] array. */
97474    for(i=0; i<(p->nCol-1); i++){
97475      p->current.iCol = i;
97476      if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
97477        sampleCopy(p, &p->aBest[i], &p->current);
97478      }
97479    }
97480  }
97481#endif
97482}
97483static const FuncDef statPushFuncdef = {
97484  2+IsStat34,      /* nArg */
97485  SQLITE_UTF8,     /* funcFlags */
97486  0,               /* pUserData */
97487  0,               /* pNext */
97488  statPush,        /* xSFunc */
97489  0,               /* xFinalize */
97490  "stat_push",     /* zName */
97491  {0}
97492};
97493
97494#define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
97495#define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
97496#define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
97497#define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
97498#define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
97499
97500/*
97501** Implementation of the stat_get(P,J) SQL function.  This routine is
97502** used to query statistical information that has been gathered into
97503** the Stat4Accum object by prior calls to stat_push().  The P parameter
97504** has type BLOB but it is really just a pointer to the Stat4Accum object.
97505** The content to returned is determined by the parameter J
97506** which is one of the STAT_GET_xxxx values defined above.
97507**
97508** The stat_get(P,J) function is not available to generic SQL.  It is
97509** inserted as part of a manually constructed bytecode program.  (See
97510** the callStatGet() routine below.)  It is guaranteed that the P
97511** parameter will always be a poiner to a Stat4Accum object, never a
97512** NULL.
97513**
97514** If neither STAT3 nor STAT4 are enabled, then J is always
97515** STAT_GET_STAT1 and is hence omitted and this routine becomes
97516** a one-parameter function, stat_get(P), that always returns the
97517** stat1 table entry information.
97518*/
97519static void statGet(
97520  sqlite3_context *context,
97521  int argc,
97522  sqlite3_value **argv
97523){
97524  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
97525#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97526  /* STAT3 and STAT4 have a parameter on this routine. */
97527  int eCall = sqlite3_value_int(argv[1]);
97528  assert( argc==2 );
97529  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
97530       || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
97531       || eCall==STAT_GET_NDLT
97532  );
97533  if( eCall==STAT_GET_STAT1 )
97534#else
97535  assert( argc==1 );
97536#endif
97537  {
97538    /* Return the value to store in the "stat" column of the sqlite_stat1
97539    ** table for this index.
97540    **
97541    ** The value is a string composed of a list of integers describing
97542    ** the index. The first integer in the list is the total number of
97543    ** entries in the index. There is one additional integer in the list
97544    ** for each indexed column. This additional integer is an estimate of
97545    ** the number of rows matched by a stabbing query on the index using
97546    ** a key with the corresponding number of fields. In other words,
97547    ** if the index is on columns (a,b) and the sqlite_stat1 value is
97548    ** "100 10 2", then SQLite estimates that:
97549    **
97550    **   * the index contains 100 rows,
97551    **   * "WHERE a=?" matches 10 rows, and
97552    **   * "WHERE a=? AND b=?" matches 2 rows.
97553    **
97554    ** If D is the count of distinct values and K is the total number of
97555    ** rows, then each estimate is computed as:
97556    **
97557    **        I = (K+D-1)/D
97558    */
97559    char *z;
97560    int i;
97561
97562    char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
97563    if( zRet==0 ){
97564      sqlite3_result_error_nomem(context);
97565      return;
97566    }
97567
97568    sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
97569    z = zRet + sqlite3Strlen30(zRet);
97570    for(i=0; i<p->nKeyCol; i++){
97571      u64 nDistinct = p->current.anDLt[i] + 1;
97572      u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
97573      sqlite3_snprintf(24, z, " %llu", iVal);
97574      z += sqlite3Strlen30(z);
97575      assert( p->current.anEq[i] );
97576    }
97577    assert( z[0]=='\0' && z>zRet );
97578
97579    sqlite3_result_text(context, zRet, -1, sqlite3_free);
97580  }
97581#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97582  else if( eCall==STAT_GET_ROWID ){
97583    if( p->iGet<0 ){
97584      samplePushPrevious(p, 0);
97585      p->iGet = 0;
97586    }
97587    if( p->iGet<p->nSample ){
97588      Stat4Sample *pS = p->a + p->iGet;
97589      if( pS->nRowid==0 ){
97590        sqlite3_result_int64(context, pS->u.iRowid);
97591      }else{
97592        sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
97593                            SQLITE_TRANSIENT);
97594      }
97595    }
97596  }else{
97597    tRowcnt *aCnt = 0;
97598
97599    assert( p->iGet<p->nSample );
97600    switch( eCall ){
97601      case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
97602      case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
97603      default: {
97604        aCnt = p->a[p->iGet].anDLt;
97605        p->iGet++;
97606        break;
97607      }
97608    }
97609
97610    if( IsStat3 ){
97611      sqlite3_result_int64(context, (i64)aCnt[0]);
97612    }else{
97613      char *zRet = sqlite3MallocZero(p->nCol * 25);
97614      if( zRet==0 ){
97615        sqlite3_result_error_nomem(context);
97616      }else{
97617        int i;
97618        char *z = zRet;
97619        for(i=0; i<p->nCol; i++){
97620          sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
97621          z += sqlite3Strlen30(z);
97622        }
97623        assert( z[0]=='\0' && z>zRet );
97624        z[-1] = '\0';
97625        sqlite3_result_text(context, zRet, -1, sqlite3_free);
97626      }
97627    }
97628  }
97629#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
97630#ifndef SQLITE_DEBUG
97631  UNUSED_PARAMETER( argc );
97632#endif
97633}
97634static const FuncDef statGetFuncdef = {
97635  1+IsStat34,      /* nArg */
97636  SQLITE_UTF8,     /* funcFlags */
97637  0,               /* pUserData */
97638  0,               /* pNext */
97639  statGet,         /* xSFunc */
97640  0,               /* xFinalize */
97641  "stat_get",      /* zName */
97642  {0}
97643};
97644
97645static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
97646  assert( regOut!=regStat4 && regOut!=regStat4+1 );
97647#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97648  sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
97649#elif SQLITE_DEBUG
97650  assert( iParam==STAT_GET_STAT1 );
97651#else
97652  UNUSED_PARAMETER( iParam );
97653#endif
97654  sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
97655                    (char*)&statGetFuncdef, P4_FUNCDEF);
97656  sqlite3VdbeChangeP5(v, 1 + IsStat34);
97657}
97658
97659/*
97660** Generate code to do an analysis of all indices associated with
97661** a single table.
97662*/
97663static void analyzeOneTable(
97664  Parse *pParse,   /* Parser context */
97665  Table *pTab,     /* Table whose indices are to be analyzed */
97666  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
97667  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
97668  int iMem,        /* Available memory locations begin here */
97669  int iTab         /* Next available cursor */
97670){
97671  sqlite3 *db = pParse->db;    /* Database handle */
97672  Index *pIdx;                 /* An index to being analyzed */
97673  int iIdxCur;                 /* Cursor open on index being analyzed */
97674  int iTabCur;                 /* Table cursor */
97675  Vdbe *v;                     /* The virtual machine being built up */
97676  int i;                       /* Loop counter */
97677  int jZeroRows = -1;          /* Jump from here if number of rows is zero */
97678  int iDb;                     /* Index of database containing pTab */
97679  u8 needTableCnt = 1;         /* True to count the table */
97680  int regNewRowid = iMem++;    /* Rowid for the inserted record */
97681  int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
97682  int regChng = iMem++;        /* Index of changed index field */
97683#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97684  int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
97685#endif
97686  int regTemp = iMem++;        /* Temporary use register */
97687  int regTabname = iMem++;     /* Register containing table name */
97688  int regIdxname = iMem++;     /* Register containing index name */
97689  int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
97690  int regPrev = iMem;          /* MUST BE LAST (see below) */
97691
97692  pParse->nMem = MAX(pParse->nMem, iMem);
97693  v = sqlite3GetVdbe(pParse);
97694  if( v==0 || NEVER(pTab==0) ){
97695    return;
97696  }
97697  if( pTab->tnum==0 ){
97698    /* Do not gather statistics on views or virtual tables */
97699    return;
97700  }
97701  if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
97702    /* Do not gather statistics on system tables */
97703    return;
97704  }
97705  assert( sqlite3BtreeHoldsAllMutexes(db) );
97706  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97707  assert( iDb>=0 );
97708  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97709#ifndef SQLITE_OMIT_AUTHORIZATION
97710  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
97711      db->aDb[iDb].zDbSName ) ){
97712    return;
97713  }
97714#endif
97715
97716  /* Establish a read-lock on the table at the shared-cache level.
97717  ** Open a read-only cursor on the table. Also allocate a cursor number
97718  ** to use for scanning indexes (iIdxCur). No index cursor is opened at
97719  ** this time though.  */
97720  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
97721  iTabCur = iTab++;
97722  iIdxCur = iTab++;
97723  pParse->nTab = MAX(pParse->nTab, iTab);
97724  sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
97725  sqlite3VdbeLoadString(v, regTabname, pTab->zName);
97726
97727  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
97728    int nCol;                     /* Number of columns in pIdx. "N" */
97729    int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
97730    int addrNextRow;              /* Address of "next_row:" */
97731    const char *zIdxName;         /* Name of the index */
97732    int nColTest;                 /* Number of columns to test for changes */
97733
97734    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
97735    if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
97736    if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
97737      nCol = pIdx->nKeyCol;
97738      zIdxName = pTab->zName;
97739      nColTest = nCol - 1;
97740    }else{
97741      nCol = pIdx->nColumn;
97742      zIdxName = pIdx->zName;
97743      nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
97744    }
97745
97746    /* Populate the register containing the index name. */
97747    sqlite3VdbeLoadString(v, regIdxname, zIdxName);
97748    VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
97749
97750    /*
97751    ** Pseudo-code for loop that calls stat_push():
97752    **
97753    **   Rewind csr
97754    **   if eof(csr) goto end_of_scan;
97755    **   regChng = 0
97756    **   goto chng_addr_0;
97757    **
97758    **  next_row:
97759    **   regChng = 0
97760    **   if( idx(0) != regPrev(0) ) goto chng_addr_0
97761    **   regChng = 1
97762    **   if( idx(1) != regPrev(1) ) goto chng_addr_1
97763    **   ...
97764    **   regChng = N
97765    **   goto chng_addr_N
97766    **
97767    **  chng_addr_0:
97768    **   regPrev(0) = idx(0)
97769    **  chng_addr_1:
97770    **   regPrev(1) = idx(1)
97771    **  ...
97772    **
97773    **  endDistinctTest:
97774    **   regRowid = idx(rowid)
97775    **   stat_push(P, regChng, regRowid)
97776    **   Next csr
97777    **   if !eof(csr) goto next_row;
97778    **
97779    **  end_of_scan:
97780    */
97781
97782    /* Make sure there are enough memory cells allocated to accommodate
97783    ** the regPrev array and a trailing rowid (the rowid slot is required
97784    ** when building a record to insert into the sample column of
97785    ** the sqlite_stat4 table.  */
97786    pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
97787
97788    /* Open a read-only cursor on the index being analyzed. */
97789    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
97790    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
97791    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
97792    VdbeComment((v, "%s", pIdx->zName));
97793
97794    /* Invoke the stat_init() function. The arguments are:
97795    **
97796    **    (1) the number of columns in the index including the rowid
97797    **        (or for a WITHOUT ROWID table, the number of PK columns),
97798    **    (2) the number of columns in the key without the rowid/pk
97799    **    (3) the number of rows in the index,
97800    **
97801    **
97802    ** The third argument is only used for STAT3 and STAT4
97803    */
97804#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97805    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
97806#endif
97807    sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
97808    sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
97809    sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
97810                     (char*)&statInitFuncdef, P4_FUNCDEF);
97811    sqlite3VdbeChangeP5(v, 2+IsStat34);
97812
97813    /* Implementation of the following:
97814    **
97815    **   Rewind csr
97816    **   if eof(csr) goto end_of_scan;
97817    **   regChng = 0
97818    **   goto next_push_0;
97819    **
97820    */
97821    addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
97822    VdbeCoverage(v);
97823    sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
97824    addrNextRow = sqlite3VdbeCurrentAddr(v);
97825
97826    if( nColTest>0 ){
97827      int endDistinctTest = sqlite3VdbeMakeLabel(v);
97828      int *aGotoChng;               /* Array of jump instruction addresses */
97829      aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
97830      if( aGotoChng==0 ) continue;
97831
97832      /*
97833      **  next_row:
97834      **   regChng = 0
97835      **   if( idx(0) != regPrev(0) ) goto chng_addr_0
97836      **   regChng = 1
97837      **   if( idx(1) != regPrev(1) ) goto chng_addr_1
97838      **   ...
97839      **   regChng = N
97840      **   goto endDistinctTest
97841      */
97842      sqlite3VdbeAddOp0(v, OP_Goto);
97843      addrNextRow = sqlite3VdbeCurrentAddr(v);
97844      if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
97845        /* For a single-column UNIQUE index, once we have found a non-NULL
97846        ** row, we know that all the rest will be distinct, so skip
97847        ** subsequent distinctness tests. */
97848        sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
97849        VdbeCoverage(v);
97850      }
97851      for(i=0; i<nColTest; i++){
97852        char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
97853        sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
97854        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
97855        aGotoChng[i] =
97856        sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
97857        sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
97858        VdbeCoverage(v);
97859      }
97860      sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
97861      sqlite3VdbeGoto(v, endDistinctTest);
97862
97863
97864      /*
97865      **  chng_addr_0:
97866      **   regPrev(0) = idx(0)
97867      **  chng_addr_1:
97868      **   regPrev(1) = idx(1)
97869      **  ...
97870      */
97871      sqlite3VdbeJumpHere(v, addrNextRow-1);
97872      for(i=0; i<nColTest; i++){
97873        sqlite3VdbeJumpHere(v, aGotoChng[i]);
97874        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
97875      }
97876      sqlite3VdbeResolveLabel(v, endDistinctTest);
97877      sqlite3DbFree(db, aGotoChng);
97878    }
97879
97880    /*
97881    **  chng_addr_N:
97882    **   regRowid = idx(rowid)            // STAT34 only
97883    **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
97884    **   Next csr
97885    **   if !eof(csr) goto next_row;
97886    */
97887#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97888    assert( regRowid==(regStat4+2) );
97889    if( HasRowid(pTab) ){
97890      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
97891    }else{
97892      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
97893      int j, k, regKey;
97894      regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
97895      for(j=0; j<pPk->nKeyCol; j++){
97896        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
97897        assert( k>=0 && k<pIdx->nColumn );
97898        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
97899        VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
97900      }
97901      sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
97902      sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
97903    }
97904#endif
97905    assert( regChng==(regStat4+1) );
97906    sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
97907                     (char*)&statPushFuncdef, P4_FUNCDEF);
97908    sqlite3VdbeChangeP5(v, 2+IsStat34);
97909    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
97910
97911    /* Add the entry to the stat1 table. */
97912    callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
97913    assert( "BBB"[0]==SQLITE_AFF_TEXT );
97914    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
97915    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
97916    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
97917    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
97918
97919    /* Add the entries to the stat3 or stat4 table. */
97920#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97921    {
97922      int regEq = regStat1;
97923      int regLt = regStat1+1;
97924      int regDLt = regStat1+2;
97925      int regSample = regStat1+3;
97926      int regCol = regStat1+4;
97927      int regSampleRowid = regCol + nCol;
97928      int addrNext;
97929      int addrIsNull;
97930      u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
97931
97932      pParse->nMem = MAX(pParse->nMem, regCol+nCol);
97933
97934      addrNext = sqlite3VdbeCurrentAddr(v);
97935      callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
97936      addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
97937      VdbeCoverage(v);
97938      callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
97939      callStatGet(v, regStat4, STAT_GET_NLT, regLt);
97940      callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
97941      sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
97942      /* We know that the regSampleRowid row exists because it was read by
97943      ** the previous loop.  Thus the not-found jump of seekOp will never
97944      ** be taken */
97945      VdbeCoverageNeverTaken(v);
97946#ifdef SQLITE_ENABLE_STAT3
97947      sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
97948#else
97949      for(i=0; i<nCol; i++){
97950        sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
97951      }
97952      sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
97953#endif
97954      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
97955      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
97956      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
97957      sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
97958      sqlite3VdbeJumpHere(v, addrIsNull);
97959    }
97960#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
97961
97962    /* End of analysis */
97963    sqlite3VdbeJumpHere(v, addrRewind);
97964  }
97965
97966
97967  /* Create a single sqlite_stat1 entry containing NULL as the index
97968  ** name and the row count as the content.
97969  */
97970  if( pOnlyIdx==0 && needTableCnt ){
97971    VdbeComment((v, "%s", pTab->zName));
97972    sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
97973    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
97974    sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
97975    assert( "BBB"[0]==SQLITE_AFF_TEXT );
97976    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
97977    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
97978    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
97979    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
97980    sqlite3VdbeJumpHere(v, jZeroRows);
97981  }
97982}
97983
97984
97985/*
97986** Generate code that will cause the most recent index analysis to
97987** be loaded into internal hash tables where is can be used.
97988*/
97989static void loadAnalysis(Parse *pParse, int iDb){
97990  Vdbe *v = sqlite3GetVdbe(pParse);
97991  if( v ){
97992    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
97993  }
97994}
97995
97996/*
97997** Generate code that will do an analysis of an entire database
97998*/
97999static void analyzeDatabase(Parse *pParse, int iDb){
98000  sqlite3 *db = pParse->db;
98001  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
98002  HashElem *k;
98003  int iStatCur;
98004  int iMem;
98005  int iTab;
98006
98007  sqlite3BeginWriteOperation(pParse, 0, iDb);
98008  iStatCur = pParse->nTab;
98009  pParse->nTab += 3;
98010  openStatTable(pParse, iDb, iStatCur, 0, 0);
98011  iMem = pParse->nMem+1;
98012  iTab = pParse->nTab;
98013  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98014  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
98015    Table *pTab = (Table*)sqliteHashData(k);
98016    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
98017  }
98018  loadAnalysis(pParse, iDb);
98019}
98020
98021/*
98022** Generate code that will do an analysis of a single table in
98023** a database.  If pOnlyIdx is not NULL then it is a single index
98024** in pTab that should be analyzed.
98025*/
98026static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
98027  int iDb;
98028  int iStatCur;
98029
98030  assert( pTab!=0 );
98031  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
98032  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
98033  sqlite3BeginWriteOperation(pParse, 0, iDb);
98034  iStatCur = pParse->nTab;
98035  pParse->nTab += 3;
98036  if( pOnlyIdx ){
98037    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
98038  }else{
98039    openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
98040  }
98041  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
98042  loadAnalysis(pParse, iDb);
98043}
98044
98045/*
98046** Generate code for the ANALYZE command.  The parser calls this routine
98047** when it recognizes an ANALYZE command.
98048**
98049**        ANALYZE                            -- 1
98050**        ANALYZE  <database>                -- 2
98051**        ANALYZE  ?<database>.?<tablename>  -- 3
98052**
98053** Form 1 causes all indices in all attached databases to be analyzed.
98054** Form 2 analyzes all indices the single database named.
98055** Form 3 analyzes all indices associated with the named table.
98056*/
98057SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
98058  sqlite3 *db = pParse->db;
98059  int iDb;
98060  int i;
98061  char *z, *zDb;
98062  Table *pTab;
98063  Index *pIdx;
98064  Token *pTableName;
98065  Vdbe *v;
98066
98067  /* Read the database schema. If an error occurs, leave an error message
98068  ** and code in pParse and return NULL. */
98069  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
98070  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
98071    return;
98072  }
98073
98074  assert( pName2!=0 || pName1==0 );
98075  if( pName1==0 ){
98076    /* Form 1:  Analyze everything */
98077    for(i=0; i<db->nDb; i++){
98078      if( i==1 ) continue;  /* Do not analyze the TEMP database */
98079      analyzeDatabase(pParse, i);
98080    }
98081  }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
98082    /* Analyze the schema named as the argument */
98083    analyzeDatabase(pParse, iDb);
98084  }else{
98085    /* Form 3: Analyze the table or index named as an argument */
98086    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
98087    if( iDb>=0 ){
98088      zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
98089      z = sqlite3NameFromToken(db, pTableName);
98090      if( z ){
98091        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
98092          analyzeTable(pParse, pIdx->pTable, pIdx);
98093        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
98094          analyzeTable(pParse, pTab, 0);
98095        }
98096        sqlite3DbFree(db, z);
98097      }
98098    }
98099  }
98100  if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
98101    sqlite3VdbeAddOp0(v, OP_Expire);
98102  }
98103}
98104
98105/*
98106** Used to pass information from the analyzer reader through to the
98107** callback routine.
98108*/
98109typedef struct analysisInfo analysisInfo;
98110struct analysisInfo {
98111  sqlite3 *db;
98112  const char *zDatabase;
98113};
98114
98115/*
98116** The first argument points to a nul-terminated string containing a
98117** list of space separated integers. Read the first nOut of these into
98118** the array aOut[].
98119*/
98120static void decodeIntArray(
98121  char *zIntArray,       /* String containing int array to decode */
98122  int nOut,              /* Number of slots in aOut[] */
98123  tRowcnt *aOut,         /* Store integers here */
98124  LogEst *aLog,          /* Or, if aOut==0, here */
98125  Index *pIndex          /* Handle extra flags for this index, if not NULL */
98126){
98127  char *z = zIntArray;
98128  int c;
98129  int i;
98130  tRowcnt v;
98131
98132#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98133  if( z==0 ) z = "";
98134#else
98135  assert( z!=0 );
98136#endif
98137  for(i=0; *z && i<nOut; i++){
98138    v = 0;
98139    while( (c=z[0])>='0' && c<='9' ){
98140      v = v*10 + c - '0';
98141      z++;
98142    }
98143#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98144    if( aOut ) aOut[i] = v;
98145    if( aLog ) aLog[i] = sqlite3LogEst(v);
98146#else
98147    assert( aOut==0 );
98148    UNUSED_PARAMETER(aOut);
98149    assert( aLog!=0 );
98150    aLog[i] = sqlite3LogEst(v);
98151#endif
98152    if( *z==' ' ) z++;
98153  }
98154#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
98155  assert( pIndex!=0 ); {
98156#else
98157  if( pIndex ){
98158#endif
98159    pIndex->bUnordered = 0;
98160    pIndex->noSkipScan = 0;
98161    while( z[0] ){
98162      if( sqlite3_strglob("unordered*", z)==0 ){
98163        pIndex->bUnordered = 1;
98164      }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
98165        pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
98166      }else if( sqlite3_strglob("noskipscan*", z)==0 ){
98167        pIndex->noSkipScan = 1;
98168      }
98169#ifdef SQLITE_ENABLE_COSTMULT
98170      else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
98171        pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
98172      }
98173#endif
98174      while( z[0]!=0 && z[0]!=' ' ) z++;
98175      while( z[0]==' ' ) z++;
98176    }
98177  }
98178}
98179
98180/*
98181** This callback is invoked once for each index when reading the
98182** sqlite_stat1 table.
98183**
98184**     argv[0] = name of the table
98185**     argv[1] = name of the index (might be NULL)
98186**     argv[2] = results of analysis - on integer for each column
98187**
98188** Entries for which argv[1]==NULL simply record the number of rows in
98189** the table.
98190*/
98191static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
98192  analysisInfo *pInfo = (analysisInfo*)pData;
98193  Index *pIndex;
98194  Table *pTable;
98195  const char *z;
98196
98197  assert( argc==3 );
98198  UNUSED_PARAMETER2(NotUsed, argc);
98199
98200  if( argv==0 || argv[0]==0 || argv[2]==0 ){
98201    return 0;
98202  }
98203  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
98204  if( pTable==0 ){
98205    return 0;
98206  }
98207  if( argv[1]==0 ){
98208    pIndex = 0;
98209  }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
98210    pIndex = sqlite3PrimaryKeyIndex(pTable);
98211  }else{
98212    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
98213  }
98214  z = argv[2];
98215
98216  if( pIndex ){
98217    tRowcnt *aiRowEst = 0;
98218    int nCol = pIndex->nKeyCol+1;
98219#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98220    /* Index.aiRowEst may already be set here if there are duplicate
98221    ** sqlite_stat1 entries for this index. In that case just clobber
98222    ** the old data with the new instead of allocating a new array.  */
98223    if( pIndex->aiRowEst==0 ){
98224      pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
98225      if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
98226    }
98227    aiRowEst = pIndex->aiRowEst;
98228#endif
98229    pIndex->bUnordered = 0;
98230    decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
98231    pIndex->hasStat1 = 1;
98232    if( pIndex->pPartIdxWhere==0 ){
98233      pTable->nRowLogEst = pIndex->aiRowLogEst[0];
98234      pTable->tabFlags |= TF_HasStat1;
98235    }
98236  }else{
98237    Index fakeIdx;
98238    fakeIdx.szIdxRow = pTable->szTabRow;
98239#ifdef SQLITE_ENABLE_COSTMULT
98240    fakeIdx.pTable = pTable;
98241#endif
98242    decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
98243    pTable->szTabRow = fakeIdx.szIdxRow;
98244    pTable->tabFlags |= TF_HasStat1;
98245  }
98246
98247  return 0;
98248}
98249
98250/*
98251** If the Index.aSample variable is not NULL, delete the aSample[] array
98252** and its contents.
98253*/
98254SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
98255#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98256  if( pIdx->aSample ){
98257    int j;
98258    for(j=0; j<pIdx->nSample; j++){
98259      IndexSample *p = &pIdx->aSample[j];
98260      sqlite3DbFree(db, p->p);
98261    }
98262    sqlite3DbFree(db, pIdx->aSample);
98263  }
98264  if( db && db->pnBytesFreed==0 ){
98265    pIdx->nSample = 0;
98266    pIdx->aSample = 0;
98267  }
98268#else
98269  UNUSED_PARAMETER(db);
98270  UNUSED_PARAMETER(pIdx);
98271#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
98272}
98273
98274#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98275/*
98276** Populate the pIdx->aAvgEq[] array based on the samples currently
98277** stored in pIdx->aSample[].
98278*/
98279static void initAvgEq(Index *pIdx){
98280  if( pIdx ){
98281    IndexSample *aSample = pIdx->aSample;
98282    IndexSample *pFinal = &aSample[pIdx->nSample-1];
98283    int iCol;
98284    int nCol = 1;
98285    if( pIdx->nSampleCol>1 ){
98286      /* If this is stat4 data, then calculate aAvgEq[] values for all
98287      ** sample columns except the last. The last is always set to 1, as
98288      ** once the trailing PK fields are considered all index keys are
98289      ** unique.  */
98290      nCol = pIdx->nSampleCol-1;
98291      pIdx->aAvgEq[nCol] = 1;
98292    }
98293    for(iCol=0; iCol<nCol; iCol++){
98294      int nSample = pIdx->nSample;
98295      int i;                    /* Used to iterate through samples */
98296      tRowcnt sumEq = 0;        /* Sum of the nEq values */
98297      tRowcnt avgEq = 0;
98298      tRowcnt nRow;             /* Number of rows in index */
98299      i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
98300      i64 nDist100;             /* Number of distinct values in index */
98301
98302      if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
98303        nRow = pFinal->anLt[iCol];
98304        nDist100 = (i64)100 * pFinal->anDLt[iCol];
98305        nSample--;
98306      }else{
98307        nRow = pIdx->aiRowEst[0];
98308        nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
98309      }
98310      pIdx->nRowEst0 = nRow;
98311
98312      /* Set nSum to the number of distinct (iCol+1) field prefixes that
98313      ** occur in the stat4 table for this index. Set sumEq to the sum of
98314      ** the nEq values for column iCol for the same set (adding the value
98315      ** only once where there exist duplicate prefixes).  */
98316      for(i=0; i<nSample; i++){
98317        if( i==(pIdx->nSample-1)
98318         || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
98319        ){
98320          sumEq += aSample[i].anEq[iCol];
98321          nSum100 += 100;
98322        }
98323      }
98324
98325      if( nDist100>nSum100 && sumEq<nRow ){
98326        avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
98327      }
98328      if( avgEq==0 ) avgEq = 1;
98329      pIdx->aAvgEq[iCol] = avgEq;
98330    }
98331  }
98332}
98333
98334/*
98335** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
98336** is supplied instead, find the PRIMARY KEY index for that table.
98337*/
98338static Index *findIndexOrPrimaryKey(
98339  sqlite3 *db,
98340  const char *zName,
98341  const char *zDb
98342){
98343  Index *pIdx = sqlite3FindIndex(db, zName, zDb);
98344  if( pIdx==0 ){
98345    Table *pTab = sqlite3FindTable(db, zName, zDb);
98346    if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
98347  }
98348  return pIdx;
98349}
98350
98351/*
98352** Load the content from either the sqlite_stat4 or sqlite_stat3 table
98353** into the relevant Index.aSample[] arrays.
98354**
98355** Arguments zSql1 and zSql2 must point to SQL statements that return
98356** data equivalent to the following (statements are different for stat3,
98357** see the caller of this function for details):
98358**
98359**    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
98360**    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
98361**
98362** where %Q is replaced with the database name before the SQL is executed.
98363*/
98364static int loadStatTbl(
98365  sqlite3 *db,                  /* Database handle */
98366  int bStat3,                   /* Assume single column records only */
98367  const char *zSql1,            /* SQL statement 1 (see above) */
98368  const char *zSql2,            /* SQL statement 2 (see above) */
98369  const char *zDb               /* Database name (e.g. "main") */
98370){
98371  int rc;                       /* Result codes from subroutines */
98372  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
98373  char *zSql;                   /* Text of the SQL statement */
98374  Index *pPrevIdx = 0;          /* Previous index in the loop */
98375  IndexSample *pSample;         /* A slot in pIdx->aSample[] */
98376
98377  assert( db->lookaside.bDisable );
98378  zSql = sqlite3MPrintf(db, zSql1, zDb);
98379  if( !zSql ){
98380    return SQLITE_NOMEM_BKPT;
98381  }
98382  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
98383  sqlite3DbFree(db, zSql);
98384  if( rc ) return rc;
98385
98386  while( sqlite3_step(pStmt)==SQLITE_ROW ){
98387    int nIdxCol = 1;              /* Number of columns in stat4 records */
98388
98389    char *zIndex;   /* Index name */
98390    Index *pIdx;    /* Pointer to the index object */
98391    int nSample;    /* Number of samples */
98392    int nByte;      /* Bytes of space required */
98393    int i;          /* Bytes of space required */
98394    tRowcnt *pSpace;
98395
98396    zIndex = (char *)sqlite3_column_text(pStmt, 0);
98397    if( zIndex==0 ) continue;
98398    nSample = sqlite3_column_int(pStmt, 1);
98399    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
98400    assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
98401    /* Index.nSample is non-zero at this point if data has already been
98402    ** loaded from the stat4 table. In this case ignore stat3 data.  */
98403    if( pIdx==0 || pIdx->nSample ) continue;
98404    if( bStat3==0 ){
98405      assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
98406      if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
98407        nIdxCol = pIdx->nKeyCol;
98408      }else{
98409        nIdxCol = pIdx->nColumn;
98410      }
98411    }
98412    pIdx->nSampleCol = nIdxCol;
98413    nByte = sizeof(IndexSample) * nSample;
98414    nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
98415    nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
98416
98417    pIdx->aSample = sqlite3DbMallocZero(db, nByte);
98418    if( pIdx->aSample==0 ){
98419      sqlite3_finalize(pStmt);
98420      return SQLITE_NOMEM_BKPT;
98421    }
98422    pSpace = (tRowcnt*)&pIdx->aSample[nSample];
98423    pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
98424    for(i=0; i<nSample; i++){
98425      pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
98426      pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
98427      pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
98428    }
98429    assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
98430  }
98431  rc = sqlite3_finalize(pStmt);
98432  if( rc ) return rc;
98433
98434  zSql = sqlite3MPrintf(db, zSql2, zDb);
98435  if( !zSql ){
98436    return SQLITE_NOMEM_BKPT;
98437  }
98438  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
98439  sqlite3DbFree(db, zSql);
98440  if( rc ) return rc;
98441
98442  while( sqlite3_step(pStmt)==SQLITE_ROW ){
98443    char *zIndex;                 /* Index name */
98444    Index *pIdx;                  /* Pointer to the index object */
98445    int nCol = 1;                 /* Number of columns in index */
98446
98447    zIndex = (char *)sqlite3_column_text(pStmt, 0);
98448    if( zIndex==0 ) continue;
98449    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
98450    if( pIdx==0 ) continue;
98451    /* This next condition is true if data has already been loaded from
98452    ** the sqlite_stat4 table. In this case ignore stat3 data.  */
98453    nCol = pIdx->nSampleCol;
98454    if( bStat3 && nCol>1 ) continue;
98455    if( pIdx!=pPrevIdx ){
98456      initAvgEq(pPrevIdx);
98457      pPrevIdx = pIdx;
98458    }
98459    pSample = &pIdx->aSample[pIdx->nSample];
98460    decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
98461    decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
98462    decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
98463
98464    /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
98465    ** This is in case the sample record is corrupted. In that case, the
98466    ** sqlite3VdbeRecordCompare() may read up to two varints past the
98467    ** end of the allocated buffer before it realizes it is dealing with
98468    ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
98469    ** a buffer overread.  */
98470    pSample->n = sqlite3_column_bytes(pStmt, 4);
98471    pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
98472    if( pSample->p==0 ){
98473      sqlite3_finalize(pStmt);
98474      return SQLITE_NOMEM_BKPT;
98475    }
98476    if( pSample->n ){
98477      memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
98478    }
98479    pIdx->nSample++;
98480  }
98481  rc = sqlite3_finalize(pStmt);
98482  if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
98483  return rc;
98484}
98485
98486/*
98487** Load content from the sqlite_stat4 and sqlite_stat3 tables into
98488** the Index.aSample[] arrays of all indices.
98489*/
98490static int loadStat4(sqlite3 *db, const char *zDb){
98491  int rc = SQLITE_OK;             /* Result codes from subroutines */
98492
98493  assert( db->lookaside.bDisable );
98494  if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
98495    rc = loadStatTbl(db, 0,
98496      "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
98497      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
98498      zDb
98499    );
98500  }
98501
98502  if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
98503    rc = loadStatTbl(db, 1,
98504      "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
98505      "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
98506      zDb
98507    );
98508  }
98509
98510  return rc;
98511}
98512#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
98513
98514/*
98515** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
98516** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
98517** arrays. The contents of sqlite_stat3/4 are used to populate the
98518** Index.aSample[] arrays.
98519**
98520** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
98521** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
98522** during compilation and the sqlite_stat3/4 table is present, no data is
98523** read from it.
98524**
98525** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
98526** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
98527** returned. However, in this case, data is read from the sqlite_stat1
98528** table (if it is present) before returning.
98529**
98530** If an OOM error occurs, this function always sets db->mallocFailed.
98531** This means if the caller does not care about other errors, the return
98532** code may be ignored.
98533*/
98534SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
98535  analysisInfo sInfo;
98536  HashElem *i;
98537  char *zSql;
98538  int rc = SQLITE_OK;
98539  Schema *pSchema = db->aDb[iDb].pSchema;
98540
98541  assert( iDb>=0 && iDb<db->nDb );
98542  assert( db->aDb[iDb].pBt!=0 );
98543
98544  /* Clear any prior statistics */
98545  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98546  for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
98547    Table *pTab = sqliteHashData(i);
98548    pTab->tabFlags &= ~TF_HasStat1;
98549  }
98550  for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
98551    Index *pIdx = sqliteHashData(i);
98552    pIdx->hasStat1 = 0;
98553#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98554    sqlite3DeleteIndexSamples(db, pIdx);
98555    pIdx->aSample = 0;
98556#endif
98557  }
98558
98559  /* Load new statistics out of the sqlite_stat1 table */
98560  sInfo.db = db;
98561  sInfo.zDatabase = db->aDb[iDb].zDbSName;
98562  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
98563    zSql = sqlite3MPrintf(db,
98564        "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
98565    if( zSql==0 ){
98566      rc = SQLITE_NOMEM_BKPT;
98567    }else{
98568      rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
98569      sqlite3DbFree(db, zSql);
98570    }
98571  }
98572
98573  /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
98574  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98575  for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
98576    Index *pIdx = sqliteHashData(i);
98577    if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
98578  }
98579
98580  /* Load the statistics from the sqlite_stat4 table. */
98581#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98582  if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
98583    db->lookaside.bDisable++;
98584    rc = loadStat4(db, sInfo.zDatabase);
98585    db->lookaside.bDisable--;
98586  }
98587  for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
98588    Index *pIdx = sqliteHashData(i);
98589    sqlite3_free(pIdx->aiRowEst);
98590    pIdx->aiRowEst = 0;
98591  }
98592#endif
98593
98594  if( rc==SQLITE_NOMEM ){
98595    sqlite3OomFault(db);
98596  }
98597  return rc;
98598}
98599
98600
98601#endif /* SQLITE_OMIT_ANALYZE */
98602
98603/************** End of analyze.c *********************************************/
98604/************** Begin file attach.c ******************************************/
98605/*
98606** 2003 April 6
98607**
98608** The author disclaims copyright to this source code.  In place of
98609** a legal notice, here is a blessing:
98610**
98611**    May you do good and not evil.
98612**    May you find forgiveness for yourself and forgive others.
98613**    May you share freely, never taking more than you give.
98614**
98615*************************************************************************
98616** This file contains code used to implement the ATTACH and DETACH commands.
98617*/
98618/* #include "sqliteInt.h" */
98619
98620#ifndef SQLITE_OMIT_ATTACH
98621/*
98622** Resolve an expression that was part of an ATTACH or DETACH statement. This
98623** is slightly different from resolving a normal SQL expression, because simple
98624** identifiers are treated as strings, not possible column names or aliases.
98625**
98626** i.e. if the parser sees:
98627**
98628**     ATTACH DATABASE abc AS def
98629**
98630** it treats the two expressions as literal strings 'abc' and 'def' instead of
98631** looking for columns of the same name.
98632**
98633** This only applies to the root node of pExpr, so the statement:
98634**
98635**     ATTACH DATABASE abc||def AS 'db2'
98636**
98637** will fail because neither abc or def can be resolved.
98638*/
98639static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
98640{
98641  int rc = SQLITE_OK;
98642  if( pExpr ){
98643    if( pExpr->op!=TK_ID ){
98644      rc = sqlite3ResolveExprNames(pName, pExpr);
98645    }else{
98646      pExpr->op = TK_STRING;
98647    }
98648  }
98649  return rc;
98650}
98651
98652/*
98653** An SQL user-function registered to do the work of an ATTACH statement. The
98654** three arguments to the function come directly from an attach statement:
98655**
98656**     ATTACH DATABASE x AS y KEY z
98657**
98658**     SELECT sqlite_attach(x, y, z)
98659**
98660** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
98661** third argument.
98662*/
98663static void attachFunc(
98664  sqlite3_context *context,
98665  int NotUsed,
98666  sqlite3_value **argv
98667){
98668  int i;
98669  int rc = 0;
98670  sqlite3 *db = sqlite3_context_db_handle(context);
98671  const char *zName;
98672  const char *zFile;
98673  char *zPath = 0;
98674  char *zErr = 0;
98675  unsigned int flags;
98676  Db *aNew;
98677  char *zErrDyn = 0;
98678  sqlite3_vfs *pVfs;
98679
98680  UNUSED_PARAMETER(NotUsed);
98681
98682  zFile = (const char *)sqlite3_value_text(argv[0]);
98683  zName = (const char *)sqlite3_value_text(argv[1]);
98684  if( zFile==0 ) zFile = "";
98685  if( zName==0 ) zName = "";
98686
98687  /* Check for the following errors:
98688  **
98689  **     * Too many attached databases,
98690  **     * Transaction currently open
98691  **     * Specified database name already being used.
98692  */
98693  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
98694    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
98695      db->aLimit[SQLITE_LIMIT_ATTACHED]
98696    );
98697    goto attach_error;
98698  }
98699  if( !db->autoCommit ){
98700    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
98701    goto attach_error;
98702  }
98703  for(i=0; i<db->nDb; i++){
98704    char *z = db->aDb[i].zDbSName;
98705    assert( z && zName );
98706    if( sqlite3StrICmp(z, zName)==0 ){
98707      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
98708      goto attach_error;
98709    }
98710  }
98711
98712  /* Allocate the new entry in the db->aDb[] array and initialize the schema
98713  ** hash tables.
98714  */
98715  if( db->aDb==db->aDbStatic ){
98716    aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
98717    if( aNew==0 ) return;
98718    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
98719  }else{
98720    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
98721    if( aNew==0 ) return;
98722  }
98723  db->aDb = aNew;
98724  aNew = &db->aDb[db->nDb];
98725  memset(aNew, 0, sizeof(*aNew));
98726
98727  /* Open the database file. If the btree is successfully opened, use
98728  ** it to obtain the database schema. At this point the schema may
98729  ** or may not be initialized.
98730  */
98731  flags = db->openFlags;
98732  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
98733  if( rc!=SQLITE_OK ){
98734    if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
98735    sqlite3_result_error(context, zErr, -1);
98736    sqlite3_free(zErr);
98737    return;
98738  }
98739  assert( pVfs );
98740  flags |= SQLITE_OPEN_MAIN_DB;
98741  rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
98742  sqlite3_free( zPath );
98743  db->nDb++;
98744  db->skipBtreeMutex = 0;
98745  if( rc==SQLITE_CONSTRAINT ){
98746    rc = SQLITE_ERROR;
98747    zErrDyn = sqlite3MPrintf(db, "database is already attached");
98748  }else if( rc==SQLITE_OK ){
98749    Pager *pPager;
98750    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
98751    if( !aNew->pSchema ){
98752      rc = SQLITE_NOMEM_BKPT;
98753    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
98754      zErrDyn = sqlite3MPrintf(db,
98755        "attached databases must use the same text encoding as main database");
98756      rc = SQLITE_ERROR;
98757    }
98758    sqlite3BtreeEnter(aNew->pBt);
98759    pPager = sqlite3BtreePager(aNew->pBt);
98760    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
98761    sqlite3BtreeSecureDelete(aNew->pBt,
98762                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
98763#ifndef SQLITE_OMIT_PAGER_PRAGMAS
98764    sqlite3BtreeSetPagerFlags(aNew->pBt,
98765                      PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
98766#endif
98767    sqlite3BtreeLeave(aNew->pBt);
98768  }
98769  aNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
98770  aNew->zDbSName = sqlite3DbStrDup(db, zName);
98771  if( rc==SQLITE_OK && aNew->zDbSName==0 ){
98772    rc = SQLITE_NOMEM_BKPT;
98773  }
98774
98775
98776#ifdef SQLITE_HAS_CODEC
98777  if( rc==SQLITE_OK ){
98778    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
98779    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
98780    int nKey;
98781    char *zKey;
98782    int t = sqlite3_value_type(argv[2]);
98783    switch( t ){
98784      case SQLITE_INTEGER:
98785      case SQLITE_FLOAT:
98786        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
98787        rc = SQLITE_ERROR;
98788        break;
98789
98790      case SQLITE_TEXT:
98791      case SQLITE_BLOB:
98792        nKey = sqlite3_value_bytes(argv[2]);
98793        zKey = (char *)sqlite3_value_blob(argv[2]);
98794        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
98795        break;
98796
98797      case SQLITE_NULL:
98798        /* No key specified.  Use the key from the main database */
98799        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
98800        if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
98801          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
98802        }
98803        break;
98804    }
98805  }
98806#endif
98807
98808  /* If the file was opened successfully, read the schema for the new database.
98809  ** If this fails, or if opening the file failed, then close the file and
98810  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
98811  ** we found it.
98812  */
98813  if( rc==SQLITE_OK ){
98814    sqlite3BtreeEnterAll(db);
98815    rc = sqlite3Init(db, &zErrDyn);
98816    sqlite3BtreeLeaveAll(db);
98817  }
98818#ifdef SQLITE_USER_AUTHENTICATION
98819  if( rc==SQLITE_OK ){
98820    u8 newAuth = 0;
98821    rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
98822    if( newAuth<db->auth.authLevel ){
98823      rc = SQLITE_AUTH_USER;
98824    }
98825  }
98826#endif
98827  if( rc ){
98828    int iDb = db->nDb - 1;
98829    assert( iDb>=2 );
98830    if( db->aDb[iDb].pBt ){
98831      sqlite3BtreeClose(db->aDb[iDb].pBt);
98832      db->aDb[iDb].pBt = 0;
98833      db->aDb[iDb].pSchema = 0;
98834    }
98835    sqlite3ResetAllSchemasOfConnection(db);
98836    db->nDb = iDb;
98837    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
98838      sqlite3OomFault(db);
98839      sqlite3DbFree(db, zErrDyn);
98840      zErrDyn = sqlite3MPrintf(db, "out of memory");
98841    }else if( zErrDyn==0 ){
98842      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
98843    }
98844    goto attach_error;
98845  }
98846
98847  return;
98848
98849attach_error:
98850  /* Return an error if we get here */
98851  if( zErrDyn ){
98852    sqlite3_result_error(context, zErrDyn, -1);
98853    sqlite3DbFree(db, zErrDyn);
98854  }
98855  if( rc ) sqlite3_result_error_code(context, rc);
98856}
98857
98858/*
98859** An SQL user-function registered to do the work of an DETACH statement. The
98860** three arguments to the function come directly from a detach statement:
98861**
98862**     DETACH DATABASE x
98863**
98864**     SELECT sqlite_detach(x)
98865*/
98866static void detachFunc(
98867  sqlite3_context *context,
98868  int NotUsed,
98869  sqlite3_value **argv
98870){
98871  const char *zName = (const char *)sqlite3_value_text(argv[0]);
98872  sqlite3 *db = sqlite3_context_db_handle(context);
98873  int i;
98874  Db *pDb = 0;
98875  char zErr[128];
98876
98877  UNUSED_PARAMETER(NotUsed);
98878
98879  if( zName==0 ) zName = "";
98880  for(i=0; i<db->nDb; i++){
98881    pDb = &db->aDb[i];
98882    if( pDb->pBt==0 ) continue;
98883    if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
98884  }
98885
98886  if( i>=db->nDb ){
98887    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
98888    goto detach_error;
98889  }
98890  if( i<2 ){
98891    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
98892    goto detach_error;
98893  }
98894  if( !db->autoCommit ){
98895    sqlite3_snprintf(sizeof(zErr), zErr,
98896                     "cannot DETACH database within transaction");
98897    goto detach_error;
98898  }
98899  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
98900    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
98901    goto detach_error;
98902  }
98903
98904  sqlite3BtreeClose(pDb->pBt);
98905  pDb->pBt = 0;
98906  pDb->pSchema = 0;
98907  sqlite3CollapseDatabaseArray(db);
98908  return;
98909
98910detach_error:
98911  sqlite3_result_error(context, zErr, -1);
98912}
98913
98914/*
98915** This procedure generates VDBE code for a single invocation of either the
98916** sqlite_detach() or sqlite_attach() SQL user functions.
98917*/
98918static void codeAttach(
98919  Parse *pParse,       /* The parser context */
98920  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
98921  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
98922  Expr *pAuthArg,      /* Expression to pass to authorization callback */
98923  Expr *pFilename,     /* Name of database file */
98924  Expr *pDbname,       /* Name of the database to use internally */
98925  Expr *pKey           /* Database key for encryption extension */
98926){
98927  int rc;
98928  NameContext sName;
98929  Vdbe *v;
98930  sqlite3* db = pParse->db;
98931  int regArgs;
98932
98933  if( pParse->nErr ) goto attach_end;
98934  memset(&sName, 0, sizeof(NameContext));
98935  sName.pParse = pParse;
98936
98937  if(
98938      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
98939      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
98940      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
98941  ){
98942    goto attach_end;
98943  }
98944
98945#ifndef SQLITE_OMIT_AUTHORIZATION
98946  if( pAuthArg ){
98947    char *zAuthArg;
98948    if( pAuthArg->op==TK_STRING ){
98949      zAuthArg = pAuthArg->u.zToken;
98950    }else{
98951      zAuthArg = 0;
98952    }
98953    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
98954    if(rc!=SQLITE_OK ){
98955      goto attach_end;
98956    }
98957  }
98958#endif /* SQLITE_OMIT_AUTHORIZATION */
98959
98960
98961  v = sqlite3GetVdbe(pParse);
98962  regArgs = sqlite3GetTempRange(pParse, 4);
98963  sqlite3ExprCode(pParse, pFilename, regArgs);
98964  sqlite3ExprCode(pParse, pDbname, regArgs+1);
98965  sqlite3ExprCode(pParse, pKey, regArgs+2);
98966
98967  assert( v || db->mallocFailed );
98968  if( v ){
98969    sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
98970                      (char *)pFunc, P4_FUNCDEF);
98971    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
98972    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
98973
98974    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
98975    ** statement only). For DETACH, set it to false (expire all existing
98976    ** statements).
98977    */
98978    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
98979  }
98980
98981attach_end:
98982  sqlite3ExprDelete(db, pFilename);
98983  sqlite3ExprDelete(db, pDbname);
98984  sqlite3ExprDelete(db, pKey);
98985}
98986
98987/*
98988** Called by the parser to compile a DETACH statement.
98989**
98990**     DETACH pDbname
98991*/
98992SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
98993  static const FuncDef detach_func = {
98994    1,                /* nArg */
98995    SQLITE_UTF8,      /* funcFlags */
98996    0,                /* pUserData */
98997    0,                /* pNext */
98998    detachFunc,       /* xSFunc */
98999    0,                /* xFinalize */
99000    "sqlite_detach",  /* zName */
99001    {0}
99002  };
99003  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
99004}
99005
99006/*
99007** Called by the parser to compile an ATTACH statement.
99008**
99009**     ATTACH p AS pDbname KEY pKey
99010*/
99011SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
99012  static const FuncDef attach_func = {
99013    3,                /* nArg */
99014    SQLITE_UTF8,      /* funcFlags */
99015    0,                /* pUserData */
99016    0,                /* pNext */
99017    attachFunc,       /* xSFunc */
99018    0,                /* xFinalize */
99019    "sqlite_attach",  /* zName */
99020    {0}
99021  };
99022  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
99023}
99024#endif /* SQLITE_OMIT_ATTACH */
99025
99026/*
99027** Initialize a DbFixer structure.  This routine must be called prior
99028** to passing the structure to one of the sqliteFixAAAA() routines below.
99029*/
99030SQLITE_PRIVATE void sqlite3FixInit(
99031  DbFixer *pFix,      /* The fixer to be initialized */
99032  Parse *pParse,      /* Error messages will be written here */
99033  int iDb,            /* This is the database that must be used */
99034  const char *zType,  /* "view", "trigger", or "index" */
99035  const Token *pName  /* Name of the view, trigger, or index */
99036){
99037  sqlite3 *db;
99038
99039  db = pParse->db;
99040  assert( db->nDb>iDb );
99041  pFix->pParse = pParse;
99042  pFix->zDb = db->aDb[iDb].zDbSName;
99043  pFix->pSchema = db->aDb[iDb].pSchema;
99044  pFix->zType = zType;
99045  pFix->pName = pName;
99046  pFix->bVarOnly = (iDb==1);
99047}
99048
99049/*
99050** The following set of routines walk through the parse tree and assign
99051** a specific database to all table references where the database name
99052** was left unspecified in the original SQL statement.  The pFix structure
99053** must have been initialized by a prior call to sqlite3FixInit().
99054**
99055** These routines are used to make sure that an index, trigger, or
99056** view in one database does not refer to objects in a different database.
99057** (Exception: indices, triggers, and views in the TEMP database are
99058** allowed to refer to anything.)  If a reference is explicitly made
99059** to an object in a different database, an error message is added to
99060** pParse->zErrMsg and these routines return non-zero.  If everything
99061** checks out, these routines return 0.
99062*/
99063SQLITE_PRIVATE int sqlite3FixSrcList(
99064  DbFixer *pFix,       /* Context of the fixation */
99065  SrcList *pList       /* The Source list to check and modify */
99066){
99067  int i;
99068  const char *zDb;
99069  struct SrcList_item *pItem;
99070
99071  if( NEVER(pList==0) ) return 0;
99072  zDb = pFix->zDb;
99073  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
99074    if( pFix->bVarOnly==0 ){
99075      if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
99076        sqlite3ErrorMsg(pFix->pParse,
99077            "%s %T cannot reference objects in database %s",
99078            pFix->zType, pFix->pName, pItem->zDatabase);
99079        return 1;
99080      }
99081      sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
99082      pItem->zDatabase = 0;
99083      pItem->pSchema = pFix->pSchema;
99084    }
99085#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
99086    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
99087    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
99088#endif
99089  }
99090  return 0;
99091}
99092#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
99093SQLITE_PRIVATE int sqlite3FixSelect(
99094  DbFixer *pFix,       /* Context of the fixation */
99095  Select *pSelect      /* The SELECT statement to be fixed to one database */
99096){
99097  while( pSelect ){
99098    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
99099      return 1;
99100    }
99101    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
99102      return 1;
99103    }
99104    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
99105      return 1;
99106    }
99107    if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
99108      return 1;
99109    }
99110    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
99111      return 1;
99112    }
99113    if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
99114      return 1;
99115    }
99116    if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
99117      return 1;
99118    }
99119    if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
99120      return 1;
99121    }
99122    pSelect = pSelect->pPrior;
99123  }
99124  return 0;
99125}
99126SQLITE_PRIVATE int sqlite3FixExpr(
99127  DbFixer *pFix,     /* Context of the fixation */
99128  Expr *pExpr        /* The expression to be fixed to one database */
99129){
99130  while( pExpr ){
99131    if( pExpr->op==TK_VARIABLE ){
99132      if( pFix->pParse->db->init.busy ){
99133        pExpr->op = TK_NULL;
99134      }else{
99135        sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
99136        return 1;
99137      }
99138    }
99139    if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
99140    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
99141      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
99142    }else{
99143      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
99144    }
99145    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
99146      return 1;
99147    }
99148    pExpr = pExpr->pLeft;
99149  }
99150  return 0;
99151}
99152SQLITE_PRIVATE int sqlite3FixExprList(
99153  DbFixer *pFix,     /* Context of the fixation */
99154  ExprList *pList    /* The expression to be fixed to one database */
99155){
99156  int i;
99157  struct ExprList_item *pItem;
99158  if( pList==0 ) return 0;
99159  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
99160    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
99161      return 1;
99162    }
99163  }
99164  return 0;
99165}
99166#endif
99167
99168#ifndef SQLITE_OMIT_TRIGGER
99169SQLITE_PRIVATE int sqlite3FixTriggerStep(
99170  DbFixer *pFix,     /* Context of the fixation */
99171  TriggerStep *pStep /* The trigger step be fixed to one database */
99172){
99173  while( pStep ){
99174    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
99175      return 1;
99176    }
99177    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
99178      return 1;
99179    }
99180    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
99181      return 1;
99182    }
99183    pStep = pStep->pNext;
99184  }
99185  return 0;
99186}
99187#endif
99188
99189/************** End of attach.c **********************************************/
99190/************** Begin file auth.c ********************************************/
99191/*
99192** 2003 January 11
99193**
99194** The author disclaims copyright to this source code.  In place of
99195** a legal notice, here is a blessing:
99196**
99197**    May you do good and not evil.
99198**    May you find forgiveness for yourself and forgive others.
99199**    May you share freely, never taking more than you give.
99200**
99201*************************************************************************
99202** This file contains code used to implement the sqlite3_set_authorizer()
99203** API.  This facility is an optional feature of the library.  Embedded
99204** systems that do not need this facility may omit it by recompiling
99205** the library with -DSQLITE_OMIT_AUTHORIZATION=1
99206*/
99207/* #include "sqliteInt.h" */
99208
99209/*
99210** All of the code in this file may be omitted by defining a single
99211** macro.
99212*/
99213#ifndef SQLITE_OMIT_AUTHORIZATION
99214
99215/*
99216** Set or clear the access authorization function.
99217**
99218** The access authorization function is be called during the compilation
99219** phase to verify that the user has read and/or write access permission on
99220** various fields of the database.  The first argument to the auth function
99221** is a copy of the 3rd argument to this routine.  The second argument
99222** to the auth function is one of these constants:
99223**
99224**       SQLITE_CREATE_INDEX
99225**       SQLITE_CREATE_TABLE
99226**       SQLITE_CREATE_TEMP_INDEX
99227**       SQLITE_CREATE_TEMP_TABLE
99228**       SQLITE_CREATE_TEMP_TRIGGER
99229**       SQLITE_CREATE_TEMP_VIEW
99230**       SQLITE_CREATE_TRIGGER
99231**       SQLITE_CREATE_VIEW
99232**       SQLITE_DELETE
99233**       SQLITE_DROP_INDEX
99234**       SQLITE_DROP_TABLE
99235**       SQLITE_DROP_TEMP_INDEX
99236**       SQLITE_DROP_TEMP_TABLE
99237**       SQLITE_DROP_TEMP_TRIGGER
99238**       SQLITE_DROP_TEMP_VIEW
99239**       SQLITE_DROP_TRIGGER
99240**       SQLITE_DROP_VIEW
99241**       SQLITE_INSERT
99242**       SQLITE_PRAGMA
99243**       SQLITE_READ
99244**       SQLITE_SELECT
99245**       SQLITE_TRANSACTION
99246**       SQLITE_UPDATE
99247**
99248** The third and fourth arguments to the auth function are the name of
99249** the table and the column that are being accessed.  The auth function
99250** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
99251** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
99252** means that the SQL statement will never-run - the sqlite3_exec() call
99253** will return with an error.  SQLITE_IGNORE means that the SQL statement
99254** should run but attempts to read the specified column will return NULL
99255** and attempts to write the column will be ignored.
99256**
99257** Setting the auth function to NULL disables this hook.  The default
99258** setting of the auth function is NULL.
99259*/
99260SQLITE_API int sqlite3_set_authorizer(
99261  sqlite3 *db,
99262  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
99263  void *pArg
99264){
99265#ifdef SQLITE_ENABLE_API_ARMOR
99266  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
99267#endif
99268  sqlite3_mutex_enter(db->mutex);
99269  db->xAuth = (sqlite3_xauth)xAuth;
99270  db->pAuthArg = pArg;
99271  sqlite3ExpirePreparedStatements(db);
99272  sqlite3_mutex_leave(db->mutex);
99273  return SQLITE_OK;
99274}
99275
99276/*
99277** Write an error message into pParse->zErrMsg that explains that the
99278** user-supplied authorization function returned an illegal value.
99279*/
99280static void sqliteAuthBadReturnCode(Parse *pParse){
99281  sqlite3ErrorMsg(pParse, "authorizer malfunction");
99282  pParse->rc = SQLITE_ERROR;
99283}
99284
99285/*
99286** Invoke the authorization callback for permission to read column zCol from
99287** table zTab in database zDb. This function assumes that an authorization
99288** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
99289**
99290** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
99291** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
99292** is treated as SQLITE_DENY. In this case an error is left in pParse.
99293*/
99294SQLITE_PRIVATE int sqlite3AuthReadCol(
99295  Parse *pParse,                  /* The parser context */
99296  const char *zTab,               /* Table name */
99297  const char *zCol,               /* Column name */
99298  int iDb                         /* Index of containing database. */
99299){
99300  sqlite3 *db = pParse->db;          /* Database handle */
99301  char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
99302  int rc;                            /* Auth callback return code */
99303
99304  if( db->init.busy ) return SQLITE_OK;
99305  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
99306#ifdef SQLITE_USER_AUTHENTICATION
99307                 ,db->auth.zAuthUser
99308#endif
99309                );
99310  if( rc==SQLITE_DENY ){
99311    if( db->nDb>2 || iDb!=0 ){
99312      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
99313    }else{
99314      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
99315    }
99316    pParse->rc = SQLITE_AUTH;
99317  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
99318    sqliteAuthBadReturnCode(pParse);
99319  }
99320  return rc;
99321}
99322
99323/*
99324** The pExpr should be a TK_COLUMN expression.  The table referred to
99325** is in pTabList or else it is the NEW or OLD table of a trigger.
99326** Check to see if it is OK to read this particular column.
99327**
99328** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
99329** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
99330** then generate an error.
99331*/
99332SQLITE_PRIVATE void sqlite3AuthRead(
99333  Parse *pParse,        /* The parser context */
99334  Expr *pExpr,          /* The expression to check authorization on */
99335  Schema *pSchema,      /* The schema of the expression */
99336  SrcList *pTabList     /* All table that pExpr might refer to */
99337){
99338  sqlite3 *db = pParse->db;
99339  Table *pTab = 0;      /* The table being read */
99340  const char *zCol;     /* Name of the column of the table */
99341  int iSrc;             /* Index in pTabList->a[] of table being read */
99342  int iDb;              /* The index of the database the expression refers to */
99343  int iCol;             /* Index of column in table */
99344
99345  if( db->xAuth==0 ) return;
99346  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
99347  if( iDb<0 ){
99348    /* An attempt to read a column out of a subquery or other
99349    ** temporary table. */
99350    return;
99351  }
99352
99353  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
99354  if( pExpr->op==TK_TRIGGER ){
99355    pTab = pParse->pTriggerTab;
99356  }else{
99357    assert( pTabList );
99358    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
99359      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
99360        pTab = pTabList->a[iSrc].pTab;
99361        break;
99362      }
99363    }
99364  }
99365  iCol = pExpr->iColumn;
99366  if( NEVER(pTab==0) ) return;
99367
99368  if( iCol>=0 ){
99369    assert( iCol<pTab->nCol );
99370    zCol = pTab->aCol[iCol].zName;
99371  }else if( pTab->iPKey>=0 ){
99372    assert( pTab->iPKey<pTab->nCol );
99373    zCol = pTab->aCol[pTab->iPKey].zName;
99374  }else{
99375    zCol = "ROWID";
99376  }
99377  assert( iDb>=0 && iDb<db->nDb );
99378  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
99379    pExpr->op = TK_NULL;
99380  }
99381}
99382
99383/*
99384** Do an authorization check using the code and arguments given.  Return
99385** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
99386** is returned, then the error count and error message in pParse are
99387** modified appropriately.
99388*/
99389SQLITE_PRIVATE int sqlite3AuthCheck(
99390  Parse *pParse,
99391  int code,
99392  const char *zArg1,
99393  const char *zArg2,
99394  const char *zArg3
99395){
99396  sqlite3 *db = pParse->db;
99397  int rc;
99398
99399  /* Don't do any authorization checks if the database is initialising
99400  ** or if the parser is being invoked from within sqlite3_declare_vtab.
99401  */
99402  if( db->init.busy || IN_DECLARE_VTAB ){
99403    return SQLITE_OK;
99404  }
99405
99406  if( db->xAuth==0 ){
99407    return SQLITE_OK;
99408  }
99409  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
99410#ifdef SQLITE_USER_AUTHENTICATION
99411                 ,db->auth.zAuthUser
99412#endif
99413                );
99414  if( rc==SQLITE_DENY ){
99415    sqlite3ErrorMsg(pParse, "not authorized");
99416    pParse->rc = SQLITE_AUTH;
99417  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
99418    rc = SQLITE_DENY;
99419    sqliteAuthBadReturnCode(pParse);
99420  }
99421  return rc;
99422}
99423
99424/*
99425** Push an authorization context.  After this routine is called, the
99426** zArg3 argument to authorization callbacks will be zContext until
99427** popped.  Or if pParse==0, this routine is a no-op.
99428*/
99429SQLITE_PRIVATE void sqlite3AuthContextPush(
99430  Parse *pParse,
99431  AuthContext *pContext,
99432  const char *zContext
99433){
99434  assert( pParse );
99435  pContext->pParse = pParse;
99436  pContext->zAuthContext = pParse->zAuthContext;
99437  pParse->zAuthContext = zContext;
99438}
99439
99440/*
99441** Pop an authorization context that was previously pushed
99442** by sqlite3AuthContextPush
99443*/
99444SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
99445  if( pContext->pParse ){
99446    pContext->pParse->zAuthContext = pContext->zAuthContext;
99447    pContext->pParse = 0;
99448  }
99449}
99450
99451#endif /* SQLITE_OMIT_AUTHORIZATION */
99452
99453/************** End of auth.c ************************************************/
99454/************** Begin file build.c *******************************************/
99455/*
99456** 2001 September 15
99457**
99458** The author disclaims copyright to this source code.  In place of
99459** a legal notice, here is a blessing:
99460**
99461**    May you do good and not evil.
99462**    May you find forgiveness for yourself and forgive others.
99463**    May you share freely, never taking more than you give.
99464**
99465*************************************************************************
99466** This file contains C code routines that are called by the SQLite parser
99467** when syntax rules are reduced.  The routines in this file handle the
99468** following kinds of SQL syntax:
99469**
99470**     CREATE TABLE
99471**     DROP TABLE
99472**     CREATE INDEX
99473**     DROP INDEX
99474**     creating ID lists
99475**     BEGIN TRANSACTION
99476**     COMMIT
99477**     ROLLBACK
99478*/
99479/* #include "sqliteInt.h" */
99480
99481#ifndef SQLITE_OMIT_SHARED_CACHE
99482/*
99483** The TableLock structure is only used by the sqlite3TableLock() and
99484** codeTableLocks() functions.
99485*/
99486struct TableLock {
99487  int iDb;               /* The database containing the table to be locked */
99488  int iTab;              /* The root page of the table to be locked */
99489  u8 isWriteLock;        /* True for write lock.  False for a read lock */
99490  const char *zLockName; /* Name of the table */
99491};
99492
99493/*
99494** Record the fact that we want to lock a table at run-time.
99495**
99496** The table to be locked has root page iTab and is found in database iDb.
99497** A read or a write lock can be taken depending on isWritelock.
99498**
99499** This routine just records the fact that the lock is desired.  The
99500** code to make the lock occur is generated by a later call to
99501** codeTableLocks() which occurs during sqlite3FinishCoding().
99502*/
99503SQLITE_PRIVATE void sqlite3TableLock(
99504  Parse *pParse,     /* Parsing context */
99505  int iDb,           /* Index of the database containing the table to lock */
99506  int iTab,          /* Root page number of the table to be locked */
99507  u8 isWriteLock,    /* True for a write lock */
99508  const char *zName  /* Name of the table to be locked */
99509){
99510  Parse *pToplevel = sqlite3ParseToplevel(pParse);
99511  int i;
99512  int nBytes;
99513  TableLock *p;
99514  assert( iDb>=0 );
99515
99516  if( iDb==1 ) return;
99517  if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
99518  for(i=0; i<pToplevel->nTableLock; i++){
99519    p = &pToplevel->aTableLock[i];
99520    if( p->iDb==iDb && p->iTab==iTab ){
99521      p->isWriteLock = (p->isWriteLock || isWriteLock);
99522      return;
99523    }
99524  }
99525
99526  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
99527  pToplevel->aTableLock =
99528      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
99529  if( pToplevel->aTableLock ){
99530    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
99531    p->iDb = iDb;
99532    p->iTab = iTab;
99533    p->isWriteLock = isWriteLock;
99534    p->zLockName = zName;
99535  }else{
99536    pToplevel->nTableLock = 0;
99537    sqlite3OomFault(pToplevel->db);
99538  }
99539}
99540
99541/*
99542** Code an OP_TableLock instruction for each table locked by the
99543** statement (configured by calls to sqlite3TableLock()).
99544*/
99545static void codeTableLocks(Parse *pParse){
99546  int i;
99547  Vdbe *pVdbe;
99548
99549  pVdbe = sqlite3GetVdbe(pParse);
99550  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
99551
99552  for(i=0; i<pParse->nTableLock; i++){
99553    TableLock *p = &pParse->aTableLock[i];
99554    int p1 = p->iDb;
99555    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
99556                      p->zLockName, P4_STATIC);
99557  }
99558}
99559#else
99560  #define codeTableLocks(x)
99561#endif
99562
99563/*
99564** Return TRUE if the given yDbMask object is empty - if it contains no
99565** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
99566** macros when SQLITE_MAX_ATTACHED is greater than 30.
99567*/
99568#if SQLITE_MAX_ATTACHED>30
99569SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
99570  int i;
99571  for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
99572  return 1;
99573}
99574#endif
99575
99576/*
99577** This routine is called after a single SQL statement has been
99578** parsed and a VDBE program to execute that statement has been
99579** prepared.  This routine puts the finishing touches on the
99580** VDBE program and resets the pParse structure for the next
99581** parse.
99582**
99583** Note that if an error occurred, it might be the case that
99584** no VDBE code was generated.
99585*/
99586SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
99587  sqlite3 *db;
99588  Vdbe *v;
99589
99590  assert( pParse->pToplevel==0 );
99591  db = pParse->db;
99592  if( pParse->nested ) return;
99593  if( db->mallocFailed || pParse->nErr ){
99594    if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
99595    return;
99596  }
99597
99598  /* Begin by generating some termination code at the end of the
99599  ** vdbe program
99600  */
99601  v = sqlite3GetVdbe(pParse);
99602  assert( !pParse->isMultiWrite
99603       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
99604  if( v ){
99605    sqlite3VdbeAddOp0(v, OP_Halt);
99606
99607#if SQLITE_USER_AUTHENTICATION
99608    if( pParse->nTableLock>0 && db->init.busy==0 ){
99609      sqlite3UserAuthInit(db);
99610      if( db->auth.authLevel<UAUTH_User ){
99611        sqlite3ErrorMsg(pParse, "user not authenticated");
99612        pParse->rc = SQLITE_AUTH_USER;
99613        return;
99614      }
99615    }
99616#endif
99617
99618    /* The cookie mask contains one bit for each database file open.
99619    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
99620    ** set for each database that is used.  Generate code to start a
99621    ** transaction on each used database and to verify the schema cookie
99622    ** on each used database.
99623    */
99624    if( db->mallocFailed==0
99625     && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
99626    ){
99627      int iDb, i;
99628      assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
99629      sqlite3VdbeJumpHere(v, 0);
99630      for(iDb=0; iDb<db->nDb; iDb++){
99631        Schema *pSchema;
99632        if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
99633        sqlite3VdbeUsesBtree(v, iDb);
99634        pSchema = db->aDb[iDb].pSchema;
99635        sqlite3VdbeAddOp4Int(v,
99636          OP_Transaction,                    /* Opcode */
99637          iDb,                               /* P1 */
99638          DbMaskTest(pParse->writeMask,iDb), /* P2 */
99639          pSchema->schema_cookie,            /* P3 */
99640          pSchema->iGeneration               /* P4 */
99641        );
99642        if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
99643        VdbeComment((v,
99644              "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
99645      }
99646#ifndef SQLITE_OMIT_VIRTUALTABLE
99647      for(i=0; i<pParse->nVtabLock; i++){
99648        char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
99649        sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
99650      }
99651      pParse->nVtabLock = 0;
99652#endif
99653
99654      /* Once all the cookies have been verified and transactions opened,
99655      ** obtain the required table-locks. This is a no-op unless the
99656      ** shared-cache feature is enabled.
99657      */
99658      codeTableLocks(pParse);
99659
99660      /* Initialize any AUTOINCREMENT data structures required.
99661      */
99662      sqlite3AutoincrementBegin(pParse);
99663
99664      /* Code constant expressions that where factored out of inner loops */
99665      if( pParse->pConstExpr ){
99666        ExprList *pEL = pParse->pConstExpr;
99667        pParse->okConstFactor = 0;
99668        for(i=0; i<pEL->nExpr; i++){
99669          sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
99670        }
99671      }
99672
99673      /* Finally, jump back to the beginning of the executable code. */
99674      sqlite3VdbeGoto(v, 1);
99675    }
99676  }
99677
99678
99679  /* Get the VDBE program ready for execution
99680  */
99681  if( v && pParse->nErr==0 && !db->mallocFailed ){
99682    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
99683    /* A minimum of one cursor is required if autoincrement is used
99684    *  See ticket [a696379c1f08866] */
99685    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
99686    sqlite3VdbeMakeReady(v, pParse);
99687    pParse->rc = SQLITE_DONE;
99688  }else{
99689    pParse->rc = SQLITE_ERROR;
99690  }
99691}
99692
99693/*
99694** Run the parser and code generator recursively in order to generate
99695** code for the SQL statement given onto the end of the pParse context
99696** currently under construction.  When the parser is run recursively
99697** this way, the final OP_Halt is not appended and other initialization
99698** and finalization steps are omitted because those are handling by the
99699** outermost parser.
99700**
99701** Not everything is nestable.  This facility is designed to permit
99702** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
99703** care if you decide to try to use this routine for some other purposes.
99704*/
99705SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
99706  va_list ap;
99707  char *zSql;
99708  char *zErrMsg = 0;
99709  sqlite3 *db = pParse->db;
99710  char saveBuf[PARSE_TAIL_SZ];
99711
99712  if( pParse->nErr ) return;
99713  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
99714  va_start(ap, zFormat);
99715  zSql = sqlite3VMPrintf(db, zFormat, ap);
99716  va_end(ap);
99717  if( zSql==0 ){
99718    return;   /* A malloc must have failed */
99719  }
99720  pParse->nested++;
99721  memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
99722  memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
99723  sqlite3RunParser(pParse, zSql, &zErrMsg);
99724  sqlite3DbFree(db, zErrMsg);
99725  sqlite3DbFree(db, zSql);
99726  memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
99727  pParse->nested--;
99728}
99729
99730#if SQLITE_USER_AUTHENTICATION
99731/*
99732** Return TRUE if zTable is the name of the system table that stores the
99733** list of users and their access credentials.
99734*/
99735SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
99736  return sqlite3_stricmp(zTable, "sqlite_user")==0;
99737}
99738#endif
99739
99740/*
99741** Locate the in-memory structure that describes a particular database
99742** table given the name of that table and (optionally) the name of the
99743** database containing the table.  Return NULL if not found.
99744**
99745** If zDatabase is 0, all databases are searched for the table and the
99746** first matching table is returned.  (No checking for duplicate table
99747** names is done.)  The search order is TEMP first, then MAIN, then any
99748** auxiliary databases added using the ATTACH command.
99749**
99750** See also sqlite3LocateTable().
99751*/
99752SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
99753  Table *p = 0;
99754  int i;
99755
99756  /* All mutexes are required for schema access.  Make sure we hold them. */
99757  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
99758#if SQLITE_USER_AUTHENTICATION
99759  /* Only the admin user is allowed to know that the sqlite_user table
99760  ** exists */
99761  if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
99762    return 0;
99763  }
99764#endif
99765  while(1){
99766    for(i=OMIT_TEMPDB; i<db->nDb; i++){
99767      int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
99768      if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
99769        assert( sqlite3SchemaMutexHeld(db, j, 0) );
99770        p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
99771        if( p ) return p;
99772      }
99773    }
99774    /* Not found.  If the name we were looking for was temp.sqlite_master
99775    ** then change the name to sqlite_temp_master and try again. */
99776    if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
99777    if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
99778    zName = TEMP_MASTER_NAME;
99779  }
99780  return 0;
99781}
99782
99783/*
99784** Locate the in-memory structure that describes a particular database
99785** table given the name of that table and (optionally) the name of the
99786** database containing the table.  Return NULL if not found.  Also leave an
99787** error message in pParse->zErrMsg.
99788**
99789** The difference between this routine and sqlite3FindTable() is that this
99790** routine leaves an error message in pParse->zErrMsg where
99791** sqlite3FindTable() does not.
99792*/
99793SQLITE_PRIVATE Table *sqlite3LocateTable(
99794  Parse *pParse,         /* context in which to report errors */
99795  u32 flags,             /* LOCATE_VIEW or LOCATE_NOERR */
99796  const char *zName,     /* Name of the table we are looking for */
99797  const char *zDbase     /* Name of the database.  Might be NULL */
99798){
99799  Table *p;
99800
99801  /* Read the database schema. If an error occurs, leave an error message
99802  ** and code in pParse and return NULL. */
99803  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
99804    return 0;
99805  }
99806
99807  p = sqlite3FindTable(pParse->db, zName, zDbase);
99808  if( p==0 ){
99809    const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
99810#ifndef SQLITE_OMIT_VIRTUALTABLE
99811    if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
99812      /* If zName is the not the name of a table in the schema created using
99813      ** CREATE, then check to see if it is the name of an virtual table that
99814      ** can be an eponymous virtual table. */
99815      Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
99816      if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
99817        pMod = sqlite3PragmaVtabRegister(pParse->db, zName);
99818      }
99819      if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
99820        return pMod->pEpoTab;
99821      }
99822    }
99823#endif
99824    if( (flags & LOCATE_NOERR)==0 ){
99825      if( zDbase ){
99826        sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
99827      }else{
99828        sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
99829      }
99830      pParse->checkSchema = 1;
99831    }
99832  }
99833
99834  return p;
99835}
99836
99837/*
99838** Locate the table identified by *p.
99839**
99840** This is a wrapper around sqlite3LocateTable(). The difference between
99841** sqlite3LocateTable() and this function is that this function restricts
99842** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
99843** non-NULL if it is part of a view or trigger program definition. See
99844** sqlite3FixSrcList() for details.
99845*/
99846SQLITE_PRIVATE Table *sqlite3LocateTableItem(
99847  Parse *pParse,
99848  u32 flags,
99849  struct SrcList_item *p
99850){
99851  const char *zDb;
99852  assert( p->pSchema==0 || p->zDatabase==0 );
99853  if( p->pSchema ){
99854    int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
99855    zDb = pParse->db->aDb[iDb].zDbSName;
99856  }else{
99857    zDb = p->zDatabase;
99858  }
99859  return sqlite3LocateTable(pParse, flags, p->zName, zDb);
99860}
99861
99862/*
99863** Locate the in-memory structure that describes
99864** a particular index given the name of that index
99865** and the name of the database that contains the index.
99866** Return NULL if not found.
99867**
99868** If zDatabase is 0, all databases are searched for the
99869** table and the first matching index is returned.  (No checking
99870** for duplicate index names is done.)  The search order is
99871** TEMP first, then MAIN, then any auxiliary databases added
99872** using the ATTACH command.
99873*/
99874SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
99875  Index *p = 0;
99876  int i;
99877  /* All mutexes are required for schema access.  Make sure we hold them. */
99878  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
99879  for(i=OMIT_TEMPDB; i<db->nDb; i++){
99880    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
99881    Schema *pSchema = db->aDb[j].pSchema;
99882    assert( pSchema );
99883    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
99884    assert( sqlite3SchemaMutexHeld(db, j, 0) );
99885    p = sqlite3HashFind(&pSchema->idxHash, zName);
99886    if( p ) break;
99887  }
99888  return p;
99889}
99890
99891/*
99892** Reclaim the memory used by an index
99893*/
99894static void freeIndex(sqlite3 *db, Index *p){
99895#ifndef SQLITE_OMIT_ANALYZE
99896  sqlite3DeleteIndexSamples(db, p);
99897#endif
99898  sqlite3ExprDelete(db, p->pPartIdxWhere);
99899  sqlite3ExprListDelete(db, p->aColExpr);
99900  sqlite3DbFree(db, p->zColAff);
99901  if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
99902#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99903  sqlite3_free(p->aiRowEst);
99904#endif
99905  sqlite3DbFree(db, p);
99906}
99907
99908/*
99909** For the index called zIdxName which is found in the database iDb,
99910** unlike that index from its Table then remove the index from
99911** the index hash table and free all memory structures associated
99912** with the index.
99913*/
99914SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
99915  Index *pIndex;
99916  Hash *pHash;
99917
99918  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99919  pHash = &db->aDb[iDb].pSchema->idxHash;
99920  pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
99921  if( ALWAYS(pIndex) ){
99922    if( pIndex->pTable->pIndex==pIndex ){
99923      pIndex->pTable->pIndex = pIndex->pNext;
99924    }else{
99925      Index *p;
99926      /* Justification of ALWAYS();  The index must be on the list of
99927      ** indices. */
99928      p = pIndex->pTable->pIndex;
99929      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
99930      if( ALWAYS(p && p->pNext==pIndex) ){
99931        p->pNext = pIndex->pNext;
99932      }
99933    }
99934    freeIndex(db, pIndex);
99935  }
99936  db->flags |= SQLITE_InternChanges;
99937}
99938
99939/*
99940** Look through the list of open database files in db->aDb[] and if
99941** any have been closed, remove them from the list.  Reallocate the
99942** db->aDb[] structure to a smaller size, if possible.
99943**
99944** Entry 0 (the "main" database) and entry 1 (the "temp" database)
99945** are never candidates for being collapsed.
99946*/
99947SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
99948  int i, j;
99949  for(i=j=2; i<db->nDb; i++){
99950    struct Db *pDb = &db->aDb[i];
99951    if( pDb->pBt==0 ){
99952      sqlite3DbFree(db, pDb->zDbSName);
99953      pDb->zDbSName = 0;
99954      continue;
99955    }
99956    if( j<i ){
99957      db->aDb[j] = db->aDb[i];
99958    }
99959    j++;
99960  }
99961  db->nDb = j;
99962  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
99963    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
99964    sqlite3DbFree(db, db->aDb);
99965    db->aDb = db->aDbStatic;
99966  }
99967}
99968
99969/*
99970** Reset the schema for the database at index iDb.  Also reset the
99971** TEMP schema.
99972*/
99973SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
99974  Db *pDb;
99975  assert( iDb<db->nDb );
99976
99977  /* Case 1:  Reset the single schema identified by iDb */
99978  pDb = &db->aDb[iDb];
99979  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99980  assert( pDb->pSchema!=0 );
99981  sqlite3SchemaClear(pDb->pSchema);
99982
99983  /* If any database other than TEMP is reset, then also reset TEMP
99984  ** since TEMP might be holding triggers that reference tables in the
99985  ** other database.
99986  */
99987  if( iDb!=1 ){
99988    pDb = &db->aDb[1];
99989    assert( pDb->pSchema!=0 );
99990    sqlite3SchemaClear(pDb->pSchema);
99991  }
99992  return;
99993}
99994
99995/*
99996** Erase all schema information from all attached databases (including
99997** "main" and "temp") for a single database connection.
99998*/
99999SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
100000  int i;
100001  sqlite3BtreeEnterAll(db);
100002  for(i=0; i<db->nDb; i++){
100003    Db *pDb = &db->aDb[i];
100004    if( pDb->pSchema ){
100005      sqlite3SchemaClear(pDb->pSchema);
100006    }
100007  }
100008  db->flags &= ~SQLITE_InternChanges;
100009  sqlite3VtabUnlockList(db);
100010  sqlite3BtreeLeaveAll(db);
100011  sqlite3CollapseDatabaseArray(db);
100012}
100013
100014/*
100015** This routine is called when a commit occurs.
100016*/
100017SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
100018  db->flags &= ~SQLITE_InternChanges;
100019}
100020
100021/*
100022** Delete memory allocated for the column names of a table or view (the
100023** Table.aCol[] array).
100024*/
100025SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
100026  int i;
100027  Column *pCol;
100028  assert( pTable!=0 );
100029  if( (pCol = pTable->aCol)!=0 ){
100030    for(i=0; i<pTable->nCol; i++, pCol++){
100031      sqlite3DbFree(db, pCol->zName);
100032      sqlite3ExprDelete(db, pCol->pDflt);
100033      sqlite3DbFree(db, pCol->zColl);
100034    }
100035    sqlite3DbFree(db, pTable->aCol);
100036  }
100037}
100038
100039/*
100040** Remove the memory data structures associated with the given
100041** Table.  No changes are made to disk by this routine.
100042**
100043** This routine just deletes the data structure.  It does not unlink
100044** the table data structure from the hash table.  But it does destroy
100045** memory structures of the indices and foreign keys associated with
100046** the table.
100047**
100048** The db parameter is optional.  It is needed if the Table object
100049** contains lookaside memory.  (Table objects in the schema do not use
100050** lookaside memory, but some ephemeral Table objects do.)  Or the
100051** db parameter can be used with db->pnBytesFreed to measure the memory
100052** used by the Table object.
100053*/
100054static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
100055  Index *pIndex, *pNext;
100056  TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
100057
100058  /* Record the number of outstanding lookaside allocations in schema Tables
100059  ** prior to doing any free() operations.  Since schema Tables do not use
100060  ** lookaside, this number should not change. */
100061  TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
100062                         db->lookaside.nOut : 0 );
100063
100064  /* Delete all indices associated with this table. */
100065  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
100066    pNext = pIndex->pNext;
100067    assert( pIndex->pSchema==pTable->pSchema
100068         || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
100069    if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
100070      char *zName = pIndex->zName;
100071      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
100072         &pIndex->pSchema->idxHash, zName, 0
100073      );
100074      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
100075      assert( pOld==pIndex || pOld==0 );
100076    }
100077    freeIndex(db, pIndex);
100078  }
100079
100080  /* Delete any foreign keys attached to this table. */
100081  sqlite3FkDelete(db, pTable);
100082
100083  /* Delete the Table structure itself.
100084  */
100085  sqlite3DeleteColumnNames(db, pTable);
100086  sqlite3DbFree(db, pTable->zName);
100087  sqlite3DbFree(db, pTable->zColAff);
100088  sqlite3SelectDelete(db, pTable->pSelect);
100089  sqlite3ExprListDelete(db, pTable->pCheck);
100090#ifndef SQLITE_OMIT_VIRTUALTABLE
100091  sqlite3VtabClear(db, pTable);
100092#endif
100093  sqlite3DbFree(db, pTable);
100094
100095  /* Verify that no lookaside memory was used by schema tables */
100096  assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
100097}
100098SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
100099  /* Do not delete the table until the reference count reaches zero. */
100100  if( !pTable ) return;
100101  if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
100102  deleteTable(db, pTable);
100103}
100104
100105
100106/*
100107** Unlink the given table from the hash tables and the delete the
100108** table structure with all its indices and foreign keys.
100109*/
100110SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
100111  Table *p;
100112  Db *pDb;
100113
100114  assert( db!=0 );
100115  assert( iDb>=0 && iDb<db->nDb );
100116  assert( zTabName );
100117  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100118  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
100119  pDb = &db->aDb[iDb];
100120  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
100121  sqlite3DeleteTable(db, p);
100122  db->flags |= SQLITE_InternChanges;
100123}
100124
100125/*
100126** Given a token, return a string that consists of the text of that
100127** token.  Space to hold the returned string
100128** is obtained from sqliteMalloc() and must be freed by the calling
100129** function.
100130**
100131** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
100132** surround the body of the token are removed.
100133**
100134** Tokens are often just pointers into the original SQL text and so
100135** are not \000 terminated and are not persistent.  The returned string
100136** is \000 terminated and is persistent.
100137*/
100138SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
100139  char *zName;
100140  if( pName ){
100141    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
100142    sqlite3Dequote(zName);
100143  }else{
100144    zName = 0;
100145  }
100146  return zName;
100147}
100148
100149/*
100150** Open the sqlite_master table stored in database number iDb for
100151** writing. The table is opened using cursor 0.
100152*/
100153SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
100154  Vdbe *v = sqlite3GetVdbe(p);
100155  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
100156  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
100157  if( p->nTab==0 ){
100158    p->nTab = 1;
100159  }
100160}
100161
100162/*
100163** Parameter zName points to a nul-terminated buffer containing the name
100164** of a database ("main", "temp" or the name of an attached db). This
100165** function returns the index of the named database in db->aDb[], or
100166** -1 if the named db cannot be found.
100167*/
100168SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
100169  int i = -1;         /* Database number */
100170  if( zName ){
100171    Db *pDb;
100172    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
100173      if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
100174      /* "main" is always an acceptable alias for the primary database
100175      ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
100176      if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
100177    }
100178  }
100179  return i;
100180}
100181
100182/*
100183** The token *pName contains the name of a database (either "main" or
100184** "temp" or the name of an attached db). This routine returns the
100185** index of the named database in db->aDb[], or -1 if the named db
100186** does not exist.
100187*/
100188SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
100189  int i;                               /* Database number */
100190  char *zName;                         /* Name we are searching for */
100191  zName = sqlite3NameFromToken(db, pName);
100192  i = sqlite3FindDbName(db, zName);
100193  sqlite3DbFree(db, zName);
100194  return i;
100195}
100196
100197/* The table or view or trigger name is passed to this routine via tokens
100198** pName1 and pName2. If the table name was fully qualified, for example:
100199**
100200** CREATE TABLE xxx.yyy (...);
100201**
100202** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
100203** the table name is not fully qualified, i.e.:
100204**
100205** CREATE TABLE yyy(...);
100206**
100207** Then pName1 is set to "yyy" and pName2 is "".
100208**
100209** This routine sets the *ppUnqual pointer to point at the token (pName1 or
100210** pName2) that stores the unqualified table name.  The index of the
100211** database "xxx" is returned.
100212*/
100213SQLITE_PRIVATE int sqlite3TwoPartName(
100214  Parse *pParse,      /* Parsing and code generating context */
100215  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
100216  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
100217  Token **pUnqual     /* Write the unqualified object name here */
100218){
100219  int iDb;                    /* Database holding the object */
100220  sqlite3 *db = pParse->db;
100221
100222  assert( pName2!=0 );
100223  if( pName2->n>0 ){
100224    if( db->init.busy ) {
100225      sqlite3ErrorMsg(pParse, "corrupt database");
100226      return -1;
100227    }
100228    *pUnqual = pName2;
100229    iDb = sqlite3FindDb(db, pName1);
100230    if( iDb<0 ){
100231      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
100232      return -1;
100233    }
100234  }else{
100235    assert( db->init.iDb==0 || db->init.busy || (db->flags & SQLITE_Vacuum)!=0);
100236    iDb = db->init.iDb;
100237    *pUnqual = pName1;
100238  }
100239  return iDb;
100240}
100241
100242/*
100243** This routine is used to check if the UTF-8 string zName is a legal
100244** unqualified name for a new schema object (table, index, view or
100245** trigger). All names are legal except those that begin with the string
100246** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
100247** is reserved for internal use.
100248*/
100249SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
100250  if( !pParse->db->init.busy && pParse->nested==0
100251          && (pParse->db->flags & SQLITE_WriteSchema)==0
100252          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
100253    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
100254    return SQLITE_ERROR;
100255  }
100256  return SQLITE_OK;
100257}
100258
100259/*
100260** Return the PRIMARY KEY index of a table
100261*/
100262SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
100263  Index *p;
100264  for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
100265  return p;
100266}
100267
100268/*
100269** Return the column of index pIdx that corresponds to table
100270** column iCol.  Return -1 if not found.
100271*/
100272SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
100273  int i;
100274  for(i=0; i<pIdx->nColumn; i++){
100275    if( iCol==pIdx->aiColumn[i] ) return i;
100276  }
100277  return -1;
100278}
100279
100280/*
100281** Begin constructing a new table representation in memory.  This is
100282** the first of several action routines that get called in response
100283** to a CREATE TABLE statement.  In particular, this routine is called
100284** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
100285** flag is true if the table should be stored in the auxiliary database
100286** file instead of in the main database file.  This is normally the case
100287** when the "TEMP" or "TEMPORARY" keyword occurs in between
100288** CREATE and TABLE.
100289**
100290** The new table record is initialized and put in pParse->pNewTable.
100291** As more of the CREATE TABLE statement is parsed, additional action
100292** routines will be called to add more information to this record.
100293** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
100294** is called to complete the construction of the new table record.
100295*/
100296SQLITE_PRIVATE void sqlite3StartTable(
100297  Parse *pParse,   /* Parser context */
100298  Token *pName1,   /* First part of the name of the table or view */
100299  Token *pName2,   /* Second part of the name of the table or view */
100300  int isTemp,      /* True if this is a TEMP table */
100301  int isView,      /* True if this is a VIEW */
100302  int isVirtual,   /* True if this is a VIRTUAL table */
100303  int noErr        /* Do nothing if table already exists */
100304){
100305  Table *pTable;
100306  char *zName = 0; /* The name of the new table */
100307  sqlite3 *db = pParse->db;
100308  Vdbe *v;
100309  int iDb;         /* Database number to create the table in */
100310  Token *pName;    /* Unqualified name of the table to create */
100311
100312  if( db->init.busy && db->init.newTnum==1 ){
100313    /* Special case:  Parsing the sqlite_master or sqlite_temp_master schema */
100314    iDb = db->init.iDb;
100315    zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
100316    pName = pName1;
100317  }else{
100318    /* The common case */
100319    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
100320    if( iDb<0 ) return;
100321    if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
100322      /* If creating a temp table, the name may not be qualified. Unless
100323      ** the database name is "temp" anyway.  */
100324      sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
100325      return;
100326    }
100327    if( !OMIT_TEMPDB && isTemp ) iDb = 1;
100328    zName = sqlite3NameFromToken(db, pName);
100329  }
100330  pParse->sNameToken = *pName;
100331  if( zName==0 ) return;
100332  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
100333    goto begin_table_error;
100334  }
100335  if( db->init.iDb==1 ) isTemp = 1;
100336#ifndef SQLITE_OMIT_AUTHORIZATION
100337  assert( isTemp==0 || isTemp==1 );
100338  assert( isView==0 || isView==1 );
100339  {
100340    static const u8 aCode[] = {
100341       SQLITE_CREATE_TABLE,
100342       SQLITE_CREATE_TEMP_TABLE,
100343       SQLITE_CREATE_VIEW,
100344       SQLITE_CREATE_TEMP_VIEW
100345    };
100346    char *zDb = db->aDb[iDb].zDbSName;
100347    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
100348      goto begin_table_error;
100349    }
100350    if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
100351                                       zName, 0, zDb) ){
100352      goto begin_table_error;
100353    }
100354  }
100355#endif
100356
100357  /* Make sure the new table name does not collide with an existing
100358  ** index or table name in the same database.  Issue an error message if
100359  ** it does. The exception is if the statement being parsed was passed
100360  ** to an sqlite3_declare_vtab() call. In that case only the column names
100361  ** and types will be used, so there is no need to test for namespace
100362  ** collisions.
100363  */
100364  if( !IN_DECLARE_VTAB ){
100365    char *zDb = db->aDb[iDb].zDbSName;
100366    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
100367      goto begin_table_error;
100368    }
100369    pTable = sqlite3FindTable(db, zName, zDb);
100370    if( pTable ){
100371      if( !noErr ){
100372        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
100373      }else{
100374        assert( !db->init.busy || CORRUPT_DB );
100375        sqlite3CodeVerifySchema(pParse, iDb);
100376      }
100377      goto begin_table_error;
100378    }
100379    if( sqlite3FindIndex(db, zName, zDb)!=0 ){
100380      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
100381      goto begin_table_error;
100382    }
100383  }
100384
100385  pTable = sqlite3DbMallocZero(db, sizeof(Table));
100386  if( pTable==0 ){
100387    assert( db->mallocFailed );
100388    pParse->rc = SQLITE_NOMEM_BKPT;
100389    pParse->nErr++;
100390    goto begin_table_error;
100391  }
100392  pTable->zName = zName;
100393  pTable->iPKey = -1;
100394  pTable->pSchema = db->aDb[iDb].pSchema;
100395  pTable->nTabRef = 1;
100396  pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
100397  assert( pParse->pNewTable==0 );
100398  pParse->pNewTable = pTable;
100399
100400  /* If this is the magic sqlite_sequence table used by autoincrement,
100401  ** then record a pointer to this table in the main database structure
100402  ** so that INSERT can find the table easily.
100403  */
100404#ifndef SQLITE_OMIT_AUTOINCREMENT
100405  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
100406    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100407    pTable->pSchema->pSeqTab = pTable;
100408  }
100409#endif
100410
100411  /* Begin generating the code that will insert the table record into
100412  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
100413  ** and allocate the record number for the table entry now.  Before any
100414  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
100415  ** indices to be created and the table record must come before the
100416  ** indices.  Hence, the record number for the table must be allocated
100417  ** now.
100418  */
100419  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
100420    int addr1;
100421    int fileFormat;
100422    int reg1, reg2, reg3;
100423    /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
100424    static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
100425    sqlite3BeginWriteOperation(pParse, 1, iDb);
100426
100427#ifndef SQLITE_OMIT_VIRTUALTABLE
100428    if( isVirtual ){
100429      sqlite3VdbeAddOp0(v, OP_VBegin);
100430    }
100431#endif
100432
100433    /* If the file format and encoding in the database have not been set,
100434    ** set them now.
100435    */
100436    reg1 = pParse->regRowid = ++pParse->nMem;
100437    reg2 = pParse->regRoot = ++pParse->nMem;
100438    reg3 = ++pParse->nMem;
100439    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
100440    sqlite3VdbeUsesBtree(v, iDb);
100441    addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
100442    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
100443                  1 : SQLITE_MAX_FILE_FORMAT;
100444    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
100445    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
100446    sqlite3VdbeJumpHere(v, addr1);
100447
100448    /* This just creates a place-holder record in the sqlite_master table.
100449    ** The record created does not contain anything yet.  It will be replaced
100450    ** by the real entry in code generated at sqlite3EndTable().
100451    **
100452    ** The rowid for the new entry is left in register pParse->regRowid.
100453    ** The root page number of the new table is left in reg pParse->regRoot.
100454    ** The rowid and root page number values are needed by the code that
100455    ** sqlite3EndTable will generate.
100456    */
100457#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
100458    if( isView || isVirtual ){
100459      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
100460    }else
100461#endif
100462    {
100463      pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
100464    }
100465    sqlite3OpenMasterTable(pParse, iDb);
100466    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
100467    sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
100468    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
100469    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
100470    sqlite3VdbeAddOp0(v, OP_Close);
100471  }
100472
100473  /* Normal (non-error) return. */
100474  return;
100475
100476  /* If an error occurs, we jump here */
100477begin_table_error:
100478  sqlite3DbFree(db, zName);
100479  return;
100480}
100481
100482/* Set properties of a table column based on the (magical)
100483** name of the column.
100484*/
100485#if SQLITE_ENABLE_HIDDEN_COLUMNS
100486SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
100487  if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
100488    pCol->colFlags |= COLFLAG_HIDDEN;
100489  }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
100490    pTab->tabFlags |= TF_OOOHidden;
100491  }
100492}
100493#endif
100494
100495
100496/*
100497** Add a new column to the table currently being constructed.
100498**
100499** The parser calls this routine once for each column declaration
100500** in a CREATE TABLE statement.  sqlite3StartTable() gets called
100501** first to get things going.  Then this routine is called for each
100502** column.
100503*/
100504SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
100505  Table *p;
100506  int i;
100507  char *z;
100508  char *zType;
100509  Column *pCol;
100510  sqlite3 *db = pParse->db;
100511  if( (p = pParse->pNewTable)==0 ) return;
100512#if SQLITE_MAX_COLUMN
100513  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
100514    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
100515    return;
100516  }
100517#endif
100518  z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
100519  if( z==0 ) return;
100520  memcpy(z, pName->z, pName->n);
100521  z[pName->n] = 0;
100522  sqlite3Dequote(z);
100523  for(i=0; i<p->nCol; i++){
100524    if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
100525      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
100526      sqlite3DbFree(db, z);
100527      return;
100528    }
100529  }
100530  if( (p->nCol & 0x7)==0 ){
100531    Column *aNew;
100532    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
100533    if( aNew==0 ){
100534      sqlite3DbFree(db, z);
100535      return;
100536    }
100537    p->aCol = aNew;
100538  }
100539  pCol = &p->aCol[p->nCol];
100540  memset(pCol, 0, sizeof(p->aCol[0]));
100541  pCol->zName = z;
100542  sqlite3ColumnPropertiesFromName(p, pCol);
100543
100544  if( pType->n==0 ){
100545    /* If there is no type specified, columns have the default affinity
100546    ** 'BLOB'. */
100547    pCol->affinity = SQLITE_AFF_BLOB;
100548    pCol->szEst = 1;
100549  }else{
100550    zType = z + sqlite3Strlen30(z) + 1;
100551    memcpy(zType, pType->z, pType->n);
100552    zType[pType->n] = 0;
100553    sqlite3Dequote(zType);
100554    pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
100555    pCol->colFlags |= COLFLAG_HASTYPE;
100556  }
100557  p->nCol++;
100558  pParse->constraintName.n = 0;
100559}
100560
100561/*
100562** This routine is called by the parser while in the middle of
100563** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
100564** been seen on a column.  This routine sets the notNull flag on
100565** the column currently under construction.
100566*/
100567SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
100568  Table *p;
100569  p = pParse->pNewTable;
100570  if( p==0 || NEVER(p->nCol<1) ) return;
100571  p->aCol[p->nCol-1].notNull = (u8)onError;
100572  p->tabFlags |= TF_HasNotNull;
100573}
100574
100575/*
100576** Scan the column type name zType (length nType) and return the
100577** associated affinity type.
100578**
100579** This routine does a case-independent search of zType for the
100580** substrings in the following table. If one of the substrings is
100581** found, the corresponding affinity is returned. If zType contains
100582** more than one of the substrings, entries toward the top of
100583** the table take priority. For example, if zType is 'BLOBINT',
100584** SQLITE_AFF_INTEGER is returned.
100585**
100586** Substring     | Affinity
100587** --------------------------------
100588** 'INT'         | SQLITE_AFF_INTEGER
100589** 'CHAR'        | SQLITE_AFF_TEXT
100590** 'CLOB'        | SQLITE_AFF_TEXT
100591** 'TEXT'        | SQLITE_AFF_TEXT
100592** 'BLOB'        | SQLITE_AFF_BLOB
100593** 'REAL'        | SQLITE_AFF_REAL
100594** 'FLOA'        | SQLITE_AFF_REAL
100595** 'DOUB'        | SQLITE_AFF_REAL
100596**
100597** If none of the substrings in the above table are found,
100598** SQLITE_AFF_NUMERIC is returned.
100599*/
100600SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
100601  u32 h = 0;
100602  char aff = SQLITE_AFF_NUMERIC;
100603  const char *zChar = 0;
100604
100605  assert( zIn!=0 );
100606  while( zIn[0] ){
100607    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
100608    zIn++;
100609    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
100610      aff = SQLITE_AFF_TEXT;
100611      zChar = zIn;
100612    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
100613      aff = SQLITE_AFF_TEXT;
100614    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
100615      aff = SQLITE_AFF_TEXT;
100616    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
100617        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
100618      aff = SQLITE_AFF_BLOB;
100619      if( zIn[0]=='(' ) zChar = zIn;
100620#ifndef SQLITE_OMIT_FLOATING_POINT
100621    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
100622        && aff==SQLITE_AFF_NUMERIC ){
100623      aff = SQLITE_AFF_REAL;
100624    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
100625        && aff==SQLITE_AFF_NUMERIC ){
100626      aff = SQLITE_AFF_REAL;
100627    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
100628        && aff==SQLITE_AFF_NUMERIC ){
100629      aff = SQLITE_AFF_REAL;
100630#endif
100631    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
100632      aff = SQLITE_AFF_INTEGER;
100633      break;
100634    }
100635  }
100636
100637  /* If pszEst is not NULL, store an estimate of the field size.  The
100638  ** estimate is scaled so that the size of an integer is 1.  */
100639  if( pszEst ){
100640    *pszEst = 1;   /* default size is approx 4 bytes */
100641    if( aff<SQLITE_AFF_NUMERIC ){
100642      if( zChar ){
100643        while( zChar[0] ){
100644          if( sqlite3Isdigit(zChar[0]) ){
100645            int v = 0;
100646            sqlite3GetInt32(zChar, &v);
100647            v = v/4 + 1;
100648            if( v>255 ) v = 255;
100649            *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
100650            break;
100651          }
100652          zChar++;
100653        }
100654      }else{
100655        *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
100656      }
100657    }
100658  }
100659  return aff;
100660}
100661
100662/*
100663** The expression is the default value for the most recently added column
100664** of the table currently under construction.
100665**
100666** Default value expressions must be constant.  Raise an exception if this
100667** is not the case.
100668**
100669** This routine is called by the parser while in the middle of
100670** parsing a CREATE TABLE statement.
100671*/
100672SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
100673  Table *p;
100674  Column *pCol;
100675  sqlite3 *db = pParse->db;
100676  p = pParse->pNewTable;
100677  if( p!=0 ){
100678    pCol = &(p->aCol[p->nCol-1]);
100679    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
100680      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
100681          pCol->zName);
100682    }else{
100683      /* A copy of pExpr is used instead of the original, as pExpr contains
100684      ** tokens that point to volatile memory. The 'span' of the expression
100685      ** is required by pragma table_info.
100686      */
100687      Expr x;
100688      sqlite3ExprDelete(db, pCol->pDflt);
100689      memset(&x, 0, sizeof(x));
100690      x.op = TK_SPAN;
100691      x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
100692                                    (int)(pSpan->zEnd - pSpan->zStart));
100693      x.pLeft = pSpan->pExpr;
100694      x.flags = EP_Skip;
100695      pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
100696      sqlite3DbFree(db, x.u.zToken);
100697    }
100698  }
100699  sqlite3ExprDelete(db, pSpan->pExpr);
100700}
100701
100702/*
100703** Backwards Compatibility Hack:
100704**
100705** Historical versions of SQLite accepted strings as column names in
100706** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
100707**
100708**     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
100709**     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
100710**
100711** This is goofy.  But to preserve backwards compatibility we continue to
100712** accept it.  This routine does the necessary conversion.  It converts
100713** the expression given in its argument from a TK_STRING into a TK_ID
100714** if the expression is just a TK_STRING with an optional COLLATE clause.
100715** If the epxression is anything other than TK_STRING, the expression is
100716** unchanged.
100717*/
100718static void sqlite3StringToId(Expr *p){
100719  if( p->op==TK_STRING ){
100720    p->op = TK_ID;
100721  }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
100722    p->pLeft->op = TK_ID;
100723  }
100724}
100725
100726/*
100727** Designate the PRIMARY KEY for the table.  pList is a list of names
100728** of columns that form the primary key.  If pList is NULL, then the
100729** most recently added column of the table is the primary key.
100730**
100731** A table can have at most one primary key.  If the table already has
100732** a primary key (and this is the second primary key) then create an
100733** error.
100734**
100735** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
100736** then we will try to use that column as the rowid.  Set the Table.iPKey
100737** field of the table under construction to be the index of the
100738** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
100739** no INTEGER PRIMARY KEY.
100740**
100741** If the key is not an INTEGER PRIMARY KEY, then create a unique
100742** index for the key.  No index is created for INTEGER PRIMARY KEYs.
100743*/
100744SQLITE_PRIVATE void sqlite3AddPrimaryKey(
100745  Parse *pParse,    /* Parsing context */
100746  ExprList *pList,  /* List of field names to be indexed */
100747  int onError,      /* What to do with a uniqueness conflict */
100748  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
100749  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
100750){
100751  Table *pTab = pParse->pNewTable;
100752  Column *pCol = 0;
100753  int iCol = -1, i;
100754  int nTerm;
100755  if( pTab==0 ) goto primary_key_exit;
100756  if( pTab->tabFlags & TF_HasPrimaryKey ){
100757    sqlite3ErrorMsg(pParse,
100758      "table \"%s\" has more than one primary key", pTab->zName);
100759    goto primary_key_exit;
100760  }
100761  pTab->tabFlags |= TF_HasPrimaryKey;
100762  if( pList==0 ){
100763    iCol = pTab->nCol - 1;
100764    pCol = &pTab->aCol[iCol];
100765    pCol->colFlags |= COLFLAG_PRIMKEY;
100766    nTerm = 1;
100767  }else{
100768    nTerm = pList->nExpr;
100769    for(i=0; i<nTerm; i++){
100770      Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
100771      assert( pCExpr!=0 );
100772      sqlite3StringToId(pCExpr);
100773      if( pCExpr->op==TK_ID ){
100774        const char *zCName = pCExpr->u.zToken;
100775        for(iCol=0; iCol<pTab->nCol; iCol++){
100776          if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
100777            pCol = &pTab->aCol[iCol];
100778            pCol->colFlags |= COLFLAG_PRIMKEY;
100779            break;
100780          }
100781        }
100782      }
100783    }
100784  }
100785  if( nTerm==1
100786   && pCol
100787   && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
100788   && sortOrder!=SQLITE_SO_DESC
100789  ){
100790    pTab->iPKey = iCol;
100791    pTab->keyConf = (u8)onError;
100792    assert( autoInc==0 || autoInc==1 );
100793    pTab->tabFlags |= autoInc*TF_Autoincrement;
100794    if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
100795  }else if( autoInc ){
100796#ifndef SQLITE_OMIT_AUTOINCREMENT
100797    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
100798       "INTEGER PRIMARY KEY");
100799#endif
100800  }else{
100801    sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
100802                           0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
100803    pList = 0;
100804  }
100805
100806primary_key_exit:
100807  sqlite3ExprListDelete(pParse->db, pList);
100808  return;
100809}
100810
100811/*
100812** Add a new CHECK constraint to the table currently under construction.
100813*/
100814SQLITE_PRIVATE void sqlite3AddCheckConstraint(
100815  Parse *pParse,    /* Parsing context */
100816  Expr *pCheckExpr  /* The check expression */
100817){
100818#ifndef SQLITE_OMIT_CHECK
100819  Table *pTab = pParse->pNewTable;
100820  sqlite3 *db = pParse->db;
100821  if( pTab && !IN_DECLARE_VTAB
100822   && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
100823  ){
100824    pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
100825    if( pParse->constraintName.n ){
100826      sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
100827    }
100828  }else
100829#endif
100830  {
100831    sqlite3ExprDelete(pParse->db, pCheckExpr);
100832  }
100833}
100834
100835/*
100836** Set the collation function of the most recently parsed table column
100837** to the CollSeq given.
100838*/
100839SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
100840  Table *p;
100841  int i;
100842  char *zColl;              /* Dequoted name of collation sequence */
100843  sqlite3 *db;
100844
100845  if( (p = pParse->pNewTable)==0 ) return;
100846  i = p->nCol-1;
100847  db = pParse->db;
100848  zColl = sqlite3NameFromToken(db, pToken);
100849  if( !zColl ) return;
100850
100851  if( sqlite3LocateCollSeq(pParse, zColl) ){
100852    Index *pIdx;
100853    sqlite3DbFree(db, p->aCol[i].zColl);
100854    p->aCol[i].zColl = zColl;
100855
100856    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
100857    ** then an index may have been created on this column before the
100858    ** collation type was added. Correct this if it is the case.
100859    */
100860    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
100861      assert( pIdx->nKeyCol==1 );
100862      if( pIdx->aiColumn[0]==i ){
100863        pIdx->azColl[0] = p->aCol[i].zColl;
100864      }
100865    }
100866  }else{
100867    sqlite3DbFree(db, zColl);
100868  }
100869}
100870
100871/*
100872** This function returns the collation sequence for database native text
100873** encoding identified by the string zName, length nName.
100874**
100875** If the requested collation sequence is not available, or not available
100876** in the database native encoding, the collation factory is invoked to
100877** request it. If the collation factory does not supply such a sequence,
100878** and the sequence is available in another text encoding, then that is
100879** returned instead.
100880**
100881** If no versions of the requested collations sequence are available, or
100882** another error occurs, NULL is returned and an error message written into
100883** pParse.
100884**
100885** This routine is a wrapper around sqlite3FindCollSeq().  This routine
100886** invokes the collation factory if the named collation cannot be found
100887** and generates an error message.
100888**
100889** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
100890*/
100891SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
100892  sqlite3 *db = pParse->db;
100893  u8 enc = ENC(db);
100894  u8 initbusy = db->init.busy;
100895  CollSeq *pColl;
100896
100897  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
100898  if( !initbusy && (!pColl || !pColl->xCmp) ){
100899    pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
100900  }
100901
100902  return pColl;
100903}
100904
100905
100906/*
100907** Generate code that will increment the schema cookie.
100908**
100909** The schema cookie is used to determine when the schema for the
100910** database changes.  After each schema change, the cookie value
100911** changes.  When a process first reads the schema it records the
100912** cookie.  Thereafter, whenever it goes to access the database,
100913** it checks the cookie to make sure the schema has not changed
100914** since it was last read.
100915**
100916** This plan is not completely bullet-proof.  It is possible for
100917** the schema to change multiple times and for the cookie to be
100918** set back to prior value.  But schema changes are infrequent
100919** and the probability of hitting the same cookie value is only
100920** 1 chance in 2^32.  So we're safe enough.
100921**
100922** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
100923** the schema-version whenever the schema changes.
100924*/
100925SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
100926  sqlite3 *db = pParse->db;
100927  Vdbe *v = pParse->pVdbe;
100928  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100929  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
100930                    db->aDb[iDb].pSchema->schema_cookie+1);
100931}
100932
100933/*
100934** Measure the number of characters needed to output the given
100935** identifier.  The number returned includes any quotes used
100936** but does not include the null terminator.
100937**
100938** The estimate is conservative.  It might be larger that what is
100939** really needed.
100940*/
100941static int identLength(const char *z){
100942  int n;
100943  for(n=0; *z; n++, z++){
100944    if( *z=='"' ){ n++; }
100945  }
100946  return n + 2;
100947}
100948
100949/*
100950** The first parameter is a pointer to an output buffer. The second
100951** parameter is a pointer to an integer that contains the offset at
100952** which to write into the output buffer. This function copies the
100953** nul-terminated string pointed to by the third parameter, zSignedIdent,
100954** to the specified offset in the buffer and updates *pIdx to refer
100955** to the first byte after the last byte written before returning.
100956**
100957** If the string zSignedIdent consists entirely of alpha-numeric
100958** characters, does not begin with a digit and is not an SQL keyword,
100959** then it is copied to the output buffer exactly as it is. Otherwise,
100960** it is quoted using double-quotes.
100961*/
100962static void identPut(char *z, int *pIdx, char *zSignedIdent){
100963  unsigned char *zIdent = (unsigned char*)zSignedIdent;
100964  int i, j, needQuote;
100965  i = *pIdx;
100966
100967  for(j=0; zIdent[j]; j++){
100968    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
100969  }
100970  needQuote = sqlite3Isdigit(zIdent[0])
100971            || sqlite3KeywordCode(zIdent, j)!=TK_ID
100972            || zIdent[j]!=0
100973            || j==0;
100974
100975  if( needQuote ) z[i++] = '"';
100976  for(j=0; zIdent[j]; j++){
100977    z[i++] = zIdent[j];
100978    if( zIdent[j]=='"' ) z[i++] = '"';
100979  }
100980  if( needQuote ) z[i++] = '"';
100981  z[i] = 0;
100982  *pIdx = i;
100983}
100984
100985/*
100986** Generate a CREATE TABLE statement appropriate for the given
100987** table.  Memory to hold the text of the statement is obtained
100988** from sqliteMalloc() and must be freed by the calling function.
100989*/
100990static char *createTableStmt(sqlite3 *db, Table *p){
100991  int i, k, n;
100992  char *zStmt;
100993  char *zSep, *zSep2, *zEnd;
100994  Column *pCol;
100995  n = 0;
100996  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
100997    n += identLength(pCol->zName) + 5;
100998  }
100999  n += identLength(p->zName);
101000  if( n<50 ){
101001    zSep = "";
101002    zSep2 = ",";
101003    zEnd = ")";
101004  }else{
101005    zSep = "\n  ";
101006    zSep2 = ",\n  ";
101007    zEnd = "\n)";
101008  }
101009  n += 35 + 6*p->nCol;
101010  zStmt = sqlite3DbMallocRaw(0, n);
101011  if( zStmt==0 ){
101012    sqlite3OomFault(db);
101013    return 0;
101014  }
101015  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
101016  k = sqlite3Strlen30(zStmt);
101017  identPut(zStmt, &k, p->zName);
101018  zStmt[k++] = '(';
101019  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
101020    static const char * const azType[] = {
101021        /* SQLITE_AFF_BLOB    */ "",
101022        /* SQLITE_AFF_TEXT    */ " TEXT",
101023        /* SQLITE_AFF_NUMERIC */ " NUM",
101024        /* SQLITE_AFF_INTEGER */ " INT",
101025        /* SQLITE_AFF_REAL    */ " REAL"
101026    };
101027    int len;
101028    const char *zType;
101029
101030    sqlite3_snprintf(n-k, &zStmt[k], zSep);
101031    k += sqlite3Strlen30(&zStmt[k]);
101032    zSep = zSep2;
101033    identPut(zStmt, &k, pCol->zName);
101034    assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
101035    assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
101036    testcase( pCol->affinity==SQLITE_AFF_BLOB );
101037    testcase( pCol->affinity==SQLITE_AFF_TEXT );
101038    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
101039    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
101040    testcase( pCol->affinity==SQLITE_AFF_REAL );
101041
101042    zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
101043    len = sqlite3Strlen30(zType);
101044    assert( pCol->affinity==SQLITE_AFF_BLOB
101045            || pCol->affinity==sqlite3AffinityType(zType, 0) );
101046    memcpy(&zStmt[k], zType, len);
101047    k += len;
101048    assert( k<=n );
101049  }
101050  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
101051  return zStmt;
101052}
101053
101054/*
101055** Resize an Index object to hold N columns total.  Return SQLITE_OK
101056** on success and SQLITE_NOMEM on an OOM error.
101057*/
101058static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
101059  char *zExtra;
101060  int nByte;
101061  if( pIdx->nColumn>=N ) return SQLITE_OK;
101062  assert( pIdx->isResized==0 );
101063  nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
101064  zExtra = sqlite3DbMallocZero(db, nByte);
101065  if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
101066  memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
101067  pIdx->azColl = (const char**)zExtra;
101068  zExtra += sizeof(char*)*N;
101069  memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
101070  pIdx->aiColumn = (i16*)zExtra;
101071  zExtra += sizeof(i16)*N;
101072  memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
101073  pIdx->aSortOrder = (u8*)zExtra;
101074  pIdx->nColumn = N;
101075  pIdx->isResized = 1;
101076  return SQLITE_OK;
101077}
101078
101079/*
101080** Estimate the total row width for a table.
101081*/
101082static void estimateTableWidth(Table *pTab){
101083  unsigned wTable = 0;
101084  const Column *pTabCol;
101085  int i;
101086  for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
101087    wTable += pTabCol->szEst;
101088  }
101089  if( pTab->iPKey<0 ) wTable++;
101090  pTab->szTabRow = sqlite3LogEst(wTable*4);
101091}
101092
101093/*
101094** Estimate the average size of a row for an index.
101095*/
101096static void estimateIndexWidth(Index *pIdx){
101097  unsigned wIndex = 0;
101098  int i;
101099  const Column *aCol = pIdx->pTable->aCol;
101100  for(i=0; i<pIdx->nColumn; i++){
101101    i16 x = pIdx->aiColumn[i];
101102    assert( x<pIdx->pTable->nCol );
101103    wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
101104  }
101105  pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
101106}
101107
101108/* Return true if value x is found any of the first nCol entries of aiCol[]
101109*/
101110static int hasColumn(const i16 *aiCol, int nCol, int x){
101111  while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
101112  return 0;
101113}
101114
101115/*
101116** This routine runs at the end of parsing a CREATE TABLE statement that
101117** has a WITHOUT ROWID clause.  The job of this routine is to convert both
101118** internal schema data structures and the generated VDBE code so that they
101119** are appropriate for a WITHOUT ROWID table instead of a rowid table.
101120** Changes include:
101121**
101122**     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
101123**     (2)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
101124**          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
101125**          data storage is a covering index btree.
101126**     (3)  Bypass the creation of the sqlite_master table entry
101127**          for the PRIMARY KEY as the primary key index is now
101128**          identified by the sqlite_master table entry of the table itself.
101129**     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
101130**          schema to the rootpage from the main table.
101131**     (5)  Add all table columns to the PRIMARY KEY Index object
101132**          so that the PRIMARY KEY is a covering index.  The surplus
101133**          columns are part of KeyInfo.nXField and are not used for
101134**          sorting or lookup or uniqueness checks.
101135**     (6)  Replace the rowid tail on all automatically generated UNIQUE
101136**          indices with the PRIMARY KEY columns.
101137**
101138** For virtual tables, only (1) is performed.
101139*/
101140static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
101141  Index *pIdx;
101142  Index *pPk;
101143  int nPk;
101144  int i, j;
101145  sqlite3 *db = pParse->db;
101146  Vdbe *v = pParse->pVdbe;
101147
101148  /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
101149  */
101150  if( !db->init.imposterTable ){
101151    for(i=0; i<pTab->nCol; i++){
101152      if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
101153        pTab->aCol[i].notNull = OE_Abort;
101154      }
101155    }
101156  }
101157
101158  /* The remaining transformations only apply to b-tree tables, not to
101159  ** virtual tables */
101160  if( IN_DECLARE_VTAB ) return;
101161
101162  /* Convert the OP_CreateTable opcode that would normally create the
101163  ** root-page for the table into an OP_CreateIndex opcode.  The index
101164  ** created will become the PRIMARY KEY index.
101165  */
101166  if( pParse->addrCrTab ){
101167    assert( v );
101168    sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
101169  }
101170
101171  /* Locate the PRIMARY KEY index.  Or, if this table was originally
101172  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
101173  */
101174  if( pTab->iPKey>=0 ){
101175    ExprList *pList;
101176    Token ipkToken;
101177    sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
101178    pList = sqlite3ExprListAppend(pParse, 0,
101179                  sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
101180    if( pList==0 ) return;
101181    pList->a[0].sortOrder = pParse->iPkSortOrder;
101182    assert( pParse->pNewTable==pTab );
101183    sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
101184                       SQLITE_IDXTYPE_PRIMARYKEY);
101185    if( db->mallocFailed ) return;
101186    pPk = sqlite3PrimaryKeyIndex(pTab);
101187    pTab->iPKey = -1;
101188  }else{
101189    pPk = sqlite3PrimaryKeyIndex(pTab);
101190
101191    /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
101192    ** table entry. This is only required if currently generating VDBE
101193    ** code for a CREATE TABLE (not when parsing one as part of reading
101194    ** a database schema).  */
101195    if( v ){
101196      assert( db->init.busy==0 );
101197      sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
101198    }
101199
101200    /*
101201    ** Remove all redundant columns from the PRIMARY KEY.  For example, change
101202    ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
101203    ** code assumes the PRIMARY KEY contains no repeated columns.
101204    */
101205    for(i=j=1; i<pPk->nKeyCol; i++){
101206      if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
101207        pPk->nColumn--;
101208      }else{
101209        pPk->aiColumn[j++] = pPk->aiColumn[i];
101210      }
101211    }
101212    pPk->nKeyCol = j;
101213  }
101214  assert( pPk!=0 );
101215  pPk->isCovering = 1;
101216  if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
101217  nPk = pPk->nKeyCol;
101218
101219  /* The root page of the PRIMARY KEY is the table root page */
101220  pPk->tnum = pTab->tnum;
101221
101222  /* Update the in-memory representation of all UNIQUE indices by converting
101223  ** the final rowid column into one or more columns of the PRIMARY KEY.
101224  */
101225  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
101226    int n;
101227    if( IsPrimaryKeyIndex(pIdx) ) continue;
101228    for(i=n=0; i<nPk; i++){
101229      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
101230    }
101231    if( n==0 ){
101232      /* This index is a superset of the primary key */
101233      pIdx->nColumn = pIdx->nKeyCol;
101234      continue;
101235    }
101236    if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
101237    for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
101238      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
101239        pIdx->aiColumn[j] = pPk->aiColumn[i];
101240        pIdx->azColl[j] = pPk->azColl[i];
101241        j++;
101242      }
101243    }
101244    assert( pIdx->nColumn>=pIdx->nKeyCol+n );
101245    assert( pIdx->nColumn>=j );
101246  }
101247
101248  /* Add all table columns to the PRIMARY KEY index
101249  */
101250  if( nPk<pTab->nCol ){
101251    if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
101252    for(i=0, j=nPk; i<pTab->nCol; i++){
101253      if( !hasColumn(pPk->aiColumn, j, i) ){
101254        assert( j<pPk->nColumn );
101255        pPk->aiColumn[j] = i;
101256        pPk->azColl[j] = sqlite3StrBINARY;
101257        j++;
101258      }
101259    }
101260    assert( pPk->nColumn==j );
101261    assert( pTab->nCol==j );
101262  }else{
101263    pPk->nColumn = pTab->nCol;
101264  }
101265}
101266
101267/*
101268** This routine is called to report the final ")" that terminates
101269** a CREATE TABLE statement.
101270**
101271** The table structure that other action routines have been building
101272** is added to the internal hash tables, assuming no errors have
101273** occurred.
101274**
101275** An entry for the table is made in the master table on disk, unless
101276** this is a temporary table or db->init.busy==1.  When db->init.busy==1
101277** it means we are reading the sqlite_master table because we just
101278** connected to the database or because the sqlite_master table has
101279** recently changed, so the entry for this table already exists in
101280** the sqlite_master table.  We do not want to create it again.
101281**
101282** If the pSelect argument is not NULL, it means that this routine
101283** was called to create a table generated from a
101284** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
101285** the new table will match the result set of the SELECT.
101286*/
101287SQLITE_PRIVATE void sqlite3EndTable(
101288  Parse *pParse,          /* Parse context */
101289  Token *pCons,           /* The ',' token after the last column defn. */
101290  Token *pEnd,            /* The ')' before options in the CREATE TABLE */
101291  u8 tabOpts,             /* Extra table options. Usually 0. */
101292  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
101293){
101294  Table *p;                 /* The new table */
101295  sqlite3 *db = pParse->db; /* The database connection */
101296  int iDb;                  /* Database in which the table lives */
101297  Index *pIdx;              /* An implied index of the table */
101298
101299  if( pEnd==0 && pSelect==0 ){
101300    return;
101301  }
101302  assert( !db->mallocFailed );
101303  p = pParse->pNewTable;
101304  if( p==0 ) return;
101305
101306  assert( !db->init.busy || !pSelect );
101307
101308  /* If the db->init.busy is 1 it means we are reading the SQL off the
101309  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
101310  ** So do not write to the disk again.  Extract the root page number
101311  ** for the table from the db->init.newTnum field.  (The page number
101312  ** should have been put there by the sqliteOpenCb routine.)
101313  **
101314  ** If the root page number is 1, that means this is the sqlite_master
101315  ** table itself.  So mark it read-only.
101316  */
101317  if( db->init.busy ){
101318    p->tnum = db->init.newTnum;
101319    if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
101320  }
101321
101322  /* Special processing for WITHOUT ROWID Tables */
101323  if( tabOpts & TF_WithoutRowid ){
101324    if( (p->tabFlags & TF_Autoincrement) ){
101325      sqlite3ErrorMsg(pParse,
101326          "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
101327      return;
101328    }
101329    if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
101330      sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
101331    }else{
101332      p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
101333      convertToWithoutRowidTable(pParse, p);
101334    }
101335  }
101336
101337  iDb = sqlite3SchemaToIndex(db, p->pSchema);
101338
101339#ifndef SQLITE_OMIT_CHECK
101340  /* Resolve names in all CHECK constraint expressions.
101341  */
101342  if( p->pCheck ){
101343    sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
101344  }
101345#endif /* !defined(SQLITE_OMIT_CHECK) */
101346
101347  /* Estimate the average row size for the table and for all implied indices */
101348  estimateTableWidth(p);
101349  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
101350    estimateIndexWidth(pIdx);
101351  }
101352
101353  /* If not initializing, then create a record for the new table
101354  ** in the SQLITE_MASTER table of the database.
101355  **
101356  ** If this is a TEMPORARY table, write the entry into the auxiliary
101357  ** file instead of into the main database file.
101358  */
101359  if( !db->init.busy ){
101360    int n;
101361    Vdbe *v;
101362    char *zType;    /* "view" or "table" */
101363    char *zType2;   /* "VIEW" or "TABLE" */
101364    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
101365
101366    v = sqlite3GetVdbe(pParse);
101367    if( NEVER(v==0) ) return;
101368
101369    sqlite3VdbeAddOp1(v, OP_Close, 0);
101370
101371    /*
101372    ** Initialize zType for the new view or table.
101373    */
101374    if( p->pSelect==0 ){
101375      /* A regular table */
101376      zType = "table";
101377      zType2 = "TABLE";
101378#ifndef SQLITE_OMIT_VIEW
101379    }else{
101380      /* A view */
101381      zType = "view";
101382      zType2 = "VIEW";
101383#endif
101384    }
101385
101386    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
101387    ** statement to populate the new table. The root-page number for the
101388    ** new table is in register pParse->regRoot.
101389    **
101390    ** Once the SELECT has been coded by sqlite3Select(), it is in a
101391    ** suitable state to query for the column names and types to be used
101392    ** by the new table.
101393    **
101394    ** A shared-cache write-lock is not required to write to the new table,
101395    ** as a schema-lock must have already been obtained to create it. Since
101396    ** a schema-lock excludes all other database users, the write-lock would
101397    ** be redundant.
101398    */
101399    if( pSelect ){
101400      SelectDest dest;    /* Where the SELECT should store results */
101401      int regYield;       /* Register holding co-routine entry-point */
101402      int addrTop;        /* Top of the co-routine */
101403      int regRec;         /* A record to be insert into the new table */
101404      int regRowid;       /* Rowid of the next row to insert */
101405      int addrInsLoop;    /* Top of the loop for inserting rows */
101406      Table *pSelTab;     /* A table that describes the SELECT results */
101407
101408      regYield = ++pParse->nMem;
101409      regRec = ++pParse->nMem;
101410      regRowid = ++pParse->nMem;
101411      assert(pParse->nTab==1);
101412      sqlite3MayAbort(pParse);
101413      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
101414      sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
101415      pParse->nTab = 2;
101416      addrTop = sqlite3VdbeCurrentAddr(v) + 1;
101417      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
101418      sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
101419      sqlite3Select(pParse, pSelect, &dest);
101420      sqlite3VdbeEndCoroutine(v, regYield);
101421      sqlite3VdbeJumpHere(v, addrTop - 1);
101422      if( pParse->nErr ) return;
101423      pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
101424      if( pSelTab==0 ) return;
101425      assert( p->aCol==0 );
101426      p->nCol = pSelTab->nCol;
101427      p->aCol = pSelTab->aCol;
101428      pSelTab->nCol = 0;
101429      pSelTab->aCol = 0;
101430      sqlite3DeleteTable(db, pSelTab);
101431      addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
101432      VdbeCoverage(v);
101433      sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
101434      sqlite3TableAffinity(v, p, 0);
101435      sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
101436      sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
101437      sqlite3VdbeGoto(v, addrInsLoop);
101438      sqlite3VdbeJumpHere(v, addrInsLoop);
101439      sqlite3VdbeAddOp1(v, OP_Close, 1);
101440    }
101441
101442    /* Compute the complete text of the CREATE statement */
101443    if( pSelect ){
101444      zStmt = createTableStmt(db, p);
101445    }else{
101446      Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
101447      n = (int)(pEnd2->z - pParse->sNameToken.z);
101448      if( pEnd2->z[0]!=';' ) n += pEnd2->n;
101449      zStmt = sqlite3MPrintf(db,
101450          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
101451      );
101452    }
101453
101454    /* A slot for the record has already been allocated in the
101455    ** SQLITE_MASTER table.  We just need to update that slot with all
101456    ** the information we've collected.
101457    */
101458    sqlite3NestedParse(pParse,
101459      "UPDATE %Q.%s "
101460         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
101461       "WHERE rowid=#%d",
101462      db->aDb[iDb].zDbSName, MASTER_NAME,
101463      zType,
101464      p->zName,
101465      p->zName,
101466      pParse->regRoot,
101467      zStmt,
101468      pParse->regRowid
101469    );
101470    sqlite3DbFree(db, zStmt);
101471    sqlite3ChangeCookie(pParse, iDb);
101472
101473#ifndef SQLITE_OMIT_AUTOINCREMENT
101474    /* Check to see if we need to create an sqlite_sequence table for
101475    ** keeping track of autoincrement keys.
101476    */
101477    if( (p->tabFlags & TF_Autoincrement)!=0 ){
101478      Db *pDb = &db->aDb[iDb];
101479      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101480      if( pDb->pSchema->pSeqTab==0 ){
101481        sqlite3NestedParse(pParse,
101482          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
101483          pDb->zDbSName
101484        );
101485      }
101486    }
101487#endif
101488
101489    /* Reparse everything to update our internal data structures */
101490    sqlite3VdbeAddParseSchemaOp(v, iDb,
101491           sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
101492  }
101493
101494
101495  /* Add the table to the in-memory representation of the database.
101496  */
101497  if( db->init.busy ){
101498    Table *pOld;
101499    Schema *pSchema = p->pSchema;
101500    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101501    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
101502    if( pOld ){
101503      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
101504      sqlite3OomFault(db);
101505      return;
101506    }
101507    pParse->pNewTable = 0;
101508    db->flags |= SQLITE_InternChanges;
101509
101510#ifndef SQLITE_OMIT_ALTERTABLE
101511    if( !p->pSelect ){
101512      const char *zName = (const char *)pParse->sNameToken.z;
101513      int nName;
101514      assert( !pSelect && pCons && pEnd );
101515      if( pCons->z==0 ){
101516        pCons = pEnd;
101517      }
101518      nName = (int)((const char *)pCons->z - zName);
101519      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
101520    }
101521#endif
101522  }
101523}
101524
101525#ifndef SQLITE_OMIT_VIEW
101526/*
101527** The parser calls this routine in order to create a new VIEW
101528*/
101529SQLITE_PRIVATE void sqlite3CreateView(
101530  Parse *pParse,     /* The parsing context */
101531  Token *pBegin,     /* The CREATE token that begins the statement */
101532  Token *pName1,     /* The token that holds the name of the view */
101533  Token *pName2,     /* The token that holds the name of the view */
101534  ExprList *pCNames, /* Optional list of view column names */
101535  Select *pSelect,   /* A SELECT statement that will become the new view */
101536  int isTemp,        /* TRUE for a TEMPORARY view */
101537  int noErr          /* Suppress error messages if VIEW already exists */
101538){
101539  Table *p;
101540  int n;
101541  const char *z;
101542  Token sEnd;
101543  DbFixer sFix;
101544  Token *pName = 0;
101545  int iDb;
101546  sqlite3 *db = pParse->db;
101547
101548  if( pParse->nVar>0 ){
101549    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
101550    goto create_view_fail;
101551  }
101552  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
101553  p = pParse->pNewTable;
101554  if( p==0 || pParse->nErr ) goto create_view_fail;
101555  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
101556  iDb = sqlite3SchemaToIndex(db, p->pSchema);
101557  sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
101558  if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
101559
101560  /* Make a copy of the entire SELECT statement that defines the view.
101561  ** This will force all the Expr.token.z values to be dynamically
101562  ** allocated rather than point to the input string - which means that
101563  ** they will persist after the current sqlite3_exec() call returns.
101564  */
101565  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
101566  p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
101567  if( db->mallocFailed ) goto create_view_fail;
101568
101569  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
101570  ** the end.
101571  */
101572  sEnd = pParse->sLastToken;
101573  assert( sEnd.z[0]!=0 );
101574  if( sEnd.z[0]!=';' ){
101575    sEnd.z += sEnd.n;
101576  }
101577  sEnd.n = 0;
101578  n = (int)(sEnd.z - pBegin->z);
101579  assert( n>0 );
101580  z = pBegin->z;
101581  while( sqlite3Isspace(z[n-1]) ){ n--; }
101582  sEnd.z = &z[n-1];
101583  sEnd.n = 1;
101584
101585  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
101586  sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
101587
101588create_view_fail:
101589  sqlite3SelectDelete(db, pSelect);
101590  sqlite3ExprListDelete(db, pCNames);
101591  return;
101592}
101593#endif /* SQLITE_OMIT_VIEW */
101594
101595#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
101596/*
101597** The Table structure pTable is really a VIEW.  Fill in the names of
101598** the columns of the view in the pTable structure.  Return the number
101599** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
101600*/
101601SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
101602  Table *pSelTab;   /* A fake table from which we get the result set */
101603  Select *pSel;     /* Copy of the SELECT that implements the view */
101604  int nErr = 0;     /* Number of errors encountered */
101605  int n;            /* Temporarily holds the number of cursors assigned */
101606  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
101607#ifndef SQLITE_OMIT_AUTHORIZATION
101608  sqlite3_xauth xAuth;       /* Saved xAuth pointer */
101609#endif
101610
101611  assert( pTable );
101612
101613#ifndef SQLITE_OMIT_VIRTUALTABLE
101614  if( sqlite3VtabCallConnect(pParse, pTable) ){
101615    return SQLITE_ERROR;
101616  }
101617  if( IsVirtual(pTable) ) return 0;
101618#endif
101619
101620#ifndef SQLITE_OMIT_VIEW
101621  /* A positive nCol means the columns names for this view are
101622  ** already known.
101623  */
101624  if( pTable->nCol>0 ) return 0;
101625
101626  /* A negative nCol is a special marker meaning that we are currently
101627  ** trying to compute the column names.  If we enter this routine with
101628  ** a negative nCol, it means two or more views form a loop, like this:
101629  **
101630  **     CREATE VIEW one AS SELECT * FROM two;
101631  **     CREATE VIEW two AS SELECT * FROM one;
101632  **
101633  ** Actually, the error above is now caught prior to reaching this point.
101634  ** But the following test is still important as it does come up
101635  ** in the following:
101636  **
101637  **     CREATE TABLE main.ex1(a);
101638  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
101639  **     SELECT * FROM temp.ex1;
101640  */
101641  if( pTable->nCol<0 ){
101642    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
101643    return 1;
101644  }
101645  assert( pTable->nCol>=0 );
101646
101647  /* If we get this far, it means we need to compute the table names.
101648  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
101649  ** "*" elements in the results set of the view and will assign cursors
101650  ** to the elements of the FROM clause.  But we do not want these changes
101651  ** to be permanent.  So the computation is done on a copy of the SELECT
101652  ** statement that defines the view.
101653  */
101654  assert( pTable->pSelect );
101655  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
101656  if( pSel ){
101657    n = pParse->nTab;
101658    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
101659    pTable->nCol = -1;
101660    db->lookaside.bDisable++;
101661#ifndef SQLITE_OMIT_AUTHORIZATION
101662    xAuth = db->xAuth;
101663    db->xAuth = 0;
101664    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
101665    db->xAuth = xAuth;
101666#else
101667    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
101668#endif
101669    pParse->nTab = n;
101670    if( pTable->pCheck ){
101671      /* CREATE VIEW name(arglist) AS ...
101672      ** The names of the columns in the table are taken from
101673      ** arglist which is stored in pTable->pCheck.  The pCheck field
101674      ** normally holds CHECK constraints on an ordinary table, but for
101675      ** a VIEW it holds the list of column names.
101676      */
101677      sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
101678                                 &pTable->nCol, &pTable->aCol);
101679      if( db->mallocFailed==0
101680       && pParse->nErr==0
101681       && pTable->nCol==pSel->pEList->nExpr
101682      ){
101683        sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
101684      }
101685    }else if( pSelTab ){
101686      /* CREATE VIEW name AS...  without an argument list.  Construct
101687      ** the column names from the SELECT statement that defines the view.
101688      */
101689      assert( pTable->aCol==0 );
101690      pTable->nCol = pSelTab->nCol;
101691      pTable->aCol = pSelTab->aCol;
101692      pSelTab->nCol = 0;
101693      pSelTab->aCol = 0;
101694      assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
101695    }else{
101696      pTable->nCol = 0;
101697      nErr++;
101698    }
101699    sqlite3DeleteTable(db, pSelTab);
101700    sqlite3SelectDelete(db, pSel);
101701    db->lookaside.bDisable--;
101702  } else {
101703    nErr++;
101704  }
101705  pTable->pSchema->schemaFlags |= DB_UnresetViews;
101706#endif /* SQLITE_OMIT_VIEW */
101707  return nErr;
101708}
101709#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
101710
101711#ifndef SQLITE_OMIT_VIEW
101712/*
101713** Clear the column names from every VIEW in database idx.
101714*/
101715static void sqliteViewResetAll(sqlite3 *db, int idx){
101716  HashElem *i;
101717  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
101718  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
101719  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
101720    Table *pTab = sqliteHashData(i);
101721    if( pTab->pSelect ){
101722      sqlite3DeleteColumnNames(db, pTab);
101723      pTab->aCol = 0;
101724      pTab->nCol = 0;
101725    }
101726  }
101727  DbClearProperty(db, idx, DB_UnresetViews);
101728}
101729#else
101730# define sqliteViewResetAll(A,B)
101731#endif /* SQLITE_OMIT_VIEW */
101732
101733/*
101734** This function is called by the VDBE to adjust the internal schema
101735** used by SQLite when the btree layer moves a table root page. The
101736** root-page of a table or index in database iDb has changed from iFrom
101737** to iTo.
101738**
101739** Ticket #1728:  The symbol table might still contain information
101740** on tables and/or indices that are the process of being deleted.
101741** If you are unlucky, one of those deleted indices or tables might
101742** have the same rootpage number as the real table or index that is
101743** being moved.  So we cannot stop searching after the first match
101744** because the first match might be for one of the deleted indices
101745** or tables and not the table/index that is actually being moved.
101746** We must continue looping until all tables and indices with
101747** rootpage==iFrom have been converted to have a rootpage of iTo
101748** in order to be certain that we got the right one.
101749*/
101750#ifndef SQLITE_OMIT_AUTOVACUUM
101751SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
101752  HashElem *pElem;
101753  Hash *pHash;
101754  Db *pDb;
101755
101756  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101757  pDb = &db->aDb[iDb];
101758  pHash = &pDb->pSchema->tblHash;
101759  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
101760    Table *pTab = sqliteHashData(pElem);
101761    if( pTab->tnum==iFrom ){
101762      pTab->tnum = iTo;
101763    }
101764  }
101765  pHash = &pDb->pSchema->idxHash;
101766  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
101767    Index *pIdx = sqliteHashData(pElem);
101768    if( pIdx->tnum==iFrom ){
101769      pIdx->tnum = iTo;
101770    }
101771  }
101772}
101773#endif
101774
101775/*
101776** Write code to erase the table with root-page iTable from database iDb.
101777** Also write code to modify the sqlite_master table and internal schema
101778** if a root-page of another table is moved by the btree-layer whilst
101779** erasing iTable (this can happen with an auto-vacuum database).
101780*/
101781static void destroyRootPage(Parse *pParse, int iTable, int iDb){
101782  Vdbe *v = sqlite3GetVdbe(pParse);
101783  int r1 = sqlite3GetTempReg(pParse);
101784  assert( iTable>1 );
101785  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
101786  sqlite3MayAbort(pParse);
101787#ifndef SQLITE_OMIT_AUTOVACUUM
101788  /* OP_Destroy stores an in integer r1. If this integer
101789  ** is non-zero, then it is the root page number of a table moved to
101790  ** location iTable. The following code modifies the sqlite_master table to
101791  ** reflect this.
101792  **
101793  ** The "#NNN" in the SQL is a special constant that means whatever value
101794  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
101795  ** token for additional information.
101796  */
101797  sqlite3NestedParse(pParse,
101798     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
101799     pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
101800#endif
101801  sqlite3ReleaseTempReg(pParse, r1);
101802}
101803
101804/*
101805** Write VDBE code to erase table pTab and all associated indices on disk.
101806** Code to update the sqlite_master tables and internal schema definitions
101807** in case a root-page belonging to another table is moved by the btree layer
101808** is also added (this can happen with an auto-vacuum database).
101809*/
101810static void destroyTable(Parse *pParse, Table *pTab){
101811#ifdef SQLITE_OMIT_AUTOVACUUM
101812  Index *pIdx;
101813  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
101814  destroyRootPage(pParse, pTab->tnum, iDb);
101815  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
101816    destroyRootPage(pParse, pIdx->tnum, iDb);
101817  }
101818#else
101819  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
101820  ** is not defined), then it is important to call OP_Destroy on the
101821  ** table and index root-pages in order, starting with the numerically
101822  ** largest root-page number. This guarantees that none of the root-pages
101823  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
101824  ** following were coded:
101825  **
101826  ** OP_Destroy 4 0
101827  ** ...
101828  ** OP_Destroy 5 0
101829  **
101830  ** and root page 5 happened to be the largest root-page number in the
101831  ** database, then root page 5 would be moved to page 4 by the
101832  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
101833  ** a free-list page.
101834  */
101835  int iTab = pTab->tnum;
101836  int iDestroyed = 0;
101837
101838  while( 1 ){
101839    Index *pIdx;
101840    int iLargest = 0;
101841
101842    if( iDestroyed==0 || iTab<iDestroyed ){
101843      iLargest = iTab;
101844    }
101845    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
101846      int iIdx = pIdx->tnum;
101847      assert( pIdx->pSchema==pTab->pSchema );
101848      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
101849        iLargest = iIdx;
101850      }
101851    }
101852    if( iLargest==0 ){
101853      return;
101854    }else{
101855      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
101856      assert( iDb>=0 && iDb<pParse->db->nDb );
101857      destroyRootPage(pParse, iLargest, iDb);
101858      iDestroyed = iLargest;
101859    }
101860  }
101861#endif
101862}
101863
101864/*
101865** Remove entries from the sqlite_statN tables (for N in (1,2,3))
101866** after a DROP INDEX or DROP TABLE command.
101867*/
101868static void sqlite3ClearStatTables(
101869  Parse *pParse,         /* The parsing context */
101870  int iDb,               /* The database number */
101871  const char *zType,     /* "idx" or "tbl" */
101872  const char *zName      /* Name of index or table */
101873){
101874  int i;
101875  const char *zDbName = pParse->db->aDb[iDb].zDbSName;
101876  for(i=1; i<=4; i++){
101877    char zTab[24];
101878    sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
101879    if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
101880      sqlite3NestedParse(pParse,
101881        "DELETE FROM %Q.%s WHERE %s=%Q",
101882        zDbName, zTab, zType, zName
101883      );
101884    }
101885  }
101886}
101887
101888/*
101889** Generate code to drop a table.
101890*/
101891SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
101892  Vdbe *v;
101893  sqlite3 *db = pParse->db;
101894  Trigger *pTrigger;
101895  Db *pDb = &db->aDb[iDb];
101896
101897  v = sqlite3GetVdbe(pParse);
101898  assert( v!=0 );
101899  sqlite3BeginWriteOperation(pParse, 1, iDb);
101900
101901#ifndef SQLITE_OMIT_VIRTUALTABLE
101902  if( IsVirtual(pTab) ){
101903    sqlite3VdbeAddOp0(v, OP_VBegin);
101904  }
101905#endif
101906
101907  /* Drop all triggers associated with the table being dropped. Code
101908  ** is generated to remove entries from sqlite_master and/or
101909  ** sqlite_temp_master if required.
101910  */
101911  pTrigger = sqlite3TriggerList(pParse, pTab);
101912  while( pTrigger ){
101913    assert( pTrigger->pSchema==pTab->pSchema ||
101914        pTrigger->pSchema==db->aDb[1].pSchema );
101915    sqlite3DropTriggerPtr(pParse, pTrigger);
101916    pTrigger = pTrigger->pNext;
101917  }
101918
101919#ifndef SQLITE_OMIT_AUTOINCREMENT
101920  /* Remove any entries of the sqlite_sequence table associated with
101921  ** the table being dropped. This is done before the table is dropped
101922  ** at the btree level, in case the sqlite_sequence table needs to
101923  ** move as a result of the drop (can happen in auto-vacuum mode).
101924  */
101925  if( pTab->tabFlags & TF_Autoincrement ){
101926    sqlite3NestedParse(pParse,
101927      "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
101928      pDb->zDbSName, pTab->zName
101929    );
101930  }
101931#endif
101932
101933  /* Drop all SQLITE_MASTER table and index entries that refer to the
101934  ** table. The program name loops through the master table and deletes
101935  ** every row that refers to a table of the same name as the one being
101936  ** dropped. Triggers are handled separately because a trigger can be
101937  ** created in the temp database that refers to a table in another
101938  ** database.
101939  */
101940  sqlite3NestedParse(pParse,
101941      "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
101942      pDb->zDbSName, MASTER_NAME, pTab->zName);
101943  if( !isView && !IsVirtual(pTab) ){
101944    destroyTable(pParse, pTab);
101945  }
101946
101947  /* Remove the table entry from SQLite's internal schema and modify
101948  ** the schema cookie.
101949  */
101950  if( IsVirtual(pTab) ){
101951    sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
101952  }
101953  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
101954  sqlite3ChangeCookie(pParse, iDb);
101955  sqliteViewResetAll(db, iDb);
101956}
101957
101958/*
101959** This routine is called to do the work of a DROP TABLE statement.
101960** pName is the name of the table to be dropped.
101961*/
101962SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
101963  Table *pTab;
101964  Vdbe *v;
101965  sqlite3 *db = pParse->db;
101966  int iDb;
101967
101968  if( db->mallocFailed ){
101969    goto exit_drop_table;
101970  }
101971  assert( pParse->nErr==0 );
101972  assert( pName->nSrc==1 );
101973  if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
101974  if( noErr ) db->suppressErr++;
101975  assert( isView==0 || isView==LOCATE_VIEW );
101976  pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
101977  if( noErr ) db->suppressErr--;
101978
101979  if( pTab==0 ){
101980    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
101981    goto exit_drop_table;
101982  }
101983  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
101984  assert( iDb>=0 && iDb<db->nDb );
101985
101986  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
101987  ** it is initialized.
101988  */
101989  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
101990    goto exit_drop_table;
101991  }
101992#ifndef SQLITE_OMIT_AUTHORIZATION
101993  {
101994    int code;
101995    const char *zTab = SCHEMA_TABLE(iDb);
101996    const char *zDb = db->aDb[iDb].zDbSName;
101997    const char *zArg2 = 0;
101998    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
101999      goto exit_drop_table;
102000    }
102001    if( isView ){
102002      if( !OMIT_TEMPDB && iDb==1 ){
102003        code = SQLITE_DROP_TEMP_VIEW;
102004      }else{
102005        code = SQLITE_DROP_VIEW;
102006      }
102007#ifndef SQLITE_OMIT_VIRTUALTABLE
102008    }else if( IsVirtual(pTab) ){
102009      code = SQLITE_DROP_VTABLE;
102010      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
102011#endif
102012    }else{
102013      if( !OMIT_TEMPDB && iDb==1 ){
102014        code = SQLITE_DROP_TEMP_TABLE;
102015      }else{
102016        code = SQLITE_DROP_TABLE;
102017      }
102018    }
102019    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
102020      goto exit_drop_table;
102021    }
102022    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
102023      goto exit_drop_table;
102024    }
102025  }
102026#endif
102027  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
102028    && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
102029    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
102030    goto exit_drop_table;
102031  }
102032
102033#ifndef SQLITE_OMIT_VIEW
102034  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
102035  ** on a table.
102036  */
102037  if( isView && pTab->pSelect==0 ){
102038    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
102039    goto exit_drop_table;
102040  }
102041  if( !isView && pTab->pSelect ){
102042    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
102043    goto exit_drop_table;
102044  }
102045#endif
102046
102047  /* Generate code to remove the table from the master table
102048  ** on disk.
102049  */
102050  v = sqlite3GetVdbe(pParse);
102051  if( v ){
102052    sqlite3BeginWriteOperation(pParse, 1, iDb);
102053    sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
102054    sqlite3FkDropTable(pParse, pName, pTab);
102055    sqlite3CodeDropTable(pParse, pTab, iDb, isView);
102056  }
102057
102058exit_drop_table:
102059  sqlite3SrcListDelete(db, pName);
102060}
102061
102062/*
102063** This routine is called to create a new foreign key on the table
102064** currently under construction.  pFromCol determines which columns
102065** in the current table point to the foreign key.  If pFromCol==0 then
102066** connect the key to the last column inserted.  pTo is the name of
102067** the table referred to (a.k.a the "parent" table).  pToCol is a list
102068** of tables in the parent pTo table.  flags contains all
102069** information about the conflict resolution algorithms specified
102070** in the ON DELETE, ON UPDATE and ON INSERT clauses.
102071**
102072** An FKey structure is created and added to the table currently
102073** under construction in the pParse->pNewTable field.
102074**
102075** The foreign key is set for IMMEDIATE processing.  A subsequent call
102076** to sqlite3DeferForeignKey() might change this to DEFERRED.
102077*/
102078SQLITE_PRIVATE void sqlite3CreateForeignKey(
102079  Parse *pParse,       /* Parsing context */
102080  ExprList *pFromCol,  /* Columns in this table that point to other table */
102081  Token *pTo,          /* Name of the other table */
102082  ExprList *pToCol,    /* Columns in the other table */
102083  int flags            /* Conflict resolution algorithms. */
102084){
102085  sqlite3 *db = pParse->db;
102086#ifndef SQLITE_OMIT_FOREIGN_KEY
102087  FKey *pFKey = 0;
102088  FKey *pNextTo;
102089  Table *p = pParse->pNewTable;
102090  int nByte;
102091  int i;
102092  int nCol;
102093  char *z;
102094
102095  assert( pTo!=0 );
102096  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
102097  if( pFromCol==0 ){
102098    int iCol = p->nCol-1;
102099    if( NEVER(iCol<0) ) goto fk_end;
102100    if( pToCol && pToCol->nExpr!=1 ){
102101      sqlite3ErrorMsg(pParse, "foreign key on %s"
102102         " should reference only one column of table %T",
102103         p->aCol[iCol].zName, pTo);
102104      goto fk_end;
102105    }
102106    nCol = 1;
102107  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
102108    sqlite3ErrorMsg(pParse,
102109        "number of columns in foreign key does not match the number of "
102110        "columns in the referenced table");
102111    goto fk_end;
102112  }else{
102113    nCol = pFromCol->nExpr;
102114  }
102115  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
102116  if( pToCol ){
102117    for(i=0; i<pToCol->nExpr; i++){
102118      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
102119    }
102120  }
102121  pFKey = sqlite3DbMallocZero(db, nByte );
102122  if( pFKey==0 ){
102123    goto fk_end;
102124  }
102125  pFKey->pFrom = p;
102126  pFKey->pNextFrom = p->pFKey;
102127  z = (char*)&pFKey->aCol[nCol];
102128  pFKey->zTo = z;
102129  memcpy(z, pTo->z, pTo->n);
102130  z[pTo->n] = 0;
102131  sqlite3Dequote(z);
102132  z += pTo->n+1;
102133  pFKey->nCol = nCol;
102134  if( pFromCol==0 ){
102135    pFKey->aCol[0].iFrom = p->nCol-1;
102136  }else{
102137    for(i=0; i<nCol; i++){
102138      int j;
102139      for(j=0; j<p->nCol; j++){
102140        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
102141          pFKey->aCol[i].iFrom = j;
102142          break;
102143        }
102144      }
102145      if( j>=p->nCol ){
102146        sqlite3ErrorMsg(pParse,
102147          "unknown column \"%s\" in foreign key definition",
102148          pFromCol->a[i].zName);
102149        goto fk_end;
102150      }
102151    }
102152  }
102153  if( pToCol ){
102154    for(i=0; i<nCol; i++){
102155      int n = sqlite3Strlen30(pToCol->a[i].zName);
102156      pFKey->aCol[i].zCol = z;
102157      memcpy(z, pToCol->a[i].zName, n);
102158      z[n] = 0;
102159      z += n+1;
102160    }
102161  }
102162  pFKey->isDeferred = 0;
102163  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
102164  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
102165
102166  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
102167  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
102168      pFKey->zTo, (void *)pFKey
102169  );
102170  if( pNextTo==pFKey ){
102171    sqlite3OomFault(db);
102172    goto fk_end;
102173  }
102174  if( pNextTo ){
102175    assert( pNextTo->pPrevTo==0 );
102176    pFKey->pNextTo = pNextTo;
102177    pNextTo->pPrevTo = pFKey;
102178  }
102179
102180  /* Link the foreign key to the table as the last step.
102181  */
102182  p->pFKey = pFKey;
102183  pFKey = 0;
102184
102185fk_end:
102186  sqlite3DbFree(db, pFKey);
102187#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
102188  sqlite3ExprListDelete(db, pFromCol);
102189  sqlite3ExprListDelete(db, pToCol);
102190}
102191
102192/*
102193** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
102194** clause is seen as part of a foreign key definition.  The isDeferred
102195** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
102196** The behavior of the most recently created foreign key is adjusted
102197** accordingly.
102198*/
102199SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
102200#ifndef SQLITE_OMIT_FOREIGN_KEY
102201  Table *pTab;
102202  FKey *pFKey;
102203  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
102204  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
102205  pFKey->isDeferred = (u8)isDeferred;
102206#endif
102207}
102208
102209/*
102210** Generate code that will erase and refill index *pIdx.  This is
102211** used to initialize a newly created index or to recompute the
102212** content of an index in response to a REINDEX command.
102213**
102214** if memRootPage is not negative, it means that the index is newly
102215** created.  The register specified by memRootPage contains the
102216** root page number of the index.  If memRootPage is negative, then
102217** the index already exists and must be cleared before being refilled and
102218** the root page number of the index is taken from pIndex->tnum.
102219*/
102220static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
102221  Table *pTab = pIndex->pTable;  /* The table that is indexed */
102222  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
102223  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
102224  int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
102225  int addr1;                     /* Address of top of loop */
102226  int addr2;                     /* Address to jump to for next iteration */
102227  int tnum;                      /* Root page of index */
102228  int iPartIdxLabel;             /* Jump to this label to skip a row */
102229  Vdbe *v;                       /* Generate code into this virtual machine */
102230  KeyInfo *pKey;                 /* KeyInfo for index */
102231  int regRecord;                 /* Register holding assembled index record */
102232  sqlite3 *db = pParse->db;      /* The database connection */
102233  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
102234
102235#ifndef SQLITE_OMIT_AUTHORIZATION
102236  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
102237      db->aDb[iDb].zDbSName ) ){
102238    return;
102239  }
102240#endif
102241
102242  /* Require a write-lock on the table to perform this operation */
102243  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
102244
102245  v = sqlite3GetVdbe(pParse);
102246  if( v==0 ) return;
102247  if( memRootPage>=0 ){
102248    tnum = memRootPage;
102249  }else{
102250    tnum = pIndex->tnum;
102251  }
102252  pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
102253  assert( pKey!=0 || db->mallocFailed || pParse->nErr );
102254
102255  /* Open the sorter cursor if we are to use one. */
102256  iSorter = pParse->nTab++;
102257  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
102258                    sqlite3KeyInfoRef(pKey), P4_KEYINFO);
102259
102260  /* Open the table. Loop through all rows of the table, inserting index
102261  ** records into the sorter. */
102262  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
102263  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
102264  regRecord = sqlite3GetTempReg(pParse);
102265
102266  sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
102267  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
102268  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
102269  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
102270  sqlite3VdbeJumpHere(v, addr1);
102271  if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
102272  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
102273                    (char *)pKey, P4_KEYINFO);
102274  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
102275
102276  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
102277  if( IsUniqueIndex(pIndex) ){
102278    int j2 = sqlite3VdbeCurrentAddr(v) + 3;
102279    sqlite3VdbeGoto(v, j2);
102280    addr2 = sqlite3VdbeCurrentAddr(v);
102281    sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
102282                         pIndex->nKeyCol); VdbeCoverage(v);
102283    sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
102284  }else{
102285    addr2 = sqlite3VdbeCurrentAddr(v);
102286  }
102287  sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
102288  sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
102289  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
102290  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
102291  sqlite3ReleaseTempReg(pParse, regRecord);
102292  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
102293  sqlite3VdbeJumpHere(v, addr1);
102294
102295  sqlite3VdbeAddOp1(v, OP_Close, iTab);
102296  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
102297  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
102298}
102299
102300/*
102301** Allocate heap space to hold an Index object with nCol columns.
102302**
102303** Increase the allocation size to provide an extra nExtra bytes
102304** of 8-byte aligned space after the Index object and return a
102305** pointer to this extra space in *ppExtra.
102306*/
102307SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
102308  sqlite3 *db,         /* Database connection */
102309  i16 nCol,            /* Total number of columns in the index */
102310  int nExtra,          /* Number of bytes of extra space to alloc */
102311  char **ppExtra       /* Pointer to the "extra" space */
102312){
102313  Index *p;            /* Allocated index object */
102314  int nByte;           /* Bytes of space for Index object + arrays */
102315
102316  nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
102317          ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
102318          ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
102319                 sizeof(i16)*nCol +            /* Index.aiColumn   */
102320                 sizeof(u8)*nCol);             /* Index.aSortOrder */
102321  p = sqlite3DbMallocZero(db, nByte + nExtra);
102322  if( p ){
102323    char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
102324    p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
102325    p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
102326    p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
102327    p->aSortOrder = (u8*)pExtra;
102328    p->nColumn = nCol;
102329    p->nKeyCol = nCol - 1;
102330    *ppExtra = ((char*)p) + nByte;
102331  }
102332  return p;
102333}
102334
102335/*
102336** Create a new index for an SQL table.  pName1.pName2 is the name of the index
102337** and pTblList is the name of the table that is to be indexed.  Both will
102338** be NULL for a primary key or an index that is created to satisfy a
102339** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
102340** as the table to be indexed.  pParse->pNewTable is a table that is
102341** currently being constructed by a CREATE TABLE statement.
102342**
102343** pList is a list of columns to be indexed.  pList will be NULL if this
102344** is a primary key or unique-constraint on the most recent column added
102345** to the table currently under construction.
102346*/
102347SQLITE_PRIVATE void sqlite3CreateIndex(
102348  Parse *pParse,     /* All information about this parse */
102349  Token *pName1,     /* First part of index name. May be NULL */
102350  Token *pName2,     /* Second part of index name. May be NULL */
102351  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
102352  ExprList *pList,   /* A list of columns to be indexed */
102353  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
102354  Token *pStart,     /* The CREATE token that begins this statement */
102355  Expr *pPIWhere,    /* WHERE clause for partial indices */
102356  int sortOrder,     /* Sort order of primary key when pList==NULL */
102357  int ifNotExist,    /* Omit error if index already exists */
102358  u8 idxType         /* The index type */
102359){
102360  Table *pTab = 0;     /* Table to be indexed */
102361  Index *pIndex = 0;   /* The index to be created */
102362  char *zName = 0;     /* Name of the index */
102363  int nName;           /* Number of characters in zName */
102364  int i, j;
102365  DbFixer sFix;        /* For assigning database names to pTable */
102366  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
102367  sqlite3 *db = pParse->db;
102368  Db *pDb;             /* The specific table containing the indexed database */
102369  int iDb;             /* Index of the database that is being written */
102370  Token *pName = 0;    /* Unqualified name of the index to create */
102371  struct ExprList_item *pListItem; /* For looping over pList */
102372  int nExtra = 0;                  /* Space allocated for zExtra[] */
102373  int nExtraCol;                   /* Number of extra columns needed */
102374  char *zExtra = 0;                /* Extra space after the Index object */
102375  Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
102376
102377  if( db->mallocFailed || pParse->nErr>0 ){
102378    goto exit_create_index;
102379  }
102380  if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
102381    goto exit_create_index;
102382  }
102383  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
102384    goto exit_create_index;
102385  }
102386
102387  /*
102388  ** Find the table that is to be indexed.  Return early if not found.
102389  */
102390  if( pTblName!=0 ){
102391
102392    /* Use the two-part index name to determine the database
102393    ** to search for the table. 'Fix' the table name to this db
102394    ** before looking up the table.
102395    */
102396    assert( pName1 && pName2 );
102397    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
102398    if( iDb<0 ) goto exit_create_index;
102399    assert( pName && pName->z );
102400
102401#ifndef SQLITE_OMIT_TEMPDB
102402    /* If the index name was unqualified, check if the table
102403    ** is a temp table. If so, set the database to 1. Do not do this
102404    ** if initialising a database schema.
102405    */
102406    if( !db->init.busy ){
102407      pTab = sqlite3SrcListLookup(pParse, pTblName);
102408      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
102409        iDb = 1;
102410      }
102411    }
102412#endif
102413
102414    sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
102415    if( sqlite3FixSrcList(&sFix, pTblName) ){
102416      /* Because the parser constructs pTblName from a single identifier,
102417      ** sqlite3FixSrcList can never fail. */
102418      assert(0);
102419    }
102420    pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
102421    assert( db->mallocFailed==0 || pTab==0 );
102422    if( pTab==0 ) goto exit_create_index;
102423    if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
102424      sqlite3ErrorMsg(pParse,
102425           "cannot create a TEMP index on non-TEMP table \"%s\"",
102426           pTab->zName);
102427      goto exit_create_index;
102428    }
102429    if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
102430  }else{
102431    assert( pName==0 );
102432    assert( pStart==0 );
102433    pTab = pParse->pNewTable;
102434    if( !pTab ) goto exit_create_index;
102435    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102436  }
102437  pDb = &db->aDb[iDb];
102438
102439  assert( pTab!=0 );
102440  assert( pParse->nErr==0 );
102441  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
102442       && db->init.busy==0
102443#if SQLITE_USER_AUTHENTICATION
102444       && sqlite3UserAuthTable(pTab->zName)==0
102445#endif
102446       && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
102447    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
102448    goto exit_create_index;
102449  }
102450#ifndef SQLITE_OMIT_VIEW
102451  if( pTab->pSelect ){
102452    sqlite3ErrorMsg(pParse, "views may not be indexed");
102453    goto exit_create_index;
102454  }
102455#endif
102456#ifndef SQLITE_OMIT_VIRTUALTABLE
102457  if( IsVirtual(pTab) ){
102458    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
102459    goto exit_create_index;
102460  }
102461#endif
102462
102463  /*
102464  ** Find the name of the index.  Make sure there is not already another
102465  ** index or table with the same name.
102466  **
102467  ** Exception:  If we are reading the names of permanent indices from the
102468  ** sqlite_master table (because some other process changed the schema) and
102469  ** one of the index names collides with the name of a temporary table or
102470  ** index, then we will continue to process this index.
102471  **
102472  ** If pName==0 it means that we are
102473  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
102474  ** own name.
102475  */
102476  if( pName ){
102477    zName = sqlite3NameFromToken(db, pName);
102478    if( zName==0 ) goto exit_create_index;
102479    assert( pName->z!=0 );
102480    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
102481      goto exit_create_index;
102482    }
102483    if( !db->init.busy ){
102484      if( sqlite3FindTable(db, zName, 0)!=0 ){
102485        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
102486        goto exit_create_index;
102487      }
102488    }
102489    if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
102490      if( !ifNotExist ){
102491        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
102492      }else{
102493        assert( !db->init.busy );
102494        sqlite3CodeVerifySchema(pParse, iDb);
102495      }
102496      goto exit_create_index;
102497    }
102498  }else{
102499    int n;
102500    Index *pLoop;
102501    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
102502    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
102503    if( zName==0 ){
102504      goto exit_create_index;
102505    }
102506
102507    /* Automatic index names generated from within sqlite3_declare_vtab()
102508    ** must have names that are distinct from normal automatic index names.
102509    ** The following statement converts "sqlite3_autoindex..." into
102510    ** "sqlite3_butoindex..." in order to make the names distinct.
102511    ** The "vtab_err.test" test demonstrates the need of this statement. */
102512    if( IN_DECLARE_VTAB ) zName[7]++;
102513  }
102514
102515  /* Check for authorization to create an index.
102516  */
102517#ifndef SQLITE_OMIT_AUTHORIZATION
102518  {
102519    const char *zDb = pDb->zDbSName;
102520    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
102521      goto exit_create_index;
102522    }
102523    i = SQLITE_CREATE_INDEX;
102524    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
102525    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
102526      goto exit_create_index;
102527    }
102528  }
102529#endif
102530
102531  /* If pList==0, it means this routine was called to make a primary
102532  ** key out of the last column added to the table under construction.
102533  ** So create a fake list to simulate this.
102534  */
102535  if( pList==0 ){
102536    Token prevCol;
102537    sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
102538    pList = sqlite3ExprListAppend(pParse, 0,
102539              sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
102540    if( pList==0 ) goto exit_create_index;
102541    assert( pList->nExpr==1 );
102542    sqlite3ExprListSetSortOrder(pList, sortOrder);
102543  }else{
102544    sqlite3ExprListCheckLength(pParse, pList, "index");
102545  }
102546
102547  /* Figure out how many bytes of space are required to store explicitly
102548  ** specified collation sequence names.
102549  */
102550  for(i=0; i<pList->nExpr; i++){
102551    Expr *pExpr = pList->a[i].pExpr;
102552    assert( pExpr!=0 );
102553    if( pExpr->op==TK_COLLATE ){
102554      nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
102555    }
102556  }
102557
102558  /*
102559  ** Allocate the index structure.
102560  */
102561  nName = sqlite3Strlen30(zName);
102562  nExtraCol = pPk ? pPk->nKeyCol : 1;
102563  pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
102564                                      nName + nExtra + 1, &zExtra);
102565  if( db->mallocFailed ){
102566    goto exit_create_index;
102567  }
102568  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
102569  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
102570  pIndex->zName = zExtra;
102571  zExtra += nName + 1;
102572  memcpy(pIndex->zName, zName, nName+1);
102573  pIndex->pTable = pTab;
102574  pIndex->onError = (u8)onError;
102575  pIndex->uniqNotNull = onError!=OE_None;
102576  pIndex->idxType = idxType;
102577  pIndex->pSchema = db->aDb[iDb].pSchema;
102578  pIndex->nKeyCol = pList->nExpr;
102579  if( pPIWhere ){
102580    sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
102581    pIndex->pPartIdxWhere = pPIWhere;
102582    pPIWhere = 0;
102583  }
102584  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102585
102586  /* Check to see if we should honor DESC requests on index columns
102587  */
102588  if( pDb->pSchema->file_format>=4 ){
102589    sortOrderMask = -1;   /* Honor DESC */
102590  }else{
102591    sortOrderMask = 0;    /* Ignore DESC */
102592  }
102593
102594  /* Analyze the list of expressions that form the terms of the index and
102595  ** report any errors.  In the common case where the expression is exactly
102596  ** a table column, store that column in aiColumn[].  For general expressions,
102597  ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
102598  **
102599  ** TODO: Issue a warning if two or more columns of the index are identical.
102600  ** TODO: Issue a warning if the table primary key is used as part of the
102601  ** index key.
102602  */
102603  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
102604    Expr *pCExpr;                  /* The i-th index expression */
102605    int requestedSortOrder;        /* ASC or DESC on the i-th expression */
102606    const char *zColl;             /* Collation sequence name */
102607
102608    sqlite3StringToId(pListItem->pExpr);
102609    sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
102610    if( pParse->nErr ) goto exit_create_index;
102611    pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
102612    if( pCExpr->op!=TK_COLUMN ){
102613      if( pTab==pParse->pNewTable ){
102614        sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
102615                                "UNIQUE constraints");
102616        goto exit_create_index;
102617      }
102618      if( pIndex->aColExpr==0 ){
102619        ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
102620        pIndex->aColExpr = pCopy;
102621        if( !db->mallocFailed ){
102622          assert( pCopy!=0 );
102623          pListItem = &pCopy->a[i];
102624        }
102625      }
102626      j = XN_EXPR;
102627      pIndex->aiColumn[i] = XN_EXPR;
102628      pIndex->uniqNotNull = 0;
102629    }else{
102630      j = pCExpr->iColumn;
102631      assert( j<=0x7fff );
102632      if( j<0 ){
102633        j = pTab->iPKey;
102634      }else if( pTab->aCol[j].notNull==0 ){
102635        pIndex->uniqNotNull = 0;
102636      }
102637      pIndex->aiColumn[i] = (i16)j;
102638    }
102639    zColl = 0;
102640    if( pListItem->pExpr->op==TK_COLLATE ){
102641      int nColl;
102642      zColl = pListItem->pExpr->u.zToken;
102643      nColl = sqlite3Strlen30(zColl) + 1;
102644      assert( nExtra>=nColl );
102645      memcpy(zExtra, zColl, nColl);
102646      zColl = zExtra;
102647      zExtra += nColl;
102648      nExtra -= nColl;
102649    }else if( j>=0 ){
102650      zColl = pTab->aCol[j].zColl;
102651    }
102652    if( !zColl ) zColl = sqlite3StrBINARY;
102653    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
102654      goto exit_create_index;
102655    }
102656    pIndex->azColl[i] = zColl;
102657    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
102658    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
102659  }
102660
102661  /* Append the table key to the end of the index.  For WITHOUT ROWID
102662  ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
102663  ** normal tables (when pPk==0) this will be the rowid.
102664  */
102665  if( pPk ){
102666    for(j=0; j<pPk->nKeyCol; j++){
102667      int x = pPk->aiColumn[j];
102668      assert( x>=0 );
102669      if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
102670        pIndex->nColumn--;
102671      }else{
102672        pIndex->aiColumn[i] = x;
102673        pIndex->azColl[i] = pPk->azColl[j];
102674        pIndex->aSortOrder[i] = pPk->aSortOrder[j];
102675        i++;
102676      }
102677    }
102678    assert( i==pIndex->nColumn );
102679  }else{
102680    pIndex->aiColumn[i] = XN_ROWID;
102681    pIndex->azColl[i] = sqlite3StrBINARY;
102682  }
102683  sqlite3DefaultRowEst(pIndex);
102684  if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
102685
102686  /* If this index contains every column of its table, then mark
102687  ** it as a covering index */
102688  assert( HasRowid(pTab)
102689      || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
102690  if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
102691    pIndex->isCovering = 1;
102692    for(j=0; j<pTab->nCol; j++){
102693      if( j==pTab->iPKey ) continue;
102694      if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
102695      pIndex->isCovering = 0;
102696      break;
102697    }
102698  }
102699
102700  if( pTab==pParse->pNewTable ){
102701    /* This routine has been called to create an automatic index as a
102702    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
102703    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
102704    ** i.e. one of:
102705    **
102706    ** CREATE TABLE t(x PRIMARY KEY, y);
102707    ** CREATE TABLE t(x, y, UNIQUE(x, y));
102708    **
102709    ** Either way, check to see if the table already has such an index. If
102710    ** so, don't bother creating this one. This only applies to
102711    ** automatically created indices. Users can do as they wish with
102712    ** explicit indices.
102713    **
102714    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
102715    ** (and thus suppressing the second one) even if they have different
102716    ** sort orders.
102717    **
102718    ** If there are different collating sequences or if the columns of
102719    ** the constraint occur in different orders, then the constraints are
102720    ** considered distinct and both result in separate indices.
102721    */
102722    Index *pIdx;
102723    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102724      int k;
102725      assert( IsUniqueIndex(pIdx) );
102726      assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
102727      assert( IsUniqueIndex(pIndex) );
102728
102729      if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
102730      for(k=0; k<pIdx->nKeyCol; k++){
102731        const char *z1;
102732        const char *z2;
102733        assert( pIdx->aiColumn[k]>=0 );
102734        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
102735        z1 = pIdx->azColl[k];
102736        z2 = pIndex->azColl[k];
102737        if( sqlite3StrICmp(z1, z2) ) break;
102738      }
102739      if( k==pIdx->nKeyCol ){
102740        if( pIdx->onError!=pIndex->onError ){
102741          /* This constraint creates the same index as a previous
102742          ** constraint specified somewhere in the CREATE TABLE statement.
102743          ** However the ON CONFLICT clauses are different. If both this
102744          ** constraint and the previous equivalent constraint have explicit
102745          ** ON CONFLICT clauses this is an error. Otherwise, use the
102746          ** explicitly specified behavior for the index.
102747          */
102748          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
102749            sqlite3ErrorMsg(pParse,
102750                "conflicting ON CONFLICT clauses specified", 0);
102751          }
102752          if( pIdx->onError==OE_Default ){
102753            pIdx->onError = pIndex->onError;
102754          }
102755        }
102756        if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
102757        goto exit_create_index;
102758      }
102759    }
102760  }
102761
102762  /* Link the new Index structure to its table and to the other
102763  ** in-memory database structures.
102764  */
102765  assert( pParse->nErr==0 );
102766  if( db->init.busy ){
102767    Index *p;
102768    assert( !IN_DECLARE_VTAB );
102769    assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
102770    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
102771                          pIndex->zName, pIndex);
102772    if( p ){
102773      assert( p==pIndex );  /* Malloc must have failed */
102774      sqlite3OomFault(db);
102775      goto exit_create_index;
102776    }
102777    db->flags |= SQLITE_InternChanges;
102778    if( pTblName!=0 ){
102779      pIndex->tnum = db->init.newTnum;
102780    }
102781  }
102782
102783  /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
102784  ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
102785  ** emit code to allocate the index rootpage on disk and make an entry for
102786  ** the index in the sqlite_master table and populate the index with
102787  ** content.  But, do not do this if we are simply reading the sqlite_master
102788  ** table to parse the schema, or if this index is the PRIMARY KEY index
102789  ** of a WITHOUT ROWID table.
102790  **
102791  ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
102792  ** or UNIQUE index in a CREATE TABLE statement.  Since the table
102793  ** has just been created, it contains no data and the index initialization
102794  ** step can be skipped.
102795  */
102796  else if( HasRowid(pTab) || pTblName!=0 ){
102797    Vdbe *v;
102798    char *zStmt;
102799    int iMem = ++pParse->nMem;
102800
102801    v = sqlite3GetVdbe(pParse);
102802    if( v==0 ) goto exit_create_index;
102803
102804    sqlite3BeginWriteOperation(pParse, 1, iDb);
102805
102806    /* Create the rootpage for the index using CreateIndex. But before
102807    ** doing so, code a Noop instruction and store its address in
102808    ** Index.tnum. This is required in case this index is actually a
102809    ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
102810    ** that case the convertToWithoutRowidTable() routine will replace
102811    ** the Noop with a Goto to jump over the VDBE code generated below. */
102812    pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
102813    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
102814
102815    /* Gather the complete text of the CREATE INDEX statement into
102816    ** the zStmt variable
102817    */
102818    if( pStart ){
102819      int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
102820      if( pName->z[n-1]==';' ) n--;
102821      /* A named index with an explicit CREATE INDEX statement */
102822      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
102823        onError==OE_None ? "" : " UNIQUE", n, pName->z);
102824    }else{
102825      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
102826      /* zStmt = sqlite3MPrintf(""); */
102827      zStmt = 0;
102828    }
102829
102830    /* Add an entry in sqlite_master for this index
102831    */
102832    sqlite3NestedParse(pParse,
102833        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
102834        db->aDb[iDb].zDbSName, MASTER_NAME,
102835        pIndex->zName,
102836        pTab->zName,
102837        iMem,
102838        zStmt
102839    );
102840    sqlite3DbFree(db, zStmt);
102841
102842    /* Fill the index with data and reparse the schema. Code an OP_Expire
102843    ** to invalidate all pre-compiled statements.
102844    */
102845    if( pTblName ){
102846      sqlite3RefillIndex(pParse, pIndex, iMem);
102847      sqlite3ChangeCookie(pParse, iDb);
102848      sqlite3VdbeAddParseSchemaOp(v, iDb,
102849         sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
102850      sqlite3VdbeAddOp0(v, OP_Expire);
102851    }
102852
102853    sqlite3VdbeJumpHere(v, pIndex->tnum);
102854  }
102855
102856  /* When adding an index to the list of indices for a table, make
102857  ** sure all indices labeled OE_Replace come after all those labeled
102858  ** OE_Ignore.  This is necessary for the correct constraint check
102859  ** processing (in sqlite3GenerateConstraintChecks()) as part of
102860  ** UPDATE and INSERT statements.
102861  */
102862  if( db->init.busy || pTblName==0 ){
102863    if( onError!=OE_Replace || pTab->pIndex==0
102864         || pTab->pIndex->onError==OE_Replace){
102865      pIndex->pNext = pTab->pIndex;
102866      pTab->pIndex = pIndex;
102867    }else{
102868      Index *pOther = pTab->pIndex;
102869      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
102870        pOther = pOther->pNext;
102871      }
102872      pIndex->pNext = pOther->pNext;
102873      pOther->pNext = pIndex;
102874    }
102875    pIndex = 0;
102876  }
102877
102878  /* Clean up before exiting */
102879exit_create_index:
102880  if( pIndex ) freeIndex(db, pIndex);
102881  sqlite3ExprDelete(db, pPIWhere);
102882  sqlite3ExprListDelete(db, pList);
102883  sqlite3SrcListDelete(db, pTblName);
102884  sqlite3DbFree(db, zName);
102885}
102886
102887/*
102888** Fill the Index.aiRowEst[] array with default information - information
102889** to be used when we have not run the ANALYZE command.
102890**
102891** aiRowEst[0] is supposed to contain the number of elements in the index.
102892** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
102893** number of rows in the table that match any particular value of the
102894** first column of the index.  aiRowEst[2] is an estimate of the number
102895** of rows that match any particular combination of the first 2 columns
102896** of the index.  And so forth.  It must always be the case that
102897*
102898**           aiRowEst[N]<=aiRowEst[N-1]
102899**           aiRowEst[N]>=1
102900**
102901** Apart from that, we have little to go on besides intuition as to
102902** how aiRowEst[] should be initialized.  The numbers generated here
102903** are based on typical values found in actual indices.
102904*/
102905SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
102906  /*                10,  9,  8,  7,  6 */
102907  LogEst aVal[] = { 33, 32, 30, 28, 26 };
102908  LogEst *a = pIdx->aiRowLogEst;
102909  int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
102910  int i;
102911
102912  /* Indexes with default row estimates should not have stat1 data */
102913  assert( !pIdx->hasStat1 );
102914
102915  /* Set the first entry (number of rows in the index) to the estimated
102916  ** number of rows in the table, or half the number of rows in the table
102917  ** for a partial index.   But do not let the estimate drop below 10. */
102918  a[0] = pIdx->pTable->nRowLogEst;
102919  if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10;  assert( 10==sqlite3LogEst(2) );
102920  if( a[0]<33 ) a[0] = 33;                  assert( 33==sqlite3LogEst(10) );
102921
102922  /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
102923  ** 6 and each subsequent value (if any) is 5.  */
102924  memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
102925  for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
102926    a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
102927  }
102928
102929  assert( 0==sqlite3LogEst(1) );
102930  if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
102931}
102932
102933/*
102934** This routine will drop an existing named index.  This routine
102935** implements the DROP INDEX statement.
102936*/
102937SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
102938  Index *pIndex;
102939  Vdbe *v;
102940  sqlite3 *db = pParse->db;
102941  int iDb;
102942
102943  assert( pParse->nErr==0 );   /* Never called with prior errors */
102944  if( db->mallocFailed ){
102945    goto exit_drop_index;
102946  }
102947  assert( pName->nSrc==1 );
102948  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
102949    goto exit_drop_index;
102950  }
102951  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
102952  if( pIndex==0 ){
102953    if( !ifExists ){
102954      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
102955    }else{
102956      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
102957    }
102958    pParse->checkSchema = 1;
102959    goto exit_drop_index;
102960  }
102961  if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
102962    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
102963      "or PRIMARY KEY constraint cannot be dropped", 0);
102964    goto exit_drop_index;
102965  }
102966  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
102967#ifndef SQLITE_OMIT_AUTHORIZATION
102968  {
102969    int code = SQLITE_DROP_INDEX;
102970    Table *pTab = pIndex->pTable;
102971    const char *zDb = db->aDb[iDb].zDbSName;
102972    const char *zTab = SCHEMA_TABLE(iDb);
102973    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
102974      goto exit_drop_index;
102975    }
102976    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
102977    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
102978      goto exit_drop_index;
102979    }
102980  }
102981#endif
102982
102983  /* Generate code to remove the index and from the master table */
102984  v = sqlite3GetVdbe(pParse);
102985  if( v ){
102986    sqlite3BeginWriteOperation(pParse, 1, iDb);
102987    sqlite3NestedParse(pParse,
102988       "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
102989       db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
102990    );
102991    sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
102992    sqlite3ChangeCookie(pParse, iDb);
102993    destroyRootPage(pParse, pIndex->tnum, iDb);
102994    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
102995  }
102996
102997exit_drop_index:
102998  sqlite3SrcListDelete(db, pName);
102999}
103000
103001/*
103002** pArray is a pointer to an array of objects. Each object in the
103003** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
103004** to extend the array so that there is space for a new object at the end.
103005**
103006** When this function is called, *pnEntry contains the current size of
103007** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
103008** in total).
103009**
103010** If the realloc() is successful (i.e. if no OOM condition occurs), the
103011** space allocated for the new object is zeroed, *pnEntry updated to
103012** reflect the new size of the array and a pointer to the new allocation
103013** returned. *pIdx is set to the index of the new array entry in this case.
103014**
103015** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
103016** unchanged and a copy of pArray returned.
103017*/
103018SQLITE_PRIVATE void *sqlite3ArrayAllocate(
103019  sqlite3 *db,      /* Connection to notify of malloc failures */
103020  void *pArray,     /* Array of objects.  Might be reallocated */
103021  int szEntry,      /* Size of each object in the array */
103022  int *pnEntry,     /* Number of objects currently in use */
103023  int *pIdx         /* Write the index of a new slot here */
103024){
103025  char *z;
103026  int n = *pnEntry;
103027  if( (n & (n-1))==0 ){
103028    int sz = (n==0) ? 1 : 2*n;
103029    void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
103030    if( pNew==0 ){
103031      *pIdx = -1;
103032      return pArray;
103033    }
103034    pArray = pNew;
103035  }
103036  z = (char*)pArray;
103037  memset(&z[n * szEntry], 0, szEntry);
103038  *pIdx = n;
103039  ++*pnEntry;
103040  return pArray;
103041}
103042
103043/*
103044** Append a new element to the given IdList.  Create a new IdList if
103045** need be.
103046**
103047** A new IdList is returned, or NULL if malloc() fails.
103048*/
103049SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
103050  int i;
103051  if( pList==0 ){
103052    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
103053    if( pList==0 ) return 0;
103054  }
103055  pList->a = sqlite3ArrayAllocate(
103056      db,
103057      pList->a,
103058      sizeof(pList->a[0]),
103059      &pList->nId,
103060      &i
103061  );
103062  if( i<0 ){
103063    sqlite3IdListDelete(db, pList);
103064    return 0;
103065  }
103066  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
103067  return pList;
103068}
103069
103070/*
103071** Delete an IdList.
103072*/
103073SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
103074  int i;
103075  if( pList==0 ) return;
103076  for(i=0; i<pList->nId; i++){
103077    sqlite3DbFree(db, pList->a[i].zName);
103078  }
103079  sqlite3DbFree(db, pList->a);
103080  sqlite3DbFree(db, pList);
103081}
103082
103083/*
103084** Return the index in pList of the identifier named zId.  Return -1
103085** if not found.
103086*/
103087SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
103088  int i;
103089  if( pList==0 ) return -1;
103090  for(i=0; i<pList->nId; i++){
103091    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
103092  }
103093  return -1;
103094}
103095
103096/*
103097** Expand the space allocated for the given SrcList object by
103098** creating nExtra new slots beginning at iStart.  iStart is zero based.
103099** New slots are zeroed.
103100**
103101** For example, suppose a SrcList initially contains two entries: A,B.
103102** To append 3 new entries onto the end, do this:
103103**
103104**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
103105**
103106** After the call above it would contain:  A, B, nil, nil, nil.
103107** If the iStart argument had been 1 instead of 2, then the result
103108** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
103109** the iStart value would be 0.  The result then would
103110** be: nil, nil, nil, A, B.
103111**
103112** If a memory allocation fails the SrcList is unchanged.  The
103113** db->mallocFailed flag will be set to true.
103114*/
103115SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
103116  sqlite3 *db,       /* Database connection to notify of OOM errors */
103117  SrcList *pSrc,     /* The SrcList to be enlarged */
103118  int nExtra,        /* Number of new slots to add to pSrc->a[] */
103119  int iStart         /* Index in pSrc->a[] of first new slot */
103120){
103121  int i;
103122
103123  /* Sanity checking on calling parameters */
103124  assert( iStart>=0 );
103125  assert( nExtra>=1 );
103126  assert( pSrc!=0 );
103127  assert( iStart<=pSrc->nSrc );
103128
103129  /* Allocate additional space if needed */
103130  if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
103131    SrcList *pNew;
103132    int nAlloc = pSrc->nSrc*2+nExtra;
103133    int nGot;
103134    pNew = sqlite3DbRealloc(db, pSrc,
103135               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
103136    if( pNew==0 ){
103137      assert( db->mallocFailed );
103138      return pSrc;
103139    }
103140    pSrc = pNew;
103141    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
103142    pSrc->nAlloc = nGot;
103143  }
103144
103145  /* Move existing slots that come after the newly inserted slots
103146  ** out of the way */
103147  for(i=pSrc->nSrc-1; i>=iStart; i--){
103148    pSrc->a[i+nExtra] = pSrc->a[i];
103149  }
103150  pSrc->nSrc += nExtra;
103151
103152  /* Zero the newly allocated slots */
103153  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
103154  for(i=iStart; i<iStart+nExtra; i++){
103155    pSrc->a[i].iCursor = -1;
103156  }
103157
103158  /* Return a pointer to the enlarged SrcList */
103159  return pSrc;
103160}
103161
103162
103163/*
103164** Append a new table name to the given SrcList.  Create a new SrcList if
103165** need be.  A new entry is created in the SrcList even if pTable is NULL.
103166**
103167** A SrcList is returned, or NULL if there is an OOM error.  The returned
103168** SrcList might be the same as the SrcList that was input or it might be
103169** a new one.  If an OOM error does occurs, then the prior value of pList
103170** that is input to this routine is automatically freed.
103171**
103172** If pDatabase is not null, it means that the table has an optional
103173** database name prefix.  Like this:  "database.table".  The pDatabase
103174** points to the table name and the pTable points to the database name.
103175** The SrcList.a[].zName field is filled with the table name which might
103176** come from pTable (if pDatabase is NULL) or from pDatabase.
103177** SrcList.a[].zDatabase is filled with the database name from pTable,
103178** or with NULL if no database is specified.
103179**
103180** In other words, if call like this:
103181**
103182**         sqlite3SrcListAppend(D,A,B,0);
103183**
103184** Then B is a table name and the database name is unspecified.  If called
103185** like this:
103186**
103187**         sqlite3SrcListAppend(D,A,B,C);
103188**
103189** Then C is the table name and B is the database name.  If C is defined
103190** then so is B.  In other words, we never have a case where:
103191**
103192**         sqlite3SrcListAppend(D,A,0,C);
103193**
103194** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
103195** before being added to the SrcList.
103196*/
103197SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
103198  sqlite3 *db,        /* Connection to notify of malloc failures */
103199  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
103200  Token *pTable,      /* Table to append */
103201  Token *pDatabase    /* Database of the table */
103202){
103203  struct SrcList_item *pItem;
103204  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
103205  assert( db!=0 );
103206  if( pList==0 ){
103207    pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
103208    if( pList==0 ) return 0;
103209    pList->nAlloc = 1;
103210    pList->nSrc = 1;
103211    memset(&pList->a[0], 0, sizeof(pList->a[0]));
103212    pList->a[0].iCursor = -1;
103213  }else{
103214    pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
103215  }
103216  if( db->mallocFailed ){
103217    sqlite3SrcListDelete(db, pList);
103218    return 0;
103219  }
103220  pItem = &pList->a[pList->nSrc-1];
103221  if( pDatabase && pDatabase->z==0 ){
103222    pDatabase = 0;
103223  }
103224  if( pDatabase ){
103225    Token *pTemp = pDatabase;
103226    pDatabase = pTable;
103227    pTable = pTemp;
103228  }
103229  pItem->zName = sqlite3NameFromToken(db, pTable);
103230  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
103231  return pList;
103232}
103233
103234/*
103235** Assign VdbeCursor index numbers to all tables in a SrcList
103236*/
103237SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
103238  int i;
103239  struct SrcList_item *pItem;
103240  assert(pList || pParse->db->mallocFailed );
103241  if( pList ){
103242    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
103243      if( pItem->iCursor>=0 ) break;
103244      pItem->iCursor = pParse->nTab++;
103245      if( pItem->pSelect ){
103246        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
103247      }
103248    }
103249  }
103250}
103251
103252/*
103253** Delete an entire SrcList including all its substructure.
103254*/
103255SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
103256  int i;
103257  struct SrcList_item *pItem;
103258  if( pList==0 ) return;
103259  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
103260    sqlite3DbFree(db, pItem->zDatabase);
103261    sqlite3DbFree(db, pItem->zName);
103262    sqlite3DbFree(db, pItem->zAlias);
103263    if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
103264    if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
103265    sqlite3DeleteTable(db, pItem->pTab);
103266    sqlite3SelectDelete(db, pItem->pSelect);
103267    sqlite3ExprDelete(db, pItem->pOn);
103268    sqlite3IdListDelete(db, pItem->pUsing);
103269  }
103270  sqlite3DbFree(db, pList);
103271}
103272
103273/*
103274** This routine is called by the parser to add a new term to the
103275** end of a growing FROM clause.  The "p" parameter is the part of
103276** the FROM clause that has already been constructed.  "p" is NULL
103277** if this is the first term of the FROM clause.  pTable and pDatabase
103278** are the name of the table and database named in the FROM clause term.
103279** pDatabase is NULL if the database name qualifier is missing - the
103280** usual case.  If the term has an alias, then pAlias points to the
103281** alias token.  If the term is a subquery, then pSubquery is the
103282** SELECT statement that the subquery encodes.  The pTable and
103283** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
103284** parameters are the content of the ON and USING clauses.
103285**
103286** Return a new SrcList which encodes is the FROM with the new
103287** term added.
103288*/
103289SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
103290  Parse *pParse,          /* Parsing context */
103291  SrcList *p,             /* The left part of the FROM clause already seen */
103292  Token *pTable,          /* Name of the table to add to the FROM clause */
103293  Token *pDatabase,       /* Name of the database containing pTable */
103294  Token *pAlias,          /* The right-hand side of the AS subexpression */
103295  Select *pSubquery,      /* A subquery used in place of a table name */
103296  Expr *pOn,              /* The ON clause of a join */
103297  IdList *pUsing          /* The USING clause of a join */
103298){
103299  struct SrcList_item *pItem;
103300  sqlite3 *db = pParse->db;
103301  if( !p && (pOn || pUsing) ){
103302    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
103303      (pOn ? "ON" : "USING")
103304    );
103305    goto append_from_error;
103306  }
103307  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
103308  if( p==0 || NEVER(p->nSrc==0) ){
103309    goto append_from_error;
103310  }
103311  pItem = &p->a[p->nSrc-1];
103312  assert( pAlias!=0 );
103313  if( pAlias->n ){
103314    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
103315  }
103316  pItem->pSelect = pSubquery;
103317  pItem->pOn = pOn;
103318  pItem->pUsing = pUsing;
103319  return p;
103320
103321 append_from_error:
103322  assert( p==0 );
103323  sqlite3ExprDelete(db, pOn);
103324  sqlite3IdListDelete(db, pUsing);
103325  sqlite3SelectDelete(db, pSubquery);
103326  return 0;
103327}
103328
103329/*
103330** Add an INDEXED BY or NOT INDEXED clause to the most recently added
103331** element of the source-list passed as the second argument.
103332*/
103333SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
103334  assert( pIndexedBy!=0 );
103335  if( p && ALWAYS(p->nSrc>0) ){
103336    struct SrcList_item *pItem = &p->a[p->nSrc-1];
103337    assert( pItem->fg.notIndexed==0 );
103338    assert( pItem->fg.isIndexedBy==0 );
103339    assert( pItem->fg.isTabFunc==0 );
103340    if( pIndexedBy->n==1 && !pIndexedBy->z ){
103341      /* A "NOT INDEXED" clause was supplied. See parse.y
103342      ** construct "indexed_opt" for details. */
103343      pItem->fg.notIndexed = 1;
103344    }else{
103345      pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
103346      pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
103347    }
103348  }
103349}
103350
103351/*
103352** Add the list of function arguments to the SrcList entry for a
103353** table-valued-function.
103354*/
103355SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
103356  if( p ){
103357    struct SrcList_item *pItem = &p->a[p->nSrc-1];
103358    assert( pItem->fg.notIndexed==0 );
103359    assert( pItem->fg.isIndexedBy==0 );
103360    assert( pItem->fg.isTabFunc==0 );
103361    pItem->u1.pFuncArg = pList;
103362    pItem->fg.isTabFunc = 1;
103363  }else{
103364    sqlite3ExprListDelete(pParse->db, pList);
103365  }
103366}
103367
103368/*
103369** When building up a FROM clause in the parser, the join operator
103370** is initially attached to the left operand.  But the code generator
103371** expects the join operator to be on the right operand.  This routine
103372** Shifts all join operators from left to right for an entire FROM
103373** clause.
103374**
103375** Example: Suppose the join is like this:
103376**
103377**           A natural cross join B
103378**
103379** The operator is "natural cross join".  The A and B operands are stored
103380** in p->a[0] and p->a[1], respectively.  The parser initially stores the
103381** operator with A.  This routine shifts that operator over to B.
103382*/
103383SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
103384  if( p ){
103385    int i;
103386    for(i=p->nSrc-1; i>0; i--){
103387      p->a[i].fg.jointype = p->a[i-1].fg.jointype;
103388    }
103389    p->a[0].fg.jointype = 0;
103390  }
103391}
103392
103393/*
103394** Generate VDBE code for a BEGIN statement.
103395*/
103396SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
103397  sqlite3 *db;
103398  Vdbe *v;
103399  int i;
103400
103401  assert( pParse!=0 );
103402  db = pParse->db;
103403  assert( db!=0 );
103404  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
103405    return;
103406  }
103407  v = sqlite3GetVdbe(pParse);
103408  if( !v ) return;
103409  if( type!=TK_DEFERRED ){
103410    for(i=0; i<db->nDb; i++){
103411      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
103412      sqlite3VdbeUsesBtree(v, i);
103413    }
103414  }
103415  sqlite3VdbeAddOp0(v, OP_AutoCommit);
103416}
103417
103418/*
103419** Generate VDBE code for a COMMIT statement.
103420*/
103421SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
103422  Vdbe *v;
103423
103424  assert( pParse!=0 );
103425  assert( pParse->db!=0 );
103426  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
103427    return;
103428  }
103429  v = sqlite3GetVdbe(pParse);
103430  if( v ){
103431    sqlite3VdbeAddOp1(v, OP_AutoCommit, 1);
103432  }
103433}
103434
103435/*
103436** Generate VDBE code for a ROLLBACK statement.
103437*/
103438SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
103439  Vdbe *v;
103440
103441  assert( pParse!=0 );
103442  assert( pParse->db!=0 );
103443  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
103444    return;
103445  }
103446  v = sqlite3GetVdbe(pParse);
103447  if( v ){
103448    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
103449  }
103450}
103451
103452/*
103453** This function is called by the parser when it parses a command to create,
103454** release or rollback an SQL savepoint.
103455*/
103456SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
103457  char *zName = sqlite3NameFromToken(pParse->db, pName);
103458  if( zName ){
103459    Vdbe *v = sqlite3GetVdbe(pParse);
103460#ifndef SQLITE_OMIT_AUTHORIZATION
103461    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
103462    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
103463#endif
103464    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
103465      sqlite3DbFree(pParse->db, zName);
103466      return;
103467    }
103468    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
103469  }
103470}
103471
103472/*
103473** Make sure the TEMP database is open and available for use.  Return
103474** the number of errors.  Leave any error messages in the pParse structure.
103475*/
103476SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
103477  sqlite3 *db = pParse->db;
103478  if( db->aDb[1].pBt==0 && !pParse->explain ){
103479    int rc;
103480    Btree *pBt;
103481    static const int flags =
103482          SQLITE_OPEN_READWRITE |
103483          SQLITE_OPEN_CREATE |
103484          SQLITE_OPEN_EXCLUSIVE |
103485          SQLITE_OPEN_DELETEONCLOSE |
103486          SQLITE_OPEN_TEMP_DB;
103487
103488    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
103489    if( rc!=SQLITE_OK ){
103490      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
103491        "file for storing temporary tables");
103492      pParse->rc = rc;
103493      return 1;
103494    }
103495    db->aDb[1].pBt = pBt;
103496    assert( db->aDb[1].pSchema );
103497    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
103498      sqlite3OomFault(db);
103499      return 1;
103500    }
103501  }
103502  return 0;
103503}
103504
103505/*
103506** Record the fact that the schema cookie will need to be verified
103507** for database iDb.  The code to actually verify the schema cookie
103508** will occur at the end of the top-level VDBE and will be generated
103509** later, by sqlite3FinishCoding().
103510*/
103511SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
103512  Parse *pToplevel = sqlite3ParseToplevel(pParse);
103513
103514  assert( iDb>=0 && iDb<pParse->db->nDb );
103515  assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
103516  assert( iDb<SQLITE_MAX_ATTACHED+2 );
103517  assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
103518  if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
103519    DbMaskSet(pToplevel->cookieMask, iDb);
103520    if( !OMIT_TEMPDB && iDb==1 ){
103521      sqlite3OpenTempDatabase(pToplevel);
103522    }
103523  }
103524}
103525
103526/*
103527** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
103528** attached database. Otherwise, invoke it for the database named zDb only.
103529*/
103530SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
103531  sqlite3 *db = pParse->db;
103532  int i;
103533  for(i=0; i<db->nDb; i++){
103534    Db *pDb = &db->aDb[i];
103535    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
103536      sqlite3CodeVerifySchema(pParse, i);
103537    }
103538  }
103539}
103540
103541/*
103542** Generate VDBE code that prepares for doing an operation that
103543** might change the database.
103544**
103545** This routine starts a new transaction if we are not already within
103546** a transaction.  If we are already within a transaction, then a checkpoint
103547** is set if the setStatement parameter is true.  A checkpoint should
103548** be set for operations that might fail (due to a constraint) part of
103549** the way through and which will need to undo some writes without having to
103550** rollback the whole transaction.  For operations where all constraints
103551** can be checked before any changes are made to the database, it is never
103552** necessary to undo a write and the checkpoint should not be set.
103553*/
103554SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
103555  Parse *pToplevel = sqlite3ParseToplevel(pParse);
103556  sqlite3CodeVerifySchema(pParse, iDb);
103557  DbMaskSet(pToplevel->writeMask, iDb);
103558  pToplevel->isMultiWrite |= setStatement;
103559}
103560
103561/*
103562** Indicate that the statement currently under construction might write
103563** more than one entry (example: deleting one row then inserting another,
103564** inserting multiple rows in a table, or inserting a row and index entries.)
103565** If an abort occurs after some of these writes have completed, then it will
103566** be necessary to undo the completed writes.
103567*/
103568SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
103569  Parse *pToplevel = sqlite3ParseToplevel(pParse);
103570  pToplevel->isMultiWrite = 1;
103571}
103572
103573/*
103574** The code generator calls this routine if is discovers that it is
103575** possible to abort a statement prior to completion.  In order to
103576** perform this abort without corrupting the database, we need to make
103577** sure that the statement is protected by a statement transaction.
103578**
103579** Technically, we only need to set the mayAbort flag if the
103580** isMultiWrite flag was previously set.  There is a time dependency
103581** such that the abort must occur after the multiwrite.  This makes
103582** some statements involving the REPLACE conflict resolution algorithm
103583** go a little faster.  But taking advantage of this time dependency
103584** makes it more difficult to prove that the code is correct (in
103585** particular, it prevents us from writing an effective
103586** implementation of sqlite3AssertMayAbort()) and so we have chosen
103587** to take the safe route and skip the optimization.
103588*/
103589SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
103590  Parse *pToplevel = sqlite3ParseToplevel(pParse);
103591  pToplevel->mayAbort = 1;
103592}
103593
103594/*
103595** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
103596** error. The onError parameter determines which (if any) of the statement
103597** and/or current transaction is rolled back.
103598*/
103599SQLITE_PRIVATE void sqlite3HaltConstraint(
103600  Parse *pParse,    /* Parsing context */
103601  int errCode,      /* extended error code */
103602  int onError,      /* Constraint type */
103603  char *p4,         /* Error message */
103604  i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
103605  u8 p5Errmsg       /* P5_ErrMsg type */
103606){
103607  Vdbe *v = sqlite3GetVdbe(pParse);
103608  assert( (errCode&0xff)==SQLITE_CONSTRAINT );
103609  if( onError==OE_Abort ){
103610    sqlite3MayAbort(pParse);
103611  }
103612  sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
103613  sqlite3VdbeChangeP5(v, p5Errmsg);
103614}
103615
103616/*
103617** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
103618*/
103619SQLITE_PRIVATE void sqlite3UniqueConstraint(
103620  Parse *pParse,    /* Parsing context */
103621  int onError,      /* Constraint type */
103622  Index *pIdx       /* The index that triggers the constraint */
103623){
103624  char *zErr;
103625  int j;
103626  StrAccum errMsg;
103627  Table *pTab = pIdx->pTable;
103628
103629  sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
103630  if( pIdx->aColExpr ){
103631    sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
103632  }else{
103633    for(j=0; j<pIdx->nKeyCol; j++){
103634      char *zCol;
103635      assert( pIdx->aiColumn[j]>=0 );
103636      zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
103637      if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
103638      sqlite3XPrintf(&errMsg, "%s.%s", pTab->zName, zCol);
103639    }
103640  }
103641  zErr = sqlite3StrAccumFinish(&errMsg);
103642  sqlite3HaltConstraint(pParse,
103643    IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
103644                            : SQLITE_CONSTRAINT_UNIQUE,
103645    onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
103646}
103647
103648
103649/*
103650** Code an OP_Halt due to non-unique rowid.
103651*/
103652SQLITE_PRIVATE void sqlite3RowidConstraint(
103653  Parse *pParse,    /* Parsing context */
103654  int onError,      /* Conflict resolution algorithm */
103655  Table *pTab       /* The table with the non-unique rowid */
103656){
103657  char *zMsg;
103658  int rc;
103659  if( pTab->iPKey>=0 ){
103660    zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
103661                          pTab->aCol[pTab->iPKey].zName);
103662    rc = SQLITE_CONSTRAINT_PRIMARYKEY;
103663  }else{
103664    zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
103665    rc = SQLITE_CONSTRAINT_ROWID;
103666  }
103667  sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
103668                        P5_ConstraintUnique);
103669}
103670
103671/*
103672** Check to see if pIndex uses the collating sequence pColl.  Return
103673** true if it does and false if it does not.
103674*/
103675#ifndef SQLITE_OMIT_REINDEX
103676static int collationMatch(const char *zColl, Index *pIndex){
103677  int i;
103678  assert( zColl!=0 );
103679  for(i=0; i<pIndex->nColumn; i++){
103680    const char *z = pIndex->azColl[i];
103681    assert( z!=0 || pIndex->aiColumn[i]<0 );
103682    if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
103683      return 1;
103684    }
103685  }
103686  return 0;
103687}
103688#endif
103689
103690/*
103691** Recompute all indices of pTab that use the collating sequence pColl.
103692** If pColl==0 then recompute all indices of pTab.
103693*/
103694#ifndef SQLITE_OMIT_REINDEX
103695static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
103696  Index *pIndex;              /* An index associated with pTab */
103697
103698  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
103699    if( zColl==0 || collationMatch(zColl, pIndex) ){
103700      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
103701      sqlite3BeginWriteOperation(pParse, 0, iDb);
103702      sqlite3RefillIndex(pParse, pIndex, -1);
103703    }
103704  }
103705}
103706#endif
103707
103708/*
103709** Recompute all indices of all tables in all databases where the
103710** indices use the collating sequence pColl.  If pColl==0 then recompute
103711** all indices everywhere.
103712*/
103713#ifndef SQLITE_OMIT_REINDEX
103714static void reindexDatabases(Parse *pParse, char const *zColl){
103715  Db *pDb;                    /* A single database */
103716  int iDb;                    /* The database index number */
103717  sqlite3 *db = pParse->db;   /* The database connection */
103718  HashElem *k;                /* For looping over tables in pDb */
103719  Table *pTab;                /* A table in the database */
103720
103721  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
103722  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
103723    assert( pDb!=0 );
103724    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
103725      pTab = (Table*)sqliteHashData(k);
103726      reindexTable(pParse, pTab, zColl);
103727    }
103728  }
103729}
103730#endif
103731
103732/*
103733** Generate code for the REINDEX command.
103734**
103735**        REINDEX                            -- 1
103736**        REINDEX  <collation>               -- 2
103737**        REINDEX  ?<database>.?<tablename>  -- 3
103738**        REINDEX  ?<database>.?<indexname>  -- 4
103739**
103740** Form 1 causes all indices in all attached databases to be rebuilt.
103741** Form 2 rebuilds all indices in all databases that use the named
103742** collating function.  Forms 3 and 4 rebuild the named index or all
103743** indices associated with the named table.
103744*/
103745#ifndef SQLITE_OMIT_REINDEX
103746SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
103747  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
103748  char *z;                    /* Name of a table or index */
103749  const char *zDb;            /* Name of the database */
103750  Table *pTab;                /* A table in the database */
103751  Index *pIndex;              /* An index associated with pTab */
103752  int iDb;                    /* The database index number */
103753  sqlite3 *db = pParse->db;   /* The database connection */
103754  Token *pObjName;            /* Name of the table or index to be reindexed */
103755
103756  /* Read the database schema. If an error occurs, leave an error message
103757  ** and code in pParse and return NULL. */
103758  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
103759    return;
103760  }
103761
103762  if( pName1==0 ){
103763    reindexDatabases(pParse, 0);
103764    return;
103765  }else if( NEVER(pName2==0) || pName2->z==0 ){
103766    char *zColl;
103767    assert( pName1->z );
103768    zColl = sqlite3NameFromToken(pParse->db, pName1);
103769    if( !zColl ) return;
103770    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
103771    if( pColl ){
103772      reindexDatabases(pParse, zColl);
103773      sqlite3DbFree(db, zColl);
103774      return;
103775    }
103776    sqlite3DbFree(db, zColl);
103777  }
103778  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
103779  if( iDb<0 ) return;
103780  z = sqlite3NameFromToken(db, pObjName);
103781  if( z==0 ) return;
103782  zDb = db->aDb[iDb].zDbSName;
103783  pTab = sqlite3FindTable(db, z, zDb);
103784  if( pTab ){
103785    reindexTable(pParse, pTab, 0);
103786    sqlite3DbFree(db, z);
103787    return;
103788  }
103789  pIndex = sqlite3FindIndex(db, z, zDb);
103790  sqlite3DbFree(db, z);
103791  if( pIndex ){
103792    sqlite3BeginWriteOperation(pParse, 0, iDb);
103793    sqlite3RefillIndex(pParse, pIndex, -1);
103794    return;
103795  }
103796  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
103797}
103798#endif
103799
103800/*
103801** Return a KeyInfo structure that is appropriate for the given Index.
103802**
103803** The caller should invoke sqlite3KeyInfoUnref() on the returned object
103804** when it has finished using it.
103805*/
103806SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
103807  int i;
103808  int nCol = pIdx->nColumn;
103809  int nKey = pIdx->nKeyCol;
103810  KeyInfo *pKey;
103811  if( pParse->nErr ) return 0;
103812  if( pIdx->uniqNotNull ){
103813    pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
103814  }else{
103815    pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
103816  }
103817  if( pKey ){
103818    assert( sqlite3KeyInfoIsWriteable(pKey) );
103819    for(i=0; i<nCol; i++){
103820      const char *zColl = pIdx->azColl[i];
103821      pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
103822                        sqlite3LocateCollSeq(pParse, zColl);
103823      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
103824    }
103825    if( pParse->nErr ){
103826      sqlite3KeyInfoUnref(pKey);
103827      pKey = 0;
103828    }
103829  }
103830  return pKey;
103831}
103832
103833#ifndef SQLITE_OMIT_CTE
103834/*
103835** This routine is invoked once per CTE by the parser while parsing a
103836** WITH clause.
103837*/
103838SQLITE_PRIVATE With *sqlite3WithAdd(
103839  Parse *pParse,          /* Parsing context */
103840  With *pWith,            /* Existing WITH clause, or NULL */
103841  Token *pName,           /* Name of the common-table */
103842  ExprList *pArglist,     /* Optional column name list for the table */
103843  Select *pQuery          /* Query used to initialize the table */
103844){
103845  sqlite3 *db = pParse->db;
103846  With *pNew;
103847  char *zName;
103848
103849  /* Check that the CTE name is unique within this WITH clause. If
103850  ** not, store an error in the Parse structure. */
103851  zName = sqlite3NameFromToken(pParse->db, pName);
103852  if( zName && pWith ){
103853    int i;
103854    for(i=0; i<pWith->nCte; i++){
103855      if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
103856        sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
103857      }
103858    }
103859  }
103860
103861  if( pWith ){
103862    int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
103863    pNew = sqlite3DbRealloc(db, pWith, nByte);
103864  }else{
103865    pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
103866  }
103867  assert( (pNew!=0 && zName!=0) || db->mallocFailed );
103868
103869  if( db->mallocFailed ){
103870    sqlite3ExprListDelete(db, pArglist);
103871    sqlite3SelectDelete(db, pQuery);
103872    sqlite3DbFree(db, zName);
103873    pNew = pWith;
103874  }else{
103875    pNew->a[pNew->nCte].pSelect = pQuery;
103876    pNew->a[pNew->nCte].pCols = pArglist;
103877    pNew->a[pNew->nCte].zName = zName;
103878    pNew->a[pNew->nCte].zCteErr = 0;
103879    pNew->nCte++;
103880  }
103881
103882  return pNew;
103883}
103884
103885/*
103886** Free the contents of the With object passed as the second argument.
103887*/
103888SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
103889  if( pWith ){
103890    int i;
103891    for(i=0; i<pWith->nCte; i++){
103892      struct Cte *pCte = &pWith->a[i];
103893      sqlite3ExprListDelete(db, pCte->pCols);
103894      sqlite3SelectDelete(db, pCte->pSelect);
103895      sqlite3DbFree(db, pCte->zName);
103896    }
103897    sqlite3DbFree(db, pWith);
103898  }
103899}
103900#endif /* !defined(SQLITE_OMIT_CTE) */
103901
103902/************** End of build.c ***********************************************/
103903/************** Begin file callback.c ****************************************/
103904/*
103905** 2005 May 23
103906**
103907** The author disclaims copyright to this source code.  In place of
103908** a legal notice, here is a blessing:
103909**
103910**    May you do good and not evil.
103911**    May you find forgiveness for yourself and forgive others.
103912**    May you share freely, never taking more than you give.
103913**
103914*************************************************************************
103915**
103916** This file contains functions used to access the internal hash tables
103917** of user defined functions and collation sequences.
103918*/
103919
103920/* #include "sqliteInt.h" */
103921
103922/*
103923** Invoke the 'collation needed' callback to request a collation sequence
103924** in the encoding enc of name zName, length nName.
103925*/
103926static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
103927  assert( !db->xCollNeeded || !db->xCollNeeded16 );
103928  if( db->xCollNeeded ){
103929    char *zExternal = sqlite3DbStrDup(db, zName);
103930    if( !zExternal ) return;
103931    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
103932    sqlite3DbFree(db, zExternal);
103933  }
103934#ifndef SQLITE_OMIT_UTF16
103935  if( db->xCollNeeded16 ){
103936    char const *zExternal;
103937    sqlite3_value *pTmp = sqlite3ValueNew(db);
103938    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
103939    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
103940    if( zExternal ){
103941      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
103942    }
103943    sqlite3ValueFree(pTmp);
103944  }
103945#endif
103946}
103947
103948/*
103949** This routine is called if the collation factory fails to deliver a
103950** collation function in the best encoding but there may be other versions
103951** of this collation function (for other text encodings) available. Use one
103952** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
103953** possible.
103954*/
103955static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
103956  CollSeq *pColl2;
103957  char *z = pColl->zName;
103958  int i;
103959  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
103960  for(i=0; i<3; i++){
103961    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
103962    if( pColl2->xCmp!=0 ){
103963      memcpy(pColl, pColl2, sizeof(CollSeq));
103964      pColl->xDel = 0;         /* Do not copy the destructor */
103965      return SQLITE_OK;
103966    }
103967  }
103968  return SQLITE_ERROR;
103969}
103970
103971/*
103972** This function is responsible for invoking the collation factory callback
103973** or substituting a collation sequence of a different encoding when the
103974** requested collation sequence is not available in the desired encoding.
103975**
103976** If it is not NULL, then pColl must point to the database native encoding
103977** collation sequence with name zName, length nName.
103978**
103979** The return value is either the collation sequence to be used in database
103980** db for collation type name zName, length nName, or NULL, if no collation
103981** sequence can be found.  If no collation is found, leave an error message.
103982**
103983** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
103984*/
103985SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
103986  Parse *pParse,        /* Parsing context */
103987  u8 enc,               /* The desired encoding for the collating sequence */
103988  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
103989  const char *zName     /* Collating sequence name */
103990){
103991  CollSeq *p;
103992  sqlite3 *db = pParse->db;
103993
103994  p = pColl;
103995  if( !p ){
103996    p = sqlite3FindCollSeq(db, enc, zName, 0);
103997  }
103998  if( !p || !p->xCmp ){
103999    /* No collation sequence of this type for this encoding is registered.
104000    ** Call the collation factory to see if it can supply us with one.
104001    */
104002    callCollNeeded(db, enc, zName);
104003    p = sqlite3FindCollSeq(db, enc, zName, 0);
104004  }
104005  if( p && !p->xCmp && synthCollSeq(db, p) ){
104006    p = 0;
104007  }
104008  assert( !p || p->xCmp );
104009  if( p==0 ){
104010    sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
104011  }
104012  return p;
104013}
104014
104015/*
104016** This routine is called on a collation sequence before it is used to
104017** check that it is defined. An undefined collation sequence exists when
104018** a database is loaded that contains references to collation sequences
104019** that have not been defined by sqlite3_create_collation() etc.
104020**
104021** If required, this routine calls the 'collation needed' callback to
104022** request a definition of the collating sequence. If this doesn't work,
104023** an equivalent collating sequence that uses a text encoding different
104024** from the main database is substituted, if one is available.
104025*/
104026SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
104027  if( pColl ){
104028    const char *zName = pColl->zName;
104029    sqlite3 *db = pParse->db;
104030    CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
104031    if( !p ){
104032      return SQLITE_ERROR;
104033    }
104034    assert( p==pColl );
104035  }
104036  return SQLITE_OK;
104037}
104038
104039
104040
104041/*
104042** Locate and return an entry from the db.aCollSeq hash table. If the entry
104043** specified by zName and nName is not found and parameter 'create' is
104044** true, then create a new entry. Otherwise return NULL.
104045**
104046** Each pointer stored in the sqlite3.aCollSeq hash table contains an
104047** array of three CollSeq structures. The first is the collation sequence
104048** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
104049**
104050** Stored immediately after the three collation sequences is a copy of
104051** the collation sequence name. A pointer to this string is stored in
104052** each collation sequence structure.
104053*/
104054static CollSeq *findCollSeqEntry(
104055  sqlite3 *db,          /* Database connection */
104056  const char *zName,    /* Name of the collating sequence */
104057  int create            /* Create a new entry if true */
104058){
104059  CollSeq *pColl;
104060  pColl = sqlite3HashFind(&db->aCollSeq, zName);
104061
104062  if( 0==pColl && create ){
104063    int nName = sqlite3Strlen30(zName);
104064    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
104065    if( pColl ){
104066      CollSeq *pDel = 0;
104067      pColl[0].zName = (char*)&pColl[3];
104068      pColl[0].enc = SQLITE_UTF8;
104069      pColl[1].zName = (char*)&pColl[3];
104070      pColl[1].enc = SQLITE_UTF16LE;
104071      pColl[2].zName = (char*)&pColl[3];
104072      pColl[2].enc = SQLITE_UTF16BE;
104073      memcpy(pColl[0].zName, zName, nName);
104074      pColl[0].zName[nName] = 0;
104075      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
104076
104077      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
104078      ** return the pColl pointer to be deleted (because it wasn't added
104079      ** to the hash table).
104080      */
104081      assert( pDel==0 || pDel==pColl );
104082      if( pDel!=0 ){
104083        sqlite3OomFault(db);
104084        sqlite3DbFree(db, pDel);
104085        pColl = 0;
104086      }
104087    }
104088  }
104089  return pColl;
104090}
104091
104092/*
104093** Parameter zName points to a UTF-8 encoded string nName bytes long.
104094** Return the CollSeq* pointer for the collation sequence named zName
104095** for the encoding 'enc' from the database 'db'.
104096**
104097** If the entry specified is not found and 'create' is true, then create a
104098** new entry.  Otherwise return NULL.
104099**
104100** A separate function sqlite3LocateCollSeq() is a wrapper around
104101** this routine.  sqlite3LocateCollSeq() invokes the collation factory
104102** if necessary and generates an error message if the collating sequence
104103** cannot be found.
104104**
104105** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
104106*/
104107SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
104108  sqlite3 *db,
104109  u8 enc,
104110  const char *zName,
104111  int create
104112){
104113  CollSeq *pColl;
104114  if( zName ){
104115    pColl = findCollSeqEntry(db, zName, create);
104116  }else{
104117    pColl = db->pDfltColl;
104118  }
104119  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
104120  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
104121  if( pColl ) pColl += enc-1;
104122  return pColl;
104123}
104124
104125/* During the search for the best function definition, this procedure
104126** is called to test how well the function passed as the first argument
104127** matches the request for a function with nArg arguments in a system
104128** that uses encoding enc. The value returned indicates how well the
104129** request is matched. A higher value indicates a better match.
104130**
104131** If nArg is -1 that means to only return a match (non-zero) if p->nArg
104132** is also -1.  In other words, we are searching for a function that
104133** takes a variable number of arguments.
104134**
104135** If nArg is -2 that means that we are searching for any function
104136** regardless of the number of arguments it uses, so return a positive
104137** match score for any
104138**
104139** The returned value is always between 0 and 6, as follows:
104140**
104141** 0: Not a match.
104142** 1: UTF8/16 conversion required and function takes any number of arguments.
104143** 2: UTF16 byte order change required and function takes any number of args.
104144** 3: encoding matches and function takes any number of arguments
104145** 4: UTF8/16 conversion required - argument count matches exactly
104146** 5: UTF16 byte order conversion required - argument count matches exactly
104147** 6: Perfect match:  encoding and argument count match exactly.
104148**
104149** If nArg==(-2) then any function with a non-null xSFunc is
104150** a perfect match and any function with xSFunc NULL is
104151** a non-match.
104152*/
104153#define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
104154static int matchQuality(
104155  FuncDef *p,     /* The function we are evaluating for match quality */
104156  int nArg,       /* Desired number of arguments.  (-1)==any */
104157  u8 enc          /* Desired text encoding */
104158){
104159  int match;
104160
104161  /* nArg of -2 is a special case */
104162  if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
104163
104164  /* Wrong number of arguments means "no match" */
104165  if( p->nArg!=nArg && p->nArg>=0 ) return 0;
104166
104167  /* Give a better score to a function with a specific number of arguments
104168  ** than to function that accepts any number of arguments. */
104169  if( p->nArg==nArg ){
104170    match = 4;
104171  }else{
104172    match = 1;
104173  }
104174
104175  /* Bonus points if the text encoding matches */
104176  if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
104177    match += 2;  /* Exact encoding match */
104178  }else if( (enc & p->funcFlags & 2)!=0 ){
104179    match += 1;  /* Both are UTF16, but with different byte orders */
104180  }
104181
104182  return match;
104183}
104184
104185/*
104186** Search a FuncDefHash for a function with the given name.  Return
104187** a pointer to the matching FuncDef if found, or 0 if there is no match.
104188*/
104189static FuncDef *functionSearch(
104190  int h,               /* Hash of the name */
104191  const char *zFunc    /* Name of function */
104192){
104193  FuncDef *p;
104194  for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
104195    if( sqlite3StrICmp(p->zName, zFunc)==0 ){
104196      return p;
104197    }
104198  }
104199  return 0;
104200}
104201
104202/*
104203** Insert a new FuncDef into a FuncDefHash hash table.
104204*/
104205SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
104206  FuncDef *aDef,      /* List of global functions to be inserted */
104207  int nDef            /* Length of the apDef[] list */
104208){
104209  int i;
104210  for(i=0; i<nDef; i++){
104211    FuncDef *pOther;
104212    const char *zName = aDef[i].zName;
104213    int nName = sqlite3Strlen30(zName);
104214    int h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
104215    pOther = functionSearch(h, zName);
104216    if( pOther ){
104217      assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
104218      aDef[i].pNext = pOther->pNext;
104219      pOther->pNext = &aDef[i];
104220    }else{
104221      aDef[i].pNext = 0;
104222      aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
104223      sqlite3BuiltinFunctions.a[h] = &aDef[i];
104224    }
104225  }
104226}
104227
104228
104229
104230/*
104231** Locate a user function given a name, a number of arguments and a flag
104232** indicating whether the function prefers UTF-16 over UTF-8.  Return a
104233** pointer to the FuncDef structure that defines that function, or return
104234** NULL if the function does not exist.
104235**
104236** If the createFlag argument is true, then a new (blank) FuncDef
104237** structure is created and liked into the "db" structure if a
104238** no matching function previously existed.
104239**
104240** If nArg is -2, then the first valid function found is returned.  A
104241** function is valid if xSFunc is non-zero.  The nArg==(-2)
104242** case is used to see if zName is a valid function name for some number
104243** of arguments.  If nArg is -2, then createFlag must be 0.
104244**
104245** If createFlag is false, then a function with the required name and
104246** number of arguments may be returned even if the eTextRep flag does not
104247** match that requested.
104248*/
104249SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
104250  sqlite3 *db,       /* An open database */
104251  const char *zName, /* Name of the function.  zero-terminated */
104252  int nArg,          /* Number of arguments.  -1 means any number */
104253  u8 enc,            /* Preferred text encoding */
104254  u8 createFlag      /* Create new entry if true and does not otherwise exist */
104255){
104256  FuncDef *p;         /* Iterator variable */
104257  FuncDef *pBest = 0; /* Best match found so far */
104258  int bestScore = 0;  /* Score of best match */
104259  int h;              /* Hash value */
104260  int nName;          /* Length of the name */
104261
104262  assert( nArg>=(-2) );
104263  assert( nArg>=(-1) || createFlag==0 );
104264  nName = sqlite3Strlen30(zName);
104265
104266  /* First search for a match amongst the application-defined functions.
104267  */
104268  p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
104269  while( p ){
104270    int score = matchQuality(p, nArg, enc);
104271    if( score>bestScore ){
104272      pBest = p;
104273      bestScore = score;
104274    }
104275    p = p->pNext;
104276  }
104277
104278  /* If no match is found, search the built-in functions.
104279  **
104280  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
104281  ** functions even if a prior app-defined function was found.  And give
104282  ** priority to built-in functions.
104283  **
104284  ** Except, if createFlag is true, that means that we are trying to
104285  ** install a new function.  Whatever FuncDef structure is returned it will
104286  ** have fields overwritten with new information appropriate for the
104287  ** new function.  But the FuncDefs for built-in functions are read-only.
104288  ** So we must not search for built-ins when creating a new function.
104289  */
104290  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
104291    bestScore = 0;
104292    h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
104293    p = functionSearch(h, zName);
104294    while( p ){
104295      int score = matchQuality(p, nArg, enc);
104296      if( score>bestScore ){
104297        pBest = p;
104298        bestScore = score;
104299      }
104300      p = p->pNext;
104301    }
104302  }
104303
104304  /* If the createFlag parameter is true and the search did not reveal an
104305  ** exact match for the name, number of arguments and encoding, then add a
104306  ** new entry to the hash table and return it.
104307  */
104308  if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
104309      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
104310    FuncDef *pOther;
104311    pBest->zName = (const char*)&pBest[1];
104312    pBest->nArg = (u16)nArg;
104313    pBest->funcFlags = enc;
104314    memcpy((char*)&pBest[1], zName, nName+1);
104315    pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
104316    if( pOther==pBest ){
104317      sqlite3DbFree(db, pBest);
104318      sqlite3OomFault(db);
104319      return 0;
104320    }else{
104321      pBest->pNext = pOther;
104322    }
104323  }
104324
104325  if( pBest && (pBest->xSFunc || createFlag) ){
104326    return pBest;
104327  }
104328  return 0;
104329}
104330
104331/*
104332** Free all resources held by the schema structure. The void* argument points
104333** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
104334** pointer itself, it just cleans up subsidiary resources (i.e. the contents
104335** of the schema hash tables).
104336**
104337** The Schema.cache_size variable is not cleared.
104338*/
104339SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
104340  Hash temp1;
104341  Hash temp2;
104342  HashElem *pElem;
104343  Schema *pSchema = (Schema *)p;
104344
104345  temp1 = pSchema->tblHash;
104346  temp2 = pSchema->trigHash;
104347  sqlite3HashInit(&pSchema->trigHash);
104348  sqlite3HashClear(&pSchema->idxHash);
104349  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
104350    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
104351  }
104352  sqlite3HashClear(&temp2);
104353  sqlite3HashInit(&pSchema->tblHash);
104354  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
104355    Table *pTab = sqliteHashData(pElem);
104356    sqlite3DeleteTable(0, pTab);
104357  }
104358  sqlite3HashClear(&temp1);
104359  sqlite3HashClear(&pSchema->fkeyHash);
104360  pSchema->pSeqTab = 0;
104361  if( pSchema->schemaFlags & DB_SchemaLoaded ){
104362    pSchema->iGeneration++;
104363    pSchema->schemaFlags &= ~DB_SchemaLoaded;
104364  }
104365}
104366
104367/*
104368** Find and return the schema associated with a BTree.  Create
104369** a new one if necessary.
104370*/
104371SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
104372  Schema * p;
104373  if( pBt ){
104374    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
104375  }else{
104376    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
104377  }
104378  if( !p ){
104379    sqlite3OomFault(db);
104380  }else if ( 0==p->file_format ){
104381    sqlite3HashInit(&p->tblHash);
104382    sqlite3HashInit(&p->idxHash);
104383    sqlite3HashInit(&p->trigHash);
104384    sqlite3HashInit(&p->fkeyHash);
104385    p->enc = SQLITE_UTF8;
104386  }
104387  return p;
104388}
104389
104390/************** End of callback.c ********************************************/
104391/************** Begin file delete.c ******************************************/
104392/*
104393** 2001 September 15
104394**
104395** The author disclaims copyright to this source code.  In place of
104396** a legal notice, here is a blessing:
104397**
104398**    May you do good and not evil.
104399**    May you find forgiveness for yourself and forgive others.
104400**    May you share freely, never taking more than you give.
104401**
104402*************************************************************************
104403** This file contains C code routines that are called by the parser
104404** in order to generate code for DELETE FROM statements.
104405*/
104406/* #include "sqliteInt.h" */
104407
104408/*
104409** While a SrcList can in general represent multiple tables and subqueries
104410** (as in the FROM clause of a SELECT statement) in this case it contains
104411** the name of a single table, as one might find in an INSERT, DELETE,
104412** or UPDATE statement.  Look up that table in the symbol table and
104413** return a pointer.  Set an error message and return NULL if the table
104414** name is not found or if any other error occurs.
104415**
104416** The following fields are initialized appropriate in pSrc:
104417**
104418**    pSrc->a[0].pTab       Pointer to the Table object
104419**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
104420**
104421*/
104422SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
104423  struct SrcList_item *pItem = pSrc->a;
104424  Table *pTab;
104425  assert( pItem && pSrc->nSrc==1 );
104426  pTab = sqlite3LocateTableItem(pParse, 0, pItem);
104427  sqlite3DeleteTable(pParse->db, pItem->pTab);
104428  pItem->pTab = pTab;
104429  if( pTab ){
104430    pTab->nTabRef++;
104431  }
104432  if( sqlite3IndexedByLookup(pParse, pItem) ){
104433    pTab = 0;
104434  }
104435  return pTab;
104436}
104437
104438/*
104439** Check to make sure the given table is writable.  If it is not
104440** writable, generate an error message and return 1.  If it is
104441** writable return 0;
104442*/
104443SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
104444  /* A table is not writable under the following circumstances:
104445  **
104446  **   1) It is a virtual table and no implementation of the xUpdate method
104447  **      has been provided, or
104448  **   2) It is a system table (i.e. sqlite_master), this call is not
104449  **      part of a nested parse and writable_schema pragma has not
104450  **      been specified.
104451  **
104452  ** In either case leave an error message in pParse and return non-zero.
104453  */
104454  if( ( IsVirtual(pTab)
104455     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
104456   || ( (pTab->tabFlags & TF_Readonly)!=0
104457     && (pParse->db->flags & SQLITE_WriteSchema)==0
104458     && pParse->nested==0 )
104459  ){
104460    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
104461    return 1;
104462  }
104463
104464#ifndef SQLITE_OMIT_VIEW
104465  if( !viewOk && pTab->pSelect ){
104466    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
104467    return 1;
104468  }
104469#endif
104470  return 0;
104471}
104472
104473
104474#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
104475/*
104476** Evaluate a view and store its result in an ephemeral table.  The
104477** pWhere argument is an optional WHERE clause that restricts the
104478** set of rows in the view that are to be added to the ephemeral table.
104479*/
104480SQLITE_PRIVATE void sqlite3MaterializeView(
104481  Parse *pParse,       /* Parsing context */
104482  Table *pView,        /* View definition */
104483  Expr *pWhere,        /* Optional WHERE clause to be added */
104484  int iCur             /* Cursor number for ephemeral table */
104485){
104486  SelectDest dest;
104487  Select *pSel;
104488  SrcList *pFrom;
104489  sqlite3 *db = pParse->db;
104490  int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
104491  pWhere = sqlite3ExprDup(db, pWhere, 0);
104492  pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
104493  if( pFrom ){
104494    assert( pFrom->nSrc==1 );
104495    pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
104496    pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
104497    assert( pFrom->a[0].pOn==0 );
104498    assert( pFrom->a[0].pUsing==0 );
104499  }
104500  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0,
104501                          SF_IncludeHidden, 0, 0);
104502  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
104503  sqlite3Select(pParse, pSel, &dest);
104504  sqlite3SelectDelete(db, pSel);
104505}
104506#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
104507
104508#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
104509/*
104510** Generate an expression tree to implement the WHERE, ORDER BY,
104511** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
104512**
104513**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
104514**                            \__________________________/
104515**                               pLimitWhere (pInClause)
104516*/
104517SQLITE_PRIVATE Expr *sqlite3LimitWhere(
104518  Parse *pParse,               /* The parser context */
104519  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
104520  Expr *pWhere,                /* The WHERE clause.  May be null */
104521  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
104522  Expr *pLimit,                /* The LIMIT clause.  May be null */
104523  Expr *pOffset,               /* The OFFSET clause.  May be null */
104524  char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
104525){
104526  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
104527  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
104528  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
104529  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
104530  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
104531  Select *pSelect = NULL;      /* Complete SELECT tree */
104532
104533  /* Check that there isn't an ORDER BY without a LIMIT clause.
104534  */
104535  if( pOrderBy && (pLimit == 0) ) {
104536    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
104537    goto limit_where_cleanup;
104538  }
104539
104540  /* We only need to generate a select expression if there
104541  ** is a limit/offset term to enforce.
104542  */
104543  if( pLimit == 0 ) {
104544    /* if pLimit is null, pOffset will always be null as well. */
104545    assert( pOffset == 0 );
104546    return pWhere;
104547  }
104548
104549  /* Generate a select expression tree to enforce the limit/offset
104550  ** term for the DELETE or UPDATE statement.  For example:
104551  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
104552  ** becomes:
104553  **   DELETE FROM table_a WHERE rowid IN (
104554  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
104555  **   );
104556  */
104557
104558  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0);
104559  if( pSelectRowid == 0 ) goto limit_where_cleanup;
104560  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
104561  if( pEList == 0 ) goto limit_where_cleanup;
104562
104563  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
104564  ** and the SELECT subtree. */
104565  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
104566  if( pSelectSrc == 0 ) {
104567    sqlite3ExprListDelete(pParse->db, pEList);
104568    goto limit_where_cleanup;
104569  }
104570
104571  /* generate the SELECT expression tree. */
104572  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
104573                             pOrderBy,0,pLimit,pOffset);
104574  if( pSelect == 0 ) return 0;
104575
104576  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
104577  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0);
104578  pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0) : 0;
104579  sqlite3PExprAddSelect(pParse, pInClause, pSelect);
104580  return pInClause;
104581
104582limit_where_cleanup:
104583  sqlite3ExprDelete(pParse->db, pWhere);
104584  sqlite3ExprListDelete(pParse->db, pOrderBy);
104585  sqlite3ExprDelete(pParse->db, pLimit);
104586  sqlite3ExprDelete(pParse->db, pOffset);
104587  return 0;
104588}
104589#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
104590       /*      && !defined(SQLITE_OMIT_SUBQUERY) */
104591
104592/*
104593** Generate code for a DELETE FROM statement.
104594**
104595**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
104596**                 \________/       \________________/
104597**                  pTabList              pWhere
104598*/
104599SQLITE_PRIVATE void sqlite3DeleteFrom(
104600  Parse *pParse,         /* The parser context */
104601  SrcList *pTabList,     /* The table from which we should delete things */
104602  Expr *pWhere           /* The WHERE clause.  May be null */
104603){
104604  Vdbe *v;               /* The virtual database engine */
104605  Table *pTab;           /* The table from which records will be deleted */
104606  int i;                 /* Loop counter */
104607  WhereInfo *pWInfo;     /* Information about the WHERE clause */
104608  Index *pIdx;           /* For looping over indices of the table */
104609  int iTabCur;           /* Cursor number for the table */
104610  int iDataCur = 0;      /* VDBE cursor for the canonical data source */
104611  int iIdxCur = 0;       /* Cursor number of the first index */
104612  int nIdx;              /* Number of indices */
104613  sqlite3 *db;           /* Main database structure */
104614  AuthContext sContext;  /* Authorization context */
104615  NameContext sNC;       /* Name context to resolve expressions in */
104616  int iDb;               /* Database number */
104617  int memCnt = -1;       /* Memory cell used for change counting */
104618  int rcauth;            /* Value returned by authorization callback */
104619  int eOnePass;          /* ONEPASS_OFF or _SINGLE or _MULTI */
104620  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
104621  u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
104622  Index *pPk;            /* The PRIMARY KEY index on the table */
104623  int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
104624  i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
104625  int iKey;              /* Memory cell holding key of row to be deleted */
104626  i16 nKey;              /* Number of memory cells in the row key */
104627  int iEphCur = 0;       /* Ephemeral table holding all primary key values */
104628  int iRowSet = 0;       /* Register for rowset of rows to delete */
104629  int addrBypass = 0;    /* Address of jump over the delete logic */
104630  int addrLoop = 0;      /* Top of the delete loop */
104631  int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
104632  int bComplex;          /* True if there are triggers or FKs or
104633                         ** subqueries in the WHERE clause */
104634
104635#ifndef SQLITE_OMIT_TRIGGER
104636  int isView;                  /* True if attempting to delete from a view */
104637  Trigger *pTrigger;           /* List of table triggers, if required */
104638#endif
104639
104640  memset(&sContext, 0, sizeof(sContext));
104641  db = pParse->db;
104642  if( pParse->nErr || db->mallocFailed ){
104643    goto delete_from_cleanup;
104644  }
104645  assert( pTabList->nSrc==1 );
104646
104647  /* Locate the table which we want to delete.  This table has to be
104648  ** put in an SrcList structure because some of the subroutines we
104649  ** will be calling are designed to work with multiple tables and expect
104650  ** an SrcList* parameter instead of just a Table* parameter.
104651  */
104652  pTab = sqlite3SrcListLookup(pParse, pTabList);
104653  if( pTab==0 )  goto delete_from_cleanup;
104654
104655  /* Figure out if we have any triggers and if the table being
104656  ** deleted from is a view
104657  */
104658#ifndef SQLITE_OMIT_TRIGGER
104659  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
104660  isView = pTab->pSelect!=0;
104661  bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
104662#else
104663# define pTrigger 0
104664# define isView 0
104665#endif
104666#ifdef SQLITE_OMIT_VIEW
104667# undef isView
104668# define isView 0
104669#endif
104670
104671  /* If pTab is really a view, make sure it has been initialized.
104672  */
104673  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
104674    goto delete_from_cleanup;
104675  }
104676
104677  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
104678    goto delete_from_cleanup;
104679  }
104680  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
104681  assert( iDb<db->nDb );
104682  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
104683                            db->aDb[iDb].zDbSName);
104684  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
104685  if( rcauth==SQLITE_DENY ){
104686    goto delete_from_cleanup;
104687  }
104688  assert(!isView || pTrigger);
104689
104690  /* Assign cursor numbers to the table and all its indices.
104691  */
104692  assert( pTabList->nSrc==1 );
104693  iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
104694  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
104695    pParse->nTab++;
104696  }
104697
104698  /* Start the view context
104699  */
104700  if( isView ){
104701    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
104702  }
104703
104704  /* Begin generating code.
104705  */
104706  v = sqlite3GetVdbe(pParse);
104707  if( v==0 ){
104708    goto delete_from_cleanup;
104709  }
104710  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
104711  sqlite3BeginWriteOperation(pParse, 1, iDb);
104712
104713  /* If we are trying to delete from a view, realize that view into
104714  ** an ephemeral table.
104715  */
104716#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
104717  if( isView ){
104718    sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
104719    iDataCur = iIdxCur = iTabCur;
104720  }
104721#endif
104722
104723  /* Resolve the column names in the WHERE clause.
104724  */
104725  memset(&sNC, 0, sizeof(sNC));
104726  sNC.pParse = pParse;
104727  sNC.pSrcList = pTabList;
104728  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
104729    goto delete_from_cleanup;
104730  }
104731
104732  /* Initialize the counter of the number of rows deleted, if
104733  ** we are counting rows.
104734  */
104735  if( db->flags & SQLITE_CountRows ){
104736    memCnt = ++pParse->nMem;
104737    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
104738  }
104739
104740#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
104741  /* Special case: A DELETE without a WHERE clause deletes everything.
104742  ** It is easier just to erase the whole table. Prior to version 3.6.5,
104743  ** this optimization caused the row change count (the value returned by
104744  ** API function sqlite3_count_changes) to be set incorrectly.  */
104745  if( rcauth==SQLITE_OK
104746   && pWhere==0
104747   && !bComplex
104748   && !IsVirtual(pTab)
104749#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
104750   && db->xPreUpdateCallback==0
104751#endif
104752  ){
104753    assert( !isView );
104754    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
104755    if( HasRowid(pTab) ){
104756      sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
104757                        pTab->zName, P4_STATIC);
104758    }
104759    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
104760      assert( pIdx->pSchema==pTab->pSchema );
104761      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
104762    }
104763  }else
104764#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
104765  {
104766    u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
104767    if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
104768    wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
104769    if( HasRowid(pTab) ){
104770      /* For a rowid table, initialize the RowSet to an empty set */
104771      pPk = 0;
104772      nPk = 1;
104773      iRowSet = ++pParse->nMem;
104774      sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
104775    }else{
104776      /* For a WITHOUT ROWID table, create an ephemeral table used to
104777      ** hold all primary keys for rows to be deleted. */
104778      pPk = sqlite3PrimaryKeyIndex(pTab);
104779      assert( pPk!=0 );
104780      nPk = pPk->nKeyCol;
104781      iPk = pParse->nMem+1;
104782      pParse->nMem += nPk;
104783      iEphCur = pParse->nTab++;
104784      addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
104785      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
104786    }
104787
104788    /* Construct a query to find the rowid or primary key for every row
104789    ** to be deleted, based on the WHERE clause. Set variable eOnePass
104790    ** to indicate the strategy used to implement this delete:
104791    **
104792    **  ONEPASS_OFF:    Two-pass approach - use a FIFO for rowids/PK values.
104793    **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.
104794    **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.
104795    */
104796    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
104797    if( pWInfo==0 ) goto delete_from_cleanup;
104798    eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
104799    assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
104800    assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
104801
104802    /* Keep track of the number of rows to be deleted */
104803    if( db->flags & SQLITE_CountRows ){
104804      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
104805    }
104806
104807    /* Extract the rowid or primary key for the current row */
104808    if( pPk ){
104809      for(i=0; i<nPk; i++){
104810        assert( pPk->aiColumn[i]>=0 );
104811        sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
104812                                        pPk->aiColumn[i], iPk+i);
104813      }
104814      iKey = iPk;
104815    }else{
104816      iKey = pParse->nMem + 1;
104817      iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
104818      if( iKey>pParse->nMem ) pParse->nMem = iKey;
104819    }
104820
104821    if( eOnePass!=ONEPASS_OFF ){
104822      /* For ONEPASS, no need to store the rowid/primary-key. There is only
104823      ** one, so just keep it in its register(s) and fall through to the
104824      ** delete code.  */
104825      nKey = nPk; /* OP_Found will use an unpacked key */
104826      aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
104827      if( aToOpen==0 ){
104828        sqlite3WhereEnd(pWInfo);
104829        goto delete_from_cleanup;
104830      }
104831      memset(aToOpen, 1, nIdx+1);
104832      aToOpen[nIdx+1] = 0;
104833      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
104834      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
104835      if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
104836    }else{
104837      if( pPk ){
104838        /* Add the PK key for this row to the temporary table */
104839        iKey = ++pParse->nMem;
104840        nKey = 0;   /* Zero tells OP_Found to use a composite key */
104841        sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
104842            sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
104843        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
104844      }else{
104845        /* Add the rowid of the row to be deleted to the RowSet */
104846        nKey = 1;  /* OP_Seek always uses a single rowid */
104847        sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
104848      }
104849    }
104850
104851    /* If this DELETE cannot use the ONEPASS strategy, this is the
104852    ** end of the WHERE loop */
104853    if( eOnePass!=ONEPASS_OFF ){
104854      addrBypass = sqlite3VdbeMakeLabel(v);
104855    }else{
104856      sqlite3WhereEnd(pWInfo);
104857    }
104858
104859    /* Unless this is a view, open cursors for the table we are
104860    ** deleting from and all its indices. If this is a view, then the
104861    ** only effect this statement has is to fire the INSTEAD OF
104862    ** triggers.
104863    */
104864    if( !isView ){
104865      int iAddrOnce = 0;
104866      if( eOnePass==ONEPASS_MULTI ){
104867        iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
104868      }
104869      testcase( IsVirtual(pTab) );
104870      sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
104871                                 iTabCur, aToOpen, &iDataCur, &iIdxCur);
104872      assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
104873      assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
104874      if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
104875    }
104876
104877    /* Set up a loop over the rowids/primary-keys that were found in the
104878    ** where-clause loop above.
104879    */
104880    if( eOnePass!=ONEPASS_OFF ){
104881      assert( nKey==nPk );  /* OP_Found will use an unpacked key */
104882      if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
104883        assert( pPk!=0 || pTab->pSelect!=0 );
104884        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
104885        VdbeCoverage(v);
104886      }
104887    }else if( pPk ){
104888      addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
104889      sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
104890      assert( nKey==0 );  /* OP_Found will use a composite key */
104891    }else{
104892      addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
104893      VdbeCoverage(v);
104894      assert( nKey==1 );
104895    }
104896
104897    /* Delete the row */
104898#ifndef SQLITE_OMIT_VIRTUALTABLE
104899    if( IsVirtual(pTab) ){
104900      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
104901      sqlite3VtabMakeWritable(pParse, pTab);
104902      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
104903      sqlite3VdbeChangeP5(v, OE_Abort);
104904      assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
104905      sqlite3MayAbort(pParse);
104906      if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
104907        pParse->isMultiWrite = 0;
104908      }
104909    }else
104910#endif
104911    {
104912      int count = (pParse->nested==0);    /* True to count changes */
104913      sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
104914          iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
104915    }
104916
104917    /* End of the loop over all rowids/primary-keys. */
104918    if( eOnePass!=ONEPASS_OFF ){
104919      sqlite3VdbeResolveLabel(v, addrBypass);
104920      sqlite3WhereEnd(pWInfo);
104921    }else if( pPk ){
104922      sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
104923      sqlite3VdbeJumpHere(v, addrLoop);
104924    }else{
104925      sqlite3VdbeGoto(v, addrLoop);
104926      sqlite3VdbeJumpHere(v, addrLoop);
104927    }
104928  } /* End non-truncate path */
104929
104930  /* Update the sqlite_sequence table by storing the content of the
104931  ** maximum rowid counter values recorded while inserting into
104932  ** autoincrement tables.
104933  */
104934  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
104935    sqlite3AutoincrementEnd(pParse);
104936  }
104937
104938  /* Return the number of rows that were deleted. If this routine is
104939  ** generating code because of a call to sqlite3NestedParse(), do not
104940  ** invoke the callback function.
104941  */
104942  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
104943    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
104944    sqlite3VdbeSetNumCols(v, 1);
104945    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
104946  }
104947
104948delete_from_cleanup:
104949  sqlite3AuthContextPop(&sContext);
104950  sqlite3SrcListDelete(db, pTabList);
104951  sqlite3ExprDelete(db, pWhere);
104952  sqlite3DbFree(db, aToOpen);
104953  return;
104954}
104955/* Make sure "isView" and other macros defined above are undefined. Otherwise
104956** they may interfere with compilation of other functions in this file
104957** (or in another file, if this file becomes part of the amalgamation).  */
104958#ifdef isView
104959 #undef isView
104960#endif
104961#ifdef pTrigger
104962 #undef pTrigger
104963#endif
104964
104965/*
104966** This routine generates VDBE code that causes a single row of a
104967** single table to be deleted.  Both the original table entry and
104968** all indices are removed.
104969**
104970** Preconditions:
104971**
104972**   1.  iDataCur is an open cursor on the btree that is the canonical data
104973**       store for the table.  (This will be either the table itself,
104974**       in the case of a rowid table, or the PRIMARY KEY index in the case
104975**       of a WITHOUT ROWID table.)
104976**
104977**   2.  Read/write cursors for all indices of pTab must be open as
104978**       cursor number iIdxCur+i for the i-th index.
104979**
104980**   3.  The primary key for the row to be deleted must be stored in a
104981**       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
104982**       that a search record formed from OP_MakeRecord is contained in the
104983**       single memory location iPk.
104984**
104985** eMode:
104986**   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
104987**   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor
104988**   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
104989**   then this function must seek iDataCur to the entry identified by iPk
104990**   and nPk before reading from it.
104991**
104992**   If eMode is ONEPASS_MULTI, then this call is being made as part
104993**   of a ONEPASS delete that affects multiple rows. In this case, if
104994**   iIdxNoSeek is a valid cursor number (>=0) and is not the same as
104995**   iDataCur, then its position should be preserved following the delete
104996**   operation. Or, if iIdxNoSeek is not a valid cursor number, the
104997**   position of iDataCur should be preserved instead.
104998**
104999** iIdxNoSeek:
105000**   If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
105001**   then it identifies an index cursor (from within array of cursors
105002**   starting at iIdxCur) that already points to the index entry to be deleted.
105003**   Except, this optimization is disabled if there are BEFORE triggers since
105004**   the trigger body might have moved the cursor.
105005*/
105006SQLITE_PRIVATE void sqlite3GenerateRowDelete(
105007  Parse *pParse,     /* Parsing context */
105008  Table *pTab,       /* Table containing the row to be deleted */
105009  Trigger *pTrigger, /* List of triggers to (potentially) fire */
105010  int iDataCur,      /* Cursor from which column data is extracted */
105011  int iIdxCur,       /* First index cursor */
105012  int iPk,           /* First memory cell containing the PRIMARY KEY */
105013  i16 nPk,           /* Number of PRIMARY KEY memory cells */
105014  u8 count,          /* If non-zero, increment the row change counter */
105015  u8 onconf,         /* Default ON CONFLICT policy for triggers */
105016  u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */
105017  int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */
105018){
105019  Vdbe *v = pParse->pVdbe;        /* Vdbe */
105020  int iOld = 0;                   /* First register in OLD.* array */
105021  int iLabel;                     /* Label resolved to end of generated code */
105022  u8 opSeek;                      /* Seek opcode */
105023
105024  /* Vdbe is guaranteed to have been allocated by this stage. */
105025  assert( v );
105026  VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
105027                         iDataCur, iIdxCur, iPk, (int)nPk));
105028
105029  /* Seek cursor iCur to the row to delete. If this row no longer exists
105030  ** (this can happen if a trigger program has already deleted it), do
105031  ** not attempt to delete it or fire any DELETE triggers.  */
105032  iLabel = sqlite3VdbeMakeLabel(v);
105033  opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
105034  if( eMode==ONEPASS_OFF ){
105035    sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
105036    VdbeCoverageIf(v, opSeek==OP_NotExists);
105037    VdbeCoverageIf(v, opSeek==OP_NotFound);
105038  }
105039
105040  /* If there are any triggers to fire, allocate a range of registers to
105041  ** use for the old.* references in the triggers.  */
105042  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
105043    u32 mask;                     /* Mask of OLD.* columns in use */
105044    int iCol;                     /* Iterator used while populating OLD.* */
105045    int addrStart;                /* Start of BEFORE trigger programs */
105046
105047    /* TODO: Could use temporary registers here. Also could attempt to
105048    ** avoid copying the contents of the rowid register.  */
105049    mask = sqlite3TriggerColmask(
105050        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
105051    );
105052    mask |= sqlite3FkOldmask(pParse, pTab);
105053    iOld = pParse->nMem+1;
105054    pParse->nMem += (1 + pTab->nCol);
105055
105056    /* Populate the OLD.* pseudo-table register array. These values will be
105057    ** used by any BEFORE and AFTER triggers that exist.  */
105058    sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
105059    for(iCol=0; iCol<pTab->nCol; iCol++){
105060      testcase( mask!=0xffffffff && iCol==31 );
105061      testcase( mask!=0xffffffff && iCol==32 );
105062      if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
105063        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
105064      }
105065    }
105066
105067    /* Invoke BEFORE DELETE trigger programs. */
105068    addrStart = sqlite3VdbeCurrentAddr(v);
105069    sqlite3CodeRowTrigger(pParse, pTrigger,
105070        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
105071    );
105072
105073    /* If any BEFORE triggers were coded, then seek the cursor to the
105074    ** row to be deleted again. It may be that the BEFORE triggers moved
105075    ** the cursor or already deleted the row that the cursor was
105076    ** pointing to.
105077    **
105078    ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
105079    ** may have moved that cursor.
105080    */
105081    if( addrStart<sqlite3VdbeCurrentAddr(v) ){
105082      sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
105083      VdbeCoverageIf(v, opSeek==OP_NotExists);
105084      VdbeCoverageIf(v, opSeek==OP_NotFound);
105085      testcase( iIdxNoSeek>=0 );
105086      iIdxNoSeek = -1;
105087    }
105088
105089    /* Do FK processing. This call checks that any FK constraints that
105090    ** refer to this table (i.e. constraints attached to other tables)
105091    ** are not violated by deleting this row.  */
105092    sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
105093  }
105094
105095  /* Delete the index and table entries. Skip this step if pTab is really
105096  ** a view (in which case the only effect of the DELETE statement is to
105097  ** fire the INSTEAD OF triggers).
105098  **
105099  ** If variable 'count' is non-zero, then this OP_Delete instruction should
105100  ** invoke the update-hook. The pre-update-hook, on the other hand should
105101  ** be invoked unless table pTab is a system table. The difference is that
105102  ** the update-hook is not invoked for rows removed by REPLACE, but the
105103  ** pre-update-hook is.
105104  */
105105  if( pTab->pSelect==0 ){
105106    u8 p5 = 0;
105107    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
105108    sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
105109    if( pParse->nested==0 ){
105110      sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
105111    }
105112    if( eMode!=ONEPASS_OFF ){
105113      sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
105114    }
105115    if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
105116      sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
105117    }
105118    if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
105119    sqlite3VdbeChangeP5(v, p5);
105120  }
105121
105122  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
105123  ** handle rows (possibly in other tables) that refer via a foreign key
105124  ** to the row just deleted. */
105125  sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
105126
105127  /* Invoke AFTER DELETE trigger programs. */
105128  sqlite3CodeRowTrigger(pParse, pTrigger,
105129      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
105130  );
105131
105132  /* Jump here if the row had already been deleted before any BEFORE
105133  ** trigger programs were invoked. Or if a trigger program throws a
105134  ** RAISE(IGNORE) exception.  */
105135  sqlite3VdbeResolveLabel(v, iLabel);
105136  VdbeModuleComment((v, "END: GenRowDel()"));
105137}
105138
105139/*
105140** This routine generates VDBE code that causes the deletion of all
105141** index entries associated with a single row of a single table, pTab
105142**
105143** Preconditions:
105144**
105145**   1.  A read/write cursor "iDataCur" must be open on the canonical storage
105146**       btree for the table pTab.  (This will be either the table itself
105147**       for rowid tables or to the primary key index for WITHOUT ROWID
105148**       tables.)
105149**
105150**   2.  Read/write cursors for all indices of pTab must be open as
105151**       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
105152**       index is the 0-th index.)
105153**
105154**   3.  The "iDataCur" cursor must be already be positioned on the row
105155**       that is to be deleted.
105156*/
105157SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
105158  Parse *pParse,     /* Parsing and code generating context */
105159  Table *pTab,       /* Table containing the row to be deleted */
105160  int iDataCur,      /* Cursor of table holding data. */
105161  int iIdxCur,       /* First index cursor */
105162  int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
105163  int iIdxNoSeek     /* Do not delete from this cursor */
105164){
105165  int i;             /* Index loop counter */
105166  int r1 = -1;       /* Register holding an index key */
105167  int iPartIdxLabel; /* Jump destination for skipping partial index entries */
105168  Index *pIdx;       /* Current index */
105169  Index *pPrior = 0; /* Prior index */
105170  Vdbe *v;           /* The prepared statement under construction */
105171  Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
105172
105173  v = pParse->pVdbe;
105174  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
105175  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
105176    assert( iIdxCur+i!=iDataCur || pPk==pIdx );
105177    if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
105178    if( pIdx==pPk ) continue;
105179    if( iIdxCur+i==iIdxNoSeek ) continue;
105180    VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
105181    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
105182        &iPartIdxLabel, pPrior, r1);
105183    sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
105184        pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
105185    sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
105186    pPrior = pIdx;
105187  }
105188}
105189
105190/*
105191** Generate code that will assemble an index key and stores it in register
105192** regOut.  The key with be for index pIdx which is an index on pTab.
105193** iCur is the index of a cursor open on the pTab table and pointing to
105194** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
105195** iCur must be the cursor of the PRIMARY KEY index.
105196**
105197** Return a register number which is the first in a block of
105198** registers that holds the elements of the index key.  The
105199** block of registers has already been deallocated by the time
105200** this routine returns.
105201**
105202** If *piPartIdxLabel is not NULL, fill it in with a label and jump
105203** to that label if pIdx is a partial index that should be skipped.
105204** The label should be resolved using sqlite3ResolvePartIdxLabel().
105205** A partial index should be skipped if its WHERE clause evaluates
105206** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
105207** will be set to zero which is an empty label that is ignored by
105208** sqlite3ResolvePartIdxLabel().
105209**
105210** The pPrior and regPrior parameters are used to implement a cache to
105211** avoid unnecessary register loads.  If pPrior is not NULL, then it is
105212** a pointer to a different index for which an index key has just been
105213** computed into register regPrior.  If the current pIdx index is generating
105214** its key into the same sequence of registers and if pPrior and pIdx share
105215** a column in common, then the register corresponding to that column already
105216** holds the correct value and the loading of that register is skipped.
105217** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
105218** on a table with multiple indices, and especially with the ROWID or
105219** PRIMARY KEY columns of the index.
105220*/
105221SQLITE_PRIVATE int sqlite3GenerateIndexKey(
105222  Parse *pParse,       /* Parsing context */
105223  Index *pIdx,         /* The index for which to generate a key */
105224  int iDataCur,        /* Cursor number from which to take column data */
105225  int regOut,          /* Put the new key into this register if not 0 */
105226  int prefixOnly,      /* Compute only a unique prefix of the key */
105227  int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
105228  Index *pPrior,       /* Previously generated index key */
105229  int regPrior         /* Register holding previous generated key */
105230){
105231  Vdbe *v = pParse->pVdbe;
105232  int j;
105233  int regBase;
105234  int nCol;
105235
105236  if( piPartIdxLabel ){
105237    if( pIdx->pPartIdxWhere ){
105238      *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
105239      pParse->iSelfTab = iDataCur;
105240      sqlite3ExprCachePush(pParse);
105241      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
105242                            SQLITE_JUMPIFNULL);
105243    }else{
105244      *piPartIdxLabel = 0;
105245    }
105246  }
105247  nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
105248  regBase = sqlite3GetTempRange(pParse, nCol);
105249  if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
105250  for(j=0; j<nCol; j++){
105251    if( pPrior
105252     && pPrior->aiColumn[j]==pIdx->aiColumn[j]
105253     && pPrior->aiColumn[j]!=XN_EXPR
105254    ){
105255      /* This column was already computed by the previous index */
105256      continue;
105257    }
105258    sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
105259    /* If the column affinity is REAL but the number is an integer, then it
105260    ** might be stored in the table as an integer (using a compact
105261    ** representation) then converted to REAL by an OP_RealAffinity opcode.
105262    ** But we are getting ready to store this value back into an index, where
105263    ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
105264    ** opcode if it is present */
105265    sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
105266  }
105267  if( regOut ){
105268    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
105269    if( pIdx->pTable->pSelect ){
105270      const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
105271      sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
105272    }
105273  }
105274  sqlite3ReleaseTempRange(pParse, regBase, nCol);
105275  return regBase;
105276}
105277
105278/*
105279** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
105280** because it was a partial index, then this routine should be called to
105281** resolve that label.
105282*/
105283SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
105284  if( iLabel ){
105285    sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
105286    sqlite3ExprCachePop(pParse);
105287  }
105288}
105289
105290/************** End of delete.c **********************************************/
105291/************** Begin file func.c ********************************************/
105292/*
105293** 2002 February 23
105294**
105295** The author disclaims copyright to this source code.  In place of
105296** a legal notice, here is a blessing:
105297**
105298**    May you do good and not evil.
105299**    May you find forgiveness for yourself and forgive others.
105300**    May you share freely, never taking more than you give.
105301**
105302*************************************************************************
105303** This file contains the C-language implementations for many of the SQL
105304** functions of SQLite.  (Some function, and in particular the date and
105305** time functions, are implemented separately.)
105306*/
105307/* #include "sqliteInt.h" */
105308/* #include <stdlib.h> */
105309/* #include <assert.h> */
105310/* #include "vdbeInt.h" */
105311
105312/*
105313** Return the collating function associated with a function.
105314*/
105315static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
105316  VdbeOp *pOp;
105317  assert( context->pVdbe!=0 );
105318  pOp = &context->pVdbe->aOp[context->iOp-1];
105319  assert( pOp->opcode==OP_CollSeq );
105320  assert( pOp->p4type==P4_COLLSEQ );
105321  return pOp->p4.pColl;
105322}
105323
105324/*
105325** Indicate that the accumulator load should be skipped on this
105326** iteration of the aggregate loop.
105327*/
105328static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
105329  context->skipFlag = 1;
105330}
105331
105332/*
105333** Implementation of the non-aggregate min() and max() functions
105334*/
105335static void minmaxFunc(
105336  sqlite3_context *context,
105337  int argc,
105338  sqlite3_value **argv
105339){
105340  int i;
105341  int mask;    /* 0 for min() or 0xffffffff for max() */
105342  int iBest;
105343  CollSeq *pColl;
105344
105345  assert( argc>1 );
105346  mask = sqlite3_user_data(context)==0 ? 0 : -1;
105347  pColl = sqlite3GetFuncCollSeq(context);
105348  assert( pColl );
105349  assert( mask==-1 || mask==0 );
105350  iBest = 0;
105351  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
105352  for(i=1; i<argc; i++){
105353    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
105354    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
105355      testcase( mask==0 );
105356      iBest = i;
105357    }
105358  }
105359  sqlite3_result_value(context, argv[iBest]);
105360}
105361
105362/*
105363** Return the type of the argument.
105364*/
105365static void typeofFunc(
105366  sqlite3_context *context,
105367  int NotUsed,
105368  sqlite3_value **argv
105369){
105370  const char *z = 0;
105371  UNUSED_PARAMETER(NotUsed);
105372  switch( sqlite3_value_type(argv[0]) ){
105373    case SQLITE_INTEGER: z = "integer"; break;
105374    case SQLITE_TEXT:    z = "text";    break;
105375    case SQLITE_FLOAT:   z = "real";    break;
105376    case SQLITE_BLOB:    z = "blob";    break;
105377    default:             z = "null";    break;
105378  }
105379  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
105380}
105381
105382
105383/*
105384** Implementation of the length() function
105385*/
105386static void lengthFunc(
105387  sqlite3_context *context,
105388  int argc,
105389  sqlite3_value **argv
105390){
105391  int len;
105392
105393  assert( argc==1 );
105394  UNUSED_PARAMETER(argc);
105395  switch( sqlite3_value_type(argv[0]) ){
105396    case SQLITE_BLOB:
105397    case SQLITE_INTEGER:
105398    case SQLITE_FLOAT: {
105399      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
105400      break;
105401    }
105402    case SQLITE_TEXT: {
105403      const unsigned char *z = sqlite3_value_text(argv[0]);
105404      if( z==0 ) return;
105405      len = 0;
105406      while( *z ){
105407        len++;
105408        SQLITE_SKIP_UTF8(z);
105409      }
105410      sqlite3_result_int(context, len);
105411      break;
105412    }
105413    default: {
105414      sqlite3_result_null(context);
105415      break;
105416    }
105417  }
105418}
105419
105420/*
105421** Implementation of the abs() function.
105422**
105423** IMP: R-23979-26855 The abs(X) function returns the absolute value of
105424** the numeric argument X.
105425*/
105426static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
105427  assert( argc==1 );
105428  UNUSED_PARAMETER(argc);
105429  switch( sqlite3_value_type(argv[0]) ){
105430    case SQLITE_INTEGER: {
105431      i64 iVal = sqlite3_value_int64(argv[0]);
105432      if( iVal<0 ){
105433        if( iVal==SMALLEST_INT64 ){
105434          /* IMP: R-31676-45509 If X is the integer -9223372036854775808
105435          ** then abs(X) throws an integer overflow error since there is no
105436          ** equivalent positive 64-bit two complement value. */
105437          sqlite3_result_error(context, "integer overflow", -1);
105438          return;
105439        }
105440        iVal = -iVal;
105441      }
105442      sqlite3_result_int64(context, iVal);
105443      break;
105444    }
105445    case SQLITE_NULL: {
105446      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
105447      sqlite3_result_null(context);
105448      break;
105449    }
105450    default: {
105451      /* Because sqlite3_value_double() returns 0.0 if the argument is not
105452      ** something that can be converted into a number, we have:
105453      ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
105454      ** that cannot be converted to a numeric value.
105455      */
105456      double rVal = sqlite3_value_double(argv[0]);
105457      if( rVal<0 ) rVal = -rVal;
105458      sqlite3_result_double(context, rVal);
105459      break;
105460    }
105461  }
105462}
105463
105464/*
105465** Implementation of the instr() function.
105466**
105467** instr(haystack,needle) finds the first occurrence of needle
105468** in haystack and returns the number of previous characters plus 1,
105469** or 0 if needle does not occur within haystack.
105470**
105471** If both haystack and needle are BLOBs, then the result is one more than
105472** the number of bytes in haystack prior to the first occurrence of needle,
105473** or 0 if needle never occurs in haystack.
105474*/
105475static void instrFunc(
105476  sqlite3_context *context,
105477  int argc,
105478  sqlite3_value **argv
105479){
105480  const unsigned char *zHaystack;
105481  const unsigned char *zNeedle;
105482  int nHaystack;
105483  int nNeedle;
105484  int typeHaystack, typeNeedle;
105485  int N = 1;
105486  int isText;
105487
105488  UNUSED_PARAMETER(argc);
105489  typeHaystack = sqlite3_value_type(argv[0]);
105490  typeNeedle = sqlite3_value_type(argv[1]);
105491  if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
105492  nHaystack = sqlite3_value_bytes(argv[0]);
105493  nNeedle = sqlite3_value_bytes(argv[1]);
105494  if( nNeedle>0 ){
105495    if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
105496      zHaystack = sqlite3_value_blob(argv[0]);
105497      zNeedle = sqlite3_value_blob(argv[1]);
105498      isText = 0;
105499    }else{
105500      zHaystack = sqlite3_value_text(argv[0]);
105501      zNeedle = sqlite3_value_text(argv[1]);
105502      isText = 1;
105503    }
105504    if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
105505    while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
105506      N++;
105507      do{
105508        nHaystack--;
105509        zHaystack++;
105510      }while( isText && (zHaystack[0]&0xc0)==0x80 );
105511    }
105512    if( nNeedle>nHaystack ) N = 0;
105513  }
105514  sqlite3_result_int(context, N);
105515}
105516
105517/*
105518** Implementation of the printf() function.
105519*/
105520static void printfFunc(
105521  sqlite3_context *context,
105522  int argc,
105523  sqlite3_value **argv
105524){
105525  PrintfArguments x;
105526  StrAccum str;
105527  const char *zFormat;
105528  int n;
105529  sqlite3 *db = sqlite3_context_db_handle(context);
105530
105531  if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
105532    x.nArg = argc-1;
105533    x.nUsed = 0;
105534    x.apArg = argv+1;
105535    sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
105536    str.printfFlags = SQLITE_PRINTF_SQLFUNC;
105537    sqlite3XPrintf(&str, zFormat, &x);
105538    n = str.nChar;
105539    sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
105540                        SQLITE_DYNAMIC);
105541  }
105542}
105543
105544/*
105545** Implementation of the substr() function.
105546**
105547** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
105548** p1 is 1-indexed.  So substr(x,1,1) returns the first character
105549** of x.  If x is text, then we actually count UTF-8 characters.
105550** If x is a blob, then we count bytes.
105551**
105552** If p1 is negative, then we begin abs(p1) from the end of x[].
105553**
105554** If p2 is negative, return the p2 characters preceding p1.
105555*/
105556static void substrFunc(
105557  sqlite3_context *context,
105558  int argc,
105559  sqlite3_value **argv
105560){
105561  const unsigned char *z;
105562  const unsigned char *z2;
105563  int len;
105564  int p0type;
105565  i64 p1, p2;
105566  int negP2 = 0;
105567
105568  assert( argc==3 || argc==2 );
105569  if( sqlite3_value_type(argv[1])==SQLITE_NULL
105570   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
105571  ){
105572    return;
105573  }
105574  p0type = sqlite3_value_type(argv[0]);
105575  p1 = sqlite3_value_int(argv[1]);
105576  if( p0type==SQLITE_BLOB ){
105577    len = sqlite3_value_bytes(argv[0]);
105578    z = sqlite3_value_blob(argv[0]);
105579    if( z==0 ) return;
105580    assert( len==sqlite3_value_bytes(argv[0]) );
105581  }else{
105582    z = sqlite3_value_text(argv[0]);
105583    if( z==0 ) return;
105584    len = 0;
105585    if( p1<0 ){
105586      for(z2=z; *z2; len++){
105587        SQLITE_SKIP_UTF8(z2);
105588      }
105589    }
105590  }
105591#ifdef SQLITE_SUBSTR_COMPATIBILITY
105592  /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
105593  ** as substr(X,1,N) - it returns the first N characters of X.  This
105594  ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
105595  ** from 2009-02-02 for compatibility of applications that exploited the
105596  ** old buggy behavior. */
105597  if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
105598#endif
105599  if( argc==3 ){
105600    p2 = sqlite3_value_int(argv[2]);
105601    if( p2<0 ){
105602      p2 = -p2;
105603      negP2 = 1;
105604    }
105605  }else{
105606    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
105607  }
105608  if( p1<0 ){
105609    p1 += len;
105610    if( p1<0 ){
105611      p2 += p1;
105612      if( p2<0 ) p2 = 0;
105613      p1 = 0;
105614    }
105615  }else if( p1>0 ){
105616    p1--;
105617  }else if( p2>0 ){
105618    p2--;
105619  }
105620  if( negP2 ){
105621    p1 -= p2;
105622    if( p1<0 ){
105623      p2 += p1;
105624      p1 = 0;
105625    }
105626  }
105627  assert( p1>=0 && p2>=0 );
105628  if( p0type!=SQLITE_BLOB ){
105629    while( *z && p1 ){
105630      SQLITE_SKIP_UTF8(z);
105631      p1--;
105632    }
105633    for(z2=z; *z2 && p2; p2--){
105634      SQLITE_SKIP_UTF8(z2);
105635    }
105636    sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
105637                          SQLITE_UTF8);
105638  }else{
105639    if( p1+p2>len ){
105640      p2 = len-p1;
105641      if( p2<0 ) p2 = 0;
105642    }
105643    sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
105644  }
105645}
105646
105647/*
105648** Implementation of the round() function
105649*/
105650#ifndef SQLITE_OMIT_FLOATING_POINT
105651static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
105652  int n = 0;
105653  double r;
105654  char *zBuf;
105655  assert( argc==1 || argc==2 );
105656  if( argc==2 ){
105657    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
105658    n = sqlite3_value_int(argv[1]);
105659    if( n>30 ) n = 30;
105660    if( n<0 ) n = 0;
105661  }
105662  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
105663  r = sqlite3_value_double(argv[0]);
105664  /* If Y==0 and X will fit in a 64-bit int,
105665  ** handle the rounding directly,
105666  ** otherwise use printf.
105667  */
105668  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
105669    r = (double)((sqlite_int64)(r+0.5));
105670  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
105671    r = -(double)((sqlite_int64)((-r)+0.5));
105672  }else{
105673    zBuf = sqlite3_mprintf("%.*f",n,r);
105674    if( zBuf==0 ){
105675      sqlite3_result_error_nomem(context);
105676      return;
105677    }
105678    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
105679    sqlite3_free(zBuf);
105680  }
105681  sqlite3_result_double(context, r);
105682}
105683#endif
105684
105685/*
105686** Allocate nByte bytes of space using sqlite3Malloc(). If the
105687** allocation fails, call sqlite3_result_error_nomem() to notify
105688** the database handle that malloc() has failed and return NULL.
105689** If nByte is larger than the maximum string or blob length, then
105690** raise an SQLITE_TOOBIG exception and return NULL.
105691*/
105692static void *contextMalloc(sqlite3_context *context, i64 nByte){
105693  char *z;
105694  sqlite3 *db = sqlite3_context_db_handle(context);
105695  assert( nByte>0 );
105696  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
105697  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
105698  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
105699    sqlite3_result_error_toobig(context);
105700    z = 0;
105701  }else{
105702    z = sqlite3Malloc(nByte);
105703    if( !z ){
105704      sqlite3_result_error_nomem(context);
105705    }
105706  }
105707  return z;
105708}
105709
105710/*
105711** Implementation of the upper() and lower() SQL functions.
105712*/
105713static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
105714  char *z1;
105715  const char *z2;
105716  int i, n;
105717  UNUSED_PARAMETER(argc);
105718  z2 = (char*)sqlite3_value_text(argv[0]);
105719  n = sqlite3_value_bytes(argv[0]);
105720  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
105721  assert( z2==(char*)sqlite3_value_text(argv[0]) );
105722  if( z2 ){
105723    z1 = contextMalloc(context, ((i64)n)+1);
105724    if( z1 ){
105725      for(i=0; i<n; i++){
105726        z1[i] = (char)sqlite3Toupper(z2[i]);
105727      }
105728      sqlite3_result_text(context, z1, n, sqlite3_free);
105729    }
105730  }
105731}
105732static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
105733  char *z1;
105734  const char *z2;
105735  int i, n;
105736  UNUSED_PARAMETER(argc);
105737  z2 = (char*)sqlite3_value_text(argv[0]);
105738  n = sqlite3_value_bytes(argv[0]);
105739  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
105740  assert( z2==(char*)sqlite3_value_text(argv[0]) );
105741  if( z2 ){
105742    z1 = contextMalloc(context, ((i64)n)+1);
105743    if( z1 ){
105744      for(i=0; i<n; i++){
105745        z1[i] = sqlite3Tolower(z2[i]);
105746      }
105747      sqlite3_result_text(context, z1, n, sqlite3_free);
105748    }
105749  }
105750}
105751
105752/*
105753** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
105754** as VDBE code so that unused argument values do not have to be computed.
105755** However, we still need some kind of function implementation for this
105756** routines in the function table.  The noopFunc macro provides this.
105757** noopFunc will never be called so it doesn't matter what the implementation
105758** is.  We might as well use the "version()" function as a substitute.
105759*/
105760#define noopFunc versionFunc   /* Substitute function - never called */
105761
105762/*
105763** Implementation of random().  Return a random integer.
105764*/
105765static void randomFunc(
105766  sqlite3_context *context,
105767  int NotUsed,
105768  sqlite3_value **NotUsed2
105769){
105770  sqlite_int64 r;
105771  UNUSED_PARAMETER2(NotUsed, NotUsed2);
105772  sqlite3_randomness(sizeof(r), &r);
105773  if( r<0 ){
105774    /* We need to prevent a random number of 0x8000000000000000
105775    ** (or -9223372036854775808) since when you do abs() of that
105776    ** number of you get the same value back again.  To do this
105777    ** in a way that is testable, mask the sign bit off of negative
105778    ** values, resulting in a positive value.  Then take the
105779    ** 2s complement of that positive value.  The end result can
105780    ** therefore be no less than -9223372036854775807.
105781    */
105782    r = -(r & LARGEST_INT64);
105783  }
105784  sqlite3_result_int64(context, r);
105785}
105786
105787/*
105788** Implementation of randomblob(N).  Return a random blob
105789** that is N bytes long.
105790*/
105791static void randomBlob(
105792  sqlite3_context *context,
105793  int argc,
105794  sqlite3_value **argv
105795){
105796  int n;
105797  unsigned char *p;
105798  assert( argc==1 );
105799  UNUSED_PARAMETER(argc);
105800  n = sqlite3_value_int(argv[0]);
105801  if( n<1 ){
105802    n = 1;
105803  }
105804  p = contextMalloc(context, n);
105805  if( p ){
105806    sqlite3_randomness(n, p);
105807    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
105808  }
105809}
105810
105811/*
105812** Implementation of the last_insert_rowid() SQL function.  The return
105813** value is the same as the sqlite3_last_insert_rowid() API function.
105814*/
105815static void last_insert_rowid(
105816  sqlite3_context *context,
105817  int NotUsed,
105818  sqlite3_value **NotUsed2
105819){
105820  sqlite3 *db = sqlite3_context_db_handle(context);
105821  UNUSED_PARAMETER2(NotUsed, NotUsed2);
105822  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
105823  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
105824  ** function. */
105825  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
105826}
105827
105828/*
105829** Implementation of the changes() SQL function.
105830**
105831** IMP: R-62073-11209 The changes() SQL function is a wrapper
105832** around the sqlite3_changes() C/C++ function and hence follows the same
105833** rules for counting changes.
105834*/
105835static void changes(
105836  sqlite3_context *context,
105837  int NotUsed,
105838  sqlite3_value **NotUsed2
105839){
105840  sqlite3 *db = sqlite3_context_db_handle(context);
105841  UNUSED_PARAMETER2(NotUsed, NotUsed2);
105842  sqlite3_result_int(context, sqlite3_changes(db));
105843}
105844
105845/*
105846** Implementation of the total_changes() SQL function.  The return value is
105847** the same as the sqlite3_total_changes() API function.
105848*/
105849static void total_changes(
105850  sqlite3_context *context,
105851  int NotUsed,
105852  sqlite3_value **NotUsed2
105853){
105854  sqlite3 *db = sqlite3_context_db_handle(context);
105855  UNUSED_PARAMETER2(NotUsed, NotUsed2);
105856  /* IMP: R-52756-41993 This function is a wrapper around the
105857  ** sqlite3_total_changes() C/C++ interface. */
105858  sqlite3_result_int(context, sqlite3_total_changes(db));
105859}
105860
105861/*
105862** A structure defining how to do GLOB-style comparisons.
105863*/
105864struct compareInfo {
105865  u8 matchAll;          /* "*" or "%" */
105866  u8 matchOne;          /* "?" or "_" */
105867  u8 matchSet;          /* "[" or 0 */
105868  u8 noCase;            /* true to ignore case differences */
105869};
105870
105871/*
105872** For LIKE and GLOB matching on EBCDIC machines, assume that every
105873** character is exactly one byte in size.  Also, provde the Utf8Read()
105874** macro for fast reading of the next character in the common case where
105875** the next character is ASCII.
105876*/
105877#if defined(SQLITE_EBCDIC)
105878# define sqlite3Utf8Read(A)        (*((*A)++))
105879# define Utf8Read(A)               (*(A++))
105880#else
105881# define Utf8Read(A)               (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
105882#endif
105883
105884static const struct compareInfo globInfo = { '*', '?', '[', 0 };
105885/* The correct SQL-92 behavior is for the LIKE operator to ignore
105886** case.  Thus  'a' LIKE 'A' would be true. */
105887static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
105888/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
105889** is case sensitive causing 'a' LIKE 'A' to be false */
105890static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
105891
105892/*
105893** Possible error returns from patternMatch()
105894*/
105895#define SQLITE_MATCH             0
105896#define SQLITE_NOMATCH           1
105897#define SQLITE_NOWILDCARDMATCH   2
105898
105899/*
105900** Compare two UTF-8 strings for equality where the first string is
105901** a GLOB or LIKE expression.  Return values:
105902**
105903**    SQLITE_MATCH:            Match
105904**    SQLITE_NOMATCH:          No match
105905**    SQLITE_NOWILDCARDMATCH:  No match in spite of having * or % wildcards.
105906**
105907** Globbing rules:
105908**
105909**      '*'       Matches any sequence of zero or more characters.
105910**
105911**      '?'       Matches exactly one character.
105912**
105913**     [...]      Matches one character from the enclosed list of
105914**                characters.
105915**
105916**     [^...]     Matches one character not in the enclosed list.
105917**
105918** With the [...] and [^...] matching, a ']' character can be included
105919** in the list by making it the first character after '[' or '^'.  A
105920** range of characters can be specified using '-'.  Example:
105921** "[a-z]" matches any single lower-case letter.  To match a '-', make
105922** it the last character in the list.
105923**
105924** Like matching rules:
105925**
105926**      '%'       Matches any sequence of zero or more characters
105927**
105928***     '_'       Matches any one character
105929**
105930**      Ec        Where E is the "esc" character and c is any other
105931**                character, including '%', '_', and esc, match exactly c.
105932**
105933** The comments within this routine usually assume glob matching.
105934**
105935** This routine is usually quick, but can be N**2 in the worst case.
105936*/
105937static int patternCompare(
105938  const u8 *zPattern,              /* The glob pattern */
105939  const u8 *zString,               /* The string to compare against the glob */
105940  const struct compareInfo *pInfo, /* Information about how to do the compare */
105941  u32 matchOther                   /* The escape char (LIKE) or '[' (GLOB) */
105942){
105943  u32 c, c2;                       /* Next pattern and input string chars */
105944  u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
105945  u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
105946  u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
105947  const u8 *zEscaped = 0;          /* One past the last escaped input char */
105948
105949  while( (c = Utf8Read(zPattern))!=0 ){
105950    if( c==matchAll ){  /* Match "*" */
105951      /* Skip over multiple "*" characters in the pattern.  If there
105952      ** are also "?" characters, skip those as well, but consume a
105953      ** single character of the input string for each "?" skipped */
105954      while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
105955        if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
105956          return SQLITE_NOWILDCARDMATCH;
105957        }
105958      }
105959      if( c==0 ){
105960        return SQLITE_MATCH;   /* "*" at the end of the pattern matches */
105961      }else if( c==matchOther ){
105962        if( pInfo->matchSet==0 ){
105963          c = sqlite3Utf8Read(&zPattern);
105964          if( c==0 ) return SQLITE_NOWILDCARDMATCH;
105965        }else{
105966          /* "[...]" immediately follows the "*".  We have to do a slow
105967          ** recursive search in this case, but it is an unusual case. */
105968          assert( matchOther<0x80 );  /* '[' is a single-byte character */
105969          while( *zString ){
105970            int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
105971            if( bMatch!=SQLITE_NOMATCH ) return bMatch;
105972            SQLITE_SKIP_UTF8(zString);
105973          }
105974          return SQLITE_NOWILDCARDMATCH;
105975        }
105976      }
105977
105978      /* At this point variable c contains the first character of the
105979      ** pattern string past the "*".  Search in the input string for the
105980      ** first matching character and recursively continue the match from
105981      ** that point.
105982      **
105983      ** For a case-insensitive search, set variable cx to be the same as
105984      ** c but in the other case and search the input string for either
105985      ** c or cx.
105986      */
105987      if( c<=0x80 ){
105988        u32 cx;
105989        int bMatch;
105990        if( noCase ){
105991          cx = sqlite3Toupper(c);
105992          c = sqlite3Tolower(c);
105993        }else{
105994          cx = c;
105995        }
105996        while( (c2 = *(zString++))!=0 ){
105997          if( c2!=c && c2!=cx ) continue;
105998          bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
105999          if( bMatch!=SQLITE_NOMATCH ) return bMatch;
106000        }
106001      }else{
106002        int bMatch;
106003        while( (c2 = Utf8Read(zString))!=0 ){
106004          if( c2!=c ) continue;
106005          bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
106006          if( bMatch!=SQLITE_NOMATCH ) return bMatch;
106007        }
106008      }
106009      return SQLITE_NOWILDCARDMATCH;
106010    }
106011    if( c==matchOther ){
106012      if( pInfo->matchSet==0 ){
106013        c = sqlite3Utf8Read(&zPattern);
106014        if( c==0 ) return SQLITE_NOMATCH;
106015        zEscaped = zPattern;
106016      }else{
106017        u32 prior_c = 0;
106018        int seen = 0;
106019        int invert = 0;
106020        c = sqlite3Utf8Read(&zString);
106021        if( c==0 ) return SQLITE_NOMATCH;
106022        c2 = sqlite3Utf8Read(&zPattern);
106023        if( c2=='^' ){
106024          invert = 1;
106025          c2 = sqlite3Utf8Read(&zPattern);
106026        }
106027        if( c2==']' ){
106028          if( c==']' ) seen = 1;
106029          c2 = sqlite3Utf8Read(&zPattern);
106030        }
106031        while( c2 && c2!=']' ){
106032          if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
106033            c2 = sqlite3Utf8Read(&zPattern);
106034            if( c>=prior_c && c<=c2 ) seen = 1;
106035            prior_c = 0;
106036          }else{
106037            if( c==c2 ){
106038              seen = 1;
106039            }
106040            prior_c = c2;
106041          }
106042          c2 = sqlite3Utf8Read(&zPattern);
106043        }
106044        if( c2==0 || (seen ^ invert)==0 ){
106045          return SQLITE_NOMATCH;
106046        }
106047        continue;
106048      }
106049    }
106050    c2 = Utf8Read(zString);
106051    if( c==c2 ) continue;
106052    if( noCase  && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
106053      continue;
106054    }
106055    if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
106056    return SQLITE_NOMATCH;
106057  }
106058  return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
106059}
106060
106061/*
106062** The sqlite3_strglob() interface.  Return 0 on a match (like strcmp()) and
106063** non-zero if there is no match.
106064*/
106065SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
106066  return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
106067}
106068
106069/*
106070** The sqlite3_strlike() interface.  Return 0 on a match and non-zero for
106071** a miss - like strcmp().
106072*/
106073SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
106074  return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
106075}
106076
106077/*
106078** Count the number of times that the LIKE operator (or GLOB which is
106079** just a variation of LIKE) gets called.  This is used for testing
106080** only.
106081*/
106082#ifdef SQLITE_TEST
106083SQLITE_API int sqlite3_like_count = 0;
106084#endif
106085
106086
106087/*
106088** Implementation of the like() SQL function.  This function implements
106089** the build-in LIKE operator.  The first argument to the function is the
106090** pattern and the second argument is the string.  So, the SQL statements:
106091**
106092**       A LIKE B
106093**
106094** is implemented as like(B,A).
106095**
106096** This same function (with a different compareInfo structure) computes
106097** the GLOB operator.
106098*/
106099static void likeFunc(
106100  sqlite3_context *context,
106101  int argc,
106102  sqlite3_value **argv
106103){
106104  const unsigned char *zA, *zB;
106105  u32 escape;
106106  int nPat;
106107  sqlite3 *db = sqlite3_context_db_handle(context);
106108  struct compareInfo *pInfo = sqlite3_user_data(context);
106109
106110#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
106111  if( sqlite3_value_type(argv[0])==SQLITE_BLOB
106112   || sqlite3_value_type(argv[1])==SQLITE_BLOB
106113  ){
106114#ifdef SQLITE_TEST
106115    sqlite3_like_count++;
106116#endif
106117    sqlite3_result_int(context, 0);
106118    return;
106119  }
106120#endif
106121  zB = sqlite3_value_text(argv[0]);
106122  zA = sqlite3_value_text(argv[1]);
106123
106124  /* Limit the length of the LIKE or GLOB pattern to avoid problems
106125  ** of deep recursion and N*N behavior in patternCompare().
106126  */
106127  nPat = sqlite3_value_bytes(argv[0]);
106128  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
106129  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
106130  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
106131    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
106132    return;
106133  }
106134  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
106135
106136  if( argc==3 ){
106137    /* The escape character string must consist of a single UTF-8 character.
106138    ** Otherwise, return an error.
106139    */
106140    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
106141    if( zEsc==0 ) return;
106142    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
106143      sqlite3_result_error(context,
106144          "ESCAPE expression must be a single character", -1);
106145      return;
106146    }
106147    escape = sqlite3Utf8Read(&zEsc);
106148  }else{
106149    escape = pInfo->matchSet;
106150  }
106151  if( zA && zB ){
106152#ifdef SQLITE_TEST
106153    sqlite3_like_count++;
106154#endif
106155    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
106156  }
106157}
106158
106159/*
106160** Implementation of the NULLIF(x,y) function.  The result is the first
106161** argument if the arguments are different.  The result is NULL if the
106162** arguments are equal to each other.
106163*/
106164static void nullifFunc(
106165  sqlite3_context *context,
106166  int NotUsed,
106167  sqlite3_value **argv
106168){
106169  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
106170  UNUSED_PARAMETER(NotUsed);
106171  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
106172    sqlite3_result_value(context, argv[0]);
106173  }
106174}
106175
106176/*
106177** Implementation of the sqlite_version() function.  The result is the version
106178** of the SQLite library that is running.
106179*/
106180static void versionFunc(
106181  sqlite3_context *context,
106182  int NotUsed,
106183  sqlite3_value **NotUsed2
106184){
106185  UNUSED_PARAMETER2(NotUsed, NotUsed2);
106186  /* IMP: R-48699-48617 This function is an SQL wrapper around the
106187  ** sqlite3_libversion() C-interface. */
106188  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
106189}
106190
106191/*
106192** Implementation of the sqlite_source_id() function. The result is a string
106193** that identifies the particular version of the source code used to build
106194** SQLite.
106195*/
106196static void sourceidFunc(
106197  sqlite3_context *context,
106198  int NotUsed,
106199  sqlite3_value **NotUsed2
106200){
106201  UNUSED_PARAMETER2(NotUsed, NotUsed2);
106202  /* IMP: R-24470-31136 This function is an SQL wrapper around the
106203  ** sqlite3_sourceid() C interface. */
106204  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
106205}
106206
106207/*
106208** Implementation of the sqlite_log() function.  This is a wrapper around
106209** sqlite3_log().  The return value is NULL.  The function exists purely for
106210** its side-effects.
106211*/
106212static void errlogFunc(
106213  sqlite3_context *context,
106214  int argc,
106215  sqlite3_value **argv
106216){
106217  UNUSED_PARAMETER(argc);
106218  UNUSED_PARAMETER(context);
106219  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
106220}
106221
106222/*
106223** Implementation of the sqlite_compileoption_used() function.
106224** The result is an integer that identifies if the compiler option
106225** was used to build SQLite.
106226*/
106227#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
106228static void compileoptionusedFunc(
106229  sqlite3_context *context,
106230  int argc,
106231  sqlite3_value **argv
106232){
106233  const char *zOptName;
106234  assert( argc==1 );
106235  UNUSED_PARAMETER(argc);
106236  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
106237  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
106238  ** function.
106239  */
106240  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
106241    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
106242  }
106243}
106244#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
106245
106246/*
106247** Implementation of the sqlite_compileoption_get() function.
106248** The result is a string that identifies the compiler options
106249** used to build SQLite.
106250*/
106251#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
106252static void compileoptiongetFunc(
106253  sqlite3_context *context,
106254  int argc,
106255  sqlite3_value **argv
106256){
106257  int n;
106258  assert( argc==1 );
106259  UNUSED_PARAMETER(argc);
106260  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
106261  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
106262  */
106263  n = sqlite3_value_int(argv[0]);
106264  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
106265}
106266#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
106267
106268/* Array for converting from half-bytes (nybbles) into ASCII hex
106269** digits. */
106270static const char hexdigits[] = {
106271  '0', '1', '2', '3', '4', '5', '6', '7',
106272  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
106273};
106274
106275/*
106276** Implementation of the QUOTE() function.  This function takes a single
106277** argument.  If the argument is numeric, the return value is the same as
106278** the argument.  If the argument is NULL, the return value is the string
106279** "NULL".  Otherwise, the argument is enclosed in single quotes with
106280** single-quote escapes.
106281*/
106282static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
106283  assert( argc==1 );
106284  UNUSED_PARAMETER(argc);
106285  switch( sqlite3_value_type(argv[0]) ){
106286    case SQLITE_FLOAT: {
106287      double r1, r2;
106288      char zBuf[50];
106289      r1 = sqlite3_value_double(argv[0]);
106290      sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
106291      sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
106292      if( r1!=r2 ){
106293        sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
106294      }
106295      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
106296      break;
106297    }
106298    case SQLITE_INTEGER: {
106299      sqlite3_result_value(context, argv[0]);
106300      break;
106301    }
106302    case SQLITE_BLOB: {
106303      char *zText = 0;
106304      char const *zBlob = sqlite3_value_blob(argv[0]);
106305      int nBlob = sqlite3_value_bytes(argv[0]);
106306      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
106307      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
106308      if( zText ){
106309        int i;
106310        for(i=0; i<nBlob; i++){
106311          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
106312          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
106313        }
106314        zText[(nBlob*2)+2] = '\'';
106315        zText[(nBlob*2)+3] = '\0';
106316        zText[0] = 'X';
106317        zText[1] = '\'';
106318        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
106319        sqlite3_free(zText);
106320      }
106321      break;
106322    }
106323    case SQLITE_TEXT: {
106324      int i,j;
106325      u64 n;
106326      const unsigned char *zArg = sqlite3_value_text(argv[0]);
106327      char *z;
106328
106329      if( zArg==0 ) return;
106330      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
106331      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
106332      if( z ){
106333        z[0] = '\'';
106334        for(i=0, j=1; zArg[i]; i++){
106335          z[j++] = zArg[i];
106336          if( zArg[i]=='\'' ){
106337            z[j++] = '\'';
106338          }
106339        }
106340        z[j++] = '\'';
106341        z[j] = 0;
106342        sqlite3_result_text(context, z, j, sqlite3_free);
106343      }
106344      break;
106345    }
106346    default: {
106347      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
106348      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
106349      break;
106350    }
106351  }
106352}
106353
106354/*
106355** The unicode() function.  Return the integer unicode code-point value
106356** for the first character of the input string.
106357*/
106358static void unicodeFunc(
106359  sqlite3_context *context,
106360  int argc,
106361  sqlite3_value **argv
106362){
106363  const unsigned char *z = sqlite3_value_text(argv[0]);
106364  (void)argc;
106365  if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
106366}
106367
106368/*
106369** The char() function takes zero or more arguments, each of which is
106370** an integer.  It constructs a string where each character of the string
106371** is the unicode character for the corresponding integer argument.
106372*/
106373static void charFunc(
106374  sqlite3_context *context,
106375  int argc,
106376  sqlite3_value **argv
106377){
106378  unsigned char *z, *zOut;
106379  int i;
106380  zOut = z = sqlite3_malloc64( argc*4+1 );
106381  if( z==0 ){
106382    sqlite3_result_error_nomem(context);
106383    return;
106384  }
106385  for(i=0; i<argc; i++){
106386    sqlite3_int64 x;
106387    unsigned c;
106388    x = sqlite3_value_int64(argv[i]);
106389    if( x<0 || x>0x10ffff ) x = 0xfffd;
106390    c = (unsigned)(x & 0x1fffff);
106391    if( c<0x00080 ){
106392      *zOut++ = (u8)(c&0xFF);
106393    }else if( c<0x00800 ){
106394      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
106395      *zOut++ = 0x80 + (u8)(c & 0x3F);
106396    }else if( c<0x10000 ){
106397      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
106398      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
106399      *zOut++ = 0x80 + (u8)(c & 0x3F);
106400    }else{
106401      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
106402      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
106403      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
106404      *zOut++ = 0x80 + (u8)(c & 0x3F);
106405    }                                                    \
106406  }
106407  sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
106408}
106409
106410/*
106411** The hex() function.  Interpret the argument as a blob.  Return
106412** a hexadecimal rendering as text.
106413*/
106414static void hexFunc(
106415  sqlite3_context *context,
106416  int argc,
106417  sqlite3_value **argv
106418){
106419  int i, n;
106420  const unsigned char *pBlob;
106421  char *zHex, *z;
106422  assert( argc==1 );
106423  UNUSED_PARAMETER(argc);
106424  pBlob = sqlite3_value_blob(argv[0]);
106425  n = sqlite3_value_bytes(argv[0]);
106426  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
106427  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
106428  if( zHex ){
106429    for(i=0; i<n; i++, pBlob++){
106430      unsigned char c = *pBlob;
106431      *(z++) = hexdigits[(c>>4)&0xf];
106432      *(z++) = hexdigits[c&0xf];
106433    }
106434    *z = 0;
106435    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
106436  }
106437}
106438
106439/*
106440** The zeroblob(N) function returns a zero-filled blob of size N bytes.
106441*/
106442static void zeroblobFunc(
106443  sqlite3_context *context,
106444  int argc,
106445  sqlite3_value **argv
106446){
106447  i64 n;
106448  int rc;
106449  assert( argc==1 );
106450  UNUSED_PARAMETER(argc);
106451  n = sqlite3_value_int64(argv[0]);
106452  if( n<0 ) n = 0;
106453  rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
106454  if( rc ){
106455    sqlite3_result_error_code(context, rc);
106456  }
106457}
106458
106459/*
106460** The replace() function.  Three arguments are all strings: call
106461** them A, B, and C. The result is also a string which is derived
106462** from A by replacing every occurrence of B with C.  The match
106463** must be exact.  Collating sequences are not used.
106464*/
106465static void replaceFunc(
106466  sqlite3_context *context,
106467  int argc,
106468  sqlite3_value **argv
106469){
106470  const unsigned char *zStr;        /* The input string A */
106471  const unsigned char *zPattern;    /* The pattern string B */
106472  const unsigned char *zRep;        /* The replacement string C */
106473  unsigned char *zOut;              /* The output */
106474  int nStr;                /* Size of zStr */
106475  int nPattern;            /* Size of zPattern */
106476  int nRep;                /* Size of zRep */
106477  i64 nOut;                /* Maximum size of zOut */
106478  int loopLimit;           /* Last zStr[] that might match zPattern[] */
106479  int i, j;                /* Loop counters */
106480
106481  assert( argc==3 );
106482  UNUSED_PARAMETER(argc);
106483  zStr = sqlite3_value_text(argv[0]);
106484  if( zStr==0 ) return;
106485  nStr = sqlite3_value_bytes(argv[0]);
106486  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
106487  zPattern = sqlite3_value_text(argv[1]);
106488  if( zPattern==0 ){
106489    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
106490            || sqlite3_context_db_handle(context)->mallocFailed );
106491    return;
106492  }
106493  if( zPattern[0]==0 ){
106494    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
106495    sqlite3_result_value(context, argv[0]);
106496    return;
106497  }
106498  nPattern = sqlite3_value_bytes(argv[1]);
106499  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
106500  zRep = sqlite3_value_text(argv[2]);
106501  if( zRep==0 ) return;
106502  nRep = sqlite3_value_bytes(argv[2]);
106503  assert( zRep==sqlite3_value_text(argv[2]) );
106504  nOut = nStr + 1;
106505  assert( nOut<SQLITE_MAX_LENGTH );
106506  zOut = contextMalloc(context, (i64)nOut);
106507  if( zOut==0 ){
106508    return;
106509  }
106510  loopLimit = nStr - nPattern;
106511  for(i=j=0; i<=loopLimit; i++){
106512    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
106513      zOut[j++] = zStr[i];
106514    }else{
106515      u8 *zOld;
106516      sqlite3 *db = sqlite3_context_db_handle(context);
106517      nOut += nRep - nPattern;
106518      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
106519      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
106520      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
106521        sqlite3_result_error_toobig(context);
106522        sqlite3_free(zOut);
106523        return;
106524      }
106525      zOld = zOut;
106526      zOut = sqlite3_realloc64(zOut, (int)nOut);
106527      if( zOut==0 ){
106528        sqlite3_result_error_nomem(context);
106529        sqlite3_free(zOld);
106530        return;
106531      }
106532      memcpy(&zOut[j], zRep, nRep);
106533      j += nRep;
106534      i += nPattern-1;
106535    }
106536  }
106537  assert( j+nStr-i+1==nOut );
106538  memcpy(&zOut[j], &zStr[i], nStr-i);
106539  j += nStr - i;
106540  assert( j<=nOut );
106541  zOut[j] = 0;
106542  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
106543}
106544
106545/*
106546** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
106547** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
106548*/
106549static void trimFunc(
106550  sqlite3_context *context,
106551  int argc,
106552  sqlite3_value **argv
106553){
106554  const unsigned char *zIn;         /* Input string */
106555  const unsigned char *zCharSet;    /* Set of characters to trim */
106556  int nIn;                          /* Number of bytes in input */
106557  int flags;                        /* 1: trimleft  2: trimright  3: trim */
106558  int i;                            /* Loop counter */
106559  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
106560  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
106561  int nChar;                        /* Number of characters in zCharSet */
106562
106563  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
106564    return;
106565  }
106566  zIn = sqlite3_value_text(argv[0]);
106567  if( zIn==0 ) return;
106568  nIn = sqlite3_value_bytes(argv[0]);
106569  assert( zIn==sqlite3_value_text(argv[0]) );
106570  if( argc==1 ){
106571    static const unsigned char lenOne[] = { 1 };
106572    static unsigned char * const azOne[] = { (u8*)" " };
106573    nChar = 1;
106574    aLen = (u8*)lenOne;
106575    azChar = (unsigned char **)azOne;
106576    zCharSet = 0;
106577  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
106578    return;
106579  }else{
106580    const unsigned char *z;
106581    for(z=zCharSet, nChar=0; *z; nChar++){
106582      SQLITE_SKIP_UTF8(z);
106583    }
106584    if( nChar>0 ){
106585      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
106586      if( azChar==0 ){
106587        return;
106588      }
106589      aLen = (unsigned char*)&azChar[nChar];
106590      for(z=zCharSet, nChar=0; *z; nChar++){
106591        azChar[nChar] = (unsigned char *)z;
106592        SQLITE_SKIP_UTF8(z);
106593        aLen[nChar] = (u8)(z - azChar[nChar]);
106594      }
106595    }
106596  }
106597  if( nChar>0 ){
106598    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
106599    if( flags & 1 ){
106600      while( nIn>0 ){
106601        int len = 0;
106602        for(i=0; i<nChar; i++){
106603          len = aLen[i];
106604          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
106605        }
106606        if( i>=nChar ) break;
106607        zIn += len;
106608        nIn -= len;
106609      }
106610    }
106611    if( flags & 2 ){
106612      while( nIn>0 ){
106613        int len = 0;
106614        for(i=0; i<nChar; i++){
106615          len = aLen[i];
106616          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
106617        }
106618        if( i>=nChar ) break;
106619        nIn -= len;
106620      }
106621    }
106622    if( zCharSet ){
106623      sqlite3_free(azChar);
106624    }
106625  }
106626  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
106627}
106628
106629
106630#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
106631/*
106632** The "unknown" function is automatically substituted in place of
106633** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
106634** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
106635** When the "sqlite3" command-line shell is built using this functionality,
106636** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
106637** involving application-defined functions to be examined in a generic
106638** sqlite3 shell.
106639*/
106640static void unknownFunc(
106641  sqlite3_context *context,
106642  int argc,
106643  sqlite3_value **argv
106644){
106645  /* no-op */
106646}
106647#endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
106648
106649
106650/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
106651** is only available if the SQLITE_SOUNDEX compile-time option is used
106652** when SQLite is built.
106653*/
106654#ifdef SQLITE_SOUNDEX
106655/*
106656** Compute the soundex encoding of a word.
106657**
106658** IMP: R-59782-00072 The soundex(X) function returns a string that is the
106659** soundex encoding of the string X.
106660*/
106661static void soundexFunc(
106662  sqlite3_context *context,
106663  int argc,
106664  sqlite3_value **argv
106665){
106666  char zResult[8];
106667  const u8 *zIn;
106668  int i, j;
106669  static const unsigned char iCode[] = {
106670    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
106671    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
106672    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
106673    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
106674    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
106675    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
106676    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
106677    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
106678  };
106679  assert( argc==1 );
106680  zIn = (u8*)sqlite3_value_text(argv[0]);
106681  if( zIn==0 ) zIn = (u8*)"";
106682  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
106683  if( zIn[i] ){
106684    u8 prevcode = iCode[zIn[i]&0x7f];
106685    zResult[0] = sqlite3Toupper(zIn[i]);
106686    for(j=1; j<4 && zIn[i]; i++){
106687      int code = iCode[zIn[i]&0x7f];
106688      if( code>0 ){
106689        if( code!=prevcode ){
106690          prevcode = code;
106691          zResult[j++] = code + '0';
106692        }
106693      }else{
106694        prevcode = 0;
106695      }
106696    }
106697    while( j<4 ){
106698      zResult[j++] = '0';
106699    }
106700    zResult[j] = 0;
106701    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
106702  }else{
106703    /* IMP: R-64894-50321 The string "?000" is returned if the argument
106704    ** is NULL or contains no ASCII alphabetic characters. */
106705    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
106706  }
106707}
106708#endif /* SQLITE_SOUNDEX */
106709
106710#ifndef SQLITE_OMIT_LOAD_EXTENSION
106711/*
106712** A function that loads a shared-library extension then returns NULL.
106713*/
106714static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
106715  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
106716  const char *zProc;
106717  sqlite3 *db = sqlite3_context_db_handle(context);
106718  char *zErrMsg = 0;
106719
106720  /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
106721  ** flag is set.  See the sqlite3_enable_load_extension() API.
106722  */
106723  if( (db->flags & SQLITE_LoadExtFunc)==0 ){
106724    sqlite3_result_error(context, "not authorized", -1);
106725    return;
106726  }
106727
106728  if( argc==2 ){
106729    zProc = (const char *)sqlite3_value_text(argv[1]);
106730  }else{
106731    zProc = 0;
106732  }
106733  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
106734    sqlite3_result_error(context, zErrMsg, -1);
106735    sqlite3_free(zErrMsg);
106736  }
106737}
106738#endif
106739
106740
106741/*
106742** An instance of the following structure holds the context of a
106743** sum() or avg() aggregate computation.
106744*/
106745typedef struct SumCtx SumCtx;
106746struct SumCtx {
106747  double rSum;      /* Floating point sum */
106748  i64 iSum;         /* Integer sum */
106749  i64 cnt;          /* Number of elements summed */
106750  u8 overflow;      /* True if integer overflow seen */
106751  u8 approx;        /* True if non-integer value was input to the sum */
106752};
106753
106754/*
106755** Routines used to compute the sum, average, and total.
106756**
106757** The SUM() function follows the (broken) SQL standard which means
106758** that it returns NULL if it sums over no inputs.  TOTAL returns
106759** 0.0 in that case.  In addition, TOTAL always returns a float where
106760** SUM might return an integer if it never encounters a floating point
106761** value.  TOTAL never fails, but SUM might through an exception if
106762** it overflows an integer.
106763*/
106764static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
106765  SumCtx *p;
106766  int type;
106767  assert( argc==1 );
106768  UNUSED_PARAMETER(argc);
106769  p = sqlite3_aggregate_context(context, sizeof(*p));
106770  type = sqlite3_value_numeric_type(argv[0]);
106771  if( p && type!=SQLITE_NULL ){
106772    p->cnt++;
106773    if( type==SQLITE_INTEGER ){
106774      i64 v = sqlite3_value_int64(argv[0]);
106775      p->rSum += v;
106776      if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
106777        p->overflow = 1;
106778      }
106779    }else{
106780      p->rSum += sqlite3_value_double(argv[0]);
106781      p->approx = 1;
106782    }
106783  }
106784}
106785static void sumFinalize(sqlite3_context *context){
106786  SumCtx *p;
106787  p = sqlite3_aggregate_context(context, 0);
106788  if( p && p->cnt>0 ){
106789    if( p->overflow ){
106790      sqlite3_result_error(context,"integer overflow",-1);
106791    }else if( p->approx ){
106792      sqlite3_result_double(context, p->rSum);
106793    }else{
106794      sqlite3_result_int64(context, p->iSum);
106795    }
106796  }
106797}
106798static void avgFinalize(sqlite3_context *context){
106799  SumCtx *p;
106800  p = sqlite3_aggregate_context(context, 0);
106801  if( p && p->cnt>0 ){
106802    sqlite3_result_double(context, p->rSum/(double)p->cnt);
106803  }
106804}
106805static void totalFinalize(sqlite3_context *context){
106806  SumCtx *p;
106807  p = sqlite3_aggregate_context(context, 0);
106808  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
106809  sqlite3_result_double(context, p ? p->rSum : (double)0);
106810}
106811
106812/*
106813** The following structure keeps track of state information for the
106814** count() aggregate function.
106815*/
106816typedef struct CountCtx CountCtx;
106817struct CountCtx {
106818  i64 n;
106819};
106820
106821/*
106822** Routines to implement the count() aggregate function.
106823*/
106824static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
106825  CountCtx *p;
106826  p = sqlite3_aggregate_context(context, sizeof(*p));
106827  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
106828    p->n++;
106829  }
106830
106831#ifndef SQLITE_OMIT_DEPRECATED
106832  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
106833  ** sure it still operates correctly, verify that its count agrees with our
106834  ** internal count when using count(*) and when the total count can be
106835  ** expressed as a 32-bit integer. */
106836  assert( argc==1 || p==0 || p->n>0x7fffffff
106837          || p->n==sqlite3_aggregate_count(context) );
106838#endif
106839}
106840static void countFinalize(sqlite3_context *context){
106841  CountCtx *p;
106842  p = sqlite3_aggregate_context(context, 0);
106843  sqlite3_result_int64(context, p ? p->n : 0);
106844}
106845
106846/*
106847** Routines to implement min() and max() aggregate functions.
106848*/
106849static void minmaxStep(
106850  sqlite3_context *context,
106851  int NotUsed,
106852  sqlite3_value **argv
106853){
106854  Mem *pArg  = (Mem *)argv[0];
106855  Mem *pBest;
106856  UNUSED_PARAMETER(NotUsed);
106857
106858  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
106859  if( !pBest ) return;
106860
106861  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
106862    if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
106863  }else if( pBest->flags ){
106864    int max;
106865    int cmp;
106866    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
106867    /* This step function is used for both the min() and max() aggregates,
106868    ** the only difference between the two being that the sense of the
106869    ** comparison is inverted. For the max() aggregate, the
106870    ** sqlite3_user_data() function returns (void *)-1. For min() it
106871    ** returns (void *)db, where db is the sqlite3* database pointer.
106872    ** Therefore the next statement sets variable 'max' to 1 for the max()
106873    ** aggregate, or 0 for min().
106874    */
106875    max = sqlite3_user_data(context)!=0;
106876    cmp = sqlite3MemCompare(pBest, pArg, pColl);
106877    if( (max && cmp<0) || (!max && cmp>0) ){
106878      sqlite3VdbeMemCopy(pBest, pArg);
106879    }else{
106880      sqlite3SkipAccumulatorLoad(context);
106881    }
106882  }else{
106883    pBest->db = sqlite3_context_db_handle(context);
106884    sqlite3VdbeMemCopy(pBest, pArg);
106885  }
106886}
106887static void minMaxFinalize(sqlite3_context *context){
106888  sqlite3_value *pRes;
106889  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
106890  if( pRes ){
106891    if( pRes->flags ){
106892      sqlite3_result_value(context, pRes);
106893    }
106894    sqlite3VdbeMemRelease(pRes);
106895  }
106896}
106897
106898/*
106899** group_concat(EXPR, ?SEPARATOR?)
106900*/
106901static void groupConcatStep(
106902  sqlite3_context *context,
106903  int argc,
106904  sqlite3_value **argv
106905){
106906  const char *zVal;
106907  StrAccum *pAccum;
106908  const char *zSep;
106909  int nVal, nSep;
106910  assert( argc==1 || argc==2 );
106911  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
106912  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
106913
106914  if( pAccum ){
106915    sqlite3 *db = sqlite3_context_db_handle(context);
106916    int firstTerm = pAccum->mxAlloc==0;
106917    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
106918    if( !firstTerm ){
106919      if( argc==2 ){
106920        zSep = (char*)sqlite3_value_text(argv[1]);
106921        nSep = sqlite3_value_bytes(argv[1]);
106922      }else{
106923        zSep = ",";
106924        nSep = 1;
106925      }
106926      if( zSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
106927    }
106928    zVal = (char*)sqlite3_value_text(argv[0]);
106929    nVal = sqlite3_value_bytes(argv[0]);
106930    if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
106931  }
106932}
106933static void groupConcatFinalize(sqlite3_context *context){
106934  StrAccum *pAccum;
106935  pAccum = sqlite3_aggregate_context(context, 0);
106936  if( pAccum ){
106937    if( pAccum->accError==STRACCUM_TOOBIG ){
106938      sqlite3_result_error_toobig(context);
106939    }else if( pAccum->accError==STRACCUM_NOMEM ){
106940      sqlite3_result_error_nomem(context);
106941    }else{
106942      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
106943                          sqlite3_free);
106944    }
106945  }
106946}
106947
106948/*
106949** This routine does per-connection function registration.  Most
106950** of the built-in functions above are part of the global function set.
106951** This routine only deals with those that are not global.
106952*/
106953SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
106954  int rc = sqlite3_overload_function(db, "MATCH", 2);
106955  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
106956  if( rc==SQLITE_NOMEM ){
106957    sqlite3OomFault(db);
106958  }
106959}
106960
106961/*
106962** Set the LIKEOPT flag on the 2-argument function with the given name.
106963*/
106964static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
106965  FuncDef *pDef;
106966  pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
106967  if( ALWAYS(pDef) ){
106968    pDef->funcFlags |= flagVal;
106969  }
106970}
106971
106972/*
106973** Register the built-in LIKE and GLOB functions.  The caseSensitive
106974** parameter determines whether or not the LIKE operator is case
106975** sensitive.  GLOB is always case sensitive.
106976*/
106977SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
106978  struct compareInfo *pInfo;
106979  if( caseSensitive ){
106980    pInfo = (struct compareInfo*)&likeInfoAlt;
106981  }else{
106982    pInfo = (struct compareInfo*)&likeInfoNorm;
106983  }
106984  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
106985  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
106986  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
106987      (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
106988  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
106989  setLikeOptFlag(db, "like",
106990      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
106991}
106992
106993/*
106994** pExpr points to an expression which implements a function.  If
106995** it is appropriate to apply the LIKE optimization to that function
106996** then set aWc[0] through aWc[2] to the wildcard characters and
106997** return TRUE.  If the function is not a LIKE-style function then
106998** return FALSE.
106999**
107000** *pIsNocase is set to true if uppercase and lowercase are equivalent for
107001** the function (default for LIKE).  If the function makes the distinction
107002** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
107003** false.
107004*/
107005SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
107006  FuncDef *pDef;
107007  if( pExpr->op!=TK_FUNCTION
107008   || !pExpr->x.pList
107009   || pExpr->x.pList->nExpr!=2
107010  ){
107011    return 0;
107012  }
107013  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
107014  pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0);
107015  if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
107016    return 0;
107017  }
107018
107019  /* The memcpy() statement assumes that the wildcard characters are
107020  ** the first three statements in the compareInfo structure.  The
107021  ** asserts() that follow verify that assumption
107022  */
107023  memcpy(aWc, pDef->pUserData, 3);
107024  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
107025  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
107026  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
107027  *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
107028  return 1;
107029}
107030
107031/*
107032** All of the FuncDef structures in the aBuiltinFunc[] array above
107033** to the global function hash table.  This occurs at start-time (as
107034** a consequence of calling sqlite3_initialize()).
107035**
107036** After this routine runs
107037*/
107038SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
107039  /*
107040  ** The following array holds FuncDef structures for all of the functions
107041  ** defined in this file.
107042  **
107043  ** The array cannot be constant since changes are made to the
107044  ** FuncDef.pHash elements at start-time.  The elements of this array
107045  ** are read-only after initialization is complete.
107046  **
107047  ** For peak efficiency, put the most frequently used function last.
107048  */
107049  static FuncDef aBuiltinFunc[] = {
107050#ifdef SQLITE_SOUNDEX
107051    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
107052#endif
107053#ifndef SQLITE_OMIT_LOAD_EXTENSION
107054    VFUNCTION(load_extension,    1, 0, 0, loadExt          ),
107055    VFUNCTION(load_extension,    2, 0, 0, loadExt          ),
107056#endif
107057#if SQLITE_USER_AUTHENTICATION
107058    FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
107059#endif
107060#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
107061    DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
107062    DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
107063#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
107064    FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
107065    FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
107066    FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
107067#ifdef SQLITE_DEBUG
107068    FUNCTION2(affinity,          1, 0, 0, noopFunc,  SQLITE_FUNC_AFFINITY),
107069#endif
107070    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
107071    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
107072    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
107073    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
107074    FUNCTION(trim,               1, 3, 0, trimFunc         ),
107075    FUNCTION(trim,               2, 3, 0, trimFunc         ),
107076    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
107077    FUNCTION(min,                0, 0, 1, 0                ),
107078    AGGREGATE2(min,              1, 0, 1, minmaxStep,      minMaxFinalize,
107079                                          SQLITE_FUNC_MINMAX ),
107080    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
107081    FUNCTION(max,                0, 1, 1, 0                ),
107082    AGGREGATE2(max,              1, 1, 1, minmaxStep,      minMaxFinalize,
107083                                          SQLITE_FUNC_MINMAX ),
107084    FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
107085    FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
107086    FUNCTION(instr,              2, 0, 0, instrFunc        ),
107087    FUNCTION(printf,            -1, 0, 0, printfFunc       ),
107088    FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
107089    FUNCTION(char,              -1, 0, 0, charFunc         ),
107090    FUNCTION(abs,                1, 0, 0, absFunc          ),
107091#ifndef SQLITE_OMIT_FLOATING_POINT
107092    FUNCTION(round,              1, 0, 0, roundFunc        ),
107093    FUNCTION(round,              2, 0, 0, roundFunc        ),
107094#endif
107095    FUNCTION(upper,              1, 0, 0, upperFunc        ),
107096    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
107097    FUNCTION(hex,                1, 0, 0, hexFunc          ),
107098    FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
107099    VFUNCTION(random,            0, 0, 0, randomFunc       ),
107100    VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
107101    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
107102    DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
107103    DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
107104    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
107105    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
107106    VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
107107    VFUNCTION(changes,           0, 0, 0, changes          ),
107108    VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
107109    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
107110    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
107111    FUNCTION(substr,             2, 0, 0, substrFunc       ),
107112    FUNCTION(substr,             3, 0, 0, substrFunc       ),
107113    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
107114    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
107115    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
107116    AGGREGATE2(count,            0, 0, 0, countStep,       countFinalize,
107117               SQLITE_FUNC_COUNT  ),
107118    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
107119    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
107120    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
107121
107122    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
107123#ifdef SQLITE_CASE_SENSITIVE_LIKE
107124    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
107125    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
107126#else
107127    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
107128    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
107129#endif
107130#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
107131    FUNCTION(unknown,           -1, 0, 0, unknownFunc      ),
107132#endif
107133    FUNCTION(coalesce,           1, 0, 0, 0                ),
107134    FUNCTION(coalesce,           0, 0, 0, 0                ),
107135    FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
107136  };
107137#ifndef SQLITE_OMIT_ALTERTABLE
107138  sqlite3AlterFunctions();
107139#endif
107140#if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
107141  sqlite3AnalyzeFunctions();
107142#endif
107143  sqlite3RegisterDateTimeFunctions();
107144  sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
107145
107146#if 0  /* Enable to print out how the built-in functions are hashed */
107147  {
107148    int i;
107149    FuncDef *p;
107150    for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
107151      printf("FUNC-HASH %02d:", i);
107152      for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
107153        int n = sqlite3Strlen30(p->zName);
107154        int h = p->zName[0] + n;
107155        printf(" %s(%d)", p->zName, h);
107156      }
107157      printf("\n");
107158    }
107159  }
107160#endif
107161}
107162
107163/************** End of func.c ************************************************/
107164/************** Begin file fkey.c ********************************************/
107165/*
107166**
107167** The author disclaims copyright to this source code.  In place of
107168** a legal notice, here is a blessing:
107169**
107170**    May you do good and not evil.
107171**    May you find forgiveness for yourself and forgive others.
107172**    May you share freely, never taking more than you give.
107173**
107174*************************************************************************
107175** This file contains code used by the compiler to add foreign key
107176** support to compiled SQL statements.
107177*/
107178/* #include "sqliteInt.h" */
107179
107180#ifndef SQLITE_OMIT_FOREIGN_KEY
107181#ifndef SQLITE_OMIT_TRIGGER
107182
107183/*
107184** Deferred and Immediate FKs
107185** --------------------------
107186**
107187** Foreign keys in SQLite come in two flavours: deferred and immediate.
107188** If an immediate foreign key constraint is violated,
107189** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
107190** statement transaction rolled back. If a
107191** deferred foreign key constraint is violated, no action is taken
107192** immediately. However if the application attempts to commit the
107193** transaction before fixing the constraint violation, the attempt fails.
107194**
107195** Deferred constraints are implemented using a simple counter associated
107196** with the database handle. The counter is set to zero each time a
107197** database transaction is opened. Each time a statement is executed
107198** that causes a foreign key violation, the counter is incremented. Each
107199** time a statement is executed that removes an existing violation from
107200** the database, the counter is decremented. When the transaction is
107201** committed, the commit fails if the current value of the counter is
107202** greater than zero. This scheme has two big drawbacks:
107203**
107204**   * When a commit fails due to a deferred foreign key constraint,
107205**     there is no way to tell which foreign constraint is not satisfied,
107206**     or which row it is not satisfied for.
107207**
107208**   * If the database contains foreign key violations when the
107209**     transaction is opened, this may cause the mechanism to malfunction.
107210**
107211** Despite these problems, this approach is adopted as it seems simpler
107212** than the alternatives.
107213**
107214** INSERT operations:
107215**
107216**   I.1) For each FK for which the table is the child table, search
107217**        the parent table for a match. If none is found increment the
107218**        constraint counter.
107219**
107220**   I.2) For each FK for which the table is the parent table,
107221**        search the child table for rows that correspond to the new
107222**        row in the parent table. Decrement the counter for each row
107223**        found (as the constraint is now satisfied).
107224**
107225** DELETE operations:
107226**
107227**   D.1) For each FK for which the table is the child table,
107228**        search the parent table for a row that corresponds to the
107229**        deleted row in the child table. If such a row is not found,
107230**        decrement the counter.
107231**
107232**   D.2) For each FK for which the table is the parent table, search
107233**        the child table for rows that correspond to the deleted row
107234**        in the parent table. For each found increment the counter.
107235**
107236** UPDATE operations:
107237**
107238**   An UPDATE command requires that all 4 steps above are taken, but only
107239**   for FK constraints for which the affected columns are actually
107240**   modified (values must be compared at runtime).
107241**
107242** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
107243** This simplifies the implementation a bit.
107244**
107245** For the purposes of immediate FK constraints, the OR REPLACE conflict
107246** resolution is considered to delete rows before the new row is inserted.
107247** If a delete caused by OR REPLACE violates an FK constraint, an exception
107248** is thrown, even if the FK constraint would be satisfied after the new
107249** row is inserted.
107250**
107251** Immediate constraints are usually handled similarly. The only difference
107252** is that the counter used is stored as part of each individual statement
107253** object (struct Vdbe). If, after the statement has run, its immediate
107254** constraint counter is greater than zero,
107255** it returns SQLITE_CONSTRAINT_FOREIGNKEY
107256** and the statement transaction is rolled back. An exception is an INSERT
107257** statement that inserts a single row only (no triggers). In this case,
107258** instead of using a counter, an exception is thrown immediately if the
107259** INSERT violates a foreign key constraint. This is necessary as such
107260** an INSERT does not open a statement transaction.
107261**
107262** TODO: How should dropping a table be handled? How should renaming a
107263** table be handled?
107264**
107265**
107266** Query API Notes
107267** ---------------
107268**
107269** Before coding an UPDATE or DELETE row operation, the code-generator
107270** for those two operations needs to know whether or not the operation
107271** requires any FK processing and, if so, which columns of the original
107272** row are required by the FK processing VDBE code (i.e. if FKs were
107273** implemented using triggers, which of the old.* columns would be
107274** accessed). No information is required by the code-generator before
107275** coding an INSERT operation. The functions used by the UPDATE/DELETE
107276** generation code to query for this information are:
107277**
107278**   sqlite3FkRequired() - Test to see if FK processing is required.
107279**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
107280**
107281**
107282** Externally accessible module functions
107283** --------------------------------------
107284**
107285**   sqlite3FkCheck()    - Check for foreign key violations.
107286**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
107287**   sqlite3FkDelete()   - Delete an FKey structure.
107288*/
107289
107290/*
107291** VDBE Calling Convention
107292** -----------------------
107293**
107294** Example:
107295**
107296**   For the following INSERT statement:
107297**
107298**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
107299**     INSERT INTO t1 VALUES(1, 2, 3.1);
107300**
107301**   Register (x):        2    (type integer)
107302**   Register (x+1):      1    (type integer)
107303**   Register (x+2):      NULL (type NULL)
107304**   Register (x+3):      3.1  (type real)
107305*/
107306
107307/*
107308** A foreign key constraint requires that the key columns in the parent
107309** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
107310** Given that pParent is the parent table for foreign key constraint pFKey,
107311** search the schema for a unique index on the parent key columns.
107312**
107313** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
107314** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
107315** is set to point to the unique index.
107316**
107317** If the parent key consists of a single column (the foreign key constraint
107318** is not a composite foreign key), output variable *paiCol is set to NULL.
107319** Otherwise, it is set to point to an allocated array of size N, where
107320** N is the number of columns in the parent key. The first element of the
107321** array is the index of the child table column that is mapped by the FK
107322** constraint to the parent table column stored in the left-most column
107323** of index *ppIdx. The second element of the array is the index of the
107324** child table column that corresponds to the second left-most column of
107325** *ppIdx, and so on.
107326**
107327** If the required index cannot be found, either because:
107328**
107329**   1) The named parent key columns do not exist, or
107330**
107331**   2) The named parent key columns do exist, but are not subject to a
107332**      UNIQUE or PRIMARY KEY constraint, or
107333**
107334**   3) No parent key columns were provided explicitly as part of the
107335**      foreign key definition, and the parent table does not have a
107336**      PRIMARY KEY, or
107337**
107338**   4) No parent key columns were provided explicitly as part of the
107339**      foreign key definition, and the PRIMARY KEY of the parent table
107340**      consists of a different number of columns to the child key in
107341**      the child table.
107342**
107343** then non-zero is returned, and a "foreign key mismatch" error loaded
107344** into pParse. If an OOM error occurs, non-zero is returned and the
107345** pParse->db->mallocFailed flag is set.
107346*/
107347SQLITE_PRIVATE int sqlite3FkLocateIndex(
107348  Parse *pParse,                  /* Parse context to store any error in */
107349  Table *pParent,                 /* Parent table of FK constraint pFKey */
107350  FKey *pFKey,                    /* Foreign key to find index for */
107351  Index **ppIdx,                  /* OUT: Unique index on parent table */
107352  int **paiCol                    /* OUT: Map of index columns in pFKey */
107353){
107354  Index *pIdx = 0;                    /* Value to return via *ppIdx */
107355  int *aiCol = 0;                     /* Value to return via *paiCol */
107356  int nCol = pFKey->nCol;             /* Number of columns in parent key */
107357  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
107358
107359  /* The caller is responsible for zeroing output parameters. */
107360  assert( ppIdx && *ppIdx==0 );
107361  assert( !paiCol || *paiCol==0 );
107362  assert( pParse );
107363
107364  /* If this is a non-composite (single column) foreign key, check if it
107365  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
107366  ** and *paiCol set to zero and return early.
107367  **
107368  ** Otherwise, for a composite foreign key (more than one column), allocate
107369  ** space for the aiCol array (returned via output parameter *paiCol).
107370  ** Non-composite foreign keys do not require the aiCol array.
107371  */
107372  if( nCol==1 ){
107373    /* The FK maps to the IPK if any of the following are true:
107374    **
107375    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
107376    **      mapped to the primary key of table pParent, or
107377    **   2) The FK is explicitly mapped to a column declared as INTEGER
107378    **      PRIMARY KEY.
107379    */
107380    if( pParent->iPKey>=0 ){
107381      if( !zKey ) return 0;
107382      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
107383    }
107384  }else if( paiCol ){
107385    assert( nCol>1 );
107386    aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
107387    if( !aiCol ) return 1;
107388    *paiCol = aiCol;
107389  }
107390
107391  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
107392    if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
107393      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
107394      ** of columns. If each indexed column corresponds to a foreign key
107395      ** column of pFKey, then this index is a winner.  */
107396
107397      if( zKey==0 ){
107398        /* If zKey is NULL, then this foreign key is implicitly mapped to
107399        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
107400        ** identified by the test.  */
107401        if( IsPrimaryKeyIndex(pIdx) ){
107402          if( aiCol ){
107403            int i;
107404            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
107405          }
107406          break;
107407        }
107408      }else{
107409        /* If zKey is non-NULL, then this foreign key was declared to
107410        ** map to an explicit list of columns in table pParent. Check if this
107411        ** index matches those columns. Also, check that the index uses
107412        ** the default collation sequences for each column. */
107413        int i, j;
107414        for(i=0; i<nCol; i++){
107415          i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
107416          const char *zDfltColl;            /* Def. collation for column */
107417          char *zIdxCol;                    /* Name of indexed column */
107418
107419          if( iCol<0 ) break; /* No foreign keys against expression indexes */
107420
107421          /* If the index uses a collation sequence that is different from
107422          ** the default collation sequence for the column, this index is
107423          ** unusable. Bail out early in this case.  */
107424          zDfltColl = pParent->aCol[iCol].zColl;
107425          if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
107426          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
107427
107428          zIdxCol = pParent->aCol[iCol].zName;
107429          for(j=0; j<nCol; j++){
107430            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
107431              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
107432              break;
107433            }
107434          }
107435          if( j==nCol ) break;
107436        }
107437        if( i==nCol ) break;      /* pIdx is usable */
107438      }
107439    }
107440  }
107441
107442  if( !pIdx ){
107443    if( !pParse->disableTriggers ){
107444      sqlite3ErrorMsg(pParse,
107445           "foreign key mismatch - \"%w\" referencing \"%w\"",
107446           pFKey->pFrom->zName, pFKey->zTo);
107447    }
107448    sqlite3DbFree(pParse->db, aiCol);
107449    return 1;
107450  }
107451
107452  *ppIdx = pIdx;
107453  return 0;
107454}
107455
107456/*
107457** This function is called when a row is inserted into or deleted from the
107458** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
107459** on the child table of pFKey, this function is invoked twice for each row
107460** affected - once to "delete" the old row, and then again to "insert" the
107461** new row.
107462**
107463** Each time it is called, this function generates VDBE code to locate the
107464** row in the parent table that corresponds to the row being inserted into
107465** or deleted from the child table. If the parent row can be found, no
107466** special action is taken. Otherwise, if the parent row can *not* be
107467** found in the parent table:
107468**
107469**   Operation | FK type   | Action taken
107470**   --------------------------------------------------------------------------
107471**   INSERT      immediate   Increment the "immediate constraint counter".
107472**
107473**   DELETE      immediate   Decrement the "immediate constraint counter".
107474**
107475**   INSERT      deferred    Increment the "deferred constraint counter".
107476**
107477**   DELETE      deferred    Decrement the "deferred constraint counter".
107478**
107479** These operations are identified in the comment at the top of this file
107480** (fkey.c) as "I.1" and "D.1".
107481*/
107482static void fkLookupParent(
107483  Parse *pParse,        /* Parse context */
107484  int iDb,              /* Index of database housing pTab */
107485  Table *pTab,          /* Parent table of FK pFKey */
107486  Index *pIdx,          /* Unique index on parent key columns in pTab */
107487  FKey *pFKey,          /* Foreign key constraint */
107488  int *aiCol,           /* Map from parent key columns to child table columns */
107489  int regData,          /* Address of array containing child table row */
107490  int nIncr,            /* Increment constraint counter by this */
107491  int isIgnore          /* If true, pretend pTab contains all NULL values */
107492){
107493  int i;                                    /* Iterator variable */
107494  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
107495  int iCur = pParse->nTab - 1;              /* Cursor number to use */
107496  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
107497
107498  /* If nIncr is less than zero, then check at runtime if there are any
107499  ** outstanding constraints to resolve. If there are not, there is no need
107500  ** to check if deleting this row resolves any outstanding violations.
107501  **
107502  ** Check if any of the key columns in the child table row are NULL. If
107503  ** any are, then the constraint is considered satisfied. No need to
107504  ** search for a matching row in the parent table.  */
107505  if( nIncr<0 ){
107506    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
107507    VdbeCoverage(v);
107508  }
107509  for(i=0; i<pFKey->nCol; i++){
107510    int iReg = aiCol[i] + regData + 1;
107511    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
107512  }
107513
107514  if( isIgnore==0 ){
107515    if( pIdx==0 ){
107516      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
107517      ** column of the parent table (table pTab).  */
107518      int iMustBeInt;               /* Address of MustBeInt instruction */
107519      int regTemp = sqlite3GetTempReg(pParse);
107520
107521      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
107522      ** apply the affinity of the parent key). If this fails, then there
107523      ** is no matching parent key. Before using MustBeInt, make a copy of
107524      ** the value. Otherwise, the value inserted into the child key column
107525      ** will have INTEGER affinity applied to it, which may not be correct.  */
107526      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
107527      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
107528      VdbeCoverage(v);
107529
107530      /* If the parent table is the same as the child table, and we are about
107531      ** to increment the constraint-counter (i.e. this is an INSERT operation),
107532      ** then check if the row being inserted matches itself. If so, do not
107533      ** increment the constraint-counter.  */
107534      if( pTab==pFKey->pFrom && nIncr==1 ){
107535        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
107536        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
107537      }
107538
107539      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
107540      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
107541      sqlite3VdbeGoto(v, iOk);
107542      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
107543      sqlite3VdbeJumpHere(v, iMustBeInt);
107544      sqlite3ReleaseTempReg(pParse, regTemp);
107545    }else{
107546      int nCol = pFKey->nCol;
107547      int regTemp = sqlite3GetTempRange(pParse, nCol);
107548      int regRec = sqlite3GetTempReg(pParse);
107549
107550      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
107551      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
107552      for(i=0; i<nCol; i++){
107553        sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
107554      }
107555
107556      /* If the parent table is the same as the child table, and we are about
107557      ** to increment the constraint-counter (i.e. this is an INSERT operation),
107558      ** then check if the row being inserted matches itself. If so, do not
107559      ** increment the constraint-counter.
107560      **
107561      ** If any of the parent-key values are NULL, then the row cannot match
107562      ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
107563      ** of the parent-key values are NULL (at this point it is known that
107564      ** none of the child key values are).
107565      */
107566      if( pTab==pFKey->pFrom && nIncr==1 ){
107567        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
107568        for(i=0; i<nCol; i++){
107569          int iChild = aiCol[i]+1+regData;
107570          int iParent = pIdx->aiColumn[i]+1+regData;
107571          assert( pIdx->aiColumn[i]>=0 );
107572          assert( aiCol[i]!=pTab->iPKey );
107573          if( pIdx->aiColumn[i]==pTab->iPKey ){
107574            /* The parent key is a composite key that includes the IPK column */
107575            iParent = regData;
107576          }
107577          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
107578          sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
107579        }
107580        sqlite3VdbeGoto(v, iOk);
107581      }
107582
107583      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
107584                        sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
107585      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
107586
107587      sqlite3ReleaseTempReg(pParse, regRec);
107588      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
107589    }
107590  }
107591
107592  if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
107593   && !pParse->pToplevel
107594   && !pParse->isMultiWrite
107595  ){
107596    /* Special case: If this is an INSERT statement that will insert exactly
107597    ** one row into the table, raise a constraint immediately instead of
107598    ** incrementing a counter. This is necessary as the VM code is being
107599    ** generated for will not open a statement transaction.  */
107600    assert( nIncr==1 );
107601    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
107602        OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
107603  }else{
107604    if( nIncr>0 && pFKey->isDeferred==0 ){
107605      sqlite3MayAbort(pParse);
107606    }
107607    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
107608  }
107609
107610  sqlite3VdbeResolveLabel(v, iOk);
107611  sqlite3VdbeAddOp1(v, OP_Close, iCur);
107612}
107613
107614
107615/*
107616** Return an Expr object that refers to a memory register corresponding
107617** to column iCol of table pTab.
107618**
107619** regBase is the first of an array of register that contains the data
107620** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
107621** column.  regBase+2 holds the second column, and so forth.
107622*/
107623static Expr *exprTableRegister(
107624  Parse *pParse,     /* Parsing and code generating context */
107625  Table *pTab,       /* The table whose content is at r[regBase]... */
107626  int regBase,       /* Contents of table pTab */
107627  i16 iCol           /* Which column of pTab is desired */
107628){
107629  Expr *pExpr;
107630  Column *pCol;
107631  const char *zColl;
107632  sqlite3 *db = pParse->db;
107633
107634  pExpr = sqlite3Expr(db, TK_REGISTER, 0);
107635  if( pExpr ){
107636    if( iCol>=0 && iCol!=pTab->iPKey ){
107637      pCol = &pTab->aCol[iCol];
107638      pExpr->iTable = regBase + iCol + 1;
107639      pExpr->affinity = pCol->affinity;
107640      zColl = pCol->zColl;
107641      if( zColl==0 ) zColl = db->pDfltColl->zName;
107642      pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
107643    }else{
107644      pExpr->iTable = regBase;
107645      pExpr->affinity = SQLITE_AFF_INTEGER;
107646    }
107647  }
107648  return pExpr;
107649}
107650
107651/*
107652** Return an Expr object that refers to column iCol of table pTab which
107653** has cursor iCur.
107654*/
107655static Expr *exprTableColumn(
107656  sqlite3 *db,      /* The database connection */
107657  Table *pTab,      /* The table whose column is desired */
107658  int iCursor,      /* The open cursor on the table */
107659  i16 iCol          /* The column that is wanted */
107660){
107661  Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
107662  if( pExpr ){
107663    pExpr->pTab = pTab;
107664    pExpr->iTable = iCursor;
107665    pExpr->iColumn = iCol;
107666  }
107667  return pExpr;
107668}
107669
107670/*
107671** This function is called to generate code executed when a row is deleted
107672** from the parent table of foreign key constraint pFKey and, if pFKey is
107673** deferred, when a row is inserted into the same table. When generating
107674** code for an SQL UPDATE operation, this function may be called twice -
107675** once to "delete" the old row and once to "insert" the new row.
107676**
107677** Parameter nIncr is passed -1 when inserting a row (as this may decrease
107678** the number of FK violations in the db) or +1 when deleting one (as this
107679** may increase the number of FK constraint problems).
107680**
107681** The code generated by this function scans through the rows in the child
107682** table that correspond to the parent table row being deleted or inserted.
107683** For each child row found, one of the following actions is taken:
107684**
107685**   Operation | FK type   | Action taken
107686**   --------------------------------------------------------------------------
107687**   DELETE      immediate   Increment the "immediate constraint counter".
107688**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
107689**                           throw a "FOREIGN KEY constraint failed" exception.
107690**
107691**   INSERT      immediate   Decrement the "immediate constraint counter".
107692**
107693**   DELETE      deferred    Increment the "deferred constraint counter".
107694**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
107695**                           throw a "FOREIGN KEY constraint failed" exception.
107696**
107697**   INSERT      deferred    Decrement the "deferred constraint counter".
107698**
107699** These operations are identified in the comment at the top of this file
107700** (fkey.c) as "I.2" and "D.2".
107701*/
107702static void fkScanChildren(
107703  Parse *pParse,                  /* Parse context */
107704  SrcList *pSrc,                  /* The child table to be scanned */
107705  Table *pTab,                    /* The parent table */
107706  Index *pIdx,                    /* Index on parent covering the foreign key */
107707  FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
107708  int *aiCol,                     /* Map from pIdx cols to child table cols */
107709  int regData,                    /* Parent row data starts here */
107710  int nIncr                       /* Amount to increment deferred counter by */
107711){
107712  sqlite3 *db = pParse->db;       /* Database handle */
107713  int i;                          /* Iterator variable */
107714  Expr *pWhere = 0;               /* WHERE clause to scan with */
107715  NameContext sNameContext;       /* Context used to resolve WHERE clause */
107716  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
107717  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
107718  Vdbe *v = sqlite3GetVdbe(pParse);
107719
107720  assert( pIdx==0 || pIdx->pTable==pTab );
107721  assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
107722  assert( pIdx!=0 || pFKey->nCol==1 );
107723  assert( pIdx!=0 || HasRowid(pTab) );
107724
107725  if( nIncr<0 ){
107726    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
107727    VdbeCoverage(v);
107728  }
107729
107730  /* Create an Expr object representing an SQL expression like:
107731  **
107732  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
107733  **
107734  ** The collation sequence used for the comparison should be that of
107735  ** the parent key columns. The affinity of the parent key column should
107736  ** be applied to each child key value before the comparison takes place.
107737  */
107738  for(i=0; i<pFKey->nCol; i++){
107739    Expr *pLeft;                  /* Value from parent table row */
107740    Expr *pRight;                 /* Column ref to child table */
107741    Expr *pEq;                    /* Expression (pLeft = pRight) */
107742    i16 iCol;                     /* Index of column in child table */
107743    const char *zCol;             /* Name of column in child table */
107744
107745    iCol = pIdx ? pIdx->aiColumn[i] : -1;
107746    pLeft = exprTableRegister(pParse, pTab, regData, iCol);
107747    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
107748    assert( iCol>=0 );
107749    zCol = pFKey->pFrom->aCol[iCol].zName;
107750    pRight = sqlite3Expr(db, TK_ID, zCol);
107751    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
107752    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
107753  }
107754
107755  /* If the child table is the same as the parent table, then add terms
107756  ** to the WHERE clause that prevent this entry from being scanned.
107757  ** The added WHERE clause terms are like this:
107758  **
107759  **     $current_rowid!=rowid
107760  **     NOT( $current_a==a AND $current_b==b AND ... )
107761  **
107762  ** The first form is used for rowid tables.  The second form is used
107763  ** for WITHOUT ROWID tables.  In the second form, the primary key is
107764  ** (a,b,...)
107765  */
107766  if( pTab==pFKey->pFrom && nIncr>0 ){
107767    Expr *pNe;                    /* Expression (pLeft != pRight) */
107768    Expr *pLeft;                  /* Value from parent table row */
107769    Expr *pRight;                 /* Column ref to child table */
107770    if( HasRowid(pTab) ){
107771      pLeft = exprTableRegister(pParse, pTab, regData, -1);
107772      pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
107773      pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
107774    }else{
107775      Expr *pEq, *pAll = 0;
107776      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
107777      assert( pIdx!=0 );
107778      for(i=0; i<pPk->nKeyCol; i++){
107779        i16 iCol = pIdx->aiColumn[i];
107780        assert( iCol>=0 );
107781        pLeft = exprTableRegister(pParse, pTab, regData, iCol);
107782        pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
107783        pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
107784        pAll = sqlite3ExprAnd(db, pAll, pEq);
107785      }
107786      pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
107787    }
107788    pWhere = sqlite3ExprAnd(db, pWhere, pNe);
107789  }
107790
107791  /* Resolve the references in the WHERE clause. */
107792  memset(&sNameContext, 0, sizeof(NameContext));
107793  sNameContext.pSrcList = pSrc;
107794  sNameContext.pParse = pParse;
107795  sqlite3ResolveExprNames(&sNameContext, pWhere);
107796
107797  /* Create VDBE to loop through the entries in pSrc that match the WHERE
107798  ** clause. For each row found, increment either the deferred or immediate
107799  ** foreign key constraint counter. */
107800  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
107801  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
107802  if( pWInfo ){
107803    sqlite3WhereEnd(pWInfo);
107804  }
107805
107806  /* Clean up the WHERE clause constructed above. */
107807  sqlite3ExprDelete(db, pWhere);
107808  if( iFkIfZero ){
107809    sqlite3VdbeJumpHere(v, iFkIfZero);
107810  }
107811}
107812
107813/*
107814** This function returns a linked list of FKey objects (connected by
107815** FKey.pNextTo) holding all children of table pTab.  For example,
107816** given the following schema:
107817**
107818**   CREATE TABLE t1(a PRIMARY KEY);
107819**   CREATE TABLE t2(b REFERENCES t1(a);
107820**
107821** Calling this function with table "t1" as an argument returns a pointer
107822** to the FKey structure representing the foreign key constraint on table
107823** "t2". Calling this function with "t2" as the argument would return a
107824** NULL pointer (as there are no FK constraints for which t2 is the parent
107825** table).
107826*/
107827SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
107828  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
107829}
107830
107831/*
107832** The second argument is a Trigger structure allocated by the
107833** fkActionTrigger() routine. This function deletes the Trigger structure
107834** and all of its sub-components.
107835**
107836** The Trigger structure or any of its sub-components may be allocated from
107837** the lookaside buffer belonging to database handle dbMem.
107838*/
107839static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
107840  if( p ){
107841    TriggerStep *pStep = p->step_list;
107842    sqlite3ExprDelete(dbMem, pStep->pWhere);
107843    sqlite3ExprListDelete(dbMem, pStep->pExprList);
107844    sqlite3SelectDelete(dbMem, pStep->pSelect);
107845    sqlite3ExprDelete(dbMem, p->pWhen);
107846    sqlite3DbFree(dbMem, p);
107847  }
107848}
107849
107850/*
107851** This function is called to generate code that runs when table pTab is
107852** being dropped from the database. The SrcList passed as the second argument
107853** to this function contains a single entry guaranteed to resolve to
107854** table pTab.
107855**
107856** Normally, no code is required. However, if either
107857**
107858**   (a) The table is the parent table of a FK constraint, or
107859**   (b) The table is the child table of a deferred FK constraint and it is
107860**       determined at runtime that there are outstanding deferred FK
107861**       constraint violations in the database,
107862**
107863** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
107864** the table from the database. Triggers are disabled while running this
107865** DELETE, but foreign key actions are not.
107866*/
107867SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
107868  sqlite3 *db = pParse->db;
107869  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
107870    int iSkip = 0;
107871    Vdbe *v = sqlite3GetVdbe(pParse);
107872
107873    assert( v );                  /* VDBE has already been allocated */
107874    if( sqlite3FkReferences(pTab)==0 ){
107875      /* Search for a deferred foreign key constraint for which this table
107876      ** is the child table. If one cannot be found, return without
107877      ** generating any VDBE code. If one can be found, then jump over
107878      ** the entire DELETE if there are no outstanding deferred constraints
107879      ** when this statement is run.  */
107880      FKey *p;
107881      for(p=pTab->pFKey; p; p=p->pNextFrom){
107882        if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
107883      }
107884      if( !p ) return;
107885      iSkip = sqlite3VdbeMakeLabel(v);
107886      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
107887    }
107888
107889    pParse->disableTriggers = 1;
107890    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
107891    pParse->disableTriggers = 0;
107892
107893    /* If the DELETE has generated immediate foreign key constraint
107894    ** violations, halt the VDBE and return an error at this point, before
107895    ** any modifications to the schema are made. This is because statement
107896    ** transactions are not able to rollback schema changes.
107897    **
107898    ** If the SQLITE_DeferFKs flag is set, then this is not required, as
107899    ** the statement transaction will not be rolled back even if FK
107900    ** constraints are violated.
107901    */
107902    if( (db->flags & SQLITE_DeferFKs)==0 ){
107903      sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
107904      VdbeCoverage(v);
107905      sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
107906          OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
107907    }
107908
107909    if( iSkip ){
107910      sqlite3VdbeResolveLabel(v, iSkip);
107911    }
107912  }
107913}
107914
107915
107916/*
107917** The second argument points to an FKey object representing a foreign key
107918** for which pTab is the child table. An UPDATE statement against pTab
107919** is currently being processed. For each column of the table that is
107920** actually updated, the corresponding element in the aChange[] array
107921** is zero or greater (if a column is unmodified the corresponding element
107922** is set to -1). If the rowid column is modified by the UPDATE statement
107923** the bChngRowid argument is non-zero.
107924**
107925** This function returns true if any of the columns that are part of the
107926** child key for FK constraint *p are modified.
107927*/
107928static int fkChildIsModified(
107929  Table *pTab,                    /* Table being updated */
107930  FKey *p,                        /* Foreign key for which pTab is the child */
107931  int *aChange,                   /* Array indicating modified columns */
107932  int bChngRowid                  /* True if rowid is modified by this update */
107933){
107934  int i;
107935  for(i=0; i<p->nCol; i++){
107936    int iChildKey = p->aCol[i].iFrom;
107937    if( aChange[iChildKey]>=0 ) return 1;
107938    if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
107939  }
107940  return 0;
107941}
107942
107943/*
107944** The second argument points to an FKey object representing a foreign key
107945** for which pTab is the parent table. An UPDATE statement against pTab
107946** is currently being processed. For each column of the table that is
107947** actually updated, the corresponding element in the aChange[] array
107948** is zero or greater (if a column is unmodified the corresponding element
107949** is set to -1). If the rowid column is modified by the UPDATE statement
107950** the bChngRowid argument is non-zero.
107951**
107952** This function returns true if any of the columns that are part of the
107953** parent key for FK constraint *p are modified.
107954*/
107955static int fkParentIsModified(
107956  Table *pTab,
107957  FKey *p,
107958  int *aChange,
107959  int bChngRowid
107960){
107961  int i;
107962  for(i=0; i<p->nCol; i++){
107963    char *zKey = p->aCol[i].zCol;
107964    int iKey;
107965    for(iKey=0; iKey<pTab->nCol; iKey++){
107966      if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
107967        Column *pCol = &pTab->aCol[iKey];
107968        if( zKey ){
107969          if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
107970        }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
107971          return 1;
107972        }
107973      }
107974    }
107975  }
107976  return 0;
107977}
107978
107979/*
107980** Return true if the parser passed as the first argument is being
107981** used to code a trigger that is really a "SET NULL" action belonging
107982** to trigger pFKey.
107983*/
107984static int isSetNullAction(Parse *pParse, FKey *pFKey){
107985  Parse *pTop = sqlite3ParseToplevel(pParse);
107986  if( pTop->pTriggerPrg ){
107987    Trigger *p = pTop->pTriggerPrg->pTrigger;
107988    if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
107989     || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
107990    ){
107991      return 1;
107992    }
107993  }
107994  return 0;
107995}
107996
107997/*
107998** This function is called when inserting, deleting or updating a row of
107999** table pTab to generate VDBE code to perform foreign key constraint
108000** processing for the operation.
108001**
108002** For a DELETE operation, parameter regOld is passed the index of the
108003** first register in an array of (pTab->nCol+1) registers containing the
108004** rowid of the row being deleted, followed by each of the column values
108005** of the row being deleted, from left to right. Parameter regNew is passed
108006** zero in this case.
108007**
108008** For an INSERT operation, regOld is passed zero and regNew is passed the
108009** first register of an array of (pTab->nCol+1) registers containing the new
108010** row data.
108011**
108012** For an UPDATE operation, this function is called twice. Once before
108013** the original record is deleted from the table using the calling convention
108014** described for DELETE. Then again after the original record is deleted
108015** but before the new record is inserted using the INSERT convention.
108016*/
108017SQLITE_PRIVATE void sqlite3FkCheck(
108018  Parse *pParse,                  /* Parse context */
108019  Table *pTab,                    /* Row is being deleted from this table */
108020  int regOld,                     /* Previous row data is stored here */
108021  int regNew,                     /* New row data is stored here */
108022  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
108023  int bChngRowid                  /* True if rowid is UPDATEd */
108024){
108025  sqlite3 *db = pParse->db;       /* Database handle */
108026  FKey *pFKey;                    /* Used to iterate through FKs */
108027  int iDb;                        /* Index of database containing pTab */
108028  const char *zDb;                /* Name of database containing pTab */
108029  int isIgnoreErrors = pParse->disableTriggers;
108030
108031  /* Exactly one of regOld and regNew should be non-zero. */
108032  assert( (regOld==0)!=(regNew==0) );
108033
108034  /* If foreign-keys are disabled, this function is a no-op. */
108035  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
108036
108037  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
108038  zDb = db->aDb[iDb].zDbSName;
108039
108040  /* Loop through all the foreign key constraints for which pTab is the
108041  ** child table (the table that the foreign key definition is part of).  */
108042  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
108043    Table *pTo;                   /* Parent table of foreign key pFKey */
108044    Index *pIdx = 0;              /* Index on key columns in pTo */
108045    int *aiFree = 0;
108046    int *aiCol;
108047    int iCol;
108048    int i;
108049    int bIgnore = 0;
108050
108051    if( aChange
108052     && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
108053     && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
108054    ){
108055      continue;
108056    }
108057
108058    /* Find the parent table of this foreign key. Also find a unique index
108059    ** on the parent key columns in the parent table. If either of these
108060    ** schema items cannot be located, set an error in pParse and return
108061    ** early.  */
108062    if( pParse->disableTriggers ){
108063      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
108064    }else{
108065      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
108066    }
108067    if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
108068      assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
108069      if( !isIgnoreErrors || db->mallocFailed ) return;
108070      if( pTo==0 ){
108071        /* If isIgnoreErrors is true, then a table is being dropped. In this
108072        ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
108073        ** before actually dropping it in order to check FK constraints.
108074        ** If the parent table of an FK constraint on the current table is
108075        ** missing, behave as if it is empty. i.e. decrement the relevant
108076        ** FK counter for each row of the current table with non-NULL keys.
108077        */
108078        Vdbe *v = sqlite3GetVdbe(pParse);
108079        int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
108080        for(i=0; i<pFKey->nCol; i++){
108081          int iReg = pFKey->aCol[i].iFrom + regOld + 1;
108082          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
108083        }
108084        sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
108085      }
108086      continue;
108087    }
108088    assert( pFKey->nCol==1 || (aiFree && pIdx) );
108089
108090    if( aiFree ){
108091      aiCol = aiFree;
108092    }else{
108093      iCol = pFKey->aCol[0].iFrom;
108094      aiCol = &iCol;
108095    }
108096    for(i=0; i<pFKey->nCol; i++){
108097      if( aiCol[i]==pTab->iPKey ){
108098        aiCol[i] = -1;
108099      }
108100      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
108101#ifndef SQLITE_OMIT_AUTHORIZATION
108102      /* Request permission to read the parent key columns. If the
108103      ** authorization callback returns SQLITE_IGNORE, behave as if any
108104      ** values read from the parent table are NULL. */
108105      if( db->xAuth ){
108106        int rcauth;
108107        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
108108        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
108109        bIgnore = (rcauth==SQLITE_IGNORE);
108110      }
108111#endif
108112    }
108113
108114    /* Take a shared-cache advisory read-lock on the parent table. Allocate
108115    ** a cursor to use to search the unique index on the parent key columns
108116    ** in the parent table.  */
108117    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
108118    pParse->nTab++;
108119
108120    if( regOld!=0 ){
108121      /* A row is being removed from the child table. Search for the parent.
108122      ** If the parent does not exist, removing the child row resolves an
108123      ** outstanding foreign key constraint violation. */
108124      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
108125    }
108126    if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
108127      /* A row is being added to the child table. If a parent row cannot
108128      ** be found, adding the child row has violated the FK constraint.
108129      **
108130      ** If this operation is being performed as part of a trigger program
108131      ** that is actually a "SET NULL" action belonging to this very
108132      ** foreign key, then omit this scan altogether. As all child key
108133      ** values are guaranteed to be NULL, it is not possible for adding
108134      ** this row to cause an FK violation.  */
108135      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
108136    }
108137
108138    sqlite3DbFree(db, aiFree);
108139  }
108140
108141  /* Loop through all the foreign key constraints that refer to this table.
108142  ** (the "child" constraints) */
108143  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
108144    Index *pIdx = 0;              /* Foreign key index for pFKey */
108145    SrcList *pSrc;
108146    int *aiCol = 0;
108147
108148    if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
108149      continue;
108150    }
108151
108152    if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
108153     && !pParse->pToplevel && !pParse->isMultiWrite
108154    ){
108155      assert( regOld==0 && regNew!=0 );
108156      /* Inserting a single row into a parent table cannot cause (or fix)
108157      ** an immediate foreign key violation. So do nothing in this case.  */
108158      continue;
108159    }
108160
108161    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
108162      if( !isIgnoreErrors || db->mallocFailed ) return;
108163      continue;
108164    }
108165    assert( aiCol || pFKey->nCol==1 );
108166
108167    /* Create a SrcList structure containing the child table.  We need the
108168    ** child table as a SrcList for sqlite3WhereBegin() */
108169    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
108170    if( pSrc ){
108171      struct SrcList_item *pItem = pSrc->a;
108172      pItem->pTab = pFKey->pFrom;
108173      pItem->zName = pFKey->pFrom->zName;
108174      pItem->pTab->nTabRef++;
108175      pItem->iCursor = pParse->nTab++;
108176
108177      if( regNew!=0 ){
108178        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
108179      }
108180      if( regOld!=0 ){
108181        int eAction = pFKey->aAction[aChange!=0];
108182        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
108183        /* If this is a deferred FK constraint, or a CASCADE or SET NULL
108184        ** action applies, then any foreign key violations caused by
108185        ** removing the parent key will be rectified by the action trigger.
108186        ** So do not set the "may-abort" flag in this case.
108187        **
108188        ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
108189        ** may-abort flag will eventually be set on this statement anyway
108190        ** (when this function is called as part of processing the UPDATE
108191        ** within the action trigger).
108192        **
108193        ** Note 2: At first glance it may seem like SQLite could simply omit
108194        ** all OP_FkCounter related scans when either CASCADE or SET NULL
108195        ** applies. The trouble starts if the CASCADE or SET NULL action
108196        ** trigger causes other triggers or action rules attached to the
108197        ** child table to fire. In these cases the fk constraint counters
108198        ** might be set incorrectly if any OP_FkCounter related scans are
108199        ** omitted.  */
108200        if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
108201          sqlite3MayAbort(pParse);
108202        }
108203      }
108204      pItem->zName = 0;
108205      sqlite3SrcListDelete(db, pSrc);
108206    }
108207    sqlite3DbFree(db, aiCol);
108208  }
108209}
108210
108211#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
108212
108213/*
108214** This function is called before generating code to update or delete a
108215** row contained in table pTab.
108216*/
108217SQLITE_PRIVATE u32 sqlite3FkOldmask(
108218  Parse *pParse,                  /* Parse context */
108219  Table *pTab                     /* Table being modified */
108220){
108221  u32 mask = 0;
108222  if( pParse->db->flags&SQLITE_ForeignKeys ){
108223    FKey *p;
108224    int i;
108225    for(p=pTab->pFKey; p; p=p->pNextFrom){
108226      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
108227    }
108228    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
108229      Index *pIdx = 0;
108230      sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
108231      if( pIdx ){
108232        for(i=0; i<pIdx->nKeyCol; i++){
108233          assert( pIdx->aiColumn[i]>=0 );
108234          mask |= COLUMN_MASK(pIdx->aiColumn[i]);
108235        }
108236      }
108237    }
108238  }
108239  return mask;
108240}
108241
108242
108243/*
108244** This function is called before generating code to update or delete a
108245** row contained in table pTab. If the operation is a DELETE, then
108246** parameter aChange is passed a NULL value. For an UPDATE, aChange points
108247** to an array of size N, where N is the number of columns in table pTab.
108248** If the i'th column is not modified by the UPDATE, then the corresponding
108249** entry in the aChange[] array is set to -1. If the column is modified,
108250** the value is 0 or greater. Parameter chngRowid is set to true if the
108251** UPDATE statement modifies the rowid fields of the table.
108252**
108253** If any foreign key processing will be required, this function returns
108254** true. If there is no foreign key related processing, this function
108255** returns false.
108256*/
108257SQLITE_PRIVATE int sqlite3FkRequired(
108258  Parse *pParse,                  /* Parse context */
108259  Table *pTab,                    /* Table being modified */
108260  int *aChange,                   /* Non-NULL for UPDATE operations */
108261  int chngRowid                   /* True for UPDATE that affects rowid */
108262){
108263  if( pParse->db->flags&SQLITE_ForeignKeys ){
108264    if( !aChange ){
108265      /* A DELETE operation. Foreign key processing is required if the
108266      ** table in question is either the child or parent table for any
108267      ** foreign key constraint.  */
108268      return (sqlite3FkReferences(pTab) || pTab->pFKey);
108269    }else{
108270      /* This is an UPDATE. Foreign key processing is only required if the
108271      ** operation modifies one or more child or parent key columns. */
108272      FKey *p;
108273
108274      /* Check if any child key columns are being modified. */
108275      for(p=pTab->pFKey; p; p=p->pNextFrom){
108276        if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
108277      }
108278
108279      /* Check if any parent key columns are being modified. */
108280      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
108281        if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
108282      }
108283    }
108284  }
108285  return 0;
108286}
108287
108288/*
108289** This function is called when an UPDATE or DELETE operation is being
108290** compiled on table pTab, which is the parent table of foreign-key pFKey.
108291** If the current operation is an UPDATE, then the pChanges parameter is
108292** passed a pointer to the list of columns being modified. If it is a
108293** DELETE, pChanges is passed a NULL pointer.
108294**
108295** It returns a pointer to a Trigger structure containing a trigger
108296** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
108297** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
108298** returned (these actions require no special handling by the triggers
108299** sub-system, code for them is created by fkScanChildren()).
108300**
108301** For example, if pFKey is the foreign key and pTab is table "p" in
108302** the following schema:
108303**
108304**   CREATE TABLE p(pk PRIMARY KEY);
108305**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
108306**
108307** then the returned trigger structure is equivalent to:
108308**
108309**   CREATE TRIGGER ... DELETE ON p BEGIN
108310**     DELETE FROM c WHERE ck = old.pk;
108311**   END;
108312**
108313** The returned pointer is cached as part of the foreign key object. It
108314** is eventually freed along with the rest of the foreign key object by
108315** sqlite3FkDelete().
108316*/
108317static Trigger *fkActionTrigger(
108318  Parse *pParse,                  /* Parse context */
108319  Table *pTab,                    /* Table being updated or deleted from */
108320  FKey *pFKey,                    /* Foreign key to get action for */
108321  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
108322){
108323  sqlite3 *db = pParse->db;       /* Database handle */
108324  int action;                     /* One of OE_None, OE_Cascade etc. */
108325  Trigger *pTrigger;              /* Trigger definition to return */
108326  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
108327
108328  action = pFKey->aAction[iAction];
108329  if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
108330    return 0;
108331  }
108332  pTrigger = pFKey->apTrigger[iAction];
108333
108334  if( action!=OE_None && !pTrigger ){
108335    char const *zFrom;            /* Name of child table */
108336    int nFrom;                    /* Length in bytes of zFrom */
108337    Index *pIdx = 0;              /* Parent key index for this FK */
108338    int *aiCol = 0;               /* child table cols -> parent key cols */
108339    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
108340    Expr *pWhere = 0;             /* WHERE clause of trigger step */
108341    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
108342    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
108343    int i;                        /* Iterator variable */
108344    Expr *pWhen = 0;              /* WHEN clause for the trigger */
108345
108346    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
108347    assert( aiCol || pFKey->nCol==1 );
108348
108349    for(i=0; i<pFKey->nCol; i++){
108350      Token tOld = { "old", 3 };  /* Literal "old" token */
108351      Token tNew = { "new", 3 };  /* Literal "new" token */
108352      Token tFromCol;             /* Name of column in child table */
108353      Token tToCol;               /* Name of column in parent table */
108354      int iFromCol;               /* Idx of column in child table */
108355      Expr *pEq;                  /* tFromCol = OLD.tToCol */
108356
108357      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
108358      assert( iFromCol>=0 );
108359      assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
108360      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
108361      sqlite3TokenInit(&tToCol,
108362                   pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
108363      sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
108364
108365      /* Create the expression "OLD.zToCol = zFromCol". It is important
108366      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
108367      ** that the affinity and collation sequence associated with the
108368      ** parent table are used for the comparison. */
108369      pEq = sqlite3PExpr(pParse, TK_EQ,
108370          sqlite3PExpr(pParse, TK_DOT,
108371            sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
108372            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
108373          sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
108374      );
108375      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
108376
108377      /* For ON UPDATE, construct the next term of the WHEN clause.
108378      ** The final WHEN clause will be like this:
108379      **
108380      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
108381      */
108382      if( pChanges ){
108383        pEq = sqlite3PExpr(pParse, TK_IS,
108384            sqlite3PExpr(pParse, TK_DOT,
108385              sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
108386              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
108387            sqlite3PExpr(pParse, TK_DOT,
108388              sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
108389              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
108390            );
108391        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
108392      }
108393
108394      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
108395        Expr *pNew;
108396        if( action==OE_Cascade ){
108397          pNew = sqlite3PExpr(pParse, TK_DOT,
108398            sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
108399            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
108400        }else if( action==OE_SetDflt ){
108401          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
108402          if( pDflt ){
108403            pNew = sqlite3ExprDup(db, pDflt, 0);
108404          }else{
108405            pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
108406          }
108407        }else{
108408          pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
108409        }
108410        pList = sqlite3ExprListAppend(pParse, pList, pNew);
108411        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
108412      }
108413    }
108414    sqlite3DbFree(db, aiCol);
108415
108416    zFrom = pFKey->pFrom->zName;
108417    nFrom = sqlite3Strlen30(zFrom);
108418
108419    if( action==OE_Restrict ){
108420      Token tFrom;
108421      Expr *pRaise;
108422
108423      tFrom.z = zFrom;
108424      tFrom.n = nFrom;
108425      pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
108426      if( pRaise ){
108427        pRaise->affinity = OE_Abort;
108428      }
108429      pSelect = sqlite3SelectNew(pParse,
108430          sqlite3ExprListAppend(pParse, 0, pRaise),
108431          sqlite3SrcListAppend(db, 0, &tFrom, 0),
108432          pWhere,
108433          0, 0, 0, 0, 0, 0
108434      );
108435      pWhere = 0;
108436    }
108437
108438    /* Disable lookaside memory allocation */
108439    db->lookaside.bDisable++;
108440
108441    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
108442        sizeof(Trigger) +         /* struct Trigger */
108443        sizeof(TriggerStep) +     /* Single step in trigger program */
108444        nFrom + 1                 /* Space for pStep->zTarget */
108445    );
108446    if( pTrigger ){
108447      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
108448      pStep->zTarget = (char *)&pStep[1];
108449      memcpy((char *)pStep->zTarget, zFrom, nFrom);
108450
108451      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
108452      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
108453      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
108454      if( pWhen ){
108455        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
108456        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
108457      }
108458    }
108459
108460    /* Re-enable the lookaside buffer, if it was disabled earlier. */
108461    db->lookaside.bDisable--;
108462
108463    sqlite3ExprDelete(db, pWhere);
108464    sqlite3ExprDelete(db, pWhen);
108465    sqlite3ExprListDelete(db, pList);
108466    sqlite3SelectDelete(db, pSelect);
108467    if( db->mallocFailed==1 ){
108468      fkTriggerDelete(db, pTrigger);
108469      return 0;
108470    }
108471    assert( pStep!=0 );
108472
108473    switch( action ){
108474      case OE_Restrict:
108475        pStep->op = TK_SELECT;
108476        break;
108477      case OE_Cascade:
108478        if( !pChanges ){
108479          pStep->op = TK_DELETE;
108480          break;
108481        }
108482      default:
108483        pStep->op = TK_UPDATE;
108484    }
108485    pStep->pTrig = pTrigger;
108486    pTrigger->pSchema = pTab->pSchema;
108487    pTrigger->pTabSchema = pTab->pSchema;
108488    pFKey->apTrigger[iAction] = pTrigger;
108489    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
108490  }
108491
108492  return pTrigger;
108493}
108494
108495/*
108496** This function is called when deleting or updating a row to implement
108497** any required CASCADE, SET NULL or SET DEFAULT actions.
108498*/
108499SQLITE_PRIVATE void sqlite3FkActions(
108500  Parse *pParse,                  /* Parse context */
108501  Table *pTab,                    /* Table being updated or deleted from */
108502  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
108503  int regOld,                     /* Address of array containing old row */
108504  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
108505  int bChngRowid                  /* True if rowid is UPDATEd */
108506){
108507  /* If foreign-key support is enabled, iterate through all FKs that
108508  ** refer to table pTab. If there is an action associated with the FK
108509  ** for this operation (either update or delete), invoke the associated
108510  ** trigger sub-program.  */
108511  if( pParse->db->flags&SQLITE_ForeignKeys ){
108512    FKey *pFKey;                  /* Iterator variable */
108513    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
108514      if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
108515        Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
108516        if( pAct ){
108517          sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
108518        }
108519      }
108520    }
108521  }
108522}
108523
108524#endif /* ifndef SQLITE_OMIT_TRIGGER */
108525
108526/*
108527** Free all memory associated with foreign key definitions attached to
108528** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
108529** hash table.
108530*/
108531SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
108532  FKey *pFKey;                    /* Iterator variable */
108533  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
108534
108535  assert( db==0 || IsVirtual(pTab)
108536         || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
108537  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
108538
108539    /* Remove the FK from the fkeyHash hash table. */
108540    if( !db || db->pnBytesFreed==0 ){
108541      if( pFKey->pPrevTo ){
108542        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
108543      }else{
108544        void *p = (void *)pFKey->pNextTo;
108545        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
108546        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
108547      }
108548      if( pFKey->pNextTo ){
108549        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
108550      }
108551    }
108552
108553    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
108554    ** classified as either immediate or deferred.
108555    */
108556    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
108557
108558    /* Delete any triggers created to implement actions for this FK. */
108559#ifndef SQLITE_OMIT_TRIGGER
108560    fkTriggerDelete(db, pFKey->apTrigger[0]);
108561    fkTriggerDelete(db, pFKey->apTrigger[1]);
108562#endif
108563
108564    pNext = pFKey->pNextFrom;
108565    sqlite3DbFree(db, pFKey);
108566  }
108567}
108568#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
108569
108570/************** End of fkey.c ************************************************/
108571/************** Begin file insert.c ******************************************/
108572/*
108573** 2001 September 15
108574**
108575** The author disclaims copyright to this source code.  In place of
108576** a legal notice, here is a blessing:
108577**
108578**    May you do good and not evil.
108579**    May you find forgiveness for yourself and forgive others.
108580**    May you share freely, never taking more than you give.
108581**
108582*************************************************************************
108583** This file contains C code routines that are called by the parser
108584** to handle INSERT statements in SQLite.
108585*/
108586/* #include "sqliteInt.h" */
108587
108588/*
108589** Generate code that will
108590**
108591**   (1) acquire a lock for table pTab then
108592**   (2) open pTab as cursor iCur.
108593**
108594** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
108595** for that table that is actually opened.
108596*/
108597SQLITE_PRIVATE void sqlite3OpenTable(
108598  Parse *pParse,  /* Generate code into this VDBE */
108599  int iCur,       /* The cursor number of the table */
108600  int iDb,        /* The database index in sqlite3.aDb[] */
108601  Table *pTab,    /* The table to be opened */
108602  int opcode      /* OP_OpenRead or OP_OpenWrite */
108603){
108604  Vdbe *v;
108605  assert( !IsVirtual(pTab) );
108606  v = sqlite3GetVdbe(pParse);
108607  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
108608  sqlite3TableLock(pParse, iDb, pTab->tnum,
108609                   (opcode==OP_OpenWrite)?1:0, pTab->zName);
108610  if( HasRowid(pTab) ){
108611    sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
108612    VdbeComment((v, "%s", pTab->zName));
108613  }else{
108614    Index *pPk = sqlite3PrimaryKeyIndex(pTab);
108615    assert( pPk!=0 );
108616    assert( pPk->tnum==pTab->tnum );
108617    sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
108618    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
108619    VdbeComment((v, "%s", pTab->zName));
108620  }
108621}
108622
108623/*
108624** Return a pointer to the column affinity string associated with index
108625** pIdx. A column affinity string has one character for each column in
108626** the table, according to the affinity of the column:
108627**
108628**  Character      Column affinity
108629**  ------------------------------
108630**  'A'            BLOB
108631**  'B'            TEXT
108632**  'C'            NUMERIC
108633**  'D'            INTEGER
108634**  'F'            REAL
108635**
108636** An extra 'D' is appended to the end of the string to cover the
108637** rowid that appears as the last column in every index.
108638**
108639** Memory for the buffer containing the column index affinity string
108640** is managed along with the rest of the Index structure. It will be
108641** released when sqlite3DeleteIndex() is called.
108642*/
108643SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
108644  if( !pIdx->zColAff ){
108645    /* The first time a column affinity string for a particular index is
108646    ** required, it is allocated and populated here. It is then stored as
108647    ** a member of the Index structure for subsequent use.
108648    **
108649    ** The column affinity string will eventually be deleted by
108650    ** sqliteDeleteIndex() when the Index structure itself is cleaned
108651    ** up.
108652    */
108653    int n;
108654    Table *pTab = pIdx->pTable;
108655    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
108656    if( !pIdx->zColAff ){
108657      sqlite3OomFault(db);
108658      return 0;
108659    }
108660    for(n=0; n<pIdx->nColumn; n++){
108661      i16 x = pIdx->aiColumn[n];
108662      if( x>=0 ){
108663        pIdx->zColAff[n] = pTab->aCol[x].affinity;
108664      }else if( x==XN_ROWID ){
108665        pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
108666      }else{
108667        char aff;
108668        assert( x==XN_EXPR );
108669        assert( pIdx->aColExpr!=0 );
108670        aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
108671        if( aff==0 ) aff = SQLITE_AFF_BLOB;
108672        pIdx->zColAff[n] = aff;
108673      }
108674    }
108675    pIdx->zColAff[n] = 0;
108676  }
108677
108678  return pIdx->zColAff;
108679}
108680
108681/*
108682** Compute the affinity string for table pTab, if it has not already been
108683** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
108684**
108685** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
108686** if iReg>0 then code an OP_Affinity opcode that will set the affinities
108687** for register iReg and following.  Or if affinities exists and iReg==0,
108688** then just set the P4 operand of the previous opcode (which should  be
108689** an OP_MakeRecord) to the affinity string.
108690**
108691** A column affinity string has one character per column:
108692**
108693**  Character      Column affinity
108694**  ------------------------------
108695**  'A'            BLOB
108696**  'B'            TEXT
108697**  'C'            NUMERIC
108698**  'D'            INTEGER
108699**  'E'            REAL
108700*/
108701SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
108702  int i;
108703  char *zColAff = pTab->zColAff;
108704  if( zColAff==0 ){
108705    sqlite3 *db = sqlite3VdbeDb(v);
108706    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
108707    if( !zColAff ){
108708      sqlite3OomFault(db);
108709      return;
108710    }
108711
108712    for(i=0; i<pTab->nCol; i++){
108713      zColAff[i] = pTab->aCol[i].affinity;
108714    }
108715    do{
108716      zColAff[i--] = 0;
108717    }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
108718    pTab->zColAff = zColAff;
108719  }
108720  i = sqlite3Strlen30(zColAff);
108721  if( i ){
108722    if( iReg ){
108723      sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
108724    }else{
108725      sqlite3VdbeChangeP4(v, -1, zColAff, i);
108726    }
108727  }
108728}
108729
108730/*
108731** Return non-zero if the table pTab in database iDb or any of its indices
108732** have been opened at any point in the VDBE program. This is used to see if
108733** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
108734** run without using a temporary table for the results of the SELECT.
108735*/
108736static int readsTable(Parse *p, int iDb, Table *pTab){
108737  Vdbe *v = sqlite3GetVdbe(p);
108738  int i;
108739  int iEnd = sqlite3VdbeCurrentAddr(v);
108740#ifndef SQLITE_OMIT_VIRTUALTABLE
108741  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
108742#endif
108743
108744  for(i=1; i<iEnd; i++){
108745    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
108746    assert( pOp!=0 );
108747    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
108748      Index *pIndex;
108749      int tnum = pOp->p2;
108750      if( tnum==pTab->tnum ){
108751        return 1;
108752      }
108753      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
108754        if( tnum==pIndex->tnum ){
108755          return 1;
108756        }
108757      }
108758    }
108759#ifndef SQLITE_OMIT_VIRTUALTABLE
108760    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
108761      assert( pOp->p4.pVtab!=0 );
108762      assert( pOp->p4type==P4_VTAB );
108763      return 1;
108764    }
108765#endif
108766  }
108767  return 0;
108768}
108769
108770#ifndef SQLITE_OMIT_AUTOINCREMENT
108771/*
108772** Locate or create an AutoincInfo structure associated with table pTab
108773** which is in database iDb.  Return the register number for the register
108774** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
108775** table.  (Also return zero when doing a VACUUM since we do not want to
108776** update the AUTOINCREMENT counters during a VACUUM.)
108777**
108778** There is at most one AutoincInfo structure per table even if the
108779** same table is autoincremented multiple times due to inserts within
108780** triggers.  A new AutoincInfo structure is created if this is the
108781** first use of table pTab.  On 2nd and subsequent uses, the original
108782** AutoincInfo structure is used.
108783**
108784** Three memory locations are allocated:
108785**
108786**   (1)  Register to hold the name of the pTab table.
108787**   (2)  Register to hold the maximum ROWID of pTab.
108788**   (3)  Register to hold the rowid in sqlite_sequence of pTab
108789**
108790** The 2nd register is the one that is returned.  That is all the
108791** insert routine needs to know about.
108792*/
108793static int autoIncBegin(
108794  Parse *pParse,      /* Parsing context */
108795  int iDb,            /* Index of the database holding pTab */
108796  Table *pTab         /* The table we are writing to */
108797){
108798  int memId = 0;      /* Register holding maximum rowid */
108799  if( (pTab->tabFlags & TF_Autoincrement)!=0
108800   && (pParse->db->flags & SQLITE_Vacuum)==0
108801  ){
108802    Parse *pToplevel = sqlite3ParseToplevel(pParse);
108803    AutoincInfo *pInfo;
108804
108805    pInfo = pToplevel->pAinc;
108806    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
108807    if( pInfo==0 ){
108808      pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
108809      if( pInfo==0 ) return 0;
108810      pInfo->pNext = pToplevel->pAinc;
108811      pToplevel->pAinc = pInfo;
108812      pInfo->pTab = pTab;
108813      pInfo->iDb = iDb;
108814      pToplevel->nMem++;                  /* Register to hold name of table */
108815      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
108816      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
108817    }
108818    memId = pInfo->regCtr;
108819  }
108820  return memId;
108821}
108822
108823/*
108824** This routine generates code that will initialize all of the
108825** register used by the autoincrement tracker.
108826*/
108827SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
108828  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
108829  sqlite3 *db = pParse->db;  /* The database connection */
108830  Db *pDb;                   /* Database only autoinc table */
108831  int memId;                 /* Register holding max rowid */
108832  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
108833
108834  /* This routine is never called during trigger-generation.  It is
108835  ** only called from the top-level */
108836  assert( pParse->pTriggerTab==0 );
108837  assert( sqlite3IsToplevel(pParse) );
108838
108839  assert( v );   /* We failed long ago if this is not so */
108840  for(p = pParse->pAinc; p; p = p->pNext){
108841    static const int iLn = VDBE_OFFSET_LINENO(2);
108842    static const VdbeOpList autoInc[] = {
108843      /* 0  */ {OP_Null,    0,  0, 0},
108844      /* 1  */ {OP_Rewind,  0,  9, 0},
108845      /* 2  */ {OP_Column,  0,  0, 0},
108846      /* 3  */ {OP_Ne,      0,  7, 0},
108847      /* 4  */ {OP_Rowid,   0,  0, 0},
108848      /* 5  */ {OP_Column,  0,  1, 0},
108849      /* 6  */ {OP_Goto,    0,  9, 0},
108850      /* 7  */ {OP_Next,    0,  2, 0},
108851      /* 8  */ {OP_Integer, 0,  0, 0},
108852      /* 9  */ {OP_Close,   0,  0, 0}
108853    };
108854    VdbeOp *aOp;
108855    pDb = &db->aDb[p->iDb];
108856    memId = p->regCtr;
108857    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
108858    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
108859    sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
108860    aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
108861    if( aOp==0 ) break;
108862    aOp[0].p2 = memId;
108863    aOp[0].p3 = memId+1;
108864    aOp[2].p3 = memId;
108865    aOp[3].p1 = memId-1;
108866    aOp[3].p3 = memId;
108867    aOp[3].p5 = SQLITE_JUMPIFNULL;
108868    aOp[4].p2 = memId+1;
108869    aOp[5].p3 = memId;
108870    aOp[8].p2 = memId;
108871  }
108872}
108873
108874/*
108875** Update the maximum rowid for an autoincrement calculation.
108876**
108877** This routine should be called when the regRowid register holds a
108878** new rowid that is about to be inserted.  If that new rowid is
108879** larger than the maximum rowid in the memId memory cell, then the
108880** memory cell is updated.
108881*/
108882static void autoIncStep(Parse *pParse, int memId, int regRowid){
108883  if( memId>0 ){
108884    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
108885  }
108886}
108887
108888/*
108889** This routine generates the code needed to write autoincrement
108890** maximum rowid values back into the sqlite_sequence register.
108891** Every statement that might do an INSERT into an autoincrement
108892** table (either directly or through triggers) needs to call this
108893** routine just before the "exit" code.
108894*/
108895static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
108896  AutoincInfo *p;
108897  Vdbe *v = pParse->pVdbe;
108898  sqlite3 *db = pParse->db;
108899
108900  assert( v );
108901  for(p = pParse->pAinc; p; p = p->pNext){
108902    static const int iLn = VDBE_OFFSET_LINENO(2);
108903    static const VdbeOpList autoIncEnd[] = {
108904      /* 0 */ {OP_NotNull,     0, 2, 0},
108905      /* 1 */ {OP_NewRowid,    0, 0, 0},
108906      /* 2 */ {OP_MakeRecord,  0, 2, 0},
108907      /* 3 */ {OP_Insert,      0, 0, 0},
108908      /* 4 */ {OP_Close,       0, 0, 0}
108909    };
108910    VdbeOp *aOp;
108911    Db *pDb = &db->aDb[p->iDb];
108912    int iRec;
108913    int memId = p->regCtr;
108914
108915    iRec = sqlite3GetTempReg(pParse);
108916    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
108917    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
108918    aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
108919    if( aOp==0 ) break;
108920    aOp[0].p1 = memId+1;
108921    aOp[1].p2 = memId+1;
108922    aOp[2].p1 = memId-1;
108923    aOp[2].p3 = iRec;
108924    aOp[3].p2 = iRec;
108925    aOp[3].p3 = memId+1;
108926    aOp[3].p5 = OPFLAG_APPEND;
108927    sqlite3ReleaseTempReg(pParse, iRec);
108928  }
108929}
108930SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
108931  if( pParse->pAinc ) autoIncrementEnd(pParse);
108932}
108933#else
108934/*
108935** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
108936** above are all no-ops
108937*/
108938# define autoIncBegin(A,B,C) (0)
108939# define autoIncStep(A,B,C)
108940#endif /* SQLITE_OMIT_AUTOINCREMENT */
108941
108942
108943/* Forward declaration */
108944static int xferOptimization(
108945  Parse *pParse,        /* Parser context */
108946  Table *pDest,         /* The table we are inserting into */
108947  Select *pSelect,      /* A SELECT statement to use as the data source */
108948  int onError,          /* How to handle constraint errors */
108949  int iDbDest           /* The database of pDest */
108950);
108951
108952/*
108953** This routine is called to handle SQL of the following forms:
108954**
108955**    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
108956**    insert into TABLE (IDLIST) select
108957**    insert into TABLE (IDLIST) default values
108958**
108959** The IDLIST following the table name is always optional.  If omitted,
108960** then a list of all (non-hidden) columns for the table is substituted.
108961** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
108962** is omitted.
108963**
108964** For the pSelect parameter holds the values to be inserted for the
108965** first two forms shown above.  A VALUES clause is really just short-hand
108966** for a SELECT statement that omits the FROM clause and everything else
108967** that follows.  If the pSelect parameter is NULL, that means that the
108968** DEFAULT VALUES form of the INSERT statement is intended.
108969**
108970** The code generated follows one of four templates.  For a simple
108971** insert with data coming from a single-row VALUES clause, the code executes
108972** once straight down through.  Pseudo-code follows (we call this
108973** the "1st template"):
108974**
108975**         open write cursor to <table> and its indices
108976**         put VALUES clause expressions into registers
108977**         write the resulting record into <table>
108978**         cleanup
108979**
108980** The three remaining templates assume the statement is of the form
108981**
108982**   INSERT INTO <table> SELECT ...
108983**
108984** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
108985** in other words if the SELECT pulls all columns from a single table
108986** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
108987** if <table2> and <table1> are distinct tables but have identical
108988** schemas, including all the same indices, then a special optimization
108989** is invoked that copies raw records from <table2> over to <table1>.
108990** See the xferOptimization() function for the implementation of this
108991** template.  This is the 2nd template.
108992**
108993**         open a write cursor to <table>
108994**         open read cursor on <table2>
108995**         transfer all records in <table2> over to <table>
108996**         close cursors
108997**         foreach index on <table>
108998**           open a write cursor on the <table> index
108999**           open a read cursor on the corresponding <table2> index
109000**           transfer all records from the read to the write cursors
109001**           close cursors
109002**         end foreach
109003**
109004** The 3rd template is for when the second template does not apply
109005** and the SELECT clause does not read from <table> at any time.
109006** The generated code follows this template:
109007**
109008**         X <- A
109009**         goto B
109010**      A: setup for the SELECT
109011**         loop over the rows in the SELECT
109012**           load values into registers R..R+n
109013**           yield X
109014**         end loop
109015**         cleanup after the SELECT
109016**         end-coroutine X
109017**      B: open write cursor to <table> and its indices
109018**      C: yield X, at EOF goto D
109019**         insert the select result into <table> from R..R+n
109020**         goto C
109021**      D: cleanup
109022**
109023** The 4th template is used if the insert statement takes its
109024** values from a SELECT but the data is being inserted into a table
109025** that is also read as part of the SELECT.  In the third form,
109026** we have to use an intermediate table to store the results of
109027** the select.  The template is like this:
109028**
109029**         X <- A
109030**         goto B
109031**      A: setup for the SELECT
109032**         loop over the tables in the SELECT
109033**           load value into register R..R+n
109034**           yield X
109035**         end loop
109036**         cleanup after the SELECT
109037**         end co-routine R
109038**      B: open temp table
109039**      L: yield X, at EOF goto M
109040**         insert row from R..R+n into temp table
109041**         goto L
109042**      M: open write cursor to <table> and its indices
109043**         rewind temp table
109044**      C: loop over rows of intermediate table
109045**           transfer values form intermediate table into <table>
109046**         end loop
109047**      D: cleanup
109048*/
109049SQLITE_PRIVATE void sqlite3Insert(
109050  Parse *pParse,        /* Parser context */
109051  SrcList *pTabList,    /* Name of table into which we are inserting */
109052  Select *pSelect,      /* A SELECT statement to use as the data source */
109053  IdList *pColumn,      /* Column names corresponding to IDLIST. */
109054  int onError           /* How to handle constraint errors */
109055){
109056  sqlite3 *db;          /* The main database structure */
109057  Table *pTab;          /* The table to insert into.  aka TABLE */
109058  char *zTab;           /* Name of the table into which we are inserting */
109059  int i, j;             /* Loop counters */
109060  Vdbe *v;              /* Generate code into this virtual machine */
109061  Index *pIdx;          /* For looping over indices of the table */
109062  int nColumn;          /* Number of columns in the data */
109063  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
109064  int iDataCur = 0;     /* VDBE cursor that is the main data repository */
109065  int iIdxCur = 0;      /* First index cursor */
109066  int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
109067  int endOfLoop;        /* Label for the end of the insertion loop */
109068  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
109069  int addrInsTop = 0;   /* Jump to label "D" */
109070  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
109071  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
109072  int iDb;              /* Index of database holding TABLE */
109073  u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
109074  u8 appendFlag = 0;    /* True if the insert is likely to be an append */
109075  u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
109076  u8 bIdListInOrder;    /* True if IDLIST is in table order */
109077  ExprList *pList = 0;  /* List of VALUES() to be inserted  */
109078
109079  /* Register allocations */
109080  int regFromSelect = 0;/* Base register for data coming from SELECT */
109081  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
109082  int regRowCount = 0;  /* Memory cell used for the row counter */
109083  int regIns;           /* Block of regs holding rowid+data being inserted */
109084  int regRowid;         /* registers holding insert rowid */
109085  int regData;          /* register holding first column to insert */
109086  int *aRegIdx = 0;     /* One register allocated to each index */
109087
109088#ifndef SQLITE_OMIT_TRIGGER
109089  int isView;                 /* True if attempting to insert into a view */
109090  Trigger *pTrigger;          /* List of triggers on pTab, if required */
109091  int tmask;                  /* Mask of trigger times */
109092#endif
109093
109094  db = pParse->db;
109095  memset(&dest, 0, sizeof(dest));
109096  if( pParse->nErr || db->mallocFailed ){
109097    goto insert_cleanup;
109098  }
109099
109100  /* If the Select object is really just a simple VALUES() list with a
109101  ** single row (the common case) then keep that one row of values
109102  ** and discard the other (unused) parts of the pSelect object
109103  */
109104  if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
109105    pList = pSelect->pEList;
109106    pSelect->pEList = 0;
109107    sqlite3SelectDelete(db, pSelect);
109108    pSelect = 0;
109109  }
109110
109111  /* Locate the table into which we will be inserting new information.
109112  */
109113  assert( pTabList->nSrc==1 );
109114  zTab = pTabList->a[0].zName;
109115  if( NEVER(zTab==0) ) goto insert_cleanup;
109116  pTab = sqlite3SrcListLookup(pParse, pTabList);
109117  if( pTab==0 ){
109118    goto insert_cleanup;
109119  }
109120  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
109121  assert( iDb<db->nDb );
109122  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
109123                       db->aDb[iDb].zDbSName) ){
109124    goto insert_cleanup;
109125  }
109126  withoutRowid = !HasRowid(pTab);
109127
109128  /* Figure out if we have any triggers and if the table being
109129  ** inserted into is a view
109130  */
109131#ifndef SQLITE_OMIT_TRIGGER
109132  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
109133  isView = pTab->pSelect!=0;
109134#else
109135# define pTrigger 0
109136# define tmask 0
109137# define isView 0
109138#endif
109139#ifdef SQLITE_OMIT_VIEW
109140# undef isView
109141# define isView 0
109142#endif
109143  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
109144
109145  /* If pTab is really a view, make sure it has been initialized.
109146  ** ViewGetColumnNames() is a no-op if pTab is not a view.
109147  */
109148  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
109149    goto insert_cleanup;
109150  }
109151
109152  /* Cannot insert into a read-only table.
109153  */
109154  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
109155    goto insert_cleanup;
109156  }
109157
109158  /* Allocate a VDBE
109159  */
109160  v = sqlite3GetVdbe(pParse);
109161  if( v==0 ) goto insert_cleanup;
109162  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
109163  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
109164
109165#ifndef SQLITE_OMIT_XFER_OPT
109166  /* If the statement is of the form
109167  **
109168  **       INSERT INTO <table1> SELECT * FROM <table2>;
109169  **
109170  ** Then special optimizations can be applied that make the transfer
109171  ** very fast and which reduce fragmentation of indices.
109172  **
109173  ** This is the 2nd template.
109174  */
109175  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
109176    assert( !pTrigger );
109177    assert( pList==0 );
109178    goto insert_end;
109179  }
109180#endif /* SQLITE_OMIT_XFER_OPT */
109181
109182  /* If this is an AUTOINCREMENT table, look up the sequence number in the
109183  ** sqlite_sequence table and store it in memory cell regAutoinc.
109184  */
109185  regAutoinc = autoIncBegin(pParse, iDb, pTab);
109186
109187  /* Allocate registers for holding the rowid of the new row,
109188  ** the content of the new row, and the assembled row record.
109189  */
109190  regRowid = regIns = pParse->nMem+1;
109191  pParse->nMem += pTab->nCol + 1;
109192  if( IsVirtual(pTab) ){
109193    regRowid++;
109194    pParse->nMem++;
109195  }
109196  regData = regRowid+1;
109197
109198  /* If the INSERT statement included an IDLIST term, then make sure
109199  ** all elements of the IDLIST really are columns of the table and
109200  ** remember the column indices.
109201  **
109202  ** If the table has an INTEGER PRIMARY KEY column and that column
109203  ** is named in the IDLIST, then record in the ipkColumn variable
109204  ** the index into IDLIST of the primary key column.  ipkColumn is
109205  ** the index of the primary key as it appears in IDLIST, not as
109206  ** is appears in the original table.  (The index of the INTEGER
109207  ** PRIMARY KEY in the original table is pTab->iPKey.)
109208  */
109209  bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
109210  if( pColumn ){
109211    for(i=0; i<pColumn->nId; i++){
109212      pColumn->a[i].idx = -1;
109213    }
109214    for(i=0; i<pColumn->nId; i++){
109215      for(j=0; j<pTab->nCol; j++){
109216        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
109217          pColumn->a[i].idx = j;
109218          if( i!=j ) bIdListInOrder = 0;
109219          if( j==pTab->iPKey ){
109220            ipkColumn = i;  assert( !withoutRowid );
109221          }
109222          break;
109223        }
109224      }
109225      if( j>=pTab->nCol ){
109226        if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
109227          ipkColumn = i;
109228          bIdListInOrder = 0;
109229        }else{
109230          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
109231              pTabList, 0, pColumn->a[i].zName);
109232          pParse->checkSchema = 1;
109233          goto insert_cleanup;
109234        }
109235      }
109236    }
109237  }
109238
109239  /* Figure out how many columns of data are supplied.  If the data
109240  ** is coming from a SELECT statement, then generate a co-routine that
109241  ** produces a single row of the SELECT on each invocation.  The
109242  ** co-routine is the common header to the 3rd and 4th templates.
109243  */
109244  if( pSelect ){
109245    /* Data is coming from a SELECT or from a multi-row VALUES clause.
109246    ** Generate a co-routine to run the SELECT. */
109247    int regYield;       /* Register holding co-routine entry-point */
109248    int addrTop;        /* Top of the co-routine */
109249    int rc;             /* Result code */
109250
109251    regYield = ++pParse->nMem;
109252    addrTop = sqlite3VdbeCurrentAddr(v) + 1;
109253    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
109254    sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
109255    dest.iSdst = bIdListInOrder ? regData : 0;
109256    dest.nSdst = pTab->nCol;
109257    rc = sqlite3Select(pParse, pSelect, &dest);
109258    regFromSelect = dest.iSdst;
109259    if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
109260    sqlite3VdbeEndCoroutine(v, regYield);
109261    sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
109262    assert( pSelect->pEList );
109263    nColumn = pSelect->pEList->nExpr;
109264
109265    /* Set useTempTable to TRUE if the result of the SELECT statement
109266    ** should be written into a temporary table (template 4).  Set to
109267    ** FALSE if each output row of the SELECT can be written directly into
109268    ** the destination table (template 3).
109269    **
109270    ** A temp table must be used if the table being updated is also one
109271    ** of the tables being read by the SELECT statement.  Also use a
109272    ** temp table in the case of row triggers.
109273    */
109274    if( pTrigger || readsTable(pParse, iDb, pTab) ){
109275      useTempTable = 1;
109276    }
109277
109278    if( useTempTable ){
109279      /* Invoke the coroutine to extract information from the SELECT
109280      ** and add it to a transient table srcTab.  The code generated
109281      ** here is from the 4th template:
109282      **
109283      **      B: open temp table
109284      **      L: yield X, goto M at EOF
109285      **         insert row from R..R+n into temp table
109286      **         goto L
109287      **      M: ...
109288      */
109289      int regRec;          /* Register to hold packed record */
109290      int regTempRowid;    /* Register to hold temp table ROWID */
109291      int addrL;           /* Label "L" */
109292
109293      srcTab = pParse->nTab++;
109294      regRec = sqlite3GetTempReg(pParse);
109295      regTempRowid = sqlite3GetTempReg(pParse);
109296      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
109297      addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
109298      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
109299      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
109300      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
109301      sqlite3VdbeGoto(v, addrL);
109302      sqlite3VdbeJumpHere(v, addrL);
109303      sqlite3ReleaseTempReg(pParse, regRec);
109304      sqlite3ReleaseTempReg(pParse, regTempRowid);
109305    }
109306  }else{
109307    /* This is the case if the data for the INSERT is coming from a
109308    ** single-row VALUES clause
109309    */
109310    NameContext sNC;
109311    memset(&sNC, 0, sizeof(sNC));
109312    sNC.pParse = pParse;
109313    srcTab = -1;
109314    assert( useTempTable==0 );
109315    if( pList ){
109316      nColumn = pList->nExpr;
109317      if( sqlite3ResolveExprListNames(&sNC, pList) ){
109318        goto insert_cleanup;
109319      }
109320    }else{
109321      nColumn = 0;
109322    }
109323  }
109324
109325  /* If there is no IDLIST term but the table has an integer primary
109326  ** key, the set the ipkColumn variable to the integer primary key
109327  ** column index in the original table definition.
109328  */
109329  if( pColumn==0 && nColumn>0 ){
109330    ipkColumn = pTab->iPKey;
109331  }
109332
109333  /* Make sure the number of columns in the source data matches the number
109334  ** of columns to be inserted into the table.
109335  */
109336  for(i=0; i<pTab->nCol; i++){
109337    nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
109338  }
109339  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
109340    sqlite3ErrorMsg(pParse,
109341       "table %S has %d columns but %d values were supplied",
109342       pTabList, 0, pTab->nCol-nHidden, nColumn);
109343    goto insert_cleanup;
109344  }
109345  if( pColumn!=0 && nColumn!=pColumn->nId ){
109346    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
109347    goto insert_cleanup;
109348  }
109349
109350  /* Initialize the count of rows to be inserted
109351  */
109352  if( db->flags & SQLITE_CountRows ){
109353    regRowCount = ++pParse->nMem;
109354    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
109355  }
109356
109357  /* If this is not a view, open the table and and all indices */
109358  if( !isView ){
109359    int nIdx;
109360    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
109361                                      &iDataCur, &iIdxCur);
109362    aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
109363    if( aRegIdx==0 ){
109364      goto insert_cleanup;
109365    }
109366    for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
109367      assert( pIdx );
109368      aRegIdx[i] = ++pParse->nMem;
109369      pParse->nMem += pIdx->nColumn;
109370    }
109371  }
109372
109373  /* This is the top of the main insertion loop */
109374  if( useTempTable ){
109375    /* This block codes the top of loop only.  The complete loop is the
109376    ** following pseudocode (template 4):
109377    **
109378    **         rewind temp table, if empty goto D
109379    **      C: loop over rows of intermediate table
109380    **           transfer values form intermediate table into <table>
109381    **         end loop
109382    **      D: ...
109383    */
109384    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
109385    addrCont = sqlite3VdbeCurrentAddr(v);
109386  }else if( pSelect ){
109387    /* This block codes the top of loop only.  The complete loop is the
109388    ** following pseudocode (template 3):
109389    **
109390    **      C: yield X, at EOF goto D
109391    **         insert the select result into <table> from R..R+n
109392    **         goto C
109393    **      D: ...
109394    */
109395    addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
109396    VdbeCoverage(v);
109397  }
109398
109399  /* Run the BEFORE and INSTEAD OF triggers, if there are any
109400  */
109401  endOfLoop = sqlite3VdbeMakeLabel(v);
109402  if( tmask & TRIGGER_BEFORE ){
109403    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
109404
109405    /* build the NEW.* reference row.  Note that if there is an INTEGER
109406    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
109407    ** translated into a unique ID for the row.  But on a BEFORE trigger,
109408    ** we do not know what the unique ID will be (because the insert has
109409    ** not happened yet) so we substitute a rowid of -1
109410    */
109411    if( ipkColumn<0 ){
109412      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
109413    }else{
109414      int addr1;
109415      assert( !withoutRowid );
109416      if( useTempTable ){
109417        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
109418      }else{
109419        assert( pSelect==0 );  /* Otherwise useTempTable is true */
109420        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
109421      }
109422      addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
109423      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
109424      sqlite3VdbeJumpHere(v, addr1);
109425      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
109426    }
109427
109428    /* Cannot have triggers on a virtual table. If it were possible,
109429    ** this block would have to account for hidden column.
109430    */
109431    assert( !IsVirtual(pTab) );
109432
109433    /* Create the new column data
109434    */
109435    for(i=j=0; i<pTab->nCol; i++){
109436      if( pColumn ){
109437        for(j=0; j<pColumn->nId; j++){
109438          if( pColumn->a[j].idx==i ) break;
109439        }
109440      }
109441      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
109442            || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
109443        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
109444      }else if( useTempTable ){
109445        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
109446      }else{
109447        assert( pSelect==0 ); /* Otherwise useTempTable is true */
109448        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
109449      }
109450      if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
109451    }
109452
109453    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
109454    ** do not attempt any conversions before assembling the record.
109455    ** If this is a real table, attempt conversions as required by the
109456    ** table column affinities.
109457    */
109458    if( !isView ){
109459      sqlite3TableAffinity(v, pTab, regCols+1);
109460    }
109461
109462    /* Fire BEFORE or INSTEAD OF triggers */
109463    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
109464        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
109465
109466    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
109467  }
109468
109469  /* Compute the content of the next row to insert into a range of
109470  ** registers beginning at regIns.
109471  */
109472  if( !isView ){
109473    if( IsVirtual(pTab) ){
109474      /* The row that the VUpdate opcode will delete: none */
109475      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
109476    }
109477    if( ipkColumn>=0 ){
109478      if( useTempTable ){
109479        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
109480      }else if( pSelect ){
109481        sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
109482      }else{
109483        VdbeOp *pOp;
109484        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
109485        pOp = sqlite3VdbeGetOp(v, -1);
109486        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
109487          appendFlag = 1;
109488          pOp->opcode = OP_NewRowid;
109489          pOp->p1 = iDataCur;
109490          pOp->p2 = regRowid;
109491          pOp->p3 = regAutoinc;
109492        }
109493      }
109494      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
109495      ** to generate a unique primary key value.
109496      */
109497      if( !appendFlag ){
109498        int addr1;
109499        if( !IsVirtual(pTab) ){
109500          addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
109501          sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
109502          sqlite3VdbeJumpHere(v, addr1);
109503        }else{
109504          addr1 = sqlite3VdbeCurrentAddr(v);
109505          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
109506        }
109507        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
109508      }
109509    }else if( IsVirtual(pTab) || withoutRowid ){
109510      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
109511    }else{
109512      sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
109513      appendFlag = 1;
109514    }
109515    autoIncStep(pParse, regAutoinc, regRowid);
109516
109517    /* Compute data for all columns of the new entry, beginning
109518    ** with the first column.
109519    */
109520    nHidden = 0;
109521    for(i=0; i<pTab->nCol; i++){
109522      int iRegStore = regRowid+1+i;
109523      if( i==pTab->iPKey ){
109524        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
109525        ** Whenever this column is read, the rowid will be substituted
109526        ** in its place.  Hence, fill this column with a NULL to avoid
109527        ** taking up data space with information that will never be used.
109528        ** As there may be shallow copies of this value, make it a soft-NULL */
109529        sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
109530        continue;
109531      }
109532      if( pColumn==0 ){
109533        if( IsHiddenColumn(&pTab->aCol[i]) ){
109534          j = -1;
109535          nHidden++;
109536        }else{
109537          j = i - nHidden;
109538        }
109539      }else{
109540        for(j=0; j<pColumn->nId; j++){
109541          if( pColumn->a[j].idx==i ) break;
109542        }
109543      }
109544      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
109545        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
109546      }else if( useTempTable ){
109547        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
109548      }else if( pSelect ){
109549        if( regFromSelect!=regData ){
109550          sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
109551        }
109552      }else{
109553        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
109554      }
109555    }
109556
109557    /* Generate code to check constraints and generate index keys and
109558    ** do the insertion.
109559    */
109560#ifndef SQLITE_OMIT_VIRTUALTABLE
109561    if( IsVirtual(pTab) ){
109562      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
109563      sqlite3VtabMakeWritable(pParse, pTab);
109564      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
109565      sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
109566      sqlite3MayAbort(pParse);
109567    }else
109568#endif
109569    {
109570      int isReplace;    /* Set to true if constraints may cause a replace */
109571      int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
109572      sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
109573          regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
109574      );
109575      sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
109576
109577      /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
109578      ** constraints or (b) there are no triggers and this table is not a
109579      ** parent table in a foreign key constraint. It is safe to set the
109580      ** flag in the second case as if any REPLACE constraint is hit, an
109581      ** OP_Delete or OP_IdxDelete instruction will be executed on each
109582      ** cursor that is disturbed. And these instructions both clear the
109583      ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
109584      ** functionality.  */
109585      bUseSeek = (isReplace==0 || (pTrigger==0 &&
109586          ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
109587      ));
109588      sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
109589          regIns, aRegIdx, 0, appendFlag, bUseSeek
109590      );
109591    }
109592  }
109593
109594  /* Update the count of rows that are inserted
109595  */
109596  if( (db->flags & SQLITE_CountRows)!=0 ){
109597    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
109598  }
109599
109600  if( pTrigger ){
109601    /* Code AFTER triggers */
109602    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
109603        pTab, regData-2-pTab->nCol, onError, endOfLoop);
109604  }
109605
109606  /* The bottom of the main insertion loop, if the data source
109607  ** is a SELECT statement.
109608  */
109609  sqlite3VdbeResolveLabel(v, endOfLoop);
109610  if( useTempTable ){
109611    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
109612    sqlite3VdbeJumpHere(v, addrInsTop);
109613    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
109614  }else if( pSelect ){
109615    sqlite3VdbeGoto(v, addrCont);
109616    sqlite3VdbeJumpHere(v, addrInsTop);
109617  }
109618
109619insert_end:
109620  /* Update the sqlite_sequence table by storing the content of the
109621  ** maximum rowid counter values recorded while inserting into
109622  ** autoincrement tables.
109623  */
109624  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
109625    sqlite3AutoincrementEnd(pParse);
109626  }
109627
109628  /*
109629  ** Return the number of rows inserted. If this routine is
109630  ** generating code because of a call to sqlite3NestedParse(), do not
109631  ** invoke the callback function.
109632  */
109633  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
109634    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
109635    sqlite3VdbeSetNumCols(v, 1);
109636    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
109637  }
109638
109639insert_cleanup:
109640  sqlite3SrcListDelete(db, pTabList);
109641  sqlite3ExprListDelete(db, pList);
109642  sqlite3SelectDelete(db, pSelect);
109643  sqlite3IdListDelete(db, pColumn);
109644  sqlite3DbFree(db, aRegIdx);
109645}
109646
109647/* Make sure "isView" and other macros defined above are undefined. Otherwise
109648** they may interfere with compilation of other functions in this file
109649** (or in another file, if this file becomes part of the amalgamation).  */
109650#ifdef isView
109651 #undef isView
109652#endif
109653#ifdef pTrigger
109654 #undef pTrigger
109655#endif
109656#ifdef tmask
109657 #undef tmask
109658#endif
109659
109660/*
109661** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
109662*/
109663#define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
109664#define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
109665
109666/* This is the Walker callback from checkConstraintUnchanged().  Set
109667** bit 0x01 of pWalker->eCode if
109668** pWalker->eCode to 0 if this expression node references any of the
109669** columns that are being modifed by an UPDATE statement.
109670*/
109671static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
109672  if( pExpr->op==TK_COLUMN ){
109673    assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
109674    if( pExpr->iColumn>=0 ){
109675      if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
109676        pWalker->eCode |= CKCNSTRNT_COLUMN;
109677      }
109678    }else{
109679      pWalker->eCode |= CKCNSTRNT_ROWID;
109680    }
109681  }
109682  return WRC_Continue;
109683}
109684
109685/*
109686** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
109687** only columns that are modified by the UPDATE are those for which
109688** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
109689**
109690** Return true if CHECK constraint pExpr does not use any of the
109691** changing columns (or the rowid if it is changing).  In other words,
109692** return true if this CHECK constraint can be skipped when validating
109693** the new row in the UPDATE statement.
109694*/
109695static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
109696  Walker w;
109697  memset(&w, 0, sizeof(w));
109698  w.eCode = 0;
109699  w.xExprCallback = checkConstraintExprNode;
109700  w.u.aiCol = aiChng;
109701  sqlite3WalkExpr(&w, pExpr);
109702  if( !chngRowid ){
109703    testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
109704    w.eCode &= ~CKCNSTRNT_ROWID;
109705  }
109706  testcase( w.eCode==0 );
109707  testcase( w.eCode==CKCNSTRNT_COLUMN );
109708  testcase( w.eCode==CKCNSTRNT_ROWID );
109709  testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
109710  return !w.eCode;
109711}
109712
109713/*
109714** Generate code to do constraint checks prior to an INSERT or an UPDATE
109715** on table pTab.
109716**
109717** The regNewData parameter is the first register in a range that contains
109718** the data to be inserted or the data after the update.  There will be
109719** pTab->nCol+1 registers in this range.  The first register (the one
109720** that regNewData points to) will contain the new rowid, or NULL in the
109721** case of a WITHOUT ROWID table.  The second register in the range will
109722** contain the content of the first table column.  The third register will
109723** contain the content of the second table column.  And so forth.
109724**
109725** The regOldData parameter is similar to regNewData except that it contains
109726** the data prior to an UPDATE rather than afterwards.  regOldData is zero
109727** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
109728** checking regOldData for zero.
109729**
109730** For an UPDATE, the pkChng boolean is true if the true primary key (the
109731** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
109732** might be modified by the UPDATE.  If pkChng is false, then the key of
109733** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
109734**
109735** For an INSERT, the pkChng boolean indicates whether or not the rowid
109736** was explicitly specified as part of the INSERT statement.  If pkChng
109737** is zero, it means that the either rowid is computed automatically or
109738** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
109739** pkChng will only be true if the INSERT statement provides an integer
109740** value for either the rowid column or its INTEGER PRIMARY KEY alias.
109741**
109742** The code generated by this routine will store new index entries into
109743** registers identified by aRegIdx[].  No index entry is created for
109744** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
109745** the same as the order of indices on the linked list of indices
109746** at pTab->pIndex.
109747**
109748** The caller must have already opened writeable cursors on the main
109749** table and all applicable indices (that is to say, all indices for which
109750** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
109751** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
109752** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
109753** for the first index in the pTab->pIndex list.  Cursors for other indices
109754** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
109755**
109756** This routine also generates code to check constraints.  NOT NULL,
109757** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
109758** then the appropriate action is performed.  There are five possible
109759** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
109760**
109761**  Constraint type  Action       What Happens
109762**  ---------------  ----------   ----------------------------------------
109763**  any              ROLLBACK     The current transaction is rolled back and
109764**                                sqlite3_step() returns immediately with a
109765**                                return code of SQLITE_CONSTRAINT.
109766**
109767**  any              ABORT        Back out changes from the current command
109768**                                only (do not do a complete rollback) then
109769**                                cause sqlite3_step() to return immediately
109770**                                with SQLITE_CONSTRAINT.
109771**
109772**  any              FAIL         Sqlite3_step() returns immediately with a
109773**                                return code of SQLITE_CONSTRAINT.  The
109774**                                transaction is not rolled back and any
109775**                                changes to prior rows are retained.
109776**
109777**  any              IGNORE       The attempt in insert or update the current
109778**                                row is skipped, without throwing an error.
109779**                                Processing continues with the next row.
109780**                                (There is an immediate jump to ignoreDest.)
109781**
109782**  NOT NULL         REPLACE      The NULL value is replace by the default
109783**                                value for that column.  If the default value
109784**                                is NULL, the action is the same as ABORT.
109785**
109786**  UNIQUE           REPLACE      The other row that conflicts with the row
109787**                                being inserted is removed.
109788**
109789**  CHECK            REPLACE      Illegal.  The results in an exception.
109790**
109791** Which action to take is determined by the overrideError parameter.
109792** Or if overrideError==OE_Default, then the pParse->onError parameter
109793** is used.  Or if pParse->onError==OE_Default then the onError value
109794** for the constraint is used.
109795*/
109796SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
109797  Parse *pParse,       /* The parser context */
109798  Table *pTab,         /* The table being inserted or updated */
109799  int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
109800  int iDataCur,        /* Canonical data cursor (main table or PK index) */
109801  int iIdxCur,         /* First index cursor */
109802  int regNewData,      /* First register in a range holding values to insert */
109803  int regOldData,      /* Previous content.  0 for INSERTs */
109804  u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
109805  u8 overrideError,    /* Override onError to this if not OE_Default */
109806  int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
109807  int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
109808  int *aiChng          /* column i is unchanged if aiChng[i]<0 */
109809){
109810  Vdbe *v;             /* VDBE under constrution */
109811  Index *pIdx;         /* Pointer to one of the indices */
109812  Index *pPk = 0;      /* The PRIMARY KEY index */
109813  sqlite3 *db;         /* Database connection */
109814  int i;               /* loop counter */
109815  int ix;              /* Index loop counter */
109816  int nCol;            /* Number of columns */
109817  int onError;         /* Conflict resolution strategy */
109818  int addr1;           /* Address of jump instruction */
109819  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
109820  int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
109821  int ipkTop = 0;      /* Top of the rowid change constraint check */
109822  int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
109823  u8 isUpdate;         /* True if this is an UPDATE operation */
109824  u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
109825
109826  isUpdate = regOldData!=0;
109827  db = pParse->db;
109828  v = sqlite3GetVdbe(pParse);
109829  assert( v!=0 );
109830  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
109831  nCol = pTab->nCol;
109832
109833  /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
109834  ** normal rowid tables.  nPkField is the number of key fields in the
109835  ** pPk index or 1 for a rowid table.  In other words, nPkField is the
109836  ** number of fields in the true primary key of the table. */
109837  if( HasRowid(pTab) ){
109838    pPk = 0;
109839    nPkField = 1;
109840  }else{
109841    pPk = sqlite3PrimaryKeyIndex(pTab);
109842    nPkField = pPk->nKeyCol;
109843  }
109844
109845  /* Record that this module has started */
109846  VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
109847                     iDataCur, iIdxCur, regNewData, regOldData, pkChng));
109848
109849  /* Test all NOT NULL constraints.
109850  */
109851  for(i=0; i<nCol; i++){
109852    if( i==pTab->iPKey ){
109853      continue;        /* ROWID is never NULL */
109854    }
109855    if( aiChng && aiChng[i]<0 ){
109856      /* Don't bother checking for NOT NULL on columns that do not change */
109857      continue;
109858    }
109859    onError = pTab->aCol[i].notNull;
109860    if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
109861    if( overrideError!=OE_Default ){
109862      onError = overrideError;
109863    }else if( onError==OE_Default ){
109864      onError = OE_Abort;
109865    }
109866    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
109867      onError = OE_Abort;
109868    }
109869    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
109870        || onError==OE_Ignore || onError==OE_Replace );
109871    switch( onError ){
109872      case OE_Abort:
109873        sqlite3MayAbort(pParse);
109874        /* Fall through */
109875      case OE_Rollback:
109876      case OE_Fail: {
109877        char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
109878                                    pTab->aCol[i].zName);
109879        sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
109880                          regNewData+1+i);
109881        sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
109882        sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
109883        VdbeCoverage(v);
109884        break;
109885      }
109886      case OE_Ignore: {
109887        sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
109888        VdbeCoverage(v);
109889        break;
109890      }
109891      default: {
109892        assert( onError==OE_Replace );
109893        addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
109894           VdbeCoverage(v);
109895        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
109896        sqlite3VdbeJumpHere(v, addr1);
109897        break;
109898      }
109899    }
109900  }
109901
109902  /* Test all CHECK constraints
109903  */
109904#ifndef SQLITE_OMIT_CHECK
109905  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
109906    ExprList *pCheck = pTab->pCheck;
109907    pParse->ckBase = regNewData+1;
109908    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
109909    for(i=0; i<pCheck->nExpr; i++){
109910      int allOk;
109911      Expr *pExpr = pCheck->a[i].pExpr;
109912      if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
109913      allOk = sqlite3VdbeMakeLabel(v);
109914      sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
109915      if( onError==OE_Ignore ){
109916        sqlite3VdbeGoto(v, ignoreDest);
109917      }else{
109918        char *zName = pCheck->a[i].zName;
109919        if( zName==0 ) zName = pTab->zName;
109920        if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
109921        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
109922                              onError, zName, P4_TRANSIENT,
109923                              P5_ConstraintCheck);
109924      }
109925      sqlite3VdbeResolveLabel(v, allOk);
109926    }
109927  }
109928#endif /* !defined(SQLITE_OMIT_CHECK) */
109929
109930  /* If rowid is changing, make sure the new rowid does not previously
109931  ** exist in the table.
109932  */
109933  if( pkChng && pPk==0 ){
109934    int addrRowidOk = sqlite3VdbeMakeLabel(v);
109935
109936    /* Figure out what action to take in case of a rowid collision */
109937    onError = pTab->keyConf;
109938    if( overrideError!=OE_Default ){
109939      onError = overrideError;
109940    }else if( onError==OE_Default ){
109941      onError = OE_Abort;
109942    }
109943
109944    if( isUpdate ){
109945      /* pkChng!=0 does not mean that the rowid has changed, only that
109946      ** it might have changed.  Skip the conflict logic below if the rowid
109947      ** is unchanged. */
109948      sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
109949      sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
109950      VdbeCoverage(v);
109951    }
109952
109953    /* If the response to a rowid conflict is REPLACE but the response
109954    ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
109955    ** to defer the running of the rowid conflict checking until after
109956    ** the UNIQUE constraints have run.
109957    */
109958    if( onError==OE_Replace && overrideError!=OE_Replace ){
109959      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
109960        if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
109961          ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
109962          break;
109963        }
109964      }
109965    }
109966
109967    /* Check to see if the new rowid already exists in the table.  Skip
109968    ** the following conflict logic if it does not. */
109969    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
109970    VdbeCoverage(v);
109971
109972    /* Generate code that deals with a rowid collision */
109973    switch( onError ){
109974      default: {
109975        onError = OE_Abort;
109976        /* Fall thru into the next case */
109977      }
109978      case OE_Rollback:
109979      case OE_Abort:
109980      case OE_Fail: {
109981        sqlite3RowidConstraint(pParse, onError, pTab);
109982        break;
109983      }
109984      case OE_Replace: {
109985        /* If there are DELETE triggers on this table and the
109986        ** recursive-triggers flag is set, call GenerateRowDelete() to
109987        ** remove the conflicting row from the table. This will fire
109988        ** the triggers and remove both the table and index b-tree entries.
109989        **
109990        ** Otherwise, if there are no triggers or the recursive-triggers
109991        ** flag is not set, but the table has one or more indexes, call
109992        ** GenerateRowIndexDelete(). This removes the index b-tree entries
109993        ** only. The table b-tree entry will be replaced by the new entry
109994        ** when it is inserted.
109995        **
109996        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
109997        ** also invoke MultiWrite() to indicate that this VDBE may require
109998        ** statement rollback (if the statement is aborted after the delete
109999        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
110000        ** but being more selective here allows statements like:
110001        **
110002        **   REPLACE INTO t(rowid) VALUES($newrowid)
110003        **
110004        ** to run without a statement journal if there are no indexes on the
110005        ** table.
110006        */
110007        Trigger *pTrigger = 0;
110008        if( db->flags&SQLITE_RecTriggers ){
110009          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
110010        }
110011        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
110012          sqlite3MultiWrite(pParse);
110013          sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
110014                                   regNewData, 1, 0, OE_Replace, 1, -1);
110015        }else{
110016#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
110017          if( HasRowid(pTab) ){
110018            /* This OP_Delete opcode fires the pre-update-hook only. It does
110019            ** not modify the b-tree. It is more efficient to let the coming
110020            ** OP_Insert replace the existing entry than it is to delete the
110021            ** existing entry and then insert a new one. */
110022            sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
110023            sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
110024          }
110025#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
110026          if( pTab->pIndex ){
110027            sqlite3MultiWrite(pParse);
110028            sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
110029          }
110030        }
110031        seenReplace = 1;
110032        break;
110033      }
110034      case OE_Ignore: {
110035        /*assert( seenReplace==0 );*/
110036        sqlite3VdbeGoto(v, ignoreDest);
110037        break;
110038      }
110039    }
110040    sqlite3VdbeResolveLabel(v, addrRowidOk);
110041    if( ipkTop ){
110042      ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
110043      sqlite3VdbeJumpHere(v, ipkTop);
110044    }
110045  }
110046
110047  /* Test all UNIQUE constraints by creating entries for each UNIQUE
110048  ** index and making sure that duplicate entries do not already exist.
110049  ** Compute the revised record entries for indices as we go.
110050  **
110051  ** This loop also handles the case of the PRIMARY KEY index for a
110052  ** WITHOUT ROWID table.
110053  */
110054  for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
110055    int regIdx;          /* Range of registers hold conent for pIdx */
110056    int regR;            /* Range of registers holding conflicting PK */
110057    int iThisCur;        /* Cursor for this UNIQUE index */
110058    int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
110059
110060    if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
110061    if( bAffinityDone==0 ){
110062      sqlite3TableAffinity(v, pTab, regNewData+1);
110063      bAffinityDone = 1;
110064    }
110065    iThisCur = iIdxCur+ix;
110066    addrUniqueOk = sqlite3VdbeMakeLabel(v);
110067
110068    /* Skip partial indices for which the WHERE clause is not true */
110069    if( pIdx->pPartIdxWhere ){
110070      sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
110071      pParse->ckBase = regNewData+1;
110072      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
110073                            SQLITE_JUMPIFNULL);
110074      pParse->ckBase = 0;
110075    }
110076
110077    /* Create a record for this index entry as it should appear after
110078    ** the insert or update.  Store that record in the aRegIdx[ix] register
110079    */
110080    regIdx = aRegIdx[ix]+1;
110081    for(i=0; i<pIdx->nColumn; i++){
110082      int iField = pIdx->aiColumn[i];
110083      int x;
110084      if( iField==XN_EXPR ){
110085        pParse->ckBase = regNewData+1;
110086        sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
110087        pParse->ckBase = 0;
110088        VdbeComment((v, "%s column %d", pIdx->zName, i));
110089      }else{
110090        if( iField==XN_ROWID || iField==pTab->iPKey ){
110091          x = regNewData;
110092        }else{
110093          x = iField + regNewData + 1;
110094        }
110095        sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
110096        VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
110097      }
110098    }
110099    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
110100    VdbeComment((v, "for %s", pIdx->zName));
110101#ifdef SQLITE_ENABLE_NULL_TRIM
110102    if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
110103#endif
110104
110105    /* In an UPDATE operation, if this index is the PRIMARY KEY index
110106    ** of a WITHOUT ROWID table and there has been no change the
110107    ** primary key, then no collision is possible.  The collision detection
110108    ** logic below can all be skipped. */
110109    if( isUpdate && pPk==pIdx && pkChng==0 ){
110110      sqlite3VdbeResolveLabel(v, addrUniqueOk);
110111      continue;
110112    }
110113
110114    /* Find out what action to take in case there is a uniqueness conflict */
110115    onError = pIdx->onError;
110116    if( onError==OE_None ){
110117      sqlite3VdbeResolveLabel(v, addrUniqueOk);
110118      continue;  /* pIdx is not a UNIQUE index */
110119    }
110120    if( overrideError!=OE_Default ){
110121      onError = overrideError;
110122    }else if( onError==OE_Default ){
110123      onError = OE_Abort;
110124    }
110125
110126    /* Collision detection may be omitted if all of the following are true:
110127    **   (1) The conflict resolution algorithm is REPLACE
110128    **   (2) The table is a WITHOUT ROWID table
110129    **   (3) There are no secondary indexes on the table
110130    **   (4) No delete triggers need to be fired if there is a conflict
110131    **   (5) No FK constraint counters need to be updated if a conflict occurs.
110132    */
110133    if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
110134     && pPk==pIdx                                   /* Condition 2 */
110135     && onError==OE_Replace                         /* Condition 1 */
110136     && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */
110137          0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
110138     && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */
110139         (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
110140    ){
110141      sqlite3VdbeResolveLabel(v, addrUniqueOk);
110142      continue;
110143    }
110144
110145    /* Check to see if the new index entry will be unique */
110146    sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
110147                         regIdx, pIdx->nKeyCol); VdbeCoverage(v);
110148
110149    /* Generate code to handle collisions */
110150    regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
110151    if( isUpdate || onError==OE_Replace ){
110152      if( HasRowid(pTab) ){
110153        sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
110154        /* Conflict only if the rowid of the existing index entry
110155        ** is different from old-rowid */
110156        if( isUpdate ){
110157          sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
110158          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
110159          VdbeCoverage(v);
110160        }
110161      }else{
110162        int x;
110163        /* Extract the PRIMARY KEY from the end of the index entry and
110164        ** store it in registers regR..regR+nPk-1 */
110165        if( pIdx!=pPk ){
110166          for(i=0; i<pPk->nKeyCol; i++){
110167            assert( pPk->aiColumn[i]>=0 );
110168            x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
110169            sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
110170            VdbeComment((v, "%s.%s", pTab->zName,
110171                         pTab->aCol[pPk->aiColumn[i]].zName));
110172          }
110173        }
110174        if( isUpdate ){
110175          /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
110176          ** table, only conflict if the new PRIMARY KEY values are actually
110177          ** different from the old.
110178          **
110179          ** For a UNIQUE index, only conflict if the PRIMARY KEY values
110180          ** of the matched index row are different from the original PRIMARY
110181          ** KEY values of this row before the update.  */
110182          int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
110183          int op = OP_Ne;
110184          int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
110185
110186          for(i=0; i<pPk->nKeyCol; i++){
110187            char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
110188            x = pPk->aiColumn[i];
110189            assert( x>=0 );
110190            if( i==(pPk->nKeyCol-1) ){
110191              addrJump = addrUniqueOk;
110192              op = OP_Eq;
110193            }
110194            sqlite3VdbeAddOp4(v, op,
110195                regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
110196            );
110197            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
110198            VdbeCoverageIf(v, op==OP_Eq);
110199            VdbeCoverageIf(v, op==OP_Ne);
110200          }
110201        }
110202      }
110203    }
110204
110205    /* Generate code that executes if the new index entry is not unique */
110206    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
110207        || onError==OE_Ignore || onError==OE_Replace );
110208    switch( onError ){
110209      case OE_Rollback:
110210      case OE_Abort:
110211      case OE_Fail: {
110212        sqlite3UniqueConstraint(pParse, onError, pIdx);
110213        break;
110214      }
110215      case OE_Ignore: {
110216        sqlite3VdbeGoto(v, ignoreDest);
110217        break;
110218      }
110219      default: {
110220        Trigger *pTrigger = 0;
110221        assert( onError==OE_Replace );
110222        sqlite3MultiWrite(pParse);
110223        if( db->flags&SQLITE_RecTriggers ){
110224          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
110225        }
110226        sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
110227            regR, nPkField, 0, OE_Replace,
110228            (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
110229        seenReplace = 1;
110230        break;
110231      }
110232    }
110233    sqlite3VdbeResolveLabel(v, addrUniqueOk);
110234    if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
110235  }
110236  if( ipkTop ){
110237    sqlite3VdbeGoto(v, ipkTop+1);
110238    sqlite3VdbeJumpHere(v, ipkBottom);
110239  }
110240
110241  *pbMayReplace = seenReplace;
110242  VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
110243}
110244
110245#ifdef SQLITE_ENABLE_NULL_TRIM
110246/*
110247** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
110248** to be the number of columns in table pTab that must not be NULL-trimmed.
110249**
110250** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
110251*/
110252SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
110253  u16 i;
110254
110255  /* Records with omitted columns are only allowed for schema format
110256  ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
110257  if( pTab->pSchema->file_format<2 ) return;
110258
110259  for(i=pTab->nCol-1; i>0; i--){
110260    if( pTab->aCol[i].pDflt!=0 ) break;
110261    if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
110262  }
110263  sqlite3VdbeChangeP5(v, i+1);
110264}
110265#endif
110266
110267/*
110268** This routine generates code to finish the INSERT or UPDATE operation
110269** that was started by a prior call to sqlite3GenerateConstraintChecks.
110270** A consecutive range of registers starting at regNewData contains the
110271** rowid and the content to be inserted.
110272**
110273** The arguments to this routine should be the same as the first six
110274** arguments to sqlite3GenerateConstraintChecks.
110275*/
110276SQLITE_PRIVATE void sqlite3CompleteInsertion(
110277  Parse *pParse,      /* The parser context */
110278  Table *pTab,        /* the table into which we are inserting */
110279  int iDataCur,       /* Cursor of the canonical data source */
110280  int iIdxCur,        /* First index cursor */
110281  int regNewData,     /* Range of content */
110282  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
110283  int update_flags,   /* True for UPDATE, False for INSERT */
110284  int appendBias,     /* True if this is likely to be an append */
110285  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
110286){
110287  Vdbe *v;            /* Prepared statements under construction */
110288  Index *pIdx;        /* An index being inserted or updated */
110289  u8 pik_flags;       /* flag values passed to the btree insert */
110290  int regData;        /* Content registers (after the rowid) */
110291  int regRec;         /* Register holding assembled record for the table */
110292  int i;              /* Loop counter */
110293  u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
110294
110295  assert( update_flags==0
110296       || update_flags==OPFLAG_ISUPDATE
110297       || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
110298  );
110299
110300  v = sqlite3GetVdbe(pParse);
110301  assert( v!=0 );
110302  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
110303  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
110304    if( aRegIdx[i]==0 ) continue;
110305    bAffinityDone = 1;
110306    if( pIdx->pPartIdxWhere ){
110307      sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
110308      VdbeCoverage(v);
110309    }
110310    pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
110311    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
110312      assert( pParse->nested==0 );
110313      pik_flags |= OPFLAG_NCHANGE;
110314      pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
110315#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
110316      if( update_flags==0 ){
110317        sqlite3VdbeAddOp4(v, OP_InsertInt,
110318            iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE
110319        );
110320        sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
110321      }
110322#endif
110323    }
110324    sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
110325                         aRegIdx[i]+1,
110326                         pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
110327    sqlite3VdbeChangeP5(v, pik_flags);
110328  }
110329  if( !HasRowid(pTab) ) return;
110330  regData = regNewData + 1;
110331  regRec = sqlite3GetTempReg(pParse);
110332  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
110333  sqlite3SetMakeRecordP5(v, pTab);
110334  if( !bAffinityDone ){
110335    sqlite3TableAffinity(v, pTab, 0);
110336    sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
110337  }
110338  if( pParse->nested ){
110339    pik_flags = 0;
110340  }else{
110341    pik_flags = OPFLAG_NCHANGE;
110342    pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
110343  }
110344  if( appendBias ){
110345    pik_flags |= OPFLAG_APPEND;
110346  }
110347  if( useSeekResult ){
110348    pik_flags |= OPFLAG_USESEEKRESULT;
110349  }
110350  sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
110351  if( !pParse->nested ){
110352    sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
110353  }
110354  sqlite3VdbeChangeP5(v, pik_flags);
110355}
110356
110357/*
110358** Allocate cursors for the pTab table and all its indices and generate
110359** code to open and initialized those cursors.
110360**
110361** The cursor for the object that contains the complete data (normally
110362** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
110363** ROWID table) is returned in *piDataCur.  The first index cursor is
110364** returned in *piIdxCur.  The number of indices is returned.
110365**
110366** Use iBase as the first cursor (either the *piDataCur for rowid tables
110367** or the first index for WITHOUT ROWID tables) if it is non-negative.
110368** If iBase is negative, then allocate the next available cursor.
110369**
110370** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
110371** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
110372** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
110373** pTab->pIndex list.
110374**
110375** If pTab is a virtual table, then this routine is a no-op and the
110376** *piDataCur and *piIdxCur values are left uninitialized.
110377*/
110378SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
110379  Parse *pParse,   /* Parsing context */
110380  Table *pTab,     /* Table to be opened */
110381  int op,          /* OP_OpenRead or OP_OpenWrite */
110382  u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
110383  int iBase,       /* Use this for the table cursor, if there is one */
110384  u8 *aToOpen,     /* If not NULL: boolean for each table and index */
110385  int *piDataCur,  /* Write the database source cursor number here */
110386  int *piIdxCur    /* Write the first index cursor number here */
110387){
110388  int i;
110389  int iDb;
110390  int iDataCur;
110391  Index *pIdx;
110392  Vdbe *v;
110393
110394  assert( op==OP_OpenRead || op==OP_OpenWrite );
110395  assert( op==OP_OpenWrite || p5==0 );
110396  if( IsVirtual(pTab) ){
110397    /* This routine is a no-op for virtual tables. Leave the output
110398    ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
110399    ** can detect if they are used by mistake in the caller. */
110400    return 0;
110401  }
110402  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
110403  v = sqlite3GetVdbe(pParse);
110404  assert( v!=0 );
110405  if( iBase<0 ) iBase = pParse->nTab;
110406  iDataCur = iBase++;
110407  if( piDataCur ) *piDataCur = iDataCur;
110408  if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
110409    sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
110410  }else{
110411    sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
110412  }
110413  if( piIdxCur ) *piIdxCur = iBase;
110414  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
110415    int iIdxCur = iBase++;
110416    assert( pIdx->pSchema==pTab->pSchema );
110417    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
110418      if( piDataCur ) *piDataCur = iIdxCur;
110419      p5 = 0;
110420    }
110421    if( aToOpen==0 || aToOpen[i+1] ){
110422      sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
110423      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
110424      sqlite3VdbeChangeP5(v, p5);
110425      VdbeComment((v, "%s", pIdx->zName));
110426    }
110427  }
110428  if( iBase>pParse->nTab ) pParse->nTab = iBase;
110429  return i;
110430}
110431
110432
110433#ifdef SQLITE_TEST
110434/*
110435** The following global variable is incremented whenever the
110436** transfer optimization is used.  This is used for testing
110437** purposes only - to make sure the transfer optimization really
110438** is happening when it is supposed to.
110439*/
110440SQLITE_API int sqlite3_xferopt_count;
110441#endif /* SQLITE_TEST */
110442
110443
110444#ifndef SQLITE_OMIT_XFER_OPT
110445/*
110446** Check to see if index pSrc is compatible as a source of data
110447** for index pDest in an insert transfer optimization.  The rules
110448** for a compatible index:
110449**
110450**    *   The index is over the same set of columns
110451**    *   The same DESC and ASC markings occurs on all columns
110452**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
110453**    *   The same collating sequence on each column
110454**    *   The index has the exact same WHERE clause
110455*/
110456static int xferCompatibleIndex(Index *pDest, Index *pSrc){
110457  int i;
110458  assert( pDest && pSrc );
110459  assert( pDest->pTable!=pSrc->pTable );
110460  if( pDest->nKeyCol!=pSrc->nKeyCol ){
110461    return 0;   /* Different number of columns */
110462  }
110463  if( pDest->onError!=pSrc->onError ){
110464    return 0;   /* Different conflict resolution strategies */
110465  }
110466  for(i=0; i<pSrc->nKeyCol; i++){
110467    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
110468      return 0;   /* Different columns indexed */
110469    }
110470    if( pSrc->aiColumn[i]==XN_EXPR ){
110471      assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
110472      if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
110473                             pDest->aColExpr->a[i].pExpr, -1)!=0 ){
110474        return 0;   /* Different expressions in the index */
110475      }
110476    }
110477    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
110478      return 0;   /* Different sort orders */
110479    }
110480    if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
110481      return 0;   /* Different collating sequences */
110482    }
110483  }
110484  if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
110485    return 0;     /* Different WHERE clauses */
110486  }
110487
110488  /* If no test above fails then the indices must be compatible */
110489  return 1;
110490}
110491
110492/*
110493** Attempt the transfer optimization on INSERTs of the form
110494**
110495**     INSERT INTO tab1 SELECT * FROM tab2;
110496**
110497** The xfer optimization transfers raw records from tab2 over to tab1.
110498** Columns are not decoded and reassembled, which greatly improves
110499** performance.  Raw index records are transferred in the same way.
110500**
110501** The xfer optimization is only attempted if tab1 and tab2 are compatible.
110502** There are lots of rules for determining compatibility - see comments
110503** embedded in the code for details.
110504**
110505** This routine returns TRUE if the optimization is guaranteed to be used.
110506** Sometimes the xfer optimization will only work if the destination table
110507** is empty - a factor that can only be determined at run-time.  In that
110508** case, this routine generates code for the xfer optimization but also
110509** does a test to see if the destination table is empty and jumps over the
110510** xfer optimization code if the test fails.  In that case, this routine
110511** returns FALSE so that the caller will know to go ahead and generate
110512** an unoptimized transfer.  This routine also returns FALSE if there
110513** is no chance that the xfer optimization can be applied.
110514**
110515** This optimization is particularly useful at making VACUUM run faster.
110516*/
110517static int xferOptimization(
110518  Parse *pParse,        /* Parser context */
110519  Table *pDest,         /* The table we are inserting into */
110520  Select *pSelect,      /* A SELECT statement to use as the data source */
110521  int onError,          /* How to handle constraint errors */
110522  int iDbDest           /* The database of pDest */
110523){
110524  sqlite3 *db = pParse->db;
110525  ExprList *pEList;                /* The result set of the SELECT */
110526  Table *pSrc;                     /* The table in the FROM clause of SELECT */
110527  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
110528  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
110529  int i;                           /* Loop counter */
110530  int iDbSrc;                      /* The database of pSrc */
110531  int iSrc, iDest;                 /* Cursors from source and destination */
110532  int addr1, addr2;                /* Loop addresses */
110533  int emptyDestTest = 0;           /* Address of test for empty pDest */
110534  int emptySrcTest = 0;            /* Address of test for empty pSrc */
110535  Vdbe *v;                         /* The VDBE we are building */
110536  int regAutoinc;                  /* Memory register used by AUTOINC */
110537  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
110538  int regData, regRowid;           /* Registers holding data and rowid */
110539
110540  if( pSelect==0 ){
110541    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
110542  }
110543  if( pParse->pWith || pSelect->pWith ){
110544    /* Do not attempt to process this query if there are an WITH clauses
110545    ** attached to it. Proceeding may generate a false "no such table: xxx"
110546    ** error if pSelect reads from a CTE named "xxx".  */
110547    return 0;
110548  }
110549  if( sqlite3TriggerList(pParse, pDest) ){
110550    return 0;   /* tab1 must not have triggers */
110551  }
110552#ifndef SQLITE_OMIT_VIRTUALTABLE
110553  if( IsVirtual(pDest) ){
110554    return 0;   /* tab1 must not be a virtual table */
110555  }
110556#endif
110557  if( onError==OE_Default ){
110558    if( pDest->iPKey>=0 ) onError = pDest->keyConf;
110559    if( onError==OE_Default ) onError = OE_Abort;
110560  }
110561  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
110562  if( pSelect->pSrc->nSrc!=1 ){
110563    return 0;   /* FROM clause must have exactly one term */
110564  }
110565  if( pSelect->pSrc->a[0].pSelect ){
110566    return 0;   /* FROM clause cannot contain a subquery */
110567  }
110568  if( pSelect->pWhere ){
110569    return 0;   /* SELECT may not have a WHERE clause */
110570  }
110571  if( pSelect->pOrderBy ){
110572    return 0;   /* SELECT may not have an ORDER BY clause */
110573  }
110574  /* Do not need to test for a HAVING clause.  If HAVING is present but
110575  ** there is no ORDER BY, we will get an error. */
110576  if( pSelect->pGroupBy ){
110577    return 0;   /* SELECT may not have a GROUP BY clause */
110578  }
110579  if( pSelect->pLimit ){
110580    return 0;   /* SELECT may not have a LIMIT clause */
110581  }
110582  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
110583  if( pSelect->pPrior ){
110584    return 0;   /* SELECT may not be a compound query */
110585  }
110586  if( pSelect->selFlags & SF_Distinct ){
110587    return 0;   /* SELECT may not be DISTINCT */
110588  }
110589  pEList = pSelect->pEList;
110590  assert( pEList!=0 );
110591  if( pEList->nExpr!=1 ){
110592    return 0;   /* The result set must have exactly one column */
110593  }
110594  assert( pEList->a[0].pExpr );
110595  if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
110596    return 0;   /* The result set must be the special operator "*" */
110597  }
110598
110599  /* At this point we have established that the statement is of the
110600  ** correct syntactic form to participate in this optimization.  Now
110601  ** we have to check the semantics.
110602  */
110603  pItem = pSelect->pSrc->a;
110604  pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
110605  if( pSrc==0 ){
110606    return 0;   /* FROM clause does not contain a real table */
110607  }
110608  if( pSrc==pDest ){
110609    return 0;   /* tab1 and tab2 may not be the same table */
110610  }
110611  if( HasRowid(pDest)!=HasRowid(pSrc) ){
110612    return 0;   /* source and destination must both be WITHOUT ROWID or not */
110613  }
110614#ifndef SQLITE_OMIT_VIRTUALTABLE
110615  if( IsVirtual(pSrc) ){
110616    return 0;   /* tab2 must not be a virtual table */
110617  }
110618#endif
110619  if( pSrc->pSelect ){
110620    return 0;   /* tab2 may not be a view */
110621  }
110622  if( pDest->nCol!=pSrc->nCol ){
110623    return 0;   /* Number of columns must be the same in tab1 and tab2 */
110624  }
110625  if( pDest->iPKey!=pSrc->iPKey ){
110626    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
110627  }
110628  for(i=0; i<pDest->nCol; i++){
110629    Column *pDestCol = &pDest->aCol[i];
110630    Column *pSrcCol = &pSrc->aCol[i];
110631#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
110632    if( (db->flags & SQLITE_Vacuum)==0
110633     && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
110634    ){
110635      return 0;    /* Neither table may have __hidden__ columns */
110636    }
110637#endif
110638    if( pDestCol->affinity!=pSrcCol->affinity ){
110639      return 0;    /* Affinity must be the same on all columns */
110640    }
110641    if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
110642      return 0;    /* Collating sequence must be the same on all columns */
110643    }
110644    if( pDestCol->notNull && !pSrcCol->notNull ){
110645      return 0;    /* tab2 must be NOT NULL if tab1 is */
110646    }
110647    /* Default values for second and subsequent columns need to match. */
110648    if( i>0 ){
110649      assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
110650      assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
110651      if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
110652       || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
110653                                       pSrcCol->pDflt->u.zToken)!=0)
110654      ){
110655        return 0;    /* Default values must be the same for all columns */
110656      }
110657    }
110658  }
110659  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
110660    if( IsUniqueIndex(pDestIdx) ){
110661      destHasUniqueIdx = 1;
110662    }
110663    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
110664      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
110665    }
110666    if( pSrcIdx==0 ){
110667      return 0;    /* pDestIdx has no corresponding index in pSrc */
110668    }
110669  }
110670#ifndef SQLITE_OMIT_CHECK
110671  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
110672    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
110673  }
110674#endif
110675#ifndef SQLITE_OMIT_FOREIGN_KEY
110676  /* Disallow the transfer optimization if the destination table constains
110677  ** any foreign key constraints.  This is more restrictive than necessary.
110678  ** But the main beneficiary of the transfer optimization is the VACUUM
110679  ** command, and the VACUUM command disables foreign key constraints.  So
110680  ** the extra complication to make this rule less restrictive is probably
110681  ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
110682  */
110683  if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
110684    return 0;
110685  }
110686#endif
110687  if( (db->flags & SQLITE_CountRows)!=0 ){
110688    return 0;  /* xfer opt does not play well with PRAGMA count_changes */
110689  }
110690
110691  /* If we get this far, it means that the xfer optimization is at
110692  ** least a possibility, though it might only work if the destination
110693  ** table (tab1) is initially empty.
110694  */
110695#ifdef SQLITE_TEST
110696  sqlite3_xferopt_count++;
110697#endif
110698  iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
110699  v = sqlite3GetVdbe(pParse);
110700  sqlite3CodeVerifySchema(pParse, iDbSrc);
110701  iSrc = pParse->nTab++;
110702  iDest = pParse->nTab++;
110703  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
110704  regData = sqlite3GetTempReg(pParse);
110705  regRowid = sqlite3GetTempReg(pParse);
110706  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
110707  assert( HasRowid(pDest) || destHasUniqueIdx );
110708  if( (db->flags & SQLITE_Vacuum)==0 && (
110709      (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
110710   || destHasUniqueIdx                              /* (2) */
110711   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
110712  )){
110713    /* In some circumstances, we are able to run the xfer optimization
110714    ** only if the destination table is initially empty. Unless the
110715    ** SQLITE_Vacuum flag is set, this block generates code to make
110716    ** that determination. If SQLITE_Vacuum is set, then the destination
110717    ** table is always empty.
110718    **
110719    ** Conditions under which the destination must be empty:
110720    **
110721    ** (1) There is no INTEGER PRIMARY KEY but there are indices.
110722    **     (If the destination is not initially empty, the rowid fields
110723    **     of index entries might need to change.)
110724    **
110725    ** (2) The destination has a unique index.  (The xfer optimization
110726    **     is unable to test uniqueness.)
110727    **
110728    ** (3) onError is something other than OE_Abort and OE_Rollback.
110729    */
110730    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
110731    emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
110732    sqlite3VdbeJumpHere(v, addr1);
110733  }
110734  if( HasRowid(pSrc) ){
110735    u8 insFlags;
110736    sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
110737    emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
110738    if( pDest->iPKey>=0 ){
110739      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
110740      addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
110741      VdbeCoverage(v);
110742      sqlite3RowidConstraint(pParse, onError, pDest);
110743      sqlite3VdbeJumpHere(v, addr2);
110744      autoIncStep(pParse, regAutoinc, regRowid);
110745    }else if( pDest->pIndex==0 ){
110746      addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
110747    }else{
110748      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
110749      assert( (pDest->tabFlags & TF_Autoincrement)==0 );
110750    }
110751    sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
110752    if( db->flags & SQLITE_Vacuum ){
110753      sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
110754      insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
110755                           OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
110756    }else{
110757      insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
110758    }
110759    sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
110760                      (char*)pDest, P4_TABLE);
110761    sqlite3VdbeChangeP5(v, insFlags);
110762    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
110763    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
110764    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
110765  }else{
110766    sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
110767    sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
110768  }
110769  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
110770    u8 idxInsFlags = 0;
110771    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
110772      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
110773    }
110774    assert( pSrcIdx );
110775    sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
110776    sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
110777    VdbeComment((v, "%s", pSrcIdx->zName));
110778    sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
110779    sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
110780    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
110781    VdbeComment((v, "%s", pDestIdx->zName));
110782    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
110783    sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
110784    if( db->flags & SQLITE_Vacuum ){
110785      /* This INSERT command is part of a VACUUM operation, which guarantees
110786      ** that the destination table is empty. If all indexed columns use
110787      ** collation sequence BINARY, then it can also be assumed that the
110788      ** index will be populated by inserting keys in strictly sorted
110789      ** order. In this case, instead of seeking within the b-tree as part
110790      ** of every OP_IdxInsert opcode, an OP_Last is added before the
110791      ** OP_IdxInsert to seek to the point within the b-tree where each key
110792      ** should be inserted. This is faster.
110793      **
110794      ** If any of the indexed columns use a collation sequence other than
110795      ** BINARY, this optimization is disabled. This is because the user
110796      ** might change the definition of a collation sequence and then run
110797      ** a VACUUM command. In that case keys may not be written in strictly
110798      ** sorted order.  */
110799      for(i=0; i<pSrcIdx->nColumn; i++){
110800        const char *zColl = pSrcIdx->azColl[i];
110801        if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
110802      }
110803      if( i==pSrcIdx->nColumn ){
110804        idxInsFlags = OPFLAG_USESEEKRESULT;
110805        sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
110806      }
110807    }
110808    if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
110809      idxInsFlags |= OPFLAG_NCHANGE;
110810    }
110811    sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
110812    sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
110813    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
110814    sqlite3VdbeJumpHere(v, addr1);
110815    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
110816    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
110817  }
110818  if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
110819  sqlite3ReleaseTempReg(pParse, regRowid);
110820  sqlite3ReleaseTempReg(pParse, regData);
110821  if( emptyDestTest ){
110822    sqlite3AutoincrementEnd(pParse);
110823    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
110824    sqlite3VdbeJumpHere(v, emptyDestTest);
110825    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
110826    return 0;
110827  }else{
110828    return 1;
110829  }
110830}
110831#endif /* SQLITE_OMIT_XFER_OPT */
110832
110833/************** End of insert.c **********************************************/
110834/************** Begin file legacy.c ******************************************/
110835/*
110836** 2001 September 15
110837**
110838** The author disclaims copyright to this source code.  In place of
110839** a legal notice, here is a blessing:
110840**
110841**    May you do good and not evil.
110842**    May you find forgiveness for yourself and forgive others.
110843**    May you share freely, never taking more than you give.
110844**
110845*************************************************************************
110846** Main file for the SQLite library.  The routines in this file
110847** implement the programmer interface to the library.  Routines in
110848** other files are for internal use by SQLite and should not be
110849** accessed by users of the library.
110850*/
110851
110852/* #include "sqliteInt.h" */
110853
110854/*
110855** Execute SQL code.  Return one of the SQLITE_ success/failure
110856** codes.  Also write an error message into memory obtained from
110857** malloc() and make *pzErrMsg point to that message.
110858**
110859** If the SQL is a query, then for each row in the query result
110860** the xCallback() function is called.  pArg becomes the first
110861** argument to xCallback().  If xCallback=NULL then no callback
110862** is invoked, even for queries.
110863*/
110864SQLITE_API int sqlite3_exec(
110865  sqlite3 *db,                /* The database on which the SQL executes */
110866  const char *zSql,           /* The SQL to be executed */
110867  sqlite3_callback xCallback, /* Invoke this callback routine */
110868  void *pArg,                 /* First argument to xCallback() */
110869  char **pzErrMsg             /* Write error messages here */
110870){
110871  int rc = SQLITE_OK;         /* Return code */
110872  const char *zLeftover;      /* Tail of unprocessed SQL */
110873  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
110874  char **azCols = 0;          /* Names of result columns */
110875  int callbackIsInit;         /* True if callback data is initialized */
110876
110877  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
110878  if( zSql==0 ) zSql = "";
110879
110880  sqlite3_mutex_enter(db->mutex);
110881  sqlite3Error(db, SQLITE_OK);
110882  while( rc==SQLITE_OK && zSql[0] ){
110883    int nCol;
110884    char **azVals = 0;
110885
110886    pStmt = 0;
110887    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
110888    assert( rc==SQLITE_OK || pStmt==0 );
110889    if( rc!=SQLITE_OK ){
110890      continue;
110891    }
110892    if( !pStmt ){
110893      /* this happens for a comment or white-space */
110894      zSql = zLeftover;
110895      continue;
110896    }
110897
110898    callbackIsInit = 0;
110899    nCol = sqlite3_column_count(pStmt);
110900
110901    while( 1 ){
110902      int i;
110903      rc = sqlite3_step(pStmt);
110904
110905      /* Invoke the callback function if required */
110906      if( xCallback && (SQLITE_ROW==rc ||
110907          (SQLITE_DONE==rc && !callbackIsInit
110908                           && db->flags&SQLITE_NullCallback)) ){
110909        if( !callbackIsInit ){
110910          azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
110911          if( azCols==0 ){
110912            goto exec_out;
110913          }
110914          for(i=0; i<nCol; i++){
110915            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
110916            /* sqlite3VdbeSetColName() installs column names as UTF8
110917            ** strings so there is no way for sqlite3_column_name() to fail. */
110918            assert( azCols[i]!=0 );
110919          }
110920          callbackIsInit = 1;
110921        }
110922        if( rc==SQLITE_ROW ){
110923          azVals = &azCols[nCol];
110924          for(i=0; i<nCol; i++){
110925            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
110926            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
110927              sqlite3OomFault(db);
110928              goto exec_out;
110929            }
110930          }
110931          azVals[i] = 0;
110932        }
110933        if( xCallback(pArg, nCol, azVals, azCols) ){
110934          /* EVIDENCE-OF: R-38229-40159 If the callback function to
110935          ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
110936          ** return SQLITE_ABORT. */
110937          rc = SQLITE_ABORT;
110938          sqlite3VdbeFinalize((Vdbe *)pStmt);
110939          pStmt = 0;
110940          sqlite3Error(db, SQLITE_ABORT);
110941          goto exec_out;
110942        }
110943      }
110944
110945      if( rc!=SQLITE_ROW ){
110946        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
110947        pStmt = 0;
110948        zSql = zLeftover;
110949        while( sqlite3Isspace(zSql[0]) ) zSql++;
110950        break;
110951      }
110952    }
110953
110954    sqlite3DbFree(db, azCols);
110955    azCols = 0;
110956  }
110957
110958exec_out:
110959  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
110960  sqlite3DbFree(db, azCols);
110961
110962  rc = sqlite3ApiExit(db, rc);
110963  if( rc!=SQLITE_OK && pzErrMsg ){
110964    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
110965    *pzErrMsg = sqlite3Malloc(nErrMsg);
110966    if( *pzErrMsg ){
110967      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
110968    }else{
110969      rc = SQLITE_NOMEM_BKPT;
110970      sqlite3Error(db, SQLITE_NOMEM);
110971    }
110972  }else if( pzErrMsg ){
110973    *pzErrMsg = 0;
110974  }
110975
110976  assert( (rc&db->errMask)==rc );
110977  sqlite3_mutex_leave(db->mutex);
110978  return rc;
110979}
110980
110981/************** End of legacy.c **********************************************/
110982/************** Begin file loadext.c *****************************************/
110983/*
110984** 2006 June 7
110985**
110986** The author disclaims copyright to this source code.  In place of
110987** a legal notice, here is a blessing:
110988**
110989**    May you do good and not evil.
110990**    May you find forgiveness for yourself and forgive others.
110991**    May you share freely, never taking more than you give.
110992**
110993*************************************************************************
110994** This file contains code used to dynamically load extensions into
110995** the SQLite library.
110996*/
110997
110998#ifndef SQLITE_CORE
110999  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
111000#endif
111001/************** Include sqlite3ext.h in the middle of loadext.c **************/
111002/************** Begin file sqlite3ext.h **************************************/
111003/*
111004** 2006 June 7
111005**
111006** The author disclaims copyright to this source code.  In place of
111007** a legal notice, here is a blessing:
111008**
111009**    May you do good and not evil.
111010**    May you find forgiveness for yourself and forgive others.
111011**    May you share freely, never taking more than you give.
111012**
111013*************************************************************************
111014** This header file defines the SQLite interface for use by
111015** shared libraries that want to be imported as extensions into
111016** an SQLite instance.  Shared libraries that intend to be loaded
111017** as extensions by SQLite should #include this file instead of
111018** sqlite3.h.
111019*/
111020#ifndef SQLITE3EXT_H
111021#define SQLITE3EXT_H
111022/* #include "sqlite3.h" */
111023
111024/*
111025** The following structure holds pointers to all of the SQLite API
111026** routines.
111027**
111028** WARNING:  In order to maintain backwards compatibility, add new
111029** interfaces to the end of this structure only.  If you insert new
111030** interfaces in the middle of this structure, then older different
111031** versions of SQLite will not be able to load each other's shared
111032** libraries!
111033*/
111034struct sqlite3_api_routines {
111035  void * (*aggregate_context)(sqlite3_context*,int nBytes);
111036  int  (*aggregate_count)(sqlite3_context*);
111037  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
111038  int  (*bind_double)(sqlite3_stmt*,int,double);
111039  int  (*bind_int)(sqlite3_stmt*,int,int);
111040  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
111041  int  (*bind_null)(sqlite3_stmt*,int);
111042  int  (*bind_parameter_count)(sqlite3_stmt*);
111043  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
111044  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
111045  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
111046  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
111047  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
111048  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
111049  int  (*busy_timeout)(sqlite3*,int ms);
111050  int  (*changes)(sqlite3*);
111051  int  (*close)(sqlite3*);
111052  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
111053                           int eTextRep,const char*));
111054  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
111055                             int eTextRep,const void*));
111056  const void * (*column_blob)(sqlite3_stmt*,int iCol);
111057  int  (*column_bytes)(sqlite3_stmt*,int iCol);
111058  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
111059  int  (*column_count)(sqlite3_stmt*pStmt);
111060  const char * (*column_database_name)(sqlite3_stmt*,int);
111061  const void * (*column_database_name16)(sqlite3_stmt*,int);
111062  const char * (*column_decltype)(sqlite3_stmt*,int i);
111063  const void * (*column_decltype16)(sqlite3_stmt*,int);
111064  double  (*column_double)(sqlite3_stmt*,int iCol);
111065  int  (*column_int)(sqlite3_stmt*,int iCol);
111066  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
111067  const char * (*column_name)(sqlite3_stmt*,int);
111068  const void * (*column_name16)(sqlite3_stmt*,int);
111069  const char * (*column_origin_name)(sqlite3_stmt*,int);
111070  const void * (*column_origin_name16)(sqlite3_stmt*,int);
111071  const char * (*column_table_name)(sqlite3_stmt*,int);
111072  const void * (*column_table_name16)(sqlite3_stmt*,int);
111073  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
111074  const void * (*column_text16)(sqlite3_stmt*,int iCol);
111075  int  (*column_type)(sqlite3_stmt*,int iCol);
111076  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
111077  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
111078  int  (*complete)(const char*sql);
111079  int  (*complete16)(const void*sql);
111080  int  (*create_collation)(sqlite3*,const char*,int,void*,
111081                           int(*)(void*,int,const void*,int,const void*));
111082  int  (*create_collation16)(sqlite3*,const void*,int,void*,
111083                             int(*)(void*,int,const void*,int,const void*));
111084  int  (*create_function)(sqlite3*,const char*,int,int,void*,
111085                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
111086                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
111087                          void (*xFinal)(sqlite3_context*));
111088  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
111089                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
111090                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
111091                            void (*xFinal)(sqlite3_context*));
111092  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
111093  int  (*data_count)(sqlite3_stmt*pStmt);
111094  sqlite3 * (*db_handle)(sqlite3_stmt*);
111095  int (*declare_vtab)(sqlite3*,const char*);
111096  int  (*enable_shared_cache)(int);
111097  int  (*errcode)(sqlite3*db);
111098  const char * (*errmsg)(sqlite3*);
111099  const void * (*errmsg16)(sqlite3*);
111100  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
111101  int  (*expired)(sqlite3_stmt*);
111102  int  (*finalize)(sqlite3_stmt*pStmt);
111103  void  (*free)(void*);
111104  void  (*free_table)(char**result);
111105  int  (*get_autocommit)(sqlite3*);
111106  void * (*get_auxdata)(sqlite3_context*,int);
111107  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
111108  int  (*global_recover)(void);
111109  void  (*interruptx)(sqlite3*);
111110  sqlite_int64  (*last_insert_rowid)(sqlite3*);
111111  const char * (*libversion)(void);
111112  int  (*libversion_number)(void);
111113  void *(*malloc)(int);
111114  char * (*mprintf)(const char*,...);
111115  int  (*open)(const char*,sqlite3**);
111116  int  (*open16)(const void*,sqlite3**);
111117  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
111118  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
111119  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
111120  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
111121  void *(*realloc)(void*,int);
111122  int  (*reset)(sqlite3_stmt*pStmt);
111123  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
111124  void  (*result_double)(sqlite3_context*,double);
111125  void  (*result_error)(sqlite3_context*,const char*,int);
111126  void  (*result_error16)(sqlite3_context*,const void*,int);
111127  void  (*result_int)(sqlite3_context*,int);
111128  void  (*result_int64)(sqlite3_context*,sqlite_int64);
111129  void  (*result_null)(sqlite3_context*);
111130  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
111131  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
111132  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
111133  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
111134  void  (*result_value)(sqlite3_context*,sqlite3_value*);
111135  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
111136  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
111137                         const char*,const char*),void*);
111138  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
111139  char * (*snprintf)(int,char*,const char*,...);
111140  int  (*step)(sqlite3_stmt*);
111141  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
111142                                char const**,char const**,int*,int*,int*);
111143  void  (*thread_cleanup)(void);
111144  int  (*total_changes)(sqlite3*);
111145  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
111146  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
111147  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
111148                                         sqlite_int64),void*);
111149  void * (*user_data)(sqlite3_context*);
111150  const void * (*value_blob)(sqlite3_value*);
111151  int  (*value_bytes)(sqlite3_value*);
111152  int  (*value_bytes16)(sqlite3_value*);
111153  double  (*value_double)(sqlite3_value*);
111154  int  (*value_int)(sqlite3_value*);
111155  sqlite_int64  (*value_int64)(sqlite3_value*);
111156  int  (*value_numeric_type)(sqlite3_value*);
111157  const unsigned char * (*value_text)(sqlite3_value*);
111158  const void * (*value_text16)(sqlite3_value*);
111159  const void * (*value_text16be)(sqlite3_value*);
111160  const void * (*value_text16le)(sqlite3_value*);
111161  int  (*value_type)(sqlite3_value*);
111162  char *(*vmprintf)(const char*,va_list);
111163  /* Added ??? */
111164  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
111165  /* Added by 3.3.13 */
111166  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
111167  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
111168  int (*clear_bindings)(sqlite3_stmt*);
111169  /* Added by 3.4.1 */
111170  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
111171                          void (*xDestroy)(void *));
111172  /* Added by 3.5.0 */
111173  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
111174  int (*blob_bytes)(sqlite3_blob*);
111175  int (*blob_close)(sqlite3_blob*);
111176  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
111177                   int,sqlite3_blob**);
111178  int (*blob_read)(sqlite3_blob*,void*,int,int);
111179  int (*blob_write)(sqlite3_blob*,const void*,int,int);
111180  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
111181                             int(*)(void*,int,const void*,int,const void*),
111182                             void(*)(void*));
111183  int (*file_control)(sqlite3*,const char*,int,void*);
111184  sqlite3_int64 (*memory_highwater)(int);
111185  sqlite3_int64 (*memory_used)(void);
111186  sqlite3_mutex *(*mutex_alloc)(int);
111187  void (*mutex_enter)(sqlite3_mutex*);
111188  void (*mutex_free)(sqlite3_mutex*);
111189  void (*mutex_leave)(sqlite3_mutex*);
111190  int (*mutex_try)(sqlite3_mutex*);
111191  int (*open_v2)(const char*,sqlite3**,int,const char*);
111192  int (*release_memory)(int);
111193  void (*result_error_nomem)(sqlite3_context*);
111194  void (*result_error_toobig)(sqlite3_context*);
111195  int (*sleep)(int);
111196  void (*soft_heap_limit)(int);
111197  sqlite3_vfs *(*vfs_find)(const char*);
111198  int (*vfs_register)(sqlite3_vfs*,int);
111199  int (*vfs_unregister)(sqlite3_vfs*);
111200  int (*xthreadsafe)(void);
111201  void (*result_zeroblob)(sqlite3_context*,int);
111202  void (*result_error_code)(sqlite3_context*,int);
111203  int (*test_control)(int, ...);
111204  void (*randomness)(int,void*);
111205  sqlite3 *(*context_db_handle)(sqlite3_context*);
111206  int (*extended_result_codes)(sqlite3*,int);
111207  int (*limit)(sqlite3*,int,int);
111208  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
111209  const char *(*sql)(sqlite3_stmt*);
111210  int (*status)(int,int*,int*,int);
111211  int (*backup_finish)(sqlite3_backup*);
111212  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
111213  int (*backup_pagecount)(sqlite3_backup*);
111214  int (*backup_remaining)(sqlite3_backup*);
111215  int (*backup_step)(sqlite3_backup*,int);
111216  const char *(*compileoption_get)(int);
111217  int (*compileoption_used)(const char*);
111218  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
111219                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
111220                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
111221                            void (*xFinal)(sqlite3_context*),
111222                            void(*xDestroy)(void*));
111223  int (*db_config)(sqlite3*,int,...);
111224  sqlite3_mutex *(*db_mutex)(sqlite3*);
111225  int (*db_status)(sqlite3*,int,int*,int*,int);
111226  int (*extended_errcode)(sqlite3*);
111227  void (*log)(int,const char*,...);
111228  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
111229  const char *(*sourceid)(void);
111230  int (*stmt_status)(sqlite3_stmt*,int,int);
111231  int (*strnicmp)(const char*,const char*,int);
111232  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
111233  int (*wal_autocheckpoint)(sqlite3*,int);
111234  int (*wal_checkpoint)(sqlite3*,const char*);
111235  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
111236  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
111237  int (*vtab_config)(sqlite3*,int op,...);
111238  int (*vtab_on_conflict)(sqlite3*);
111239  /* Version 3.7.16 and later */
111240  int (*close_v2)(sqlite3*);
111241  const char *(*db_filename)(sqlite3*,const char*);
111242  int (*db_readonly)(sqlite3*,const char*);
111243  int (*db_release_memory)(sqlite3*);
111244  const char *(*errstr)(int);
111245  int (*stmt_busy)(sqlite3_stmt*);
111246  int (*stmt_readonly)(sqlite3_stmt*);
111247  int (*stricmp)(const char*,const char*);
111248  int (*uri_boolean)(const char*,const char*,int);
111249  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
111250  const char *(*uri_parameter)(const char*,const char*);
111251  char *(*vsnprintf)(int,char*,const char*,va_list);
111252  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
111253  /* Version 3.8.7 and later */
111254  int (*auto_extension)(void(*)(void));
111255  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
111256                     void(*)(void*));
111257  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
111258                      void(*)(void*),unsigned char);
111259  int (*cancel_auto_extension)(void(*)(void));
111260  int (*load_extension)(sqlite3*,const char*,const char*,char**);
111261  void *(*malloc64)(sqlite3_uint64);
111262  sqlite3_uint64 (*msize)(void*);
111263  void *(*realloc64)(void*,sqlite3_uint64);
111264  void (*reset_auto_extension)(void);
111265  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
111266                        void(*)(void*));
111267  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
111268                         void(*)(void*), unsigned char);
111269  int (*strglob)(const char*,const char*);
111270  /* Version 3.8.11 and later */
111271  sqlite3_value *(*value_dup)(const sqlite3_value*);
111272  void (*value_free)(sqlite3_value*);
111273  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
111274  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
111275  /* Version 3.9.0 and later */
111276  unsigned int (*value_subtype)(sqlite3_value*);
111277  void (*result_subtype)(sqlite3_context*,unsigned int);
111278  /* Version 3.10.0 and later */
111279  int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
111280  int (*strlike)(const char*,const char*,unsigned int);
111281  int (*db_cacheflush)(sqlite3*);
111282  /* Version 3.12.0 and later */
111283  int (*system_errno)(sqlite3*);
111284  /* Version 3.14.0 and later */
111285  int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
111286  char *(*expanded_sql)(sqlite3_stmt*);
111287  /* Version 3.18.0 and later */
111288  void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
111289};
111290
111291/*
111292** This is the function signature used for all extension entry points.  It
111293** is also defined in the file "loadext.c".
111294*/
111295typedef int (*sqlite3_loadext_entry)(
111296  sqlite3 *db,                       /* Handle to the database. */
111297  char **pzErrMsg,                   /* Used to set error string on failure. */
111298  const sqlite3_api_routines *pThunk /* Extension API function pointers. */
111299);
111300
111301/*
111302** The following macros redefine the API routines so that they are
111303** redirected through the global sqlite3_api structure.
111304**
111305** This header file is also used by the loadext.c source file
111306** (part of the main SQLite library - not an extension) so that
111307** it can get access to the sqlite3_api_routines structure
111308** definition.  But the main library does not want to redefine
111309** the API.  So the redefinition macros are only valid if the
111310** SQLITE_CORE macros is undefined.
111311*/
111312#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
111313#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
111314#ifndef SQLITE_OMIT_DEPRECATED
111315#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
111316#endif
111317#define sqlite3_bind_blob              sqlite3_api->bind_blob
111318#define sqlite3_bind_double            sqlite3_api->bind_double
111319#define sqlite3_bind_int               sqlite3_api->bind_int
111320#define sqlite3_bind_int64             sqlite3_api->bind_int64
111321#define sqlite3_bind_null              sqlite3_api->bind_null
111322#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
111323#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
111324#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
111325#define sqlite3_bind_text              sqlite3_api->bind_text
111326#define sqlite3_bind_text16            sqlite3_api->bind_text16
111327#define sqlite3_bind_value             sqlite3_api->bind_value
111328#define sqlite3_busy_handler           sqlite3_api->busy_handler
111329#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
111330#define sqlite3_changes                sqlite3_api->changes
111331#define sqlite3_close                  sqlite3_api->close
111332#define sqlite3_collation_needed       sqlite3_api->collation_needed
111333#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
111334#define sqlite3_column_blob            sqlite3_api->column_blob
111335#define sqlite3_column_bytes           sqlite3_api->column_bytes
111336#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
111337#define sqlite3_column_count           sqlite3_api->column_count
111338#define sqlite3_column_database_name   sqlite3_api->column_database_name
111339#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
111340#define sqlite3_column_decltype        sqlite3_api->column_decltype
111341#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
111342#define sqlite3_column_double          sqlite3_api->column_double
111343#define sqlite3_column_int             sqlite3_api->column_int
111344#define sqlite3_column_int64           sqlite3_api->column_int64
111345#define sqlite3_column_name            sqlite3_api->column_name
111346#define sqlite3_column_name16          sqlite3_api->column_name16
111347#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
111348#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
111349#define sqlite3_column_table_name      sqlite3_api->column_table_name
111350#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
111351#define sqlite3_column_text            sqlite3_api->column_text
111352#define sqlite3_column_text16          sqlite3_api->column_text16
111353#define sqlite3_column_type            sqlite3_api->column_type
111354#define sqlite3_column_value           sqlite3_api->column_value
111355#define sqlite3_commit_hook            sqlite3_api->commit_hook
111356#define sqlite3_complete               sqlite3_api->complete
111357#define sqlite3_complete16             sqlite3_api->complete16
111358#define sqlite3_create_collation       sqlite3_api->create_collation
111359#define sqlite3_create_collation16     sqlite3_api->create_collation16
111360#define sqlite3_create_function        sqlite3_api->create_function
111361#define sqlite3_create_function16      sqlite3_api->create_function16
111362#define sqlite3_create_module          sqlite3_api->create_module
111363#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
111364#define sqlite3_data_count             sqlite3_api->data_count
111365#define sqlite3_db_handle              sqlite3_api->db_handle
111366#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
111367#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
111368#define sqlite3_errcode                sqlite3_api->errcode
111369#define sqlite3_errmsg                 sqlite3_api->errmsg
111370#define sqlite3_errmsg16               sqlite3_api->errmsg16
111371#define sqlite3_exec                   sqlite3_api->exec
111372#ifndef SQLITE_OMIT_DEPRECATED
111373#define sqlite3_expired                sqlite3_api->expired
111374#endif
111375#define sqlite3_finalize               sqlite3_api->finalize
111376#define sqlite3_free                   sqlite3_api->free
111377#define sqlite3_free_table             sqlite3_api->free_table
111378#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
111379#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
111380#define sqlite3_get_table              sqlite3_api->get_table
111381#ifndef SQLITE_OMIT_DEPRECATED
111382#define sqlite3_global_recover         sqlite3_api->global_recover
111383#endif
111384#define sqlite3_interrupt              sqlite3_api->interruptx
111385#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
111386#define sqlite3_libversion             sqlite3_api->libversion
111387#define sqlite3_libversion_number      sqlite3_api->libversion_number
111388#define sqlite3_malloc                 sqlite3_api->malloc
111389#define sqlite3_mprintf                sqlite3_api->mprintf
111390#define sqlite3_open                   sqlite3_api->open
111391#define sqlite3_open16                 sqlite3_api->open16
111392#define sqlite3_prepare                sqlite3_api->prepare
111393#define sqlite3_prepare16              sqlite3_api->prepare16
111394#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
111395#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
111396#define sqlite3_profile                sqlite3_api->profile
111397#define sqlite3_progress_handler       sqlite3_api->progress_handler
111398#define sqlite3_realloc                sqlite3_api->realloc
111399#define sqlite3_reset                  sqlite3_api->reset
111400#define sqlite3_result_blob            sqlite3_api->result_blob
111401#define sqlite3_result_double          sqlite3_api->result_double
111402#define sqlite3_result_error           sqlite3_api->result_error
111403#define sqlite3_result_error16         sqlite3_api->result_error16
111404#define sqlite3_result_int             sqlite3_api->result_int
111405#define sqlite3_result_int64           sqlite3_api->result_int64
111406#define sqlite3_result_null            sqlite3_api->result_null
111407#define sqlite3_result_text            sqlite3_api->result_text
111408#define sqlite3_result_text16          sqlite3_api->result_text16
111409#define sqlite3_result_text16be        sqlite3_api->result_text16be
111410#define sqlite3_result_text16le        sqlite3_api->result_text16le
111411#define sqlite3_result_value           sqlite3_api->result_value
111412#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
111413#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
111414#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
111415#define sqlite3_snprintf               sqlite3_api->snprintf
111416#define sqlite3_step                   sqlite3_api->step
111417#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
111418#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
111419#define sqlite3_total_changes          sqlite3_api->total_changes
111420#define sqlite3_trace                  sqlite3_api->trace
111421#ifndef SQLITE_OMIT_DEPRECATED
111422#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
111423#endif
111424#define sqlite3_update_hook            sqlite3_api->update_hook
111425#define sqlite3_user_data              sqlite3_api->user_data
111426#define sqlite3_value_blob             sqlite3_api->value_blob
111427#define sqlite3_value_bytes            sqlite3_api->value_bytes
111428#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
111429#define sqlite3_value_double           sqlite3_api->value_double
111430#define sqlite3_value_int              sqlite3_api->value_int
111431#define sqlite3_value_int64            sqlite3_api->value_int64
111432#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
111433#define sqlite3_value_text             sqlite3_api->value_text
111434#define sqlite3_value_text16           sqlite3_api->value_text16
111435#define sqlite3_value_text16be         sqlite3_api->value_text16be
111436#define sqlite3_value_text16le         sqlite3_api->value_text16le
111437#define sqlite3_value_type             sqlite3_api->value_type
111438#define sqlite3_vmprintf               sqlite3_api->vmprintf
111439#define sqlite3_vsnprintf              sqlite3_api->vsnprintf
111440#define sqlite3_overload_function      sqlite3_api->overload_function
111441#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
111442#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
111443#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
111444#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
111445#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
111446#define sqlite3_blob_close             sqlite3_api->blob_close
111447#define sqlite3_blob_open              sqlite3_api->blob_open
111448#define sqlite3_blob_read              sqlite3_api->blob_read
111449#define sqlite3_blob_write             sqlite3_api->blob_write
111450#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
111451#define sqlite3_file_control           sqlite3_api->file_control
111452#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
111453#define sqlite3_memory_used            sqlite3_api->memory_used
111454#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
111455#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
111456#define sqlite3_mutex_free             sqlite3_api->mutex_free
111457#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
111458#define sqlite3_mutex_try              sqlite3_api->mutex_try
111459#define sqlite3_open_v2                sqlite3_api->open_v2
111460#define sqlite3_release_memory         sqlite3_api->release_memory
111461#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
111462#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
111463#define sqlite3_sleep                  sqlite3_api->sleep
111464#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
111465#define sqlite3_vfs_find               sqlite3_api->vfs_find
111466#define sqlite3_vfs_register           sqlite3_api->vfs_register
111467#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
111468#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
111469#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
111470#define sqlite3_result_error_code      sqlite3_api->result_error_code
111471#define sqlite3_test_control           sqlite3_api->test_control
111472#define sqlite3_randomness             sqlite3_api->randomness
111473#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
111474#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
111475#define sqlite3_limit                  sqlite3_api->limit
111476#define sqlite3_next_stmt              sqlite3_api->next_stmt
111477#define sqlite3_sql                    sqlite3_api->sql
111478#define sqlite3_status                 sqlite3_api->status
111479#define sqlite3_backup_finish          sqlite3_api->backup_finish
111480#define sqlite3_backup_init            sqlite3_api->backup_init
111481#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
111482#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
111483#define sqlite3_backup_step            sqlite3_api->backup_step
111484#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
111485#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
111486#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
111487#define sqlite3_db_config              sqlite3_api->db_config
111488#define sqlite3_db_mutex               sqlite3_api->db_mutex
111489#define sqlite3_db_status              sqlite3_api->db_status
111490#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
111491#define sqlite3_log                    sqlite3_api->log
111492#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
111493#define sqlite3_sourceid               sqlite3_api->sourceid
111494#define sqlite3_stmt_status            sqlite3_api->stmt_status
111495#define sqlite3_strnicmp               sqlite3_api->strnicmp
111496#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
111497#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
111498#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
111499#define sqlite3_wal_hook               sqlite3_api->wal_hook
111500#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
111501#define sqlite3_vtab_config            sqlite3_api->vtab_config
111502#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
111503/* Version 3.7.16 and later */
111504#define sqlite3_close_v2               sqlite3_api->close_v2
111505#define sqlite3_db_filename            sqlite3_api->db_filename
111506#define sqlite3_db_readonly            sqlite3_api->db_readonly
111507#define sqlite3_db_release_memory      sqlite3_api->db_release_memory
111508#define sqlite3_errstr                 sqlite3_api->errstr
111509#define sqlite3_stmt_busy              sqlite3_api->stmt_busy
111510#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
111511#define sqlite3_stricmp                sqlite3_api->stricmp
111512#define sqlite3_uri_boolean            sqlite3_api->uri_boolean
111513#define sqlite3_uri_int64              sqlite3_api->uri_int64
111514#define sqlite3_uri_parameter          sqlite3_api->uri_parameter
111515#define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
111516#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
111517/* Version 3.8.7 and later */
111518#define sqlite3_auto_extension         sqlite3_api->auto_extension
111519#define sqlite3_bind_blob64            sqlite3_api->bind_blob64
111520#define sqlite3_bind_text64            sqlite3_api->bind_text64
111521#define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
111522#define sqlite3_load_extension         sqlite3_api->load_extension
111523#define sqlite3_malloc64               sqlite3_api->malloc64
111524#define sqlite3_msize                  sqlite3_api->msize
111525#define sqlite3_realloc64              sqlite3_api->realloc64
111526#define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
111527#define sqlite3_result_blob64          sqlite3_api->result_blob64
111528#define sqlite3_result_text64          sqlite3_api->result_text64
111529#define sqlite3_strglob                sqlite3_api->strglob
111530/* Version 3.8.11 and later */
111531#define sqlite3_value_dup              sqlite3_api->value_dup
111532#define sqlite3_value_free             sqlite3_api->value_free
111533#define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64
111534#define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64
111535/* Version 3.9.0 and later */
111536#define sqlite3_value_subtype          sqlite3_api->value_subtype
111537#define sqlite3_result_subtype         sqlite3_api->result_subtype
111538/* Version 3.10.0 and later */
111539#define sqlite3_status64               sqlite3_api->status64
111540#define sqlite3_strlike                sqlite3_api->strlike
111541#define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush
111542/* Version 3.12.0 and later */
111543#define sqlite3_system_errno           sqlite3_api->system_errno
111544/* Version 3.14.0 and later */
111545#define sqlite3_trace_v2               sqlite3_api->trace_v2
111546#define sqlite3_expanded_sql           sqlite3_api->expanded_sql
111547/* Version 3.18.0 and later */
111548#define sqlite3_set_last_insert_rowid  sqlite3_api->set_last_insert_rowid
111549#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
111550
111551#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
111552  /* This case when the file really is being compiled as a loadable
111553  ** extension */
111554# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
111555# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
111556# define SQLITE_EXTENSION_INIT3     \
111557    extern const sqlite3_api_routines *sqlite3_api;
111558#else
111559  /* This case when the file is being statically linked into the
111560  ** application */
111561# define SQLITE_EXTENSION_INIT1     /*no-op*/
111562# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
111563# define SQLITE_EXTENSION_INIT3     /*no-op*/
111564#endif
111565
111566#endif /* SQLITE3EXT_H */
111567
111568/************** End of sqlite3ext.h ******************************************/
111569/************** Continuing where we left off in loadext.c ********************/
111570/* #include "sqliteInt.h" */
111571
111572#ifndef SQLITE_OMIT_LOAD_EXTENSION
111573/*
111574** Some API routines are omitted when various features are
111575** excluded from a build of SQLite.  Substitute a NULL pointer
111576** for any missing APIs.
111577*/
111578#ifndef SQLITE_ENABLE_COLUMN_METADATA
111579# define sqlite3_column_database_name   0
111580# define sqlite3_column_database_name16 0
111581# define sqlite3_column_table_name      0
111582# define sqlite3_column_table_name16    0
111583# define sqlite3_column_origin_name     0
111584# define sqlite3_column_origin_name16   0
111585#endif
111586
111587#ifdef SQLITE_OMIT_AUTHORIZATION
111588# define sqlite3_set_authorizer         0
111589#endif
111590
111591#ifdef SQLITE_OMIT_UTF16
111592# define sqlite3_bind_text16            0
111593# define sqlite3_collation_needed16     0
111594# define sqlite3_column_decltype16      0
111595# define sqlite3_column_name16          0
111596# define sqlite3_column_text16          0
111597# define sqlite3_complete16             0
111598# define sqlite3_create_collation16     0
111599# define sqlite3_create_function16      0
111600# define sqlite3_errmsg16               0
111601# define sqlite3_open16                 0
111602# define sqlite3_prepare16              0
111603# define sqlite3_prepare16_v2           0
111604# define sqlite3_result_error16         0
111605# define sqlite3_result_text16          0
111606# define sqlite3_result_text16be        0
111607# define sqlite3_result_text16le        0
111608# define sqlite3_value_text16           0
111609# define sqlite3_value_text16be         0
111610# define sqlite3_value_text16le         0
111611# define sqlite3_column_database_name16 0
111612# define sqlite3_column_table_name16    0
111613# define sqlite3_column_origin_name16   0
111614#endif
111615
111616#ifdef SQLITE_OMIT_COMPLETE
111617# define sqlite3_complete 0
111618# define sqlite3_complete16 0
111619#endif
111620
111621#ifdef SQLITE_OMIT_DECLTYPE
111622# define sqlite3_column_decltype16      0
111623# define sqlite3_column_decltype        0
111624#endif
111625
111626#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
111627# define sqlite3_progress_handler 0
111628#endif
111629
111630#ifdef SQLITE_OMIT_VIRTUALTABLE
111631# define sqlite3_create_module 0
111632# define sqlite3_create_module_v2 0
111633# define sqlite3_declare_vtab 0
111634# define sqlite3_vtab_config 0
111635# define sqlite3_vtab_on_conflict 0
111636#endif
111637
111638#ifdef SQLITE_OMIT_SHARED_CACHE
111639# define sqlite3_enable_shared_cache 0
111640#endif
111641
111642#if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
111643# define sqlite3_profile       0
111644# define sqlite3_trace         0
111645#endif
111646
111647#ifdef SQLITE_OMIT_GET_TABLE
111648# define sqlite3_free_table    0
111649# define sqlite3_get_table     0
111650#endif
111651
111652#ifdef SQLITE_OMIT_INCRBLOB
111653#define sqlite3_bind_zeroblob  0
111654#define sqlite3_blob_bytes     0
111655#define sqlite3_blob_close     0
111656#define sqlite3_blob_open      0
111657#define sqlite3_blob_read      0
111658#define sqlite3_blob_write     0
111659#define sqlite3_blob_reopen    0
111660#endif
111661
111662#if defined(SQLITE_OMIT_TRACE)
111663# define sqlite3_trace_v2      0
111664#endif
111665
111666/*
111667** The following structure contains pointers to all SQLite API routines.
111668** A pointer to this structure is passed into extensions when they are
111669** loaded so that the extension can make calls back into the SQLite
111670** library.
111671**
111672** When adding new APIs, add them to the bottom of this structure
111673** in order to preserve backwards compatibility.
111674**
111675** Extensions that use newer APIs should first call the
111676** sqlite3_libversion_number() to make sure that the API they
111677** intend to use is supported by the library.  Extensions should
111678** also check to make sure that the pointer to the function is
111679** not NULL before calling it.
111680*/
111681static const sqlite3_api_routines sqlite3Apis = {
111682  sqlite3_aggregate_context,
111683#ifndef SQLITE_OMIT_DEPRECATED
111684  sqlite3_aggregate_count,
111685#else
111686  0,
111687#endif
111688  sqlite3_bind_blob,
111689  sqlite3_bind_double,
111690  sqlite3_bind_int,
111691  sqlite3_bind_int64,
111692  sqlite3_bind_null,
111693  sqlite3_bind_parameter_count,
111694  sqlite3_bind_parameter_index,
111695  sqlite3_bind_parameter_name,
111696  sqlite3_bind_text,
111697  sqlite3_bind_text16,
111698  sqlite3_bind_value,
111699  sqlite3_busy_handler,
111700  sqlite3_busy_timeout,
111701  sqlite3_changes,
111702  sqlite3_close,
111703  sqlite3_collation_needed,
111704  sqlite3_collation_needed16,
111705  sqlite3_column_blob,
111706  sqlite3_column_bytes,
111707  sqlite3_column_bytes16,
111708  sqlite3_column_count,
111709  sqlite3_column_database_name,
111710  sqlite3_column_database_name16,
111711  sqlite3_column_decltype,
111712  sqlite3_column_decltype16,
111713  sqlite3_column_double,
111714  sqlite3_column_int,
111715  sqlite3_column_int64,
111716  sqlite3_column_name,
111717  sqlite3_column_name16,
111718  sqlite3_column_origin_name,
111719  sqlite3_column_origin_name16,
111720  sqlite3_column_table_name,
111721  sqlite3_column_table_name16,
111722  sqlite3_column_text,
111723  sqlite3_column_text16,
111724  sqlite3_column_type,
111725  sqlite3_column_value,
111726  sqlite3_commit_hook,
111727  sqlite3_complete,
111728  sqlite3_complete16,
111729  sqlite3_create_collation,
111730  sqlite3_create_collation16,
111731  sqlite3_create_function,
111732  sqlite3_create_function16,
111733  sqlite3_create_module,
111734  sqlite3_data_count,
111735  sqlite3_db_handle,
111736  sqlite3_declare_vtab,
111737  sqlite3_enable_shared_cache,
111738  sqlite3_errcode,
111739  sqlite3_errmsg,
111740  sqlite3_errmsg16,
111741  sqlite3_exec,
111742#ifndef SQLITE_OMIT_DEPRECATED
111743  sqlite3_expired,
111744#else
111745  0,
111746#endif
111747  sqlite3_finalize,
111748  sqlite3_free,
111749  sqlite3_free_table,
111750  sqlite3_get_autocommit,
111751  sqlite3_get_auxdata,
111752  sqlite3_get_table,
111753  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
111754  sqlite3_interrupt,
111755  sqlite3_last_insert_rowid,
111756  sqlite3_libversion,
111757  sqlite3_libversion_number,
111758  sqlite3_malloc,
111759  sqlite3_mprintf,
111760  sqlite3_open,
111761  sqlite3_open16,
111762  sqlite3_prepare,
111763  sqlite3_prepare16,
111764  sqlite3_profile,
111765  sqlite3_progress_handler,
111766  sqlite3_realloc,
111767  sqlite3_reset,
111768  sqlite3_result_blob,
111769  sqlite3_result_double,
111770  sqlite3_result_error,
111771  sqlite3_result_error16,
111772  sqlite3_result_int,
111773  sqlite3_result_int64,
111774  sqlite3_result_null,
111775  sqlite3_result_text,
111776  sqlite3_result_text16,
111777  sqlite3_result_text16be,
111778  sqlite3_result_text16le,
111779  sqlite3_result_value,
111780  sqlite3_rollback_hook,
111781  sqlite3_set_authorizer,
111782  sqlite3_set_auxdata,
111783  sqlite3_snprintf,
111784  sqlite3_step,
111785  sqlite3_table_column_metadata,
111786#ifndef SQLITE_OMIT_DEPRECATED
111787  sqlite3_thread_cleanup,
111788#else
111789  0,
111790#endif
111791  sqlite3_total_changes,
111792  sqlite3_trace,
111793#ifndef SQLITE_OMIT_DEPRECATED
111794  sqlite3_transfer_bindings,
111795#else
111796  0,
111797#endif
111798  sqlite3_update_hook,
111799  sqlite3_user_data,
111800  sqlite3_value_blob,
111801  sqlite3_value_bytes,
111802  sqlite3_value_bytes16,
111803  sqlite3_value_double,
111804  sqlite3_value_int,
111805  sqlite3_value_int64,
111806  sqlite3_value_numeric_type,
111807  sqlite3_value_text,
111808  sqlite3_value_text16,
111809  sqlite3_value_text16be,
111810  sqlite3_value_text16le,
111811  sqlite3_value_type,
111812  sqlite3_vmprintf,
111813  /*
111814  ** The original API set ends here.  All extensions can call any
111815  ** of the APIs above provided that the pointer is not NULL.  But
111816  ** before calling APIs that follow, extension should check the
111817  ** sqlite3_libversion_number() to make sure they are dealing with
111818  ** a library that is new enough to support that API.
111819  *************************************************************************
111820  */
111821  sqlite3_overload_function,
111822
111823  /*
111824  ** Added after 3.3.13
111825  */
111826  sqlite3_prepare_v2,
111827  sqlite3_prepare16_v2,
111828  sqlite3_clear_bindings,
111829
111830  /*
111831  ** Added for 3.4.1
111832  */
111833  sqlite3_create_module_v2,
111834
111835  /*
111836  ** Added for 3.5.0
111837  */
111838  sqlite3_bind_zeroblob,
111839  sqlite3_blob_bytes,
111840  sqlite3_blob_close,
111841  sqlite3_blob_open,
111842  sqlite3_blob_read,
111843  sqlite3_blob_write,
111844  sqlite3_create_collation_v2,
111845  sqlite3_file_control,
111846  sqlite3_memory_highwater,
111847  sqlite3_memory_used,
111848#ifdef SQLITE_MUTEX_OMIT
111849  0,
111850  0,
111851  0,
111852  0,
111853  0,
111854#else
111855  sqlite3_mutex_alloc,
111856  sqlite3_mutex_enter,
111857  sqlite3_mutex_free,
111858  sqlite3_mutex_leave,
111859  sqlite3_mutex_try,
111860#endif
111861  sqlite3_open_v2,
111862  sqlite3_release_memory,
111863  sqlite3_result_error_nomem,
111864  sqlite3_result_error_toobig,
111865  sqlite3_sleep,
111866  sqlite3_soft_heap_limit,
111867  sqlite3_vfs_find,
111868  sqlite3_vfs_register,
111869  sqlite3_vfs_unregister,
111870
111871  /*
111872  ** Added for 3.5.8
111873  */
111874  sqlite3_threadsafe,
111875  sqlite3_result_zeroblob,
111876  sqlite3_result_error_code,
111877  sqlite3_test_control,
111878  sqlite3_randomness,
111879  sqlite3_context_db_handle,
111880
111881  /*
111882  ** Added for 3.6.0
111883  */
111884  sqlite3_extended_result_codes,
111885  sqlite3_limit,
111886  sqlite3_next_stmt,
111887  sqlite3_sql,
111888  sqlite3_status,
111889
111890  /*
111891  ** Added for 3.7.4
111892  */
111893  sqlite3_backup_finish,
111894  sqlite3_backup_init,
111895  sqlite3_backup_pagecount,
111896  sqlite3_backup_remaining,
111897  sqlite3_backup_step,
111898#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
111899  sqlite3_compileoption_get,
111900  sqlite3_compileoption_used,
111901#else
111902  0,
111903  0,
111904#endif
111905  sqlite3_create_function_v2,
111906  sqlite3_db_config,
111907  sqlite3_db_mutex,
111908  sqlite3_db_status,
111909  sqlite3_extended_errcode,
111910  sqlite3_log,
111911  sqlite3_soft_heap_limit64,
111912  sqlite3_sourceid,
111913  sqlite3_stmt_status,
111914  sqlite3_strnicmp,
111915#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
111916  sqlite3_unlock_notify,
111917#else
111918  0,
111919#endif
111920#ifndef SQLITE_OMIT_WAL
111921  sqlite3_wal_autocheckpoint,
111922  sqlite3_wal_checkpoint,
111923  sqlite3_wal_hook,
111924#else
111925  0,
111926  0,
111927  0,
111928#endif
111929  sqlite3_blob_reopen,
111930  sqlite3_vtab_config,
111931  sqlite3_vtab_on_conflict,
111932  sqlite3_close_v2,
111933  sqlite3_db_filename,
111934  sqlite3_db_readonly,
111935  sqlite3_db_release_memory,
111936  sqlite3_errstr,
111937  sqlite3_stmt_busy,
111938  sqlite3_stmt_readonly,
111939  sqlite3_stricmp,
111940  sqlite3_uri_boolean,
111941  sqlite3_uri_int64,
111942  sqlite3_uri_parameter,
111943  sqlite3_vsnprintf,
111944  sqlite3_wal_checkpoint_v2,
111945  /* Version 3.8.7 and later */
111946  sqlite3_auto_extension,
111947  sqlite3_bind_blob64,
111948  sqlite3_bind_text64,
111949  sqlite3_cancel_auto_extension,
111950  sqlite3_load_extension,
111951  sqlite3_malloc64,
111952  sqlite3_msize,
111953  sqlite3_realloc64,
111954  sqlite3_reset_auto_extension,
111955  sqlite3_result_blob64,
111956  sqlite3_result_text64,
111957  sqlite3_strglob,
111958  /* Version 3.8.11 and later */
111959  (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
111960  sqlite3_value_free,
111961  sqlite3_result_zeroblob64,
111962  sqlite3_bind_zeroblob64,
111963  /* Version 3.9.0 and later */
111964  sqlite3_value_subtype,
111965  sqlite3_result_subtype,
111966  /* Version 3.10.0 and later */
111967  sqlite3_status64,
111968  sqlite3_strlike,
111969  sqlite3_db_cacheflush,
111970  /* Version 3.12.0 and later */
111971  sqlite3_system_errno,
111972  /* Version 3.14.0 and later */
111973  sqlite3_trace_v2,
111974  sqlite3_expanded_sql,
111975  /* Version 3.18.0 and later */
111976  sqlite3_set_last_insert_rowid
111977};
111978
111979/*
111980** Attempt to load an SQLite extension library contained in the file
111981** zFile.  The entry point is zProc.  zProc may be 0 in which case a
111982** default entry point name (sqlite3_extension_init) is used.  Use
111983** of the default name is recommended.
111984**
111985** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
111986**
111987** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
111988** error message text.  The calling function should free this memory
111989** by calling sqlite3DbFree(db, ).
111990*/
111991static int sqlite3LoadExtension(
111992  sqlite3 *db,          /* Load the extension into this database connection */
111993  const char *zFile,    /* Name of the shared library containing extension */
111994  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
111995  char **pzErrMsg       /* Put error message here if not 0 */
111996){
111997  sqlite3_vfs *pVfs = db->pVfs;
111998  void *handle;
111999  sqlite3_loadext_entry xInit;
112000  char *zErrmsg = 0;
112001  const char *zEntry;
112002  char *zAltEntry = 0;
112003  void **aHandle;
112004  u64 nMsg = 300 + sqlite3Strlen30(zFile);
112005  int ii;
112006  int rc;
112007
112008  /* Shared library endings to try if zFile cannot be loaded as written */
112009  static const char *azEndings[] = {
112010#if SQLITE_OS_WIN
112011     "dll"
112012#elif defined(__APPLE__)
112013     "dylib"
112014#else
112015     "so"
112016#endif
112017  };
112018
112019
112020  if( pzErrMsg ) *pzErrMsg = 0;
112021
112022  /* Ticket #1863.  To avoid a creating security problems for older
112023  ** applications that relink against newer versions of SQLite, the
112024  ** ability to run load_extension is turned off by default.  One
112025  ** must call either sqlite3_enable_load_extension(db) or
112026  ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
112027  ** to turn on extension loading.
112028  */
112029  if( (db->flags & SQLITE_LoadExtension)==0 ){
112030    if( pzErrMsg ){
112031      *pzErrMsg = sqlite3_mprintf("not authorized");
112032    }
112033    return SQLITE_ERROR;
112034  }
112035
112036  zEntry = zProc ? zProc : "sqlite3_extension_init";
112037
112038  handle = sqlite3OsDlOpen(pVfs, zFile);
112039#if SQLITE_OS_UNIX || SQLITE_OS_WIN
112040  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
112041    char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
112042    if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
112043    handle = sqlite3OsDlOpen(pVfs, zAltFile);
112044    sqlite3_free(zAltFile);
112045  }
112046#endif
112047  if( handle==0 ){
112048    if( pzErrMsg ){
112049      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
112050      if( zErrmsg ){
112051        sqlite3_snprintf(nMsg, zErrmsg,
112052            "unable to open shared library [%s]", zFile);
112053        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
112054      }
112055    }
112056    return SQLITE_ERROR;
112057  }
112058  xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
112059
112060  /* If no entry point was specified and the default legacy
112061  ** entry point name "sqlite3_extension_init" was not found, then
112062  ** construct an entry point name "sqlite3_X_init" where the X is
112063  ** replaced by the lowercase value of every ASCII alphabetic
112064  ** character in the filename after the last "/" upto the first ".",
112065  ** and eliding the first three characters if they are "lib".
112066  ** Examples:
112067  **
112068  **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
112069  **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
112070  */
112071  if( xInit==0 && zProc==0 ){
112072    int iFile, iEntry, c;
112073    int ncFile = sqlite3Strlen30(zFile);
112074    zAltEntry = sqlite3_malloc64(ncFile+30);
112075    if( zAltEntry==0 ){
112076      sqlite3OsDlClose(pVfs, handle);
112077      return SQLITE_NOMEM_BKPT;
112078    }
112079    memcpy(zAltEntry, "sqlite3_", 8);
112080    for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
112081    iFile++;
112082    if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
112083    for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
112084      if( sqlite3Isalpha(c) ){
112085        zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
112086      }
112087    }
112088    memcpy(zAltEntry+iEntry, "_init", 6);
112089    zEntry = zAltEntry;
112090    xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
112091  }
112092  if( xInit==0 ){
112093    if( pzErrMsg ){
112094      nMsg += sqlite3Strlen30(zEntry);
112095      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
112096      if( zErrmsg ){
112097        sqlite3_snprintf(nMsg, zErrmsg,
112098            "no entry point [%s] in shared library [%s]", zEntry, zFile);
112099        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
112100      }
112101    }
112102    sqlite3OsDlClose(pVfs, handle);
112103    sqlite3_free(zAltEntry);
112104    return SQLITE_ERROR;
112105  }
112106  sqlite3_free(zAltEntry);
112107  rc = xInit(db, &zErrmsg, &sqlite3Apis);
112108  if( rc ){
112109    if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
112110    if( pzErrMsg ){
112111      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
112112    }
112113    sqlite3_free(zErrmsg);
112114    sqlite3OsDlClose(pVfs, handle);
112115    return SQLITE_ERROR;
112116  }
112117
112118  /* Append the new shared library handle to the db->aExtension array. */
112119  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
112120  if( aHandle==0 ){
112121    return SQLITE_NOMEM_BKPT;
112122  }
112123  if( db->nExtension>0 ){
112124    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
112125  }
112126  sqlite3DbFree(db, db->aExtension);
112127  db->aExtension = aHandle;
112128
112129  db->aExtension[db->nExtension++] = handle;
112130  return SQLITE_OK;
112131}
112132SQLITE_API int sqlite3_load_extension(
112133  sqlite3 *db,          /* Load the extension into this database connection */
112134  const char *zFile,    /* Name of the shared library containing extension */
112135  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
112136  char **pzErrMsg       /* Put error message here if not 0 */
112137){
112138  int rc;
112139  sqlite3_mutex_enter(db->mutex);
112140  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
112141  rc = sqlite3ApiExit(db, rc);
112142  sqlite3_mutex_leave(db->mutex);
112143  return rc;
112144}
112145
112146/*
112147** Call this routine when the database connection is closing in order
112148** to clean up loaded extensions
112149*/
112150SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
112151  int i;
112152  assert( sqlite3_mutex_held(db->mutex) );
112153  for(i=0; i<db->nExtension; i++){
112154    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
112155  }
112156  sqlite3DbFree(db, db->aExtension);
112157}
112158
112159/*
112160** Enable or disable extension loading.  Extension loading is disabled by
112161** default so as not to open security holes in older applications.
112162*/
112163SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
112164  sqlite3_mutex_enter(db->mutex);
112165  if( onoff ){
112166    db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
112167  }else{
112168    db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
112169  }
112170  sqlite3_mutex_leave(db->mutex);
112171  return SQLITE_OK;
112172}
112173
112174#endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
112175
112176/*
112177** The following object holds the list of automatically loaded
112178** extensions.
112179**
112180** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
112181** mutex must be held while accessing this list.
112182*/
112183typedef struct sqlite3AutoExtList sqlite3AutoExtList;
112184static SQLITE_WSD struct sqlite3AutoExtList {
112185  u32 nExt;              /* Number of entries in aExt[] */
112186  void (**aExt)(void);   /* Pointers to the extension init functions */
112187} sqlite3Autoext = { 0, 0 };
112188
112189/* The "wsdAutoext" macro will resolve to the autoextension
112190** state vector.  If writable static data is unsupported on the target,
112191** we have to locate the state vector at run-time.  In the more common
112192** case where writable static data is supported, wsdStat can refer directly
112193** to the "sqlite3Autoext" state vector declared above.
112194*/
112195#ifdef SQLITE_OMIT_WSD
112196# define wsdAutoextInit \
112197  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
112198# define wsdAutoext x[0]
112199#else
112200# define wsdAutoextInit
112201# define wsdAutoext sqlite3Autoext
112202#endif
112203
112204
112205/*
112206** Register a statically linked extension that is automatically
112207** loaded by every new database connection.
112208*/
112209SQLITE_API int sqlite3_auto_extension(
112210  void (*xInit)(void)
112211){
112212  int rc = SQLITE_OK;
112213#ifndef SQLITE_OMIT_AUTOINIT
112214  rc = sqlite3_initialize();
112215  if( rc ){
112216    return rc;
112217  }else
112218#endif
112219  {
112220    u32 i;
112221#if SQLITE_THREADSAFE
112222    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
112223#endif
112224    wsdAutoextInit;
112225    sqlite3_mutex_enter(mutex);
112226    for(i=0; i<wsdAutoext.nExt; i++){
112227      if( wsdAutoext.aExt[i]==xInit ) break;
112228    }
112229    if( i==wsdAutoext.nExt ){
112230      u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
112231      void (**aNew)(void);
112232      aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
112233      if( aNew==0 ){
112234        rc = SQLITE_NOMEM_BKPT;
112235      }else{
112236        wsdAutoext.aExt = aNew;
112237        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
112238        wsdAutoext.nExt++;
112239      }
112240    }
112241    sqlite3_mutex_leave(mutex);
112242    assert( (rc&0xff)==rc );
112243    return rc;
112244  }
112245}
112246
112247/*
112248** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
112249** set of routines that is invoked for each new database connection, if it
112250** is currently on the list.  If xInit is not on the list, then this
112251** routine is a no-op.
112252**
112253** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
112254** was not on the list.
112255*/
112256SQLITE_API int sqlite3_cancel_auto_extension(
112257  void (*xInit)(void)
112258){
112259#if SQLITE_THREADSAFE
112260  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
112261#endif
112262  int i;
112263  int n = 0;
112264  wsdAutoextInit;
112265  sqlite3_mutex_enter(mutex);
112266  for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
112267    if( wsdAutoext.aExt[i]==xInit ){
112268      wsdAutoext.nExt--;
112269      wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
112270      n++;
112271      break;
112272    }
112273  }
112274  sqlite3_mutex_leave(mutex);
112275  return n;
112276}
112277
112278/*
112279** Reset the automatic extension loading mechanism.
112280*/
112281SQLITE_API void sqlite3_reset_auto_extension(void){
112282#ifndef SQLITE_OMIT_AUTOINIT
112283  if( sqlite3_initialize()==SQLITE_OK )
112284#endif
112285  {
112286#if SQLITE_THREADSAFE
112287    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
112288#endif
112289    wsdAutoextInit;
112290    sqlite3_mutex_enter(mutex);
112291    sqlite3_free(wsdAutoext.aExt);
112292    wsdAutoext.aExt = 0;
112293    wsdAutoext.nExt = 0;
112294    sqlite3_mutex_leave(mutex);
112295  }
112296}
112297
112298/*
112299** Load all automatic extensions.
112300**
112301** If anything goes wrong, set an error in the database connection.
112302*/
112303SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
112304  u32 i;
112305  int go = 1;
112306  int rc;
112307  sqlite3_loadext_entry xInit;
112308
112309  wsdAutoextInit;
112310  if( wsdAutoext.nExt==0 ){
112311    /* Common case: early out without every having to acquire a mutex */
112312    return;
112313  }
112314  for(i=0; go; i++){
112315    char *zErrmsg;
112316#if SQLITE_THREADSAFE
112317    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
112318#endif
112319#ifdef SQLITE_OMIT_LOAD_EXTENSION
112320    const sqlite3_api_routines *pThunk = 0;
112321#else
112322    const sqlite3_api_routines *pThunk = &sqlite3Apis;
112323#endif
112324    sqlite3_mutex_enter(mutex);
112325    if( i>=wsdAutoext.nExt ){
112326      xInit = 0;
112327      go = 0;
112328    }else{
112329      xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
112330    }
112331    sqlite3_mutex_leave(mutex);
112332    zErrmsg = 0;
112333    if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
112334      sqlite3ErrorWithMsg(db, rc,
112335            "automatic extension loading failed: %s", zErrmsg);
112336      go = 0;
112337    }
112338    sqlite3_free(zErrmsg);
112339  }
112340}
112341
112342/************** End of loadext.c *********************************************/
112343/************** Begin file pragma.c ******************************************/
112344/*
112345** 2003 April 6
112346**
112347** The author disclaims copyright to this source code.  In place of
112348** a legal notice, here is a blessing:
112349**
112350**    May you do good and not evil.
112351**    May you find forgiveness for yourself and forgive others.
112352**    May you share freely, never taking more than you give.
112353**
112354*************************************************************************
112355** This file contains code used to implement the PRAGMA command.
112356*/
112357/* #include "sqliteInt.h" */
112358
112359#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
112360#  if defined(__APPLE__)
112361#    define SQLITE_ENABLE_LOCKING_STYLE 1
112362#  else
112363#    define SQLITE_ENABLE_LOCKING_STYLE 0
112364#  endif
112365#endif
112366
112367/***************************************************************************
112368** The "pragma.h" include file is an automatically generated file that
112369** that includes the PragType_XXXX macro definitions and the aPragmaName[]
112370** object.  This ensures that the aPragmaName[] table is arranged in
112371** lexicographical order to facility a binary search of the pragma name.
112372** Do not edit pragma.h directly.  Edit and rerun the script in at
112373** ../tool/mkpragmatab.tcl. */
112374/************** Include pragma.h in the middle of pragma.c *******************/
112375/************** Begin file pragma.h ******************************************/
112376/* DO NOT EDIT!
112377** This file is automatically generated by the script at
112378** ../tool/mkpragmatab.tcl.  To update the set of pragmas, edit
112379** that script and rerun it.
112380*/
112381
112382/* The various pragma types */
112383#define PragTyp_HEADER_VALUE                   0
112384#define PragTyp_AUTO_VACUUM                    1
112385#define PragTyp_FLAG                           2
112386#define PragTyp_BUSY_TIMEOUT                   3
112387#define PragTyp_CACHE_SIZE                     4
112388#define PragTyp_CACHE_SPILL                    5
112389#define PragTyp_CASE_SENSITIVE_LIKE            6
112390#define PragTyp_COLLATION_LIST                 7
112391#define PragTyp_COMPILE_OPTIONS                8
112392#define PragTyp_DATA_STORE_DIRECTORY           9
112393#define PragTyp_DATABASE_LIST                 10
112394#define PragTyp_DEFAULT_CACHE_SIZE            11
112395#define PragTyp_ENCODING                      12
112396#define PragTyp_FOREIGN_KEY_CHECK             13
112397#define PragTyp_FOREIGN_KEY_LIST              14
112398#define PragTyp_INCREMENTAL_VACUUM            15
112399#define PragTyp_INDEX_INFO                    16
112400#define PragTyp_INDEX_LIST                    17
112401#define PragTyp_INTEGRITY_CHECK               18
112402#define PragTyp_JOURNAL_MODE                  19
112403#define PragTyp_JOURNAL_SIZE_LIMIT            20
112404#define PragTyp_LOCK_PROXY_FILE               21
112405#define PragTyp_LOCKING_MODE                  22
112406#define PragTyp_PAGE_COUNT                    23
112407#define PragTyp_MMAP_SIZE                     24
112408#define PragTyp_OPTIMIZE                      25
112409#define PragTyp_PAGE_SIZE                     26
112410#define PragTyp_SECURE_DELETE                 27
112411#define PragTyp_SHRINK_MEMORY                 28
112412#define PragTyp_SOFT_HEAP_LIMIT               29
112413#define PragTyp_SYNCHRONOUS                   30
112414#define PragTyp_TABLE_INFO                    31
112415#define PragTyp_TEMP_STORE                    32
112416#define PragTyp_TEMP_STORE_DIRECTORY          33
112417#define PragTyp_THREADS                       34
112418#define PragTyp_WAL_AUTOCHECKPOINT            35
112419#define PragTyp_WAL_CHECKPOINT                36
112420#define PragTyp_ACTIVATE_EXTENSIONS           37
112421#define PragTyp_HEXKEY                        38
112422#define PragTyp_KEY                           39
112423#define PragTyp_REKEY                         40
112424#define PragTyp_LOCK_STATUS                   41
112425#define PragTyp_PARSER_TRACE                  42
112426#define PragTyp_STATS                         43
112427
112428/* Property flags associated with various pragma. */
112429#define PragFlg_NeedSchema 0x01 /* Force schema load before running */
112430#define PragFlg_NoColumns  0x02 /* OP_ResultRow called with zero columns */
112431#define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
112432#define PragFlg_ReadOnly   0x08 /* Read-only HEADER_VALUE */
112433#define PragFlg_Result0    0x10 /* Acts as query when no argument */
112434#define PragFlg_Result1    0x20 /* Acts as query when has one argument */
112435#define PragFlg_SchemaOpt  0x40 /* Schema restricts name search if present */
112436#define PragFlg_SchemaReq  0x80 /* Schema required - "main" is default */
112437
112438/* Names of columns for pragmas that return multi-column result
112439** or that return single-column results where the name of the
112440** result column is different from the name of the pragma
112441*/
112442static const char *const pragCName[] = {
112443  /*   0 */ "cache_size",  /* Used by: default_cache_size */
112444  /*   1 */ "cid",         /* Used by: table_info */
112445  /*   2 */ "name",
112446  /*   3 */ "type",
112447  /*   4 */ "notnull",
112448  /*   5 */ "dflt_value",
112449  /*   6 */ "pk",
112450  /*   7 */ "tbl",         /* Used by: stats */
112451  /*   8 */ "idx",
112452  /*   9 */ "wdth",
112453  /*  10 */ "hght",
112454  /*  11 */ "flgs",
112455  /*  12 */ "seqno",       /* Used by: index_info */
112456  /*  13 */ "cid",
112457  /*  14 */ "name",
112458  /*  15 */ "seqno",       /* Used by: index_xinfo */
112459  /*  16 */ "cid",
112460  /*  17 */ "name",
112461  /*  18 */ "desc",
112462  /*  19 */ "coll",
112463  /*  20 */ "key",
112464  /*  21 */ "seq",         /* Used by: index_list */
112465  /*  22 */ "name",
112466  /*  23 */ "unique",
112467  /*  24 */ "origin",
112468  /*  25 */ "partial",
112469  /*  26 */ "seq",         /* Used by: database_list */
112470  /*  27 */ "name",
112471  /*  28 */ "file",
112472  /*  29 */ "seq",         /* Used by: collation_list */
112473  /*  30 */ "name",
112474  /*  31 */ "id",          /* Used by: foreign_key_list */
112475  /*  32 */ "seq",
112476  /*  33 */ "table",
112477  /*  34 */ "from",
112478  /*  35 */ "to",
112479  /*  36 */ "on_update",
112480  /*  37 */ "on_delete",
112481  /*  38 */ "match",
112482  /*  39 */ "table",       /* Used by: foreign_key_check */
112483  /*  40 */ "rowid",
112484  /*  41 */ "parent",
112485  /*  42 */ "fkid",
112486  /*  43 */ "busy",        /* Used by: wal_checkpoint */
112487  /*  44 */ "log",
112488  /*  45 */ "checkpointed",
112489  /*  46 */ "timeout",     /* Used by: busy_timeout */
112490  /*  47 */ "database",    /* Used by: lock_status */
112491  /*  48 */ "status",
112492};
112493
112494/* Definitions of all built-in pragmas */
112495typedef struct PragmaName {
112496  const char *const zName; /* Name of pragma */
112497  u8 ePragTyp;             /* PragTyp_XXX value */
112498  u8 mPragFlg;             /* Zero or more PragFlg_XXX values */
112499  u8 iPragCName;           /* Start of column names in pragCName[] */
112500  u8 nPragCName;           /* Num of col names. 0 means use pragma name */
112501  u32 iArg;                /* Extra argument */
112502} PragmaName;
112503static const PragmaName aPragmaName[] = {
112504#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
112505 {/* zName:     */ "activate_extensions",
112506  /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
112507  /* ePragFlg:  */ 0,
112508  /* ColNames:  */ 0, 0,
112509  /* iArg:      */ 0 },
112510#endif
112511#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
112512 {/* zName:     */ "application_id",
112513  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
112514  /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
112515  /* ColNames:  */ 0, 0,
112516  /* iArg:      */ BTREE_APPLICATION_ID },
112517#endif
112518#if !defined(SQLITE_OMIT_AUTOVACUUM)
112519 {/* zName:     */ "auto_vacuum",
112520  /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
112521  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
112522  /* ColNames:  */ 0, 0,
112523  /* iArg:      */ 0 },
112524#endif
112525#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112526#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
112527 {/* zName:     */ "automatic_index",
112528  /* ePragTyp:  */ PragTyp_FLAG,
112529  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112530  /* ColNames:  */ 0, 0,
112531  /* iArg:      */ SQLITE_AutoIndex },
112532#endif
112533#endif
112534 {/* zName:     */ "busy_timeout",
112535  /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
112536  /* ePragFlg:  */ PragFlg_Result0,
112537  /* ColNames:  */ 46, 1,
112538  /* iArg:      */ 0 },
112539#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
112540 {/* zName:     */ "cache_size",
112541  /* ePragTyp:  */ PragTyp_CACHE_SIZE,
112542  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
112543  /* ColNames:  */ 0, 0,
112544  /* iArg:      */ 0 },
112545#endif
112546#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112547 {/* zName:     */ "cache_spill",
112548  /* ePragTyp:  */ PragTyp_CACHE_SPILL,
112549  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
112550  /* ColNames:  */ 0, 0,
112551  /* iArg:      */ 0 },
112552#endif
112553 {/* zName:     */ "case_sensitive_like",
112554  /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
112555  /* ePragFlg:  */ PragFlg_NoColumns,
112556  /* ColNames:  */ 0, 0,
112557  /* iArg:      */ 0 },
112558 {/* zName:     */ "cell_size_check",
112559  /* ePragTyp:  */ PragTyp_FLAG,
112560  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112561  /* ColNames:  */ 0, 0,
112562  /* iArg:      */ SQLITE_CellSizeCk },
112563#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112564 {/* zName:     */ "checkpoint_fullfsync",
112565  /* ePragTyp:  */ PragTyp_FLAG,
112566  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112567  /* ColNames:  */ 0, 0,
112568  /* iArg:      */ SQLITE_CkptFullFSync },
112569#endif
112570#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
112571 {/* zName:     */ "collation_list",
112572  /* ePragTyp:  */ PragTyp_COLLATION_LIST,
112573  /* ePragFlg:  */ PragFlg_Result0,
112574  /* ColNames:  */ 29, 2,
112575  /* iArg:      */ 0 },
112576#endif
112577#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
112578 {/* zName:     */ "compile_options",
112579  /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
112580  /* ePragFlg:  */ PragFlg_Result0,
112581  /* ColNames:  */ 0, 0,
112582  /* iArg:      */ 0 },
112583#endif
112584#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112585 {/* zName:     */ "count_changes",
112586  /* ePragTyp:  */ PragTyp_FLAG,
112587  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112588  /* ColNames:  */ 0, 0,
112589  /* iArg:      */ SQLITE_CountRows },
112590#endif
112591#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
112592 {/* zName:     */ "data_store_directory",
112593  /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
112594  /* ePragFlg:  */ PragFlg_NoColumns1,
112595  /* ColNames:  */ 0, 0,
112596  /* iArg:      */ 0 },
112597#endif
112598#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
112599 {/* zName:     */ "data_version",
112600  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
112601  /* ePragFlg:  */ PragFlg_ReadOnly|PragFlg_Result0,
112602  /* ColNames:  */ 0, 0,
112603  /* iArg:      */ BTREE_DATA_VERSION },
112604#endif
112605#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
112606 {/* zName:     */ "database_list",
112607  /* ePragTyp:  */ PragTyp_DATABASE_LIST,
112608  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,
112609  /* ColNames:  */ 26, 3,
112610  /* iArg:      */ 0 },
112611#endif
112612#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
112613 {/* zName:     */ "default_cache_size",
112614  /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
112615  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
112616  /* ColNames:  */ 0, 1,
112617  /* iArg:      */ 0 },
112618#endif
112619#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112620#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
112621 {/* zName:     */ "defer_foreign_keys",
112622  /* ePragTyp:  */ PragTyp_FLAG,
112623  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112624  /* ColNames:  */ 0, 0,
112625  /* iArg:      */ SQLITE_DeferFKs },
112626#endif
112627#endif
112628#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112629 {/* zName:     */ "empty_result_callbacks",
112630  /* ePragTyp:  */ PragTyp_FLAG,
112631  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112632  /* ColNames:  */ 0, 0,
112633  /* iArg:      */ SQLITE_NullCallback },
112634#endif
112635#if !defined(SQLITE_OMIT_UTF16)
112636 {/* zName:     */ "encoding",
112637  /* ePragTyp:  */ PragTyp_ENCODING,
112638  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112639  /* ColNames:  */ 0, 0,
112640  /* iArg:      */ 0 },
112641#endif
112642#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
112643 {/* zName:     */ "foreign_key_check",
112644  /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
112645  /* ePragFlg:  */ PragFlg_NeedSchema,
112646  /* ColNames:  */ 39, 4,
112647  /* iArg:      */ 0 },
112648#endif
112649#if !defined(SQLITE_OMIT_FOREIGN_KEY)
112650 {/* zName:     */ "foreign_key_list",
112651  /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
112652  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
112653  /* ColNames:  */ 31, 8,
112654  /* iArg:      */ 0 },
112655#endif
112656#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112657#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
112658 {/* zName:     */ "foreign_keys",
112659  /* ePragTyp:  */ PragTyp_FLAG,
112660  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112661  /* ColNames:  */ 0, 0,
112662  /* iArg:      */ SQLITE_ForeignKeys },
112663#endif
112664#endif
112665#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
112666 {/* zName:     */ "freelist_count",
112667  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
112668  /* ePragFlg:  */ PragFlg_ReadOnly|PragFlg_Result0,
112669  /* ColNames:  */ 0, 0,
112670  /* iArg:      */ BTREE_FREE_PAGE_COUNT },
112671#endif
112672#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112673 {/* zName:     */ "full_column_names",
112674  /* ePragTyp:  */ PragTyp_FLAG,
112675  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112676  /* ColNames:  */ 0, 0,
112677  /* iArg:      */ SQLITE_FullColNames },
112678 {/* zName:     */ "fullfsync",
112679  /* ePragTyp:  */ PragTyp_FLAG,
112680  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112681  /* ColNames:  */ 0, 0,
112682  /* iArg:      */ SQLITE_FullFSync },
112683#endif
112684#if defined(SQLITE_HAS_CODEC)
112685 {/* zName:     */ "hexkey",
112686  /* ePragTyp:  */ PragTyp_HEXKEY,
112687  /* ePragFlg:  */ 0,
112688  /* ColNames:  */ 0, 0,
112689  /* iArg:      */ 0 },
112690 {/* zName:     */ "hexrekey",
112691  /* ePragTyp:  */ PragTyp_HEXKEY,
112692  /* ePragFlg:  */ 0,
112693  /* ColNames:  */ 0, 0,
112694  /* iArg:      */ 0 },
112695#endif
112696#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112697#if !defined(SQLITE_OMIT_CHECK)
112698 {/* zName:     */ "ignore_check_constraints",
112699  /* ePragTyp:  */ PragTyp_FLAG,
112700  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112701  /* ColNames:  */ 0, 0,
112702  /* iArg:      */ SQLITE_IgnoreChecks },
112703#endif
112704#endif
112705#if !defined(SQLITE_OMIT_AUTOVACUUM)
112706 {/* zName:     */ "incremental_vacuum",
112707  /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
112708  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_NoColumns,
112709  /* ColNames:  */ 0, 0,
112710  /* iArg:      */ 0 },
112711#endif
112712#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
112713 {/* zName:     */ "index_info",
112714  /* ePragTyp:  */ PragTyp_INDEX_INFO,
112715  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
112716  /* ColNames:  */ 12, 3,
112717  /* iArg:      */ 0 },
112718 {/* zName:     */ "index_list",
112719  /* ePragTyp:  */ PragTyp_INDEX_LIST,
112720  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
112721  /* ColNames:  */ 21, 5,
112722  /* iArg:      */ 0 },
112723 {/* zName:     */ "index_xinfo",
112724  /* ePragTyp:  */ PragTyp_INDEX_INFO,
112725  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
112726  /* ColNames:  */ 15, 6,
112727  /* iArg:      */ 1 },
112728#endif
112729#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
112730 {/* zName:     */ "integrity_check",
112731  /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
112732  /* ePragFlg:  */ PragFlg_NeedSchema,
112733  /* ColNames:  */ 0, 0,
112734  /* iArg:      */ 0 },
112735#endif
112736#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
112737 {/* zName:     */ "journal_mode",
112738  /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
112739  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
112740  /* ColNames:  */ 0, 0,
112741  /* iArg:      */ 0 },
112742 {/* zName:     */ "journal_size_limit",
112743  /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
112744  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,
112745  /* ColNames:  */ 0, 0,
112746  /* iArg:      */ 0 },
112747#endif
112748#if defined(SQLITE_HAS_CODEC)
112749 {/* zName:     */ "key",
112750  /* ePragTyp:  */ PragTyp_KEY,
112751  /* ePragFlg:  */ 0,
112752  /* ColNames:  */ 0, 0,
112753  /* iArg:      */ 0 },
112754#endif
112755#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112756 {/* zName:     */ "legacy_file_format",
112757  /* ePragTyp:  */ PragTyp_FLAG,
112758  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112759  /* ColNames:  */ 0, 0,
112760  /* iArg:      */ SQLITE_LegacyFileFmt },
112761#endif
112762#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
112763 {/* zName:     */ "lock_proxy_file",
112764  /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
112765  /* ePragFlg:  */ PragFlg_NoColumns1,
112766  /* ColNames:  */ 0, 0,
112767  /* iArg:      */ 0 },
112768#endif
112769#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
112770 {/* zName:     */ "lock_status",
112771  /* ePragTyp:  */ PragTyp_LOCK_STATUS,
112772  /* ePragFlg:  */ PragFlg_Result0,
112773  /* ColNames:  */ 47, 2,
112774  /* iArg:      */ 0 },
112775#endif
112776#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
112777 {/* zName:     */ "locking_mode",
112778  /* ePragTyp:  */ PragTyp_LOCKING_MODE,
112779  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,
112780  /* ColNames:  */ 0, 0,
112781  /* iArg:      */ 0 },
112782 {/* zName:     */ "max_page_count",
112783  /* ePragTyp:  */ PragTyp_PAGE_COUNT,
112784  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
112785  /* ColNames:  */ 0, 0,
112786  /* iArg:      */ 0 },
112787 {/* zName:     */ "mmap_size",
112788  /* ePragTyp:  */ PragTyp_MMAP_SIZE,
112789  /* ePragFlg:  */ 0,
112790  /* ColNames:  */ 0, 0,
112791  /* iArg:      */ 0 },
112792#endif
112793 {/* zName:     */ "optimize",
112794  /* ePragTyp:  */ PragTyp_OPTIMIZE,
112795  /* ePragFlg:  */ PragFlg_Result1,
112796  /* ColNames:  */ 0, 0,
112797  /* iArg:      */ 0 },
112798#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
112799 {/* zName:     */ "page_count",
112800  /* ePragTyp:  */ PragTyp_PAGE_COUNT,
112801  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
112802  /* ColNames:  */ 0, 0,
112803  /* iArg:      */ 0 },
112804 {/* zName:     */ "page_size",
112805  /* ePragTyp:  */ PragTyp_PAGE_SIZE,
112806  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
112807  /* ColNames:  */ 0, 0,
112808  /* iArg:      */ 0 },
112809#endif
112810#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
112811 {/* zName:     */ "parser_trace",
112812  /* ePragTyp:  */ PragTyp_PARSER_TRACE,
112813  /* ePragFlg:  */ 0,
112814  /* ColNames:  */ 0, 0,
112815  /* iArg:      */ 0 },
112816#endif
112817#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112818 {/* zName:     */ "query_only",
112819  /* ePragTyp:  */ PragTyp_FLAG,
112820  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112821  /* ColNames:  */ 0, 0,
112822  /* iArg:      */ SQLITE_QueryOnly },
112823#endif
112824#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
112825 {/* zName:     */ "quick_check",
112826  /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
112827  /* ePragFlg:  */ PragFlg_NeedSchema,
112828  /* ColNames:  */ 0, 0,
112829  /* iArg:      */ 0 },
112830#endif
112831#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112832 {/* zName:     */ "read_uncommitted",
112833  /* ePragTyp:  */ PragTyp_FLAG,
112834  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112835  /* ColNames:  */ 0, 0,
112836  /* iArg:      */ SQLITE_ReadUncommitted },
112837 {/* zName:     */ "recursive_triggers",
112838  /* ePragTyp:  */ PragTyp_FLAG,
112839  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112840  /* ColNames:  */ 0, 0,
112841  /* iArg:      */ SQLITE_RecTriggers },
112842#endif
112843#if defined(SQLITE_HAS_CODEC)
112844 {/* zName:     */ "rekey",
112845  /* ePragTyp:  */ PragTyp_REKEY,
112846  /* ePragFlg:  */ 0,
112847  /* ColNames:  */ 0, 0,
112848  /* iArg:      */ 0 },
112849#endif
112850#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112851 {/* zName:     */ "reverse_unordered_selects",
112852  /* ePragTyp:  */ PragTyp_FLAG,
112853  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112854  /* ColNames:  */ 0, 0,
112855  /* iArg:      */ SQLITE_ReverseOrder },
112856#endif
112857#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
112858 {/* zName:     */ "schema_version",
112859  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
112860  /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
112861  /* ColNames:  */ 0, 0,
112862  /* iArg:      */ BTREE_SCHEMA_VERSION },
112863#endif
112864#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
112865 {/* zName:     */ "secure_delete",
112866  /* ePragTyp:  */ PragTyp_SECURE_DELETE,
112867  /* ePragFlg:  */ PragFlg_Result0,
112868  /* ColNames:  */ 0, 0,
112869  /* iArg:      */ 0 },
112870#endif
112871#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112872 {/* zName:     */ "short_column_names",
112873  /* ePragTyp:  */ PragTyp_FLAG,
112874  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112875  /* ColNames:  */ 0, 0,
112876  /* iArg:      */ SQLITE_ShortColNames },
112877#endif
112878 {/* zName:     */ "shrink_memory",
112879  /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
112880  /* ePragFlg:  */ PragFlg_NoColumns,
112881  /* ColNames:  */ 0, 0,
112882  /* iArg:      */ 0 },
112883 {/* zName:     */ "soft_heap_limit",
112884  /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
112885  /* ePragFlg:  */ PragFlg_Result0,
112886  /* ColNames:  */ 0, 0,
112887  /* iArg:      */ 0 },
112888#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112889#if defined(SQLITE_DEBUG)
112890 {/* zName:     */ "sql_trace",
112891  /* ePragTyp:  */ PragTyp_FLAG,
112892  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112893  /* ColNames:  */ 0, 0,
112894  /* iArg:      */ SQLITE_SqlTrace },
112895#endif
112896#endif
112897#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
112898 {/* zName:     */ "stats",
112899  /* ePragTyp:  */ PragTyp_STATS,
112900  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
112901  /* ColNames:  */ 7, 5,
112902  /* iArg:      */ 0 },
112903#endif
112904#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
112905 {/* zName:     */ "synchronous",
112906  /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
112907  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
112908  /* ColNames:  */ 0, 0,
112909  /* iArg:      */ 0 },
112910#endif
112911#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
112912 {/* zName:     */ "table_info",
112913  /* ePragTyp:  */ PragTyp_TABLE_INFO,
112914  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
112915  /* ColNames:  */ 1, 6,
112916  /* iArg:      */ 0 },
112917#endif
112918#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
112919 {/* zName:     */ "temp_store",
112920  /* ePragTyp:  */ PragTyp_TEMP_STORE,
112921  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112922  /* ColNames:  */ 0, 0,
112923  /* iArg:      */ 0 },
112924 {/* zName:     */ "temp_store_directory",
112925  /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
112926  /* ePragFlg:  */ PragFlg_NoColumns1,
112927  /* ColNames:  */ 0, 0,
112928  /* iArg:      */ 0 },
112929#endif
112930 {/* zName:     */ "threads",
112931  /* ePragTyp:  */ PragTyp_THREADS,
112932  /* ePragFlg:  */ PragFlg_Result0,
112933  /* ColNames:  */ 0, 0,
112934  /* iArg:      */ 0 },
112935#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
112936 {/* zName:     */ "user_version",
112937  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
112938  /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
112939  /* ColNames:  */ 0, 0,
112940  /* iArg:      */ BTREE_USER_VERSION },
112941#endif
112942#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112943#if defined(SQLITE_DEBUG)
112944 {/* zName:     */ "vdbe_addoptrace",
112945  /* ePragTyp:  */ PragTyp_FLAG,
112946  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112947  /* ColNames:  */ 0, 0,
112948  /* iArg:      */ SQLITE_VdbeAddopTrace },
112949 {/* zName:     */ "vdbe_debug",
112950  /* ePragTyp:  */ PragTyp_FLAG,
112951  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112952  /* ColNames:  */ 0, 0,
112953  /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
112954 {/* zName:     */ "vdbe_eqp",
112955  /* ePragTyp:  */ PragTyp_FLAG,
112956  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112957  /* ColNames:  */ 0, 0,
112958  /* iArg:      */ SQLITE_VdbeEQP },
112959 {/* zName:     */ "vdbe_listing",
112960  /* ePragTyp:  */ PragTyp_FLAG,
112961  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112962  /* ColNames:  */ 0, 0,
112963  /* iArg:      */ SQLITE_VdbeListing },
112964 {/* zName:     */ "vdbe_trace",
112965  /* ePragTyp:  */ PragTyp_FLAG,
112966  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112967  /* ColNames:  */ 0, 0,
112968  /* iArg:      */ SQLITE_VdbeTrace },
112969#endif
112970#endif
112971#if !defined(SQLITE_OMIT_WAL)
112972 {/* zName:     */ "wal_autocheckpoint",
112973  /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
112974  /* ePragFlg:  */ 0,
112975  /* ColNames:  */ 0, 0,
112976  /* iArg:      */ 0 },
112977 {/* zName:     */ "wal_checkpoint",
112978  /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
112979  /* ePragFlg:  */ PragFlg_NeedSchema,
112980  /* ColNames:  */ 43, 3,
112981  /* iArg:      */ 0 },
112982#endif
112983#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
112984 {/* zName:     */ "writable_schema",
112985  /* ePragTyp:  */ PragTyp_FLAG,
112986  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
112987  /* ColNames:  */ 0, 0,
112988  /* iArg:      */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
112989#endif
112990};
112991/* Number of pragmas: 60 on by default, 74 total. */
112992
112993/************** End of pragma.h **********************************************/
112994/************** Continuing where we left off in pragma.c *********************/
112995
112996/*
112997** Interpret the given string as a safety level.  Return 0 for OFF,
112998** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or
112999** unrecognized string argument.  The FULL and EXTRA option is disallowed
113000** if the omitFull parameter it 1.
113001**
113002** Note that the values returned are one less that the values that
113003** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
113004** to support legacy SQL code.  The safety level used to be boolean
113005** and older scripts may have used numbers 0 for OFF and 1 for ON.
113006*/
113007static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
113008                             /* 123456789 123456789 123 */
113009  static const char zText[] = "onoffalseyestruextrafull";
113010  static const u8 iOffset[] = {0, 1, 2,  4,    9,  12,  15,   20};
113011  static const u8 iLength[] = {2, 2, 3,  5,    3,   4,   5,    4};
113012  static const u8 iValue[] =  {1, 0, 0,  0,    1,   1,   3,    2};
113013                            /* on no off false yes true extra full */
113014  int i, n;
113015  if( sqlite3Isdigit(*z) ){
113016    return (u8)sqlite3Atoi(z);
113017  }
113018  n = sqlite3Strlen30(z);
113019  for(i=0; i<ArraySize(iLength); i++){
113020    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
113021     && (!omitFull || iValue[i]<=1)
113022    ){
113023      return iValue[i];
113024    }
113025  }
113026  return dflt;
113027}
113028
113029/*
113030** Interpret the given string as a boolean value.
113031*/
113032SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
113033  return getSafetyLevel(z,1,dflt)!=0;
113034}
113035
113036/* The sqlite3GetBoolean() function is used by other modules but the
113037** remainder of this file is specific to PRAGMA processing.  So omit
113038** the rest of the file if PRAGMAs are omitted from the build.
113039*/
113040#if !defined(SQLITE_OMIT_PRAGMA)
113041
113042/*
113043** Interpret the given string as a locking mode value.
113044*/
113045static int getLockingMode(const char *z){
113046  if( z ){
113047    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
113048    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
113049  }
113050  return PAGER_LOCKINGMODE_QUERY;
113051}
113052
113053#ifndef SQLITE_OMIT_AUTOVACUUM
113054/*
113055** Interpret the given string as an auto-vacuum mode value.
113056**
113057** The following strings, "none", "full" and "incremental" are
113058** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
113059*/
113060static int getAutoVacuum(const char *z){
113061  int i;
113062  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
113063  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
113064  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
113065  i = sqlite3Atoi(z);
113066  return (u8)((i>=0&&i<=2)?i:0);
113067}
113068#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
113069
113070#ifndef SQLITE_OMIT_PAGER_PRAGMAS
113071/*
113072** Interpret the given string as a temp db location. Return 1 for file
113073** backed temporary databases, 2 for the Red-Black tree in memory database
113074** and 0 to use the compile-time default.
113075*/
113076static int getTempStore(const char *z){
113077  if( z[0]>='0' && z[0]<='2' ){
113078    return z[0] - '0';
113079  }else if( sqlite3StrICmp(z, "file")==0 ){
113080    return 1;
113081  }else if( sqlite3StrICmp(z, "memory")==0 ){
113082    return 2;
113083  }else{
113084    return 0;
113085  }
113086}
113087#endif /* SQLITE_PAGER_PRAGMAS */
113088
113089#ifndef SQLITE_OMIT_PAGER_PRAGMAS
113090/*
113091** Invalidate temp storage, either when the temp storage is changed
113092** from default, or when 'file' and the temp_store_directory has changed
113093*/
113094static int invalidateTempStorage(Parse *pParse){
113095  sqlite3 *db = pParse->db;
113096  if( db->aDb[1].pBt!=0 ){
113097    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
113098      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
113099        "from within a transaction");
113100      return SQLITE_ERROR;
113101    }
113102    sqlite3BtreeClose(db->aDb[1].pBt);
113103    db->aDb[1].pBt = 0;
113104    sqlite3ResetAllSchemasOfConnection(db);
113105  }
113106  return SQLITE_OK;
113107}
113108#endif /* SQLITE_PAGER_PRAGMAS */
113109
113110#ifndef SQLITE_OMIT_PAGER_PRAGMAS
113111/*
113112** If the TEMP database is open, close it and mark the database schema
113113** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
113114** or DEFAULT_TEMP_STORE pragmas.
113115*/
113116static int changeTempStorage(Parse *pParse, const char *zStorageType){
113117  int ts = getTempStore(zStorageType);
113118  sqlite3 *db = pParse->db;
113119  if( db->temp_store==ts ) return SQLITE_OK;
113120  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
113121    return SQLITE_ERROR;
113122  }
113123  db->temp_store = (u8)ts;
113124  return SQLITE_OK;
113125}
113126#endif /* SQLITE_PAGER_PRAGMAS */
113127
113128/*
113129** Set result column names for a pragma.
113130*/
113131static void setPragmaResultColumnNames(
113132  Vdbe *v,                     /* The query under construction */
113133  const PragmaName *pPragma    /* The pragma */
113134){
113135  u8 n = pPragma->nPragCName;
113136  sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
113137  if( n==0 ){
113138    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
113139  }else{
113140    int i, j;
113141    for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
113142      sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
113143    }
113144  }
113145}
113146
113147/*
113148** Generate code to return a single integer value.
113149*/
113150static void returnSingleInt(Vdbe *v, i64 value){
113151  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
113152  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
113153}
113154
113155/*
113156** Generate code to return a single text value.
113157*/
113158static void returnSingleText(
113159  Vdbe *v,                /* Prepared statement under construction */
113160  const char *zValue      /* Value to be returned */
113161){
113162  if( zValue ){
113163    sqlite3VdbeLoadString(v, 1, (const char*)zValue);
113164    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
113165  }
113166}
113167
113168
113169/*
113170** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
113171** set these values for all pagers.
113172*/
113173#ifndef SQLITE_OMIT_PAGER_PRAGMAS
113174static void setAllPagerFlags(sqlite3 *db){
113175  if( db->autoCommit ){
113176    Db *pDb = db->aDb;
113177    int n = db->nDb;
113178    assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
113179    assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
113180    assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
113181    assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
113182             ==  PAGER_FLAGS_MASK );
113183    assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
113184    while( (n--) > 0 ){
113185      if( pDb->pBt ){
113186        sqlite3BtreeSetPagerFlags(pDb->pBt,
113187                 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
113188      }
113189      pDb++;
113190    }
113191  }
113192}
113193#else
113194# define setAllPagerFlags(X)  /* no-op */
113195#endif
113196
113197
113198/*
113199** Return a human-readable name for a constraint resolution action.
113200*/
113201#ifndef SQLITE_OMIT_FOREIGN_KEY
113202static const char *actionName(u8 action){
113203  const char *zName;
113204  switch( action ){
113205    case OE_SetNull:  zName = "SET NULL";        break;
113206    case OE_SetDflt:  zName = "SET DEFAULT";     break;
113207    case OE_Cascade:  zName = "CASCADE";         break;
113208    case OE_Restrict: zName = "RESTRICT";        break;
113209    default:          zName = "NO ACTION";
113210                      assert( action==OE_None ); break;
113211  }
113212  return zName;
113213}
113214#endif
113215
113216
113217/*
113218** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
113219** defined in pager.h. This function returns the associated lowercase
113220** journal-mode name.
113221*/
113222SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
113223  static char * const azModeName[] = {
113224    "delete", "persist", "off", "truncate", "memory"
113225#ifndef SQLITE_OMIT_WAL
113226     , "wal"
113227#endif
113228  };
113229  assert( PAGER_JOURNALMODE_DELETE==0 );
113230  assert( PAGER_JOURNALMODE_PERSIST==1 );
113231  assert( PAGER_JOURNALMODE_OFF==2 );
113232  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
113233  assert( PAGER_JOURNALMODE_MEMORY==4 );
113234  assert( PAGER_JOURNALMODE_WAL==5 );
113235  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
113236
113237  if( eMode==ArraySize(azModeName) ) return 0;
113238  return azModeName[eMode];
113239}
113240
113241/*
113242** Locate a pragma in the aPragmaName[] array.
113243*/
113244static const PragmaName *pragmaLocate(const char *zName){
113245  int upr, lwr, mid = 0, rc;
113246  lwr = 0;
113247  upr = ArraySize(aPragmaName)-1;
113248  while( lwr<=upr ){
113249    mid = (lwr+upr)/2;
113250    rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
113251    if( rc==0 ) break;
113252    if( rc<0 ){
113253      upr = mid - 1;
113254    }else{
113255      lwr = mid + 1;
113256    }
113257  }
113258  return lwr>upr ? 0 : &aPragmaName[mid];
113259}
113260
113261/*
113262** Helper subroutine for PRAGMA integrity_check:
113263**
113264** Generate code to output a single-column result row with the result
113265** held in register regResult.  Decrement the result count and halt if
113266** the maximum number of result rows have been issued.
113267*/
113268static int integrityCheckResultRow(Vdbe *v, int regResult){
113269  int addr;
113270  sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 1);
113271  addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
113272  VdbeCoverage(v);
113273  sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
113274  return addr;
113275}
113276
113277/*
113278** Process a pragma statement.
113279**
113280** Pragmas are of this form:
113281**
113282**      PRAGMA [schema.]id [= value]
113283**
113284** The identifier might also be a string.  The value is a string, and
113285** identifier, or a number.  If minusFlag is true, then the value is
113286** a number that was preceded by a minus sign.
113287**
113288** If the left side is "database.id" then pId1 is the database name
113289** and pId2 is the id.  If the left side is just "id" then pId1 is the
113290** id and pId2 is any empty string.
113291*/
113292SQLITE_PRIVATE void sqlite3Pragma(
113293  Parse *pParse,
113294  Token *pId1,        /* First part of [schema.]id field */
113295  Token *pId2,        /* Second part of [schema.]id field, or NULL */
113296  Token *pValue,      /* Token for <value>, or NULL */
113297  int minusFlag       /* True if a '-' sign preceded <value> */
113298){
113299  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
113300  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
113301  const char *zDb = 0;   /* The database name */
113302  Token *pId;            /* Pointer to <id> token */
113303  char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
113304  int iDb;               /* Database index for <database> */
113305  int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
113306  sqlite3 *db = pParse->db;    /* The database connection */
113307  Db *pDb;                     /* The specific database being pragmaed */
113308  Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
113309  const PragmaName *pPragma;   /* The pragma */
113310
113311  if( v==0 ) return;
113312  sqlite3VdbeRunOnlyOnce(v);
113313  pParse->nMem = 2;
113314
113315  /* Interpret the [schema.] part of the pragma statement. iDb is the
113316  ** index of the database this pragma is being applied to in db.aDb[]. */
113317  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
113318  if( iDb<0 ) return;
113319  pDb = &db->aDb[iDb];
113320
113321  /* If the temp database has been explicitly named as part of the
113322  ** pragma, make sure it is open.
113323  */
113324  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
113325    return;
113326  }
113327
113328  zLeft = sqlite3NameFromToken(db, pId);
113329  if( !zLeft ) return;
113330  if( minusFlag ){
113331    zRight = sqlite3MPrintf(db, "-%T", pValue);
113332  }else{
113333    zRight = sqlite3NameFromToken(db, pValue);
113334  }
113335
113336  assert( pId2 );
113337  zDb = pId2->n>0 ? pDb->zDbSName : 0;
113338  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
113339    goto pragma_out;
113340  }
113341
113342  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
113343  ** connection.  If it returns SQLITE_OK, then assume that the VFS
113344  ** handled the pragma and generate a no-op prepared statement.
113345  **
113346  ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
113347  ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
113348  ** object corresponding to the database file to which the pragma
113349  ** statement refers.
113350  **
113351  ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
113352  ** file control is an array of pointers to strings (char**) in which the
113353  ** second element of the array is the name of the pragma and the third
113354  ** element is the argument to the pragma or NULL if the pragma has no
113355  ** argument.
113356  */
113357  aFcntl[0] = 0;
113358  aFcntl[1] = zLeft;
113359  aFcntl[2] = zRight;
113360  aFcntl[3] = 0;
113361  db->busyHandler.nBusy = 0;
113362  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
113363  if( rc==SQLITE_OK ){
113364    sqlite3VdbeSetNumCols(v, 1);
113365    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
113366    returnSingleText(v, aFcntl[0]);
113367    sqlite3_free(aFcntl[0]);
113368    goto pragma_out;
113369  }
113370  if( rc!=SQLITE_NOTFOUND ){
113371    if( aFcntl[0] ){
113372      sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
113373      sqlite3_free(aFcntl[0]);
113374    }
113375    pParse->nErr++;
113376    pParse->rc = rc;
113377    goto pragma_out;
113378  }
113379
113380  /* Locate the pragma in the lookup table */
113381  pPragma = pragmaLocate(zLeft);
113382  if( pPragma==0 ) goto pragma_out;
113383
113384  /* Make sure the database schema is loaded if the pragma requires that */
113385  if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
113386    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
113387  }
113388
113389  /* Register the result column names for pragmas that return results */
113390  if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
113391   && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
113392  ){
113393    setPragmaResultColumnNames(v, pPragma);
113394  }
113395
113396  /* Jump to the appropriate pragma handler */
113397  switch( pPragma->ePragTyp ){
113398
113399#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
113400  /*
113401  **  PRAGMA [schema.]default_cache_size
113402  **  PRAGMA [schema.]default_cache_size=N
113403  **
113404  ** The first form reports the current persistent setting for the
113405  ** page cache size.  The value returned is the maximum number of
113406  ** pages in the page cache.  The second form sets both the current
113407  ** page cache size value and the persistent page cache size value
113408  ** stored in the database file.
113409  **
113410  ** Older versions of SQLite would set the default cache size to a
113411  ** negative number to indicate synchronous=OFF.  These days, synchronous
113412  ** is always on by default regardless of the sign of the default cache
113413  ** size.  But continue to take the absolute value of the default cache
113414  ** size of historical compatibility.
113415  */
113416  case PragTyp_DEFAULT_CACHE_SIZE: {
113417    static const int iLn = VDBE_OFFSET_LINENO(2);
113418    static const VdbeOpList getCacheSize[] = {
113419      { OP_Transaction, 0, 0,        0},                         /* 0 */
113420      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
113421      { OP_IfPos,       1, 8,        0},
113422      { OP_Integer,     0, 2,        0},
113423      { OP_Subtract,    1, 2,        1},
113424      { OP_IfPos,       1, 8,        0},
113425      { OP_Integer,     0, 1,        0},                         /* 6 */
113426      { OP_Noop,        0, 0,        0},
113427      { OP_ResultRow,   1, 1,        0},
113428    };
113429    VdbeOp *aOp;
113430    sqlite3VdbeUsesBtree(v, iDb);
113431    if( !zRight ){
113432      pParse->nMem += 2;
113433      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
113434      aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
113435      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
113436      aOp[0].p1 = iDb;
113437      aOp[1].p1 = iDb;
113438      aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
113439    }else{
113440      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
113441      sqlite3BeginWriteOperation(pParse, 0, iDb);
113442      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
113443      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
113444      pDb->pSchema->cache_size = size;
113445      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
113446    }
113447    break;
113448  }
113449#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
113450
113451#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
113452  /*
113453  **  PRAGMA [schema.]page_size
113454  **  PRAGMA [schema.]page_size=N
113455  **
113456  ** The first form reports the current setting for the
113457  ** database page size in bytes.  The second form sets the
113458  ** database page size value.  The value can only be set if
113459  ** the database has not yet been created.
113460  */
113461  case PragTyp_PAGE_SIZE: {
113462    Btree *pBt = pDb->pBt;
113463    assert( pBt!=0 );
113464    if( !zRight ){
113465      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
113466      returnSingleInt(v, size);
113467    }else{
113468      /* Malloc may fail when setting the page-size, as there is an internal
113469      ** buffer that the pager module resizes using sqlite3_realloc().
113470      */
113471      db->nextPagesize = sqlite3Atoi(zRight);
113472      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
113473        sqlite3OomFault(db);
113474      }
113475    }
113476    break;
113477  }
113478
113479  /*
113480  **  PRAGMA [schema.]secure_delete
113481  **  PRAGMA [schema.]secure_delete=ON/OFF
113482  **
113483  ** The first form reports the current setting for the
113484  ** secure_delete flag.  The second form changes the secure_delete
113485  ** flag setting and reports thenew value.
113486  */
113487  case PragTyp_SECURE_DELETE: {
113488    Btree *pBt = pDb->pBt;
113489    int b = -1;
113490    assert( pBt!=0 );
113491    if( zRight ){
113492      b = sqlite3GetBoolean(zRight, 0);
113493    }
113494    if( pId2->n==0 && b>=0 ){
113495      int ii;
113496      for(ii=0; ii<db->nDb; ii++){
113497        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
113498      }
113499    }
113500    b = sqlite3BtreeSecureDelete(pBt, b);
113501    returnSingleInt(v, b);
113502    break;
113503  }
113504
113505  /*
113506  **  PRAGMA [schema.]max_page_count
113507  **  PRAGMA [schema.]max_page_count=N
113508  **
113509  ** The first form reports the current setting for the
113510  ** maximum number of pages in the database file.  The
113511  ** second form attempts to change this setting.  Both
113512  ** forms return the current setting.
113513  **
113514  ** The absolute value of N is used.  This is undocumented and might
113515  ** change.  The only purpose is to provide an easy way to test
113516  ** the sqlite3AbsInt32() function.
113517  **
113518  **  PRAGMA [schema.]page_count
113519  **
113520  ** Return the number of pages in the specified database.
113521  */
113522  case PragTyp_PAGE_COUNT: {
113523    int iReg;
113524    sqlite3CodeVerifySchema(pParse, iDb);
113525    iReg = ++pParse->nMem;
113526    if( sqlite3Tolower(zLeft[0])=='p' ){
113527      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
113528    }else{
113529      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
113530                        sqlite3AbsInt32(sqlite3Atoi(zRight)));
113531    }
113532    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
113533    break;
113534  }
113535
113536  /*
113537  **  PRAGMA [schema.]locking_mode
113538  **  PRAGMA [schema.]locking_mode = (normal|exclusive)
113539  */
113540  case PragTyp_LOCKING_MODE: {
113541    const char *zRet = "normal";
113542    int eMode = getLockingMode(zRight);
113543
113544    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
113545      /* Simple "PRAGMA locking_mode;" statement. This is a query for
113546      ** the current default locking mode (which may be different to
113547      ** the locking-mode of the main database).
113548      */
113549      eMode = db->dfltLockMode;
113550    }else{
113551      Pager *pPager;
113552      if( pId2->n==0 ){
113553        /* This indicates that no database name was specified as part
113554        ** of the PRAGMA command. In this case the locking-mode must be
113555        ** set on all attached databases, as well as the main db file.
113556        **
113557        ** Also, the sqlite3.dfltLockMode variable is set so that
113558        ** any subsequently attached databases also use the specified
113559        ** locking mode.
113560        */
113561        int ii;
113562        assert(pDb==&db->aDb[0]);
113563        for(ii=2; ii<db->nDb; ii++){
113564          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
113565          sqlite3PagerLockingMode(pPager, eMode);
113566        }
113567        db->dfltLockMode = (u8)eMode;
113568      }
113569      pPager = sqlite3BtreePager(pDb->pBt);
113570      eMode = sqlite3PagerLockingMode(pPager, eMode);
113571    }
113572
113573    assert( eMode==PAGER_LOCKINGMODE_NORMAL
113574            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
113575    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
113576      zRet = "exclusive";
113577    }
113578    returnSingleText(v, zRet);
113579    break;
113580  }
113581
113582  /*
113583  **  PRAGMA [schema.]journal_mode
113584  **  PRAGMA [schema.]journal_mode =
113585  **                      (delete|persist|off|truncate|memory|wal|off)
113586  */
113587  case PragTyp_JOURNAL_MODE: {
113588    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
113589    int ii;           /* Loop counter */
113590
113591    if( zRight==0 ){
113592      /* If there is no "=MODE" part of the pragma, do a query for the
113593      ** current mode */
113594      eMode = PAGER_JOURNALMODE_QUERY;
113595    }else{
113596      const char *zMode;
113597      int n = sqlite3Strlen30(zRight);
113598      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
113599        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
113600      }
113601      if( !zMode ){
113602        /* If the "=MODE" part does not match any known journal mode,
113603        ** then do a query */
113604        eMode = PAGER_JOURNALMODE_QUERY;
113605      }
113606    }
113607    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
113608      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
113609      iDb = 0;
113610      pId2->n = 1;
113611    }
113612    for(ii=db->nDb-1; ii>=0; ii--){
113613      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
113614        sqlite3VdbeUsesBtree(v, ii);
113615        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
113616      }
113617    }
113618    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
113619    break;
113620  }
113621
113622  /*
113623  **  PRAGMA [schema.]journal_size_limit
113624  **  PRAGMA [schema.]journal_size_limit=N
113625  **
113626  ** Get or set the size limit on rollback journal files.
113627  */
113628  case PragTyp_JOURNAL_SIZE_LIMIT: {
113629    Pager *pPager = sqlite3BtreePager(pDb->pBt);
113630    i64 iLimit = -2;
113631    if( zRight ){
113632      sqlite3DecOrHexToI64(zRight, &iLimit);
113633      if( iLimit<-1 ) iLimit = -1;
113634    }
113635    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
113636    returnSingleInt(v, iLimit);
113637    break;
113638  }
113639
113640#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
113641
113642  /*
113643  **  PRAGMA [schema.]auto_vacuum
113644  **  PRAGMA [schema.]auto_vacuum=N
113645  **
113646  ** Get or set the value of the database 'auto-vacuum' parameter.
113647  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
113648  */
113649#ifndef SQLITE_OMIT_AUTOVACUUM
113650  case PragTyp_AUTO_VACUUM: {
113651    Btree *pBt = pDb->pBt;
113652    assert( pBt!=0 );
113653    if( !zRight ){
113654      returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
113655    }else{
113656      int eAuto = getAutoVacuum(zRight);
113657      assert( eAuto>=0 && eAuto<=2 );
113658      db->nextAutovac = (u8)eAuto;
113659      /* Call SetAutoVacuum() to set initialize the internal auto and
113660      ** incr-vacuum flags. This is required in case this connection
113661      ** creates the database file. It is important that it is created
113662      ** as an auto-vacuum capable db.
113663      */
113664      rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
113665      if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
113666        /* When setting the auto_vacuum mode to either "full" or
113667        ** "incremental", write the value of meta[6] in the database
113668        ** file. Before writing to meta[6], check that meta[3] indicates
113669        ** that this really is an auto-vacuum capable database.
113670        */
113671        static const int iLn = VDBE_OFFSET_LINENO(2);
113672        static const VdbeOpList setMeta6[] = {
113673          { OP_Transaction,    0,         1,                 0},    /* 0 */
113674          { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
113675          { OP_If,             1,         0,                 0},    /* 2 */
113676          { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
113677          { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 0},    /* 4 */
113678        };
113679        VdbeOp *aOp;
113680        int iAddr = sqlite3VdbeCurrentAddr(v);
113681        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
113682        aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
113683        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
113684        aOp[0].p1 = iDb;
113685        aOp[1].p1 = iDb;
113686        aOp[2].p2 = iAddr+4;
113687        aOp[4].p1 = iDb;
113688        aOp[4].p3 = eAuto - 1;
113689        sqlite3VdbeUsesBtree(v, iDb);
113690      }
113691    }
113692    break;
113693  }
113694#endif
113695
113696  /*
113697  **  PRAGMA [schema.]incremental_vacuum(N)
113698  **
113699  ** Do N steps of incremental vacuuming on a database.
113700  */
113701#ifndef SQLITE_OMIT_AUTOVACUUM
113702  case PragTyp_INCREMENTAL_VACUUM: {
113703    int iLimit, addr;
113704    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
113705      iLimit = 0x7fffffff;
113706    }
113707    sqlite3BeginWriteOperation(pParse, 0, iDb);
113708    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
113709    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
113710    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
113711    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
113712    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
113713    sqlite3VdbeJumpHere(v, addr);
113714    break;
113715  }
113716#endif
113717
113718#ifndef SQLITE_OMIT_PAGER_PRAGMAS
113719  /*
113720  **  PRAGMA [schema.]cache_size
113721  **  PRAGMA [schema.]cache_size=N
113722  **
113723  ** The first form reports the current local setting for the
113724  ** page cache size. The second form sets the local
113725  ** page cache size value.  If N is positive then that is the
113726  ** number of pages in the cache.  If N is negative, then the
113727  ** number of pages is adjusted so that the cache uses -N kibibytes
113728  ** of memory.
113729  */
113730  case PragTyp_CACHE_SIZE: {
113731    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
113732    if( !zRight ){
113733      returnSingleInt(v, pDb->pSchema->cache_size);
113734    }else{
113735      int size = sqlite3Atoi(zRight);
113736      pDb->pSchema->cache_size = size;
113737      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
113738    }
113739    break;
113740  }
113741
113742  /*
113743  **  PRAGMA [schema.]cache_spill
113744  **  PRAGMA cache_spill=BOOLEAN
113745  **  PRAGMA [schema.]cache_spill=N
113746  **
113747  ** The first form reports the current local setting for the
113748  ** page cache spill size. The second form turns cache spill on
113749  ** or off.  When turnning cache spill on, the size is set to the
113750  ** current cache_size.  The third form sets a spill size that
113751  ** may be different form the cache size.
113752  ** If N is positive then that is the
113753  ** number of pages in the cache.  If N is negative, then the
113754  ** number of pages is adjusted so that the cache uses -N kibibytes
113755  ** of memory.
113756  **
113757  ** If the number of cache_spill pages is less then the number of
113758  ** cache_size pages, no spilling occurs until the page count exceeds
113759  ** the number of cache_size pages.
113760  **
113761  ** The cache_spill=BOOLEAN setting applies to all attached schemas,
113762  ** not just the schema specified.
113763  */
113764  case PragTyp_CACHE_SPILL: {
113765    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
113766    if( !zRight ){
113767      returnSingleInt(v,
113768         (db->flags & SQLITE_CacheSpill)==0 ? 0 :
113769            sqlite3BtreeSetSpillSize(pDb->pBt,0));
113770    }else{
113771      int size = 1;
113772      if( sqlite3GetInt32(zRight, &size) ){
113773        sqlite3BtreeSetSpillSize(pDb->pBt, size);
113774      }
113775      if( sqlite3GetBoolean(zRight, size!=0) ){
113776        db->flags |= SQLITE_CacheSpill;
113777      }else{
113778        db->flags &= ~SQLITE_CacheSpill;
113779      }
113780      setAllPagerFlags(db);
113781    }
113782    break;
113783  }
113784
113785  /*
113786  **  PRAGMA [schema.]mmap_size(N)
113787  **
113788  ** Used to set mapping size limit. The mapping size limit is
113789  ** used to limit the aggregate size of all memory mapped regions of the
113790  ** database file. If this parameter is set to zero, then memory mapping
113791  ** is not used at all.  If N is negative, then the default memory map
113792  ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
113793  ** The parameter N is measured in bytes.
113794  **
113795  ** This value is advisory.  The underlying VFS is free to memory map
113796  ** as little or as much as it wants.  Except, if N is set to 0 then the
113797  ** upper layers will never invoke the xFetch interfaces to the VFS.
113798  */
113799  case PragTyp_MMAP_SIZE: {
113800    sqlite3_int64 sz;
113801#if SQLITE_MAX_MMAP_SIZE>0
113802    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
113803    if( zRight ){
113804      int ii;
113805      sqlite3DecOrHexToI64(zRight, &sz);
113806      if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
113807      if( pId2->n==0 ) db->szMmap = sz;
113808      for(ii=db->nDb-1; ii>=0; ii--){
113809        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
113810          sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
113811        }
113812      }
113813    }
113814    sz = -1;
113815    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
113816#else
113817    sz = 0;
113818    rc = SQLITE_OK;
113819#endif
113820    if( rc==SQLITE_OK ){
113821      returnSingleInt(v, sz);
113822    }else if( rc!=SQLITE_NOTFOUND ){
113823      pParse->nErr++;
113824      pParse->rc = rc;
113825    }
113826    break;
113827  }
113828
113829  /*
113830  **   PRAGMA temp_store
113831  **   PRAGMA temp_store = "default"|"memory"|"file"
113832  **
113833  ** Return or set the local value of the temp_store flag.  Changing
113834  ** the local value does not make changes to the disk file and the default
113835  ** value will be restored the next time the database is opened.
113836  **
113837  ** Note that it is possible for the library compile-time options to
113838  ** override this setting
113839  */
113840  case PragTyp_TEMP_STORE: {
113841    if( !zRight ){
113842      returnSingleInt(v, db->temp_store);
113843    }else{
113844      changeTempStorage(pParse, zRight);
113845    }
113846    break;
113847  }
113848
113849  /*
113850  **   PRAGMA temp_store_directory
113851  **   PRAGMA temp_store_directory = ""|"directory_name"
113852  **
113853  ** Return or set the local value of the temp_store_directory flag.  Changing
113854  ** the value sets a specific directory to be used for temporary files.
113855  ** Setting to a null string reverts to the default temporary directory search.
113856  ** If temporary directory is changed, then invalidateTempStorage.
113857  **
113858  */
113859  case PragTyp_TEMP_STORE_DIRECTORY: {
113860    if( !zRight ){
113861      returnSingleText(v, sqlite3_temp_directory);
113862    }else{
113863#ifndef SQLITE_OMIT_WSD
113864      if( zRight[0] ){
113865        int res;
113866        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
113867        if( rc!=SQLITE_OK || res==0 ){
113868          sqlite3ErrorMsg(pParse, "not a writable directory");
113869          goto pragma_out;
113870        }
113871      }
113872      if( SQLITE_TEMP_STORE==0
113873       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
113874       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
113875      ){
113876        invalidateTempStorage(pParse);
113877      }
113878      sqlite3_free(sqlite3_temp_directory);
113879      if( zRight[0] ){
113880        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
113881      }else{
113882        sqlite3_temp_directory = 0;
113883      }
113884#endif /* SQLITE_OMIT_WSD */
113885    }
113886    break;
113887  }
113888
113889#if SQLITE_OS_WIN
113890  /*
113891  **   PRAGMA data_store_directory
113892  **   PRAGMA data_store_directory = ""|"directory_name"
113893  **
113894  ** Return or set the local value of the data_store_directory flag.  Changing
113895  ** the value sets a specific directory to be used for database files that
113896  ** were specified with a relative pathname.  Setting to a null string reverts
113897  ** to the default database directory, which for database files specified with
113898  ** a relative path will probably be based on the current directory for the
113899  ** process.  Database file specified with an absolute path are not impacted
113900  ** by this setting, regardless of its value.
113901  **
113902  */
113903  case PragTyp_DATA_STORE_DIRECTORY: {
113904    if( !zRight ){
113905      returnSingleText(v, sqlite3_data_directory);
113906    }else{
113907#ifndef SQLITE_OMIT_WSD
113908      if( zRight[0] ){
113909        int res;
113910        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
113911        if( rc!=SQLITE_OK || res==0 ){
113912          sqlite3ErrorMsg(pParse, "not a writable directory");
113913          goto pragma_out;
113914        }
113915      }
113916      sqlite3_free(sqlite3_data_directory);
113917      if( zRight[0] ){
113918        sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
113919      }else{
113920        sqlite3_data_directory = 0;
113921      }
113922#endif /* SQLITE_OMIT_WSD */
113923    }
113924    break;
113925  }
113926#endif
113927
113928#if SQLITE_ENABLE_LOCKING_STYLE
113929  /*
113930  **   PRAGMA [schema.]lock_proxy_file
113931  **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
113932  **
113933  ** Return or set the value of the lock_proxy_file flag.  Changing
113934  ** the value sets a specific file to be used for database access locks.
113935  **
113936  */
113937  case PragTyp_LOCK_PROXY_FILE: {
113938    if( !zRight ){
113939      Pager *pPager = sqlite3BtreePager(pDb->pBt);
113940      char *proxy_file_path = NULL;
113941      sqlite3_file *pFile = sqlite3PagerFile(pPager);
113942      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
113943                           &proxy_file_path);
113944      returnSingleText(v, proxy_file_path);
113945    }else{
113946      Pager *pPager = sqlite3BtreePager(pDb->pBt);
113947      sqlite3_file *pFile = sqlite3PagerFile(pPager);
113948      int res;
113949      if( zRight[0] ){
113950        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
113951                                     zRight);
113952      } else {
113953        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
113954                                     NULL);
113955      }
113956      if( res!=SQLITE_OK ){
113957        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
113958        goto pragma_out;
113959      }
113960    }
113961    break;
113962  }
113963#endif /* SQLITE_ENABLE_LOCKING_STYLE */
113964
113965  /*
113966  **   PRAGMA [schema.]synchronous
113967  **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
113968  **
113969  ** Return or set the local value of the synchronous flag.  Changing
113970  ** the local value does not make changes to the disk file and the
113971  ** default value will be restored the next time the database is
113972  ** opened.
113973  */
113974  case PragTyp_SYNCHRONOUS: {
113975    if( !zRight ){
113976      returnSingleInt(v, pDb->safety_level-1);
113977    }else{
113978      if( !db->autoCommit ){
113979        sqlite3ErrorMsg(pParse,
113980            "Safety level may not be changed inside a transaction");
113981      }else if( iDb!=1 ){
113982        int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
113983        if( iLevel==0 ) iLevel = 1;
113984        pDb->safety_level = iLevel;
113985        pDb->bSyncSet = 1;
113986        setAllPagerFlags(db);
113987      }
113988    }
113989    break;
113990  }
113991#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
113992
113993#ifndef SQLITE_OMIT_FLAG_PRAGMAS
113994  case PragTyp_FLAG: {
113995    if( zRight==0 ){
113996      setPragmaResultColumnNames(v, pPragma);
113997      returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
113998    }else{
113999      int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
114000      if( db->autoCommit==0 ){
114001        /* Foreign key support may not be enabled or disabled while not
114002        ** in auto-commit mode.  */
114003        mask &= ~(SQLITE_ForeignKeys);
114004      }
114005#if SQLITE_USER_AUTHENTICATION
114006      if( db->auth.authLevel==UAUTH_User ){
114007        /* Do not allow non-admin users to modify the schema arbitrarily */
114008        mask &= ~(SQLITE_WriteSchema);
114009      }
114010#endif
114011
114012      if( sqlite3GetBoolean(zRight, 0) ){
114013        db->flags |= mask;
114014      }else{
114015        db->flags &= ~mask;
114016        if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
114017      }
114018
114019      /* Many of the flag-pragmas modify the code generated by the SQL
114020      ** compiler (eg. count_changes). So add an opcode to expire all
114021      ** compiled SQL statements after modifying a pragma value.
114022      */
114023      sqlite3VdbeAddOp0(v, OP_Expire);
114024      setAllPagerFlags(db);
114025    }
114026    break;
114027  }
114028#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
114029
114030#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
114031  /*
114032  **   PRAGMA table_info(<table>)
114033  **
114034  ** Return a single row for each column of the named table. The columns of
114035  ** the returned data set are:
114036  **
114037  ** cid:        Column id (numbered from left to right, starting at 0)
114038  ** name:       Column name
114039  ** type:       Column declaration type.
114040  ** notnull:    True if 'NOT NULL' is part of column declaration
114041  ** dflt_value: The default value for the column, if any.
114042  */
114043  case PragTyp_TABLE_INFO: if( zRight ){
114044    Table *pTab;
114045    pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
114046    if( pTab ){
114047      int i, k;
114048      int nHidden = 0;
114049      Column *pCol;
114050      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
114051      pParse->nMem = 6;
114052      sqlite3CodeVerifySchema(pParse, iDb);
114053      sqlite3ViewGetColumnNames(pParse, pTab);
114054      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
114055        if( IsHiddenColumn(pCol) ){
114056          nHidden++;
114057          continue;
114058        }
114059        if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
114060          k = 0;
114061        }else if( pPk==0 ){
114062          k = 1;
114063        }else{
114064          for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
114065        }
114066        assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
114067        sqlite3VdbeMultiLoad(v, 1, "issisi",
114068               i-nHidden,
114069               pCol->zName,
114070               sqlite3ColumnType(pCol,""),
114071               pCol->notNull ? 1 : 0,
114072               pCol->pDflt ? pCol->pDflt->u.zToken : 0,
114073               k);
114074        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
114075      }
114076    }
114077  }
114078  break;
114079
114080#ifdef SQLITE_DEBUG
114081  case PragTyp_STATS: {
114082    Index *pIdx;
114083    HashElem *i;
114084    pParse->nMem = 5;
114085    sqlite3CodeVerifySchema(pParse, iDb);
114086    for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
114087      Table *pTab = sqliteHashData(i);
114088      sqlite3VdbeMultiLoad(v, 1, "ssiii",
114089           pTab->zName,
114090           0,
114091           pTab->szTabRow,
114092           pTab->nRowLogEst,
114093           pTab->tabFlags);
114094      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
114095      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
114096        sqlite3VdbeMultiLoad(v, 2, "siii",
114097           pIdx->zName,
114098           pIdx->szIdxRow,
114099           pIdx->aiRowLogEst[0],
114100           pIdx->hasStat1);
114101        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
114102      }
114103    }
114104  }
114105  break;
114106#endif
114107
114108  case PragTyp_INDEX_INFO: if( zRight ){
114109    Index *pIdx;
114110    Table *pTab;
114111    pIdx = sqlite3FindIndex(db, zRight, zDb);
114112    if( pIdx ){
114113      int i;
114114      int mx;
114115      if( pPragma->iArg ){
114116        /* PRAGMA index_xinfo (newer version with more rows and columns) */
114117        mx = pIdx->nColumn;
114118        pParse->nMem = 6;
114119      }else{
114120        /* PRAGMA index_info (legacy version) */
114121        mx = pIdx->nKeyCol;
114122        pParse->nMem = 3;
114123      }
114124      pTab = pIdx->pTable;
114125      sqlite3CodeVerifySchema(pParse, iDb);
114126      assert( pParse->nMem<=pPragma->nPragCName );
114127      for(i=0; i<mx; i++){
114128        i16 cnum = pIdx->aiColumn[i];
114129        sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
114130                             cnum<0 ? 0 : pTab->aCol[cnum].zName);
114131        if( pPragma->iArg ){
114132          sqlite3VdbeMultiLoad(v, 4, "isi",
114133            pIdx->aSortOrder[i],
114134            pIdx->azColl[i],
114135            i<pIdx->nKeyCol);
114136        }
114137        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
114138      }
114139    }
114140  }
114141  break;
114142
114143  case PragTyp_INDEX_LIST: if( zRight ){
114144    Index *pIdx;
114145    Table *pTab;
114146    int i;
114147    pTab = sqlite3FindTable(db, zRight, zDb);
114148    if( pTab ){
114149      pParse->nMem = 5;
114150      sqlite3CodeVerifySchema(pParse, iDb);
114151      for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
114152        const char *azOrigin[] = { "c", "u", "pk" };
114153        sqlite3VdbeMultiLoad(v, 1, "isisi",
114154           i,
114155           pIdx->zName,
114156           IsUniqueIndex(pIdx),
114157           azOrigin[pIdx->idxType],
114158           pIdx->pPartIdxWhere!=0);
114159        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
114160      }
114161    }
114162  }
114163  break;
114164
114165  case PragTyp_DATABASE_LIST: {
114166    int i;
114167    pParse->nMem = 3;
114168    for(i=0; i<db->nDb; i++){
114169      if( db->aDb[i].pBt==0 ) continue;
114170      assert( db->aDb[i].zDbSName!=0 );
114171      sqlite3VdbeMultiLoad(v, 1, "iss",
114172         i,
114173         db->aDb[i].zDbSName,
114174         sqlite3BtreeGetFilename(db->aDb[i].pBt));
114175      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
114176    }
114177  }
114178  break;
114179
114180  case PragTyp_COLLATION_LIST: {
114181    int i = 0;
114182    HashElem *p;
114183    pParse->nMem = 2;
114184    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
114185      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
114186      sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
114187      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
114188    }
114189  }
114190  break;
114191#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
114192
114193#ifndef SQLITE_OMIT_FOREIGN_KEY
114194  case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
114195    FKey *pFK;
114196    Table *pTab;
114197    pTab = sqlite3FindTable(db, zRight, zDb);
114198    if( pTab ){
114199      pFK = pTab->pFKey;
114200      if( pFK ){
114201        int i = 0;
114202        pParse->nMem = 8;
114203        sqlite3CodeVerifySchema(pParse, iDb);
114204        while(pFK){
114205          int j;
114206          for(j=0; j<pFK->nCol; j++){
114207            sqlite3VdbeMultiLoad(v, 1, "iissssss",
114208                   i,
114209                   j,
114210                   pFK->zTo,
114211                   pTab->aCol[pFK->aCol[j].iFrom].zName,
114212                   pFK->aCol[j].zCol,
114213                   actionName(pFK->aAction[1]),  /* ON UPDATE */
114214                   actionName(pFK->aAction[0]),  /* ON DELETE */
114215                   "NONE");
114216            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
114217          }
114218          ++i;
114219          pFK = pFK->pNextFrom;
114220        }
114221      }
114222    }
114223  }
114224  break;
114225#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
114226
114227#ifndef SQLITE_OMIT_FOREIGN_KEY
114228#ifndef SQLITE_OMIT_TRIGGER
114229  case PragTyp_FOREIGN_KEY_CHECK: {
114230    FKey *pFK;             /* A foreign key constraint */
114231    Table *pTab;           /* Child table contain "REFERENCES" keyword */
114232    Table *pParent;        /* Parent table that child points to */
114233    Index *pIdx;           /* Index in the parent table */
114234    int i;                 /* Loop counter:  Foreign key number for pTab */
114235    int j;                 /* Loop counter:  Field of the foreign key */
114236    HashElem *k;           /* Loop counter:  Next table in schema */
114237    int x;                 /* result variable */
114238    int regResult;         /* 3 registers to hold a result row */
114239    int regKey;            /* Register to hold key for checking the FK */
114240    int regRow;            /* Registers to hold a row from pTab */
114241    int addrTop;           /* Top of a loop checking foreign keys */
114242    int addrOk;            /* Jump here if the key is OK */
114243    int *aiCols;           /* child to parent column mapping */
114244
114245    regResult = pParse->nMem+1;
114246    pParse->nMem += 4;
114247    regKey = ++pParse->nMem;
114248    regRow = ++pParse->nMem;
114249    sqlite3CodeVerifySchema(pParse, iDb);
114250    k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
114251    while( k ){
114252      if( zRight ){
114253        pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
114254        k = 0;
114255      }else{
114256        pTab = (Table*)sqliteHashData(k);
114257        k = sqliteHashNext(k);
114258      }
114259      if( pTab==0 || pTab->pFKey==0 ) continue;
114260      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
114261      if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
114262      sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
114263      sqlite3VdbeLoadString(v, regResult, pTab->zName);
114264      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
114265        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
114266        if( pParent==0 ) continue;
114267        pIdx = 0;
114268        sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
114269        x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
114270        if( x==0 ){
114271          if( pIdx==0 ){
114272            sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
114273          }else{
114274            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
114275            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
114276          }
114277        }else{
114278          k = 0;
114279          break;
114280        }
114281      }
114282      assert( pParse->nErr>0 || pFK==0 );
114283      if( pFK ) break;
114284      if( pParse->nTab<i ) pParse->nTab = i;
114285      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
114286      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
114287        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
114288        pIdx = 0;
114289        aiCols = 0;
114290        if( pParent ){
114291          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
114292          assert( x==0 );
114293        }
114294        addrOk = sqlite3VdbeMakeLabel(v);
114295        if( pParent && pIdx==0 ){
114296          int iKey = pFK->aCol[0].iFrom;
114297          assert( iKey>=0 && iKey<pTab->nCol );
114298          if( iKey!=pTab->iPKey ){
114299            sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
114300            sqlite3ColumnDefault(v, pTab, iKey, regRow);
114301            sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
114302          }else{
114303            sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
114304          }
114305          sqlite3VdbeAddOp3(v, OP_SeekRowid, i, 0, regRow); VdbeCoverage(v);
114306          sqlite3VdbeGoto(v, addrOk);
114307          sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
114308        }else{
114309          for(j=0; j<pFK->nCol; j++){
114310            sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
114311                            aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
114312            sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
114313          }
114314          if( pParent ){
114315            sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
114316                              sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
114317            sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
114318            VdbeCoverage(v);
114319          }
114320        }
114321        sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
114322        sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
114323        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
114324        sqlite3VdbeResolveLabel(v, addrOk);
114325        sqlite3DbFree(db, aiCols);
114326      }
114327      sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
114328      sqlite3VdbeJumpHere(v, addrTop);
114329    }
114330  }
114331  break;
114332#endif /* !defined(SQLITE_OMIT_TRIGGER) */
114333#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
114334
114335#ifndef NDEBUG
114336  case PragTyp_PARSER_TRACE: {
114337    if( zRight ){
114338      if( sqlite3GetBoolean(zRight, 0) ){
114339        sqlite3ParserTrace(stdout, "parser: ");
114340      }else{
114341        sqlite3ParserTrace(0, 0);
114342      }
114343    }
114344  }
114345  break;
114346#endif
114347
114348  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
114349  ** used will be case sensitive or not depending on the RHS.
114350  */
114351  case PragTyp_CASE_SENSITIVE_LIKE: {
114352    if( zRight ){
114353      sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
114354    }
114355  }
114356  break;
114357
114358#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
114359# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
114360#endif
114361
114362#ifndef SQLITE_OMIT_INTEGRITY_CHECK
114363  /*    PRAGMA integrity_check
114364  **    PRAGMA integrity_check(N)
114365  **    PRAGMA quick_check
114366  **    PRAGMA quick_check(N)
114367  **
114368  ** Verify the integrity of the database.
114369  **
114370  ** The "quick_check" is reduced version of
114371  ** integrity_check designed to detect most database corruption
114372  ** without the overhead of cross-checking indexes.  Quick_check
114373  ** is linear time wherease integrity_check is O(NlogN).
114374  */
114375  case PragTyp_INTEGRITY_CHECK: {
114376    int i, j, addr, mxErr;
114377
114378    int isQuick = (sqlite3Tolower(zLeft[0])=='q');
114379
114380    /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
114381    ** then iDb is set to the index of the database identified by <db>.
114382    ** In this case, the integrity of database iDb only is verified by
114383    ** the VDBE created below.
114384    **
114385    ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
114386    ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
114387    ** to -1 here, to indicate that the VDBE should verify the integrity
114388    ** of all attached databases.  */
114389    assert( iDb>=0 );
114390    assert( iDb==0 || pId2->z );
114391    if( pId2->z==0 ) iDb = -1;
114392
114393    /* Initialize the VDBE program */
114394    pParse->nMem = 6;
114395
114396    /* Set the maximum error count */
114397    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
114398    if( zRight ){
114399      sqlite3GetInt32(zRight, &mxErr);
114400      if( mxErr<=0 ){
114401        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
114402      }
114403    }
114404    sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
114405
114406    /* Do an integrity check on each database file */
114407    for(i=0; i<db->nDb; i++){
114408      HashElem *x;
114409      Hash *pTbls;
114410      int *aRoot;
114411      int cnt = 0;
114412      int mxIdx = 0;
114413      int nIdx;
114414
114415      if( OMIT_TEMPDB && i==1 ) continue;
114416      if( iDb>=0 && i!=iDb ) continue;
114417
114418      sqlite3CodeVerifySchema(pParse, i);
114419
114420      /* Do an integrity check of the B-Tree
114421      **
114422      ** Begin by finding the root pages numbers
114423      ** for all tables and indices in the database.
114424      */
114425      assert( sqlite3SchemaMutexHeld(db, i, 0) );
114426      pTbls = &db->aDb[i].pSchema->tblHash;
114427      for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
114428        Table *pTab = sqliteHashData(x);
114429        Index *pIdx;
114430        if( HasRowid(pTab) ) cnt++;
114431        for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
114432        if( nIdx>mxIdx ) mxIdx = nIdx;
114433      }
114434      aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
114435      if( aRoot==0 ) break;
114436      for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
114437        Table *pTab = sqliteHashData(x);
114438        Index *pIdx;
114439        if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum;
114440        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
114441          aRoot[cnt++] = pIdx->tnum;
114442        }
114443      }
114444      aRoot[cnt] = 0;
114445
114446      /* Make sure sufficient number of registers have been allocated */
114447      pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
114448
114449      /* Do the b-tree integrity checks */
114450      sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
114451      sqlite3VdbeChangeP5(v, (u8)i);
114452      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
114453      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
114454         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
114455         P4_DYNAMIC);
114456      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
114457      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
114458      integrityCheckResultRow(v, 2);
114459      sqlite3VdbeJumpHere(v, addr);
114460
114461      /* Make sure all the indices are constructed correctly.
114462      */
114463      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
114464        Table *pTab = sqliteHashData(x);
114465        Index *pIdx, *pPk;
114466        Index *pPrior = 0;
114467        int loopTop;
114468        int iDataCur, iIdxCur;
114469        int r1 = -1;
114470
114471        if( pTab->tnum<1 ) continue;  /* Skip VIEWs or VIRTUAL TABLEs */
114472        if( pTab->pCheck==0
114473         && (pTab->tabFlags & TF_HasNotNull)==0
114474         && (pTab->pIndex==0 || isQuick)
114475        ){
114476          continue;  /* No additional checks needed for this table */
114477        }
114478        pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
114479        sqlite3ExprCacheClear(pParse);
114480        sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
114481                                   1, 0, &iDataCur, &iIdxCur);
114482        sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
114483        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
114484          sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
114485        }
114486        assert( pParse->nMem>=8+j );
114487        assert( sqlite3NoTempsInRange(pParse,1,7+j) );
114488        sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
114489        loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
114490        /* Verify that all NOT NULL columns really are NOT NULL */
114491        for(j=0; j<pTab->nCol; j++){
114492          char *zErr;
114493          int jmp2;
114494          if( j==pTab->iPKey ) continue;
114495          if( pTab->aCol[j].notNull==0 ) continue;
114496          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
114497          sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
114498          jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
114499          zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
114500                              pTab->aCol[j].zName);
114501          sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
114502          integrityCheckResultRow(v, 3);
114503          sqlite3VdbeJumpHere(v, jmp2);
114504        }
114505        /* Verify CHECK constraints */
114506        if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
114507          int addrCkFault = sqlite3VdbeMakeLabel(v);
114508          int addrCkOk = sqlite3VdbeMakeLabel(v);
114509          ExprList *pCheck = pTab->pCheck;
114510          char *zErr;
114511          int k;
114512          pParse->iSelfTab = iDataCur;
114513          sqlite3ExprCachePush(pParse);
114514          for(k=pCheck->nExpr-1; k>0; k--){
114515            sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
114516          }
114517          sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
114518                            SQLITE_JUMPIFNULL);
114519          sqlite3VdbeResolveLabel(v, addrCkFault);
114520          zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
114521                                pTab->zName);
114522          sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
114523          integrityCheckResultRow(v, 3);
114524          sqlite3VdbeResolveLabel(v, addrCkOk);
114525          sqlite3ExprCachePop(pParse);
114526        }
114527        /* Validate index entries for the current row */
114528        for(j=0, pIdx=pTab->pIndex; pIdx && !isQuick; pIdx=pIdx->pNext, j++){
114529          int jmp2, jmp3, jmp4, jmp5;
114530          int ckUniq = sqlite3VdbeMakeLabel(v);
114531          if( pPk==pIdx ) continue;
114532          r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
114533                                       pPrior, r1);
114534          pPrior = pIdx;
114535          sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
114536          /* Verify that an index entry exists for the current table row */
114537          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
114538                                      pIdx->nColumn); VdbeCoverage(v);
114539          sqlite3VdbeLoadString(v, 3, "row ");
114540          sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
114541          sqlite3VdbeLoadString(v, 4, " missing from index ");
114542          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
114543          jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
114544          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
114545          jmp4 = integrityCheckResultRow(v, 3);
114546          sqlite3VdbeJumpHere(v, jmp2);
114547          /* For UNIQUE indexes, verify that only one entry exists with the
114548          ** current key.  The entry is unique if (1) any column is NULL
114549          ** or (2) the next entry has a different key */
114550          if( IsUniqueIndex(pIdx) ){
114551            int uniqOk = sqlite3VdbeMakeLabel(v);
114552            int jmp6;
114553            int kk;
114554            for(kk=0; kk<pIdx->nKeyCol; kk++){
114555              int iCol = pIdx->aiColumn[kk];
114556              assert( iCol!=XN_ROWID && iCol<pTab->nCol );
114557              if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
114558              sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
114559              VdbeCoverage(v);
114560            }
114561            jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
114562            sqlite3VdbeGoto(v, uniqOk);
114563            sqlite3VdbeJumpHere(v, jmp6);
114564            sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
114565                                 pIdx->nKeyCol); VdbeCoverage(v);
114566            sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
114567            sqlite3VdbeGoto(v, jmp5);
114568            sqlite3VdbeResolveLabel(v, uniqOk);
114569          }
114570          sqlite3VdbeJumpHere(v, jmp4);
114571          sqlite3ResolvePartIdxLabel(pParse, jmp3);
114572        }
114573        sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
114574        sqlite3VdbeJumpHere(v, loopTop-1);
114575#ifndef SQLITE_OMIT_BTREECOUNT
114576        if( !isQuick ){
114577          sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
114578          for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
114579            if( pPk==pIdx ) continue;
114580            sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
114581            addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
114582            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
114583            sqlite3VdbeLoadString(v, 3, pIdx->zName);
114584            sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
114585            integrityCheckResultRow(v, 7);
114586            sqlite3VdbeJumpHere(v, addr);
114587          }
114588        }
114589#endif /* SQLITE_OMIT_BTREECOUNT */
114590      }
114591    }
114592    {
114593      static const int iLn = VDBE_OFFSET_LINENO(2);
114594      static const VdbeOpList endCode[] = {
114595        { OP_AddImm,      1, 0,        0},    /* 0 */
114596        { OP_IfNotZero,   1, 4,        0},    /* 1 */
114597        { OP_String8,     0, 3,        0},    /* 2 */
114598        { OP_ResultRow,   3, 1,        0},    /* 3 */
114599      };
114600      VdbeOp *aOp;
114601
114602      aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
114603      if( aOp ){
114604        aOp[0].p2 = 1-mxErr;
114605        aOp[2].p4type = P4_STATIC;
114606        aOp[2].p4.z = "ok";
114607      }
114608    }
114609  }
114610  break;
114611#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
114612
114613#ifndef SQLITE_OMIT_UTF16
114614  /*
114615  **   PRAGMA encoding
114616  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
114617  **
114618  ** In its first form, this pragma returns the encoding of the main
114619  ** database. If the database is not initialized, it is initialized now.
114620  **
114621  ** The second form of this pragma is a no-op if the main database file
114622  ** has not already been initialized. In this case it sets the default
114623  ** encoding that will be used for the main database file if a new file
114624  ** is created. If an existing main database file is opened, then the
114625  ** default text encoding for the existing database is used.
114626  **
114627  ** In all cases new databases created using the ATTACH command are
114628  ** created to use the same default text encoding as the main database. If
114629  ** the main database has not been initialized and/or created when ATTACH
114630  ** is executed, this is done before the ATTACH operation.
114631  **
114632  ** In the second form this pragma sets the text encoding to be used in
114633  ** new database files created using this database handle. It is only
114634  ** useful if invoked immediately after the main database i
114635  */
114636  case PragTyp_ENCODING: {
114637    static const struct EncName {
114638      char *zName;
114639      u8 enc;
114640    } encnames[] = {
114641      { "UTF8",     SQLITE_UTF8        },
114642      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
114643      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
114644      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
114645      { "UTF16le",  SQLITE_UTF16LE     },
114646      { "UTF16be",  SQLITE_UTF16BE     },
114647      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
114648      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
114649      { 0, 0 }
114650    };
114651    const struct EncName *pEnc;
114652    if( !zRight ){    /* "PRAGMA encoding" */
114653      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
114654      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
114655      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
114656      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
114657      returnSingleText(v, encnames[ENC(pParse->db)].zName);
114658    }else{                        /* "PRAGMA encoding = XXX" */
114659      /* Only change the value of sqlite.enc if the database handle is not
114660      ** initialized. If the main database exists, the new sqlite.enc value
114661      ** will be overwritten when the schema is next loaded. If it does not
114662      ** already exists, it will be created to use the new encoding value.
114663      */
114664      if(
114665        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
114666        DbHasProperty(db, 0, DB_Empty)
114667      ){
114668        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
114669          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
114670            SCHEMA_ENC(db) = ENC(db) =
114671                pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
114672            break;
114673          }
114674        }
114675        if( !pEnc->zName ){
114676          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
114677        }
114678      }
114679    }
114680  }
114681  break;
114682#endif /* SQLITE_OMIT_UTF16 */
114683
114684#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
114685  /*
114686  **   PRAGMA [schema.]schema_version
114687  **   PRAGMA [schema.]schema_version = <integer>
114688  **
114689  **   PRAGMA [schema.]user_version
114690  **   PRAGMA [schema.]user_version = <integer>
114691  **
114692  **   PRAGMA [schema.]freelist_count
114693  **
114694  **   PRAGMA [schema.]data_version
114695  **
114696  **   PRAGMA [schema.]application_id
114697  **   PRAGMA [schema.]application_id = <integer>
114698  **
114699  ** The pragma's schema_version and user_version are used to set or get
114700  ** the value of the schema-version and user-version, respectively. Both
114701  ** the schema-version and the user-version are 32-bit signed integers
114702  ** stored in the database header.
114703  **
114704  ** The schema-cookie is usually only manipulated internally by SQLite. It
114705  ** is incremented by SQLite whenever the database schema is modified (by
114706  ** creating or dropping a table or index). The schema version is used by
114707  ** SQLite each time a query is executed to ensure that the internal cache
114708  ** of the schema used when compiling the SQL query matches the schema of
114709  ** the database against which the compiled query is actually executed.
114710  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
114711  ** the schema-version is potentially dangerous and may lead to program
114712  ** crashes or database corruption. Use with caution!
114713  **
114714  ** The user-version is not used internally by SQLite. It may be used by
114715  ** applications for any purpose.
114716  */
114717  case PragTyp_HEADER_VALUE: {
114718    int iCookie = pPragma->iArg;  /* Which cookie to read or write */
114719    sqlite3VdbeUsesBtree(v, iDb);
114720    if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
114721      /* Write the specified cookie value */
114722      static const VdbeOpList setCookie[] = {
114723        { OP_Transaction,    0,  1,  0},    /* 0 */
114724        { OP_SetCookie,      0,  0,  0},    /* 1 */
114725      };
114726      VdbeOp *aOp;
114727      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
114728      aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
114729      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
114730      aOp[0].p1 = iDb;
114731      aOp[1].p1 = iDb;
114732      aOp[1].p2 = iCookie;
114733      aOp[1].p3 = sqlite3Atoi(zRight);
114734    }else{
114735      /* Read the specified cookie value */
114736      static const VdbeOpList readCookie[] = {
114737        { OP_Transaction,     0,  0,  0},    /* 0 */
114738        { OP_ReadCookie,      0,  1,  0},    /* 1 */
114739        { OP_ResultRow,       1,  1,  0}
114740      };
114741      VdbeOp *aOp;
114742      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
114743      aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
114744      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
114745      aOp[0].p1 = iDb;
114746      aOp[1].p1 = iDb;
114747      aOp[1].p3 = iCookie;
114748      sqlite3VdbeReusable(v);
114749    }
114750  }
114751  break;
114752#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
114753
114754#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
114755  /*
114756  **   PRAGMA compile_options
114757  **
114758  ** Return the names of all compile-time options used in this build,
114759  ** one option per row.
114760  */
114761  case PragTyp_COMPILE_OPTIONS: {
114762    int i = 0;
114763    const char *zOpt;
114764    pParse->nMem = 1;
114765    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
114766      sqlite3VdbeLoadString(v, 1, zOpt);
114767      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
114768    }
114769    sqlite3VdbeReusable(v);
114770  }
114771  break;
114772#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
114773
114774#ifndef SQLITE_OMIT_WAL
114775  /*
114776  **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
114777  **
114778  ** Checkpoint the database.
114779  */
114780  case PragTyp_WAL_CHECKPOINT: {
114781    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
114782    int eMode = SQLITE_CHECKPOINT_PASSIVE;
114783    if( zRight ){
114784      if( sqlite3StrICmp(zRight, "full")==0 ){
114785        eMode = SQLITE_CHECKPOINT_FULL;
114786      }else if( sqlite3StrICmp(zRight, "restart")==0 ){
114787        eMode = SQLITE_CHECKPOINT_RESTART;
114788      }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
114789        eMode = SQLITE_CHECKPOINT_TRUNCATE;
114790      }
114791    }
114792    pParse->nMem = 3;
114793    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
114794    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
114795  }
114796  break;
114797
114798  /*
114799  **   PRAGMA wal_autocheckpoint
114800  **   PRAGMA wal_autocheckpoint = N
114801  **
114802  ** Configure a database connection to automatically checkpoint a database
114803  ** after accumulating N frames in the log. Or query for the current value
114804  ** of N.
114805  */
114806  case PragTyp_WAL_AUTOCHECKPOINT: {
114807    if( zRight ){
114808      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
114809    }
114810    returnSingleInt(v,
114811       db->xWalCallback==sqlite3WalDefaultHook ?
114812           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
114813  }
114814  break;
114815#endif
114816
114817  /*
114818  **  PRAGMA shrink_memory
114819  **
114820  ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
114821  ** connection on which it is invoked to free up as much memory as it
114822  ** can, by calling sqlite3_db_release_memory().
114823  */
114824  case PragTyp_SHRINK_MEMORY: {
114825    sqlite3_db_release_memory(db);
114826    break;
114827  }
114828
114829  /*
114830  **  PRAGMA optimize
114831  **  PRAGMA optimize(MASK)
114832  **  PRAGMA schema.optimize
114833  **  PRAGMA schema.optimize(MASK)
114834  **
114835  ** Attempt to optimize the database.  All schemas are optimized in the first
114836  ** two forms, and only the specified schema is optimized in the latter two.
114837  **
114838  ** The details of optimizations performed by this pragma are expected
114839  ** to change and improve over time.  Applications should anticipate that
114840  ** this pragma will perform new optimizations in future releases.
114841  **
114842  ** The optional argument is a bitmask of optimizations to perform:
114843  **
114844  **    0x0001    Debugging mode.  Do not actually perform any optimizations
114845  **              but instead return one line of text for each optimization
114846  **              that would have been done.  Off by default.
114847  **
114848  **    0x0002    Run ANALYZE on tables that might benefit.  On by default.
114849  **              See below for additional information.
114850  **
114851  **    0x0004    (Not yet implemented) Record usage and performance
114852  **              information from the current session in the
114853  **              database file so that it will be available to "optimize"
114854  **              pragmas run by future database connections.
114855  **
114856  **    0x0008    (Not yet implemented) Create indexes that might have
114857  **              been helpful to recent queries
114858  **
114859  ** The default MASK is and always shall be 0xfffe.  0xfffe means perform all    ** of the optimizations listed above except Debug Mode, including new
114860  ** optimizations that have not yet been invented.  If new optimizations are
114861  ** ever added that should be off by default, those off-by-default
114862  ** optimizations will have bitmasks of 0x10000 or larger.
114863  **
114864  ** DETERMINATION OF WHEN TO RUN ANALYZE
114865  **
114866  ** In the current implementation, a table is analyzed if only if all of
114867  ** the following are true:
114868  **
114869  ** (1) MASK bit 0x02 is set.
114870  **
114871  ** (2) The query planner used sqlite_stat1-style statistics for one or
114872  **     more indexes of the table at some point during the lifetime of
114873  **     the current connection.
114874  **
114875  ** (3) One or more indexes of the table are currently unanalyzed OR
114876  **     the number of rows in the table has increased by 25 times or more
114877  **     since the last time ANALYZE was run.
114878  **
114879  ** The rules for when tables are analyzed are likely to change in
114880  ** future releases.
114881  */
114882  case PragTyp_OPTIMIZE: {
114883    int iDbLast;           /* Loop termination point for the schema loop */
114884    int iTabCur;           /* Cursor for a table whose size needs checking */
114885    HashElem *k;           /* Loop over tables of a schema */
114886    Schema *pSchema;       /* The current schema */
114887    Table *pTab;           /* A table in the schema */
114888    Index *pIdx;           /* An index of the table */
114889    LogEst szThreshold;    /* Size threshold above which reanalysis is needd */
114890    char *zSubSql;         /* SQL statement for the OP_SqlExec opcode */
114891    u32 opMask;            /* Mask of operations to perform */
114892
114893    if( zRight ){
114894      opMask = (u32)sqlite3Atoi(zRight);
114895      if( (opMask & 0x02)==0 ) break;
114896    }else{
114897      opMask = 0xfffe;
114898    }
114899    iTabCur = pParse->nTab++;
114900    for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
114901      if( iDb==1 ) continue;
114902      sqlite3CodeVerifySchema(pParse, iDb);
114903      pSchema = db->aDb[iDb].pSchema;
114904      for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
114905        pTab = (Table*)sqliteHashData(k);
114906
114907        /* If table pTab has not been used in a way that would benefit from
114908        ** having analysis statistics during the current session, then skip it.
114909        ** This also has the effect of skipping virtual tables and views */
114910        if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
114911
114912        /* Reanalyze if the table is 25 times larger than the last analysis */
114913        szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
114914        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
114915          if( !pIdx->hasStat1 ){
114916            szThreshold = 0; /* Always analyze if any index lacks statistics */
114917            break;
114918          }
114919        }
114920        if( szThreshold ){
114921          sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
114922          sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
114923                         sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
114924          VdbeCoverage(v);
114925        }
114926        zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
114927                                 db->aDb[iDb].zDbSName, pTab->zName);
114928        if( opMask & 0x01 ){
114929          int r1 = sqlite3GetTempReg(pParse);
114930          sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
114931          sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
114932        }else{
114933          sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
114934        }
114935      }
114936    }
114937    sqlite3VdbeAddOp0(v, OP_Expire);
114938    break;
114939  }
114940
114941  /*
114942  **   PRAGMA busy_timeout
114943  **   PRAGMA busy_timeout = N
114944  **
114945  ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
114946  ** if one is set.  If no busy handler or a different busy handler is set
114947  ** then 0 is returned.  Setting the busy_timeout to 0 or negative
114948  ** disables the timeout.
114949  */
114950  /*case PragTyp_BUSY_TIMEOUT*/ default: {
114951    assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
114952    if( zRight ){
114953      sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
114954    }
114955    returnSingleInt(v, db->busyTimeout);
114956    break;
114957  }
114958
114959  /*
114960  **   PRAGMA soft_heap_limit
114961  **   PRAGMA soft_heap_limit = N
114962  **
114963  ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
114964  ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
114965  ** specified and is a non-negative integer.
114966  ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
114967  ** returns the same integer that would be returned by the
114968  ** sqlite3_soft_heap_limit64(-1) C-language function.
114969  */
114970  case PragTyp_SOFT_HEAP_LIMIT: {
114971    sqlite3_int64 N;
114972    if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
114973      sqlite3_soft_heap_limit64(N);
114974    }
114975    returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
114976    break;
114977  }
114978
114979  /*
114980  **   PRAGMA threads
114981  **   PRAGMA threads = N
114982  **
114983  ** Configure the maximum number of worker threads.  Return the new
114984  ** maximum, which might be less than requested.
114985  */
114986  case PragTyp_THREADS: {
114987    sqlite3_int64 N;
114988    if( zRight
114989     && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
114990     && N>=0
114991    ){
114992      sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
114993    }
114994    returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
114995    break;
114996  }
114997
114998#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
114999  /*
115000  ** Report the current state of file logs for all databases
115001  */
115002  case PragTyp_LOCK_STATUS: {
115003    static const char *const azLockName[] = {
115004      "unlocked", "shared", "reserved", "pending", "exclusive"
115005    };
115006    int i;
115007    pParse->nMem = 2;
115008    for(i=0; i<db->nDb; i++){
115009      Btree *pBt;
115010      const char *zState = "unknown";
115011      int j;
115012      if( db->aDb[i].zDbSName==0 ) continue;
115013      pBt = db->aDb[i].pBt;
115014      if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
115015        zState = "closed";
115016      }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
115017                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
115018         zState = azLockName[j];
115019      }
115020      sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
115021      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
115022    }
115023    break;
115024  }
115025#endif
115026
115027#ifdef SQLITE_HAS_CODEC
115028  case PragTyp_KEY: {
115029    if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
115030    break;
115031  }
115032  case PragTyp_REKEY: {
115033    if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
115034    break;
115035  }
115036  case PragTyp_HEXKEY: {
115037    if( zRight ){
115038      u8 iByte;
115039      int i;
115040      char zKey[40];
115041      for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
115042        iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
115043        if( (i&1)!=0 ) zKey[i/2] = iByte;
115044      }
115045      if( (zLeft[3] & 0xf)==0xb ){
115046        sqlite3_key_v2(db, zDb, zKey, i/2);
115047      }else{
115048        sqlite3_rekey_v2(db, zDb, zKey, i/2);
115049      }
115050    }
115051    break;
115052  }
115053#endif
115054#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
115055  case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
115056#ifdef SQLITE_HAS_CODEC
115057    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
115058      sqlite3_activate_see(&zRight[4]);
115059    }
115060#endif
115061#ifdef SQLITE_ENABLE_CEROD
115062    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
115063      sqlite3_activate_cerod(&zRight[6]);
115064    }
115065#endif
115066  }
115067  break;
115068#endif
115069
115070  } /* End of the PRAGMA switch */
115071
115072  /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
115073  ** purpose is to execute assert() statements to verify that if the
115074  ** PragFlg_NoColumns1 flag is set and the caller specified an argument
115075  ** to the PRAGMA, the implementation has not added any OP_ResultRow
115076  ** instructions to the VM.  */
115077  if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
115078    sqlite3VdbeVerifyNoResultRow(v);
115079  }
115080
115081pragma_out:
115082  sqlite3DbFree(db, zLeft);
115083  sqlite3DbFree(db, zRight);
115084}
115085#ifndef SQLITE_OMIT_VIRTUALTABLE
115086/*****************************************************************************
115087** Implementation of an eponymous virtual table that runs a pragma.
115088**
115089*/
115090typedef struct PragmaVtab PragmaVtab;
115091typedef struct PragmaVtabCursor PragmaVtabCursor;
115092struct PragmaVtab {
115093  sqlite3_vtab base;        /* Base class.  Must be first */
115094  sqlite3 *db;              /* The database connection to which it belongs */
115095  const PragmaName *pName;  /* Name of the pragma */
115096  u8 nHidden;               /* Number of hidden columns */
115097  u8 iHidden;               /* Index of the first hidden column */
115098};
115099struct PragmaVtabCursor {
115100  sqlite3_vtab_cursor base; /* Base class.  Must be first */
115101  sqlite3_stmt *pPragma;    /* The pragma statement to run */
115102  sqlite_int64 iRowid;      /* Current rowid */
115103  char *azArg[2];           /* Value of the argument and schema */
115104};
115105
115106/*
115107** Pragma virtual table module xConnect method.
115108*/
115109static int pragmaVtabConnect(
115110  sqlite3 *db,
115111  void *pAux,
115112  int argc, const char *const*argv,
115113  sqlite3_vtab **ppVtab,
115114  char **pzErr
115115){
115116  const PragmaName *pPragma = (const PragmaName*)pAux;
115117  PragmaVtab *pTab = 0;
115118  int rc;
115119  int i, j;
115120  char cSep = '(';
115121  StrAccum acc;
115122  char zBuf[200];
115123
115124  UNUSED_PARAMETER(argc);
115125  UNUSED_PARAMETER(argv);
115126  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
115127  sqlite3StrAccumAppendAll(&acc, "CREATE TABLE x");
115128  for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
115129    sqlite3XPrintf(&acc, "%c\"%s\"", cSep, pragCName[j]);
115130    cSep = ',';
115131  }
115132  if( i==0 ){
115133    sqlite3XPrintf(&acc, "(\"%s\"", pPragma->zName);
115134    cSep = ',';
115135    i++;
115136  }
115137  j = 0;
115138  if( pPragma->mPragFlg & PragFlg_Result1 ){
115139    sqlite3StrAccumAppendAll(&acc, ",arg HIDDEN");
115140    j++;
115141  }
115142  if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
115143    sqlite3StrAccumAppendAll(&acc, ",schema HIDDEN");
115144    j++;
115145  }
115146  sqlite3StrAccumAppend(&acc, ")", 1);
115147  sqlite3StrAccumFinish(&acc);
115148  assert( strlen(zBuf) < sizeof(zBuf)-1 );
115149  rc = sqlite3_declare_vtab(db, zBuf);
115150  if( rc==SQLITE_OK ){
115151    pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
115152    if( pTab==0 ){
115153      rc = SQLITE_NOMEM;
115154    }else{
115155      memset(pTab, 0, sizeof(PragmaVtab));
115156      pTab->pName = pPragma;
115157      pTab->db = db;
115158      pTab->iHidden = i;
115159      pTab->nHidden = j;
115160    }
115161  }else{
115162    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
115163  }
115164
115165  *ppVtab = (sqlite3_vtab*)pTab;
115166  return rc;
115167}
115168
115169/*
115170** Pragma virtual table module xDisconnect method.
115171*/
115172static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
115173  PragmaVtab *pTab = (PragmaVtab*)pVtab;
115174  sqlite3_free(pTab);
115175  return SQLITE_OK;
115176}
115177
115178/* Figure out the best index to use to search a pragma virtual table.
115179**
115180** There are not really any index choices.  But we want to encourage the
115181** query planner to give == constraints on as many hidden parameters as
115182** possible, and especially on the first hidden parameter.  So return a
115183** high cost if hidden parameters are unconstrained.
115184*/
115185static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
115186  PragmaVtab *pTab = (PragmaVtab*)tab;
115187  const struct sqlite3_index_constraint *pConstraint;
115188  int i, j;
115189  int seen[2];
115190
115191  pIdxInfo->estimatedCost = (double)1;
115192  if( pTab->nHidden==0 ){ return SQLITE_OK; }
115193  pConstraint = pIdxInfo->aConstraint;
115194  seen[0] = 0;
115195  seen[1] = 0;
115196  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
115197    if( pConstraint->usable==0 ) continue;
115198    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
115199    if( pConstraint->iColumn < pTab->iHidden ) continue;
115200    j = pConstraint->iColumn - pTab->iHidden;
115201    assert( j < 2 );
115202    seen[j] = i+1;
115203  }
115204  if( seen[0]==0 ){
115205    pIdxInfo->estimatedCost = (double)2147483647;
115206    pIdxInfo->estimatedRows = 2147483647;
115207    return SQLITE_OK;
115208  }
115209  j = seen[0]-1;
115210  pIdxInfo->aConstraintUsage[j].argvIndex = 1;
115211  pIdxInfo->aConstraintUsage[j].omit = 1;
115212  if( seen[1]==0 ) return SQLITE_OK;
115213  pIdxInfo->estimatedCost = (double)20;
115214  pIdxInfo->estimatedRows = 20;
115215  j = seen[1]-1;
115216  pIdxInfo->aConstraintUsage[j].argvIndex = 2;
115217  pIdxInfo->aConstraintUsage[j].omit = 1;
115218  return SQLITE_OK;
115219}
115220
115221/* Create a new cursor for the pragma virtual table */
115222static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
115223  PragmaVtabCursor *pCsr;
115224  pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
115225  if( pCsr==0 ) return SQLITE_NOMEM;
115226  memset(pCsr, 0, sizeof(PragmaVtabCursor));
115227  pCsr->base.pVtab = pVtab;
115228  *ppCursor = &pCsr->base;
115229  return SQLITE_OK;
115230}
115231
115232/* Clear all content from pragma virtual table cursor. */
115233static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
115234  int i;
115235  sqlite3_finalize(pCsr->pPragma);
115236  pCsr->pPragma = 0;
115237  for(i=0; i<ArraySize(pCsr->azArg); i++){
115238    sqlite3_free(pCsr->azArg[i]);
115239    pCsr->azArg[i] = 0;
115240  }
115241}
115242
115243/* Close a pragma virtual table cursor */
115244static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
115245  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
115246  pragmaVtabCursorClear(pCsr);
115247  sqlite3_free(pCsr);
115248  return SQLITE_OK;
115249}
115250
115251/* Advance the pragma virtual table cursor to the next row */
115252static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
115253  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
115254  int rc = SQLITE_OK;
115255
115256  /* Increment the xRowid value */
115257  pCsr->iRowid++;
115258  assert( pCsr->pPragma );
115259  if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
115260    rc = sqlite3_finalize(pCsr->pPragma);
115261    pCsr->pPragma = 0;
115262    pragmaVtabCursorClear(pCsr);
115263  }
115264  return rc;
115265}
115266
115267/*
115268** Pragma virtual table module xFilter method.
115269*/
115270static int pragmaVtabFilter(
115271  sqlite3_vtab_cursor *pVtabCursor,
115272  int idxNum, const char *idxStr,
115273  int argc, sqlite3_value **argv
115274){
115275  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
115276  PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
115277  int rc;
115278  int i, j;
115279  StrAccum acc;
115280  char *zSql;
115281
115282  UNUSED_PARAMETER(idxNum);
115283  UNUSED_PARAMETER(idxStr);
115284  pragmaVtabCursorClear(pCsr);
115285  j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
115286  for(i=0; i<argc; i++, j++){
115287    assert( j<ArraySize(pCsr->azArg) );
115288    pCsr->azArg[j] = sqlite3_mprintf("%s", sqlite3_value_text(argv[i]));
115289    if( pCsr->azArg[j]==0 ){
115290      return SQLITE_NOMEM;
115291    }
115292  }
115293  sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
115294  sqlite3StrAccumAppendAll(&acc, "PRAGMA ");
115295  if( pCsr->azArg[1] ){
115296    sqlite3XPrintf(&acc, "%Q.", pCsr->azArg[1]);
115297  }
115298  sqlite3StrAccumAppendAll(&acc, pTab->pName->zName);
115299  if( pCsr->azArg[0] ){
115300    sqlite3XPrintf(&acc, "=%Q", pCsr->azArg[0]);
115301  }
115302  zSql = sqlite3StrAccumFinish(&acc);
115303  if( zSql==0 ) return SQLITE_NOMEM;
115304  rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
115305  sqlite3_free(zSql);
115306  if( rc!=SQLITE_OK ){
115307    pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
115308    return rc;
115309  }
115310  return pragmaVtabNext(pVtabCursor);
115311}
115312
115313/*
115314** Pragma virtual table module xEof method.
115315*/
115316static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
115317  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
115318  return (pCsr->pPragma==0);
115319}
115320
115321/* The xColumn method simply returns the corresponding column from
115322** the PRAGMA.
115323*/
115324static int pragmaVtabColumn(
115325  sqlite3_vtab_cursor *pVtabCursor,
115326  sqlite3_context *ctx,
115327  int i
115328){
115329  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
115330  PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
115331  if( i<pTab->iHidden ){
115332    sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
115333  }else{
115334    sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
115335  }
115336  return SQLITE_OK;
115337}
115338
115339/*
115340** Pragma virtual table module xRowid method.
115341*/
115342static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
115343  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
115344  *p = pCsr->iRowid;
115345  return SQLITE_OK;
115346}
115347
115348/* The pragma virtual table object */
115349static const sqlite3_module pragmaVtabModule = {
115350  0,                           /* iVersion */
115351  0,                           /* xCreate - create a table */
115352  pragmaVtabConnect,           /* xConnect - connect to an existing table */
115353  pragmaVtabBestIndex,         /* xBestIndex - Determine search strategy */
115354  pragmaVtabDisconnect,        /* xDisconnect - Disconnect from a table */
115355  0,                           /* xDestroy - Drop a table */
115356  pragmaVtabOpen,              /* xOpen - open a cursor */
115357  pragmaVtabClose,             /* xClose - close a cursor */
115358  pragmaVtabFilter,            /* xFilter - configure scan constraints */
115359  pragmaVtabNext,              /* xNext - advance a cursor */
115360  pragmaVtabEof,               /* xEof */
115361  pragmaVtabColumn,            /* xColumn - read data */
115362  pragmaVtabRowid,             /* xRowid - read data */
115363  0,                           /* xUpdate - write data */
115364  0,                           /* xBegin - begin transaction */
115365  0,                           /* xSync - sync transaction */
115366  0,                           /* xCommit - commit transaction */
115367  0,                           /* xRollback - rollback transaction */
115368  0,                           /* xFindFunction - function overloading */
115369  0,                           /* xRename - rename the table */
115370  0,                           /* xSavepoint */
115371  0,                           /* xRelease */
115372  0                            /* xRollbackTo */
115373};
115374
115375/*
115376** Check to see if zTabName is really the name of a pragma.  If it is,
115377** then register an eponymous virtual table for that pragma and return
115378** a pointer to the Module object for the new virtual table.
115379*/
115380SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
115381  const PragmaName *pName;
115382  assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
115383  pName = pragmaLocate(zName+7);
115384  if( pName==0 ) return 0;
115385  if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
115386  assert( sqlite3HashFind(&db->aModule, zName)==0 );
115387  return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
115388}
115389
115390#endif /* SQLITE_OMIT_VIRTUALTABLE */
115391
115392#endif /* SQLITE_OMIT_PRAGMA */
115393
115394/************** End of pragma.c **********************************************/
115395/************** Begin file prepare.c *****************************************/
115396/*
115397** 2005 May 25
115398**
115399** The author disclaims copyright to this source code.  In place of
115400** a legal notice, here is a blessing:
115401**
115402**    May you do good and not evil.
115403**    May you find forgiveness for yourself and forgive others.
115404**    May you share freely, never taking more than you give.
115405**
115406*************************************************************************
115407** This file contains the implementation of the sqlite3_prepare()
115408** interface, and routines that contribute to loading the database schema
115409** from disk.
115410*/
115411/* #include "sqliteInt.h" */
115412
115413/*
115414** Fill the InitData structure with an error message that indicates
115415** that the database is corrupt.
115416*/
115417static void corruptSchema(
115418  InitData *pData,     /* Initialization context */
115419  const char *zObj,    /* Object being parsed at the point of error */
115420  const char *zExtra   /* Error information */
115421){
115422  sqlite3 *db = pData->db;
115423  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
115424    char *z;
115425    if( zObj==0 ) zObj = "?";
115426    z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
115427    if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
115428    sqlite3DbFree(db, *pData->pzErrMsg);
115429    *pData->pzErrMsg = z;
115430  }
115431  pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
115432}
115433
115434/*
115435** This is the callback routine for the code that initializes the
115436** database.  See sqlite3Init() below for additional information.
115437** This routine is also called from the OP_ParseSchema opcode of the VDBE.
115438**
115439** Each callback contains the following information:
115440**
115441**     argv[0] = name of thing being created
115442**     argv[1] = root page number for table or index. 0 for trigger or view.
115443**     argv[2] = SQL text for the CREATE statement.
115444**
115445*/
115446SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
115447  InitData *pData = (InitData*)pInit;
115448  sqlite3 *db = pData->db;
115449  int iDb = pData->iDb;
115450
115451  assert( argc==3 );
115452  UNUSED_PARAMETER2(NotUsed, argc);
115453  assert( sqlite3_mutex_held(db->mutex) );
115454  DbClearProperty(db, iDb, DB_Empty);
115455  if( db->mallocFailed ){
115456    corruptSchema(pData, argv[0], 0);
115457    return 1;
115458  }
115459
115460  assert( iDb>=0 && iDb<db->nDb );
115461  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
115462  if( argv[1]==0 ){
115463    corruptSchema(pData, argv[0], 0);
115464  }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
115465    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
115466    ** But because db->init.busy is set to 1, no VDBE code is generated
115467    ** or executed.  All the parser does is build the internal data
115468    ** structures that describe the table, index, or view.
115469    */
115470    int rc;
115471    u8 saved_iDb = db->init.iDb;
115472    sqlite3_stmt *pStmt;
115473    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
115474
115475    assert( db->init.busy );
115476    db->init.iDb = iDb;
115477    db->init.newTnum = sqlite3Atoi(argv[1]);
115478    db->init.orphanTrigger = 0;
115479    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
115480    rc = db->errCode;
115481    assert( (rc&0xFF)==(rcp&0xFF) );
115482    db->init.iDb = saved_iDb;
115483    assert( saved_iDb==0 || (db->flags & SQLITE_Vacuum)!=0 );
115484    if( SQLITE_OK!=rc ){
115485      if( db->init.orphanTrigger ){
115486        assert( iDb==1 );
115487      }else{
115488        pData->rc = rc;
115489        if( rc==SQLITE_NOMEM ){
115490          sqlite3OomFault(db);
115491        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
115492          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
115493        }
115494      }
115495    }
115496    sqlite3_finalize(pStmt);
115497  }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
115498    corruptSchema(pData, argv[0], 0);
115499  }else{
115500    /* If the SQL column is blank it means this is an index that
115501    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
115502    ** constraint for a CREATE TABLE.  The index should have already
115503    ** been created when we processed the CREATE TABLE.  All we have
115504    ** to do here is record the root page number for that index.
115505    */
115506    Index *pIndex;
115507    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
115508    if( pIndex==0 ){
115509      /* This can occur if there exists an index on a TEMP table which
115510      ** has the same name as another index on a permanent index.  Since
115511      ** the permanent table is hidden by the TEMP table, we can also
115512      ** safely ignore the index on the permanent table.
115513      */
115514      /* Do Nothing */;
115515    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
115516      corruptSchema(pData, argv[0], "invalid rootpage");
115517    }
115518  }
115519  return 0;
115520}
115521
115522/*
115523** Attempt to read the database schema and initialize internal
115524** data structures for a single database file.  The index of the
115525** database file is given by iDb.  iDb==0 is used for the main
115526** database.  iDb==1 should never be used.  iDb>=2 is used for
115527** auxiliary databases.  Return one of the SQLITE_ error codes to
115528** indicate success or failure.
115529*/
115530static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
115531  int rc;
115532  int i;
115533#ifndef SQLITE_OMIT_DEPRECATED
115534  int size;
115535#endif
115536  Db *pDb;
115537  char const *azArg[4];
115538  int meta[5];
115539  InitData initData;
115540  const char *zMasterName;
115541  int openedTransaction = 0;
115542
115543  assert( iDb>=0 && iDb<db->nDb );
115544  assert( db->aDb[iDb].pSchema );
115545  assert( sqlite3_mutex_held(db->mutex) );
115546  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
115547
115548  /* Construct the in-memory representation schema tables (sqlite_master or
115549  ** sqlite_temp_master) by invoking the parser directly.  The appropriate
115550  ** table name will be inserted automatically by the parser so we can just
115551  ** use the abbreviation "x" here.  The parser will also automatically tag
115552  ** the schema table as read-only. */
115553  azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
115554  azArg[1] = "1";
115555  azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
115556                            "rootpage integer,sql text)";
115557  azArg[3] = 0;
115558  initData.db = db;
115559  initData.iDb = iDb;
115560  initData.rc = SQLITE_OK;
115561  initData.pzErrMsg = pzErrMsg;
115562  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
115563  if( initData.rc ){
115564    rc = initData.rc;
115565    goto error_out;
115566  }
115567
115568  /* Create a cursor to hold the database open
115569  */
115570  pDb = &db->aDb[iDb];
115571  if( pDb->pBt==0 ){
115572    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
115573      DbSetProperty(db, 1, DB_SchemaLoaded);
115574    }
115575    return SQLITE_OK;
115576  }
115577
115578  /* If there is not already a read-only (or read-write) transaction opened
115579  ** on the b-tree database, open one now. If a transaction is opened, it
115580  ** will be closed before this function returns.  */
115581  sqlite3BtreeEnter(pDb->pBt);
115582  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
115583    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
115584    if( rc!=SQLITE_OK ){
115585      sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
115586      goto initone_error_out;
115587    }
115588    openedTransaction = 1;
115589  }
115590
115591  /* Get the database meta information.
115592  **
115593  ** Meta values are as follows:
115594  **    meta[0]   Schema cookie.  Changes with each schema change.
115595  **    meta[1]   File format of schema layer.
115596  **    meta[2]   Size of the page cache.
115597  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
115598  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
115599  **    meta[5]   User version
115600  **    meta[6]   Incremental vacuum mode
115601  **    meta[7]   unused
115602  **    meta[8]   unused
115603  **    meta[9]   unused
115604  **
115605  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
115606  ** the possible values of meta[4].
115607  */
115608  for(i=0; i<ArraySize(meta); i++){
115609    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
115610  }
115611  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
115612
115613  /* If opening a non-empty database, check the text encoding. For the
115614  ** main database, set sqlite3.enc to the encoding of the main database.
115615  ** For an attached db, it is an error if the encoding is not the same
115616  ** as sqlite3.enc.
115617  */
115618  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
115619    if( iDb==0 ){
115620#ifndef SQLITE_OMIT_UTF16
115621      u8 encoding;
115622      /* If opening the main database, set ENC(db). */
115623      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
115624      if( encoding==0 ) encoding = SQLITE_UTF8;
115625      ENC(db) = encoding;
115626#else
115627      ENC(db) = SQLITE_UTF8;
115628#endif
115629    }else{
115630      /* If opening an attached database, the encoding much match ENC(db) */
115631      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
115632        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
115633            " text encoding as main database");
115634        rc = SQLITE_ERROR;
115635        goto initone_error_out;
115636      }
115637    }
115638  }else{
115639    DbSetProperty(db, iDb, DB_Empty);
115640  }
115641  pDb->pSchema->enc = ENC(db);
115642
115643  if( pDb->pSchema->cache_size==0 ){
115644#ifndef SQLITE_OMIT_DEPRECATED
115645    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
115646    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
115647    pDb->pSchema->cache_size = size;
115648#else
115649    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
115650#endif
115651    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
115652  }
115653
115654  /*
115655  ** file_format==1    Version 3.0.0.
115656  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
115657  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
115658  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
115659  */
115660  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
115661  if( pDb->pSchema->file_format==0 ){
115662    pDb->pSchema->file_format = 1;
115663  }
115664  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
115665    sqlite3SetString(pzErrMsg, db, "unsupported file format");
115666    rc = SQLITE_CORRUPT_BKPT; // Android Change from "rc = SQLITE_ERROR;";
115667    goto initone_error_out;
115668  }
115669
115670  /* Ticket #2804:  When we open a database in the newer file format,
115671  ** clear the legacy_file_format pragma flag so that a VACUUM will
115672  ** not downgrade the database and thus invalidate any descending
115673  ** indices that the user might have created.
115674  */
115675  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
115676    db->flags &= ~SQLITE_LegacyFileFmt;
115677  }
115678
115679  /* Read the schema information out of the schema tables
115680  */
115681  assert( db->init.busy );
115682  {
115683    char *zSql;
115684    zSql = sqlite3MPrintf(db,
115685        "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
115686        db->aDb[iDb].zDbSName, zMasterName);
115687#ifndef SQLITE_OMIT_AUTHORIZATION
115688    {
115689      sqlite3_xauth xAuth;
115690      xAuth = db->xAuth;
115691      db->xAuth = 0;
115692#endif
115693      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
115694#ifndef SQLITE_OMIT_AUTHORIZATION
115695      db->xAuth = xAuth;
115696    }
115697#endif
115698    if( rc==SQLITE_OK ) rc = initData.rc;
115699    sqlite3DbFree(db, zSql);
115700#ifndef SQLITE_OMIT_ANALYZE
115701    if( rc==SQLITE_OK ){
115702      sqlite3AnalysisLoad(db, iDb);
115703    }
115704#endif
115705  }
115706  if( db->mallocFailed ){
115707    rc = SQLITE_NOMEM_BKPT;
115708    sqlite3ResetAllSchemasOfConnection(db);
115709  }
115710  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
115711    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
115712    ** the schema loaded, even if errors occurred. In this situation the
115713    ** current sqlite3_prepare() operation will fail, but the following one
115714    ** will attempt to compile the supplied statement against whatever subset
115715    ** of the schema was loaded before the error occurred. The primary
115716    ** purpose of this is to allow access to the sqlite_master table
115717    ** even when its contents have been corrupted.
115718    */
115719    DbSetProperty(db, iDb, DB_SchemaLoaded);
115720    rc = SQLITE_OK;
115721  }
115722
115723  /* Jump here for an error that occurs after successfully allocating
115724  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
115725  ** before that point, jump to error_out.
115726  */
115727initone_error_out:
115728  if( openedTransaction ){
115729    sqlite3BtreeCommit(pDb->pBt);
115730  }
115731  sqlite3BtreeLeave(pDb->pBt);
115732
115733error_out:
115734  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
115735    sqlite3OomFault(db);
115736  }
115737  return rc;
115738}
115739
115740/*
115741** Initialize all database files - the main database file, the file
115742** used to store temporary tables, and any additional database files
115743** created using ATTACH statements.  Return a success code.  If an
115744** error occurs, write an error message into *pzErrMsg.
115745**
115746** After a database is initialized, the DB_SchemaLoaded bit is set
115747** bit is set in the flags field of the Db structure. If the database
115748** file was of zero-length, then the DB_Empty flag is also set.
115749*/
115750SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
115751  int i, rc;
115752  int commit_internal = !(db->flags&SQLITE_InternChanges);
115753
115754  assert( sqlite3_mutex_held(db->mutex) );
115755  assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
115756  assert( db->init.busy==0 );
115757  rc = SQLITE_OK;
115758  db->init.busy = 1;
115759  ENC(db) = SCHEMA_ENC(db);
115760  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
115761    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
115762    rc = sqlite3InitOne(db, i, pzErrMsg);
115763    if( rc ){
115764      sqlite3ResetOneSchema(db, i);
115765    }
115766  }
115767
115768  /* Once all the other databases have been initialized, load the schema
115769  ** for the TEMP database. This is loaded last, as the TEMP database
115770  ** schema may contain references to objects in other databases.
115771  */
115772#ifndef SQLITE_OMIT_TEMPDB
115773  assert( db->nDb>1 );
115774  if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
115775    rc = sqlite3InitOne(db, 1, pzErrMsg);
115776    if( rc ){
115777      sqlite3ResetOneSchema(db, 1);
115778    }
115779  }
115780#endif
115781
115782  db->init.busy = 0;
115783  if( rc==SQLITE_OK && commit_internal ){
115784    sqlite3CommitInternalChanges(db);
115785  }
115786
115787  return rc;
115788}
115789
115790/*
115791** This routine is a no-op if the database schema is already initialized.
115792** Otherwise, the schema is loaded. An error code is returned.
115793*/
115794SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
115795  int rc = SQLITE_OK;
115796  sqlite3 *db = pParse->db;
115797  assert( sqlite3_mutex_held(db->mutex) );
115798  if( !db->init.busy ){
115799    rc = sqlite3Init(db, &pParse->zErrMsg);
115800  }
115801  if( rc!=SQLITE_OK ){
115802    pParse->rc = rc;
115803    pParse->nErr++;
115804  }
115805  return rc;
115806}
115807
115808
115809/*
115810** Check schema cookies in all databases.  If any cookie is out
115811** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
115812** make no changes to pParse->rc.
115813*/
115814static void schemaIsValid(Parse *pParse){
115815  sqlite3 *db = pParse->db;
115816  int iDb;
115817  int rc;
115818  int cookie;
115819
115820  assert( pParse->checkSchema );
115821  assert( sqlite3_mutex_held(db->mutex) );
115822  for(iDb=0; iDb<db->nDb; iDb++){
115823    int openedTransaction = 0;         /* True if a transaction is opened */
115824    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
115825    if( pBt==0 ) continue;
115826
115827    /* If there is not already a read-only (or read-write) transaction opened
115828    ** on the b-tree database, open one now. If a transaction is opened, it
115829    ** will be closed immediately after reading the meta-value. */
115830    if( !sqlite3BtreeIsInReadTrans(pBt) ){
115831      rc = sqlite3BtreeBeginTrans(pBt, 0);
115832      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
115833        sqlite3OomFault(db);
115834      }
115835      if( rc!=SQLITE_OK ) return;
115836      openedTransaction = 1;
115837    }
115838
115839    /* Read the schema cookie from the database. If it does not match the
115840    ** value stored as part of the in-memory schema representation,
115841    ** set Parse.rc to SQLITE_SCHEMA. */
115842    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
115843    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
115844    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
115845      sqlite3ResetOneSchema(db, iDb);
115846      pParse->rc = SQLITE_SCHEMA;
115847    }
115848
115849    /* Close the transaction, if one was opened. */
115850    if( openedTransaction ){
115851      sqlite3BtreeCommit(pBt);
115852    }
115853  }
115854}
115855
115856/*
115857** Convert a schema pointer into the iDb index that indicates
115858** which database file in db->aDb[] the schema refers to.
115859**
115860** If the same database is attached more than once, the first
115861** attached database is returned.
115862*/
115863SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
115864  int i = -1000000;
115865
115866  /* If pSchema is NULL, then return -1000000. This happens when code in
115867  ** expr.c is trying to resolve a reference to a transient table (i.e. one
115868  ** created by a sub-select). In this case the return value of this
115869  ** function should never be used.
115870  **
115871  ** We return -1000000 instead of the more usual -1 simply because using
115872  ** -1000000 as the incorrect index into db->aDb[] is much
115873  ** more likely to cause a segfault than -1 (of course there are assert()
115874  ** statements too, but it never hurts to play the odds).
115875  */
115876  assert( sqlite3_mutex_held(db->mutex) );
115877  if( pSchema ){
115878    for(i=0; ALWAYS(i<db->nDb); i++){
115879      if( db->aDb[i].pSchema==pSchema ){
115880        break;
115881      }
115882    }
115883    assert( i>=0 && i<db->nDb );
115884  }
115885  return i;
115886}
115887
115888/*
115889** Free all memory allocations in the pParse object
115890*/
115891SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
115892  if( pParse ){
115893    sqlite3 *db = pParse->db;
115894    sqlite3DbFree(db, pParse->aLabel);
115895    sqlite3ExprListDelete(db, pParse->pConstExpr);
115896    if( db ){
115897      assert( db->lookaside.bDisable >= pParse->disableLookaside );
115898      db->lookaside.bDisable -= pParse->disableLookaside;
115899    }
115900    pParse->disableLookaside = 0;
115901  }
115902}
115903
115904/*
115905** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
115906*/
115907static int sqlite3Prepare(
115908  sqlite3 *db,              /* Database handle. */
115909  const char *zSql,         /* UTF-8 encoded SQL statement. */
115910  int nBytes,               /* Length of zSql in bytes. */
115911  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
115912  Vdbe *pReprepare,         /* VM being reprepared */
115913  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
115914  const char **pzTail       /* OUT: End of parsed string */
115915){
115916  char *zErrMsg = 0;        /* Error message */
115917  int rc = SQLITE_OK;       /* Result code */
115918  int i;                    /* Loop counter */
115919  Parse sParse;             /* Parsing context */
115920
115921  memset(&sParse, 0, PARSE_HDR_SZ);
115922  memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
115923  sParse.pReprepare = pReprepare;
115924  assert( ppStmt && *ppStmt==0 );
115925  /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
115926  assert( sqlite3_mutex_held(db->mutex) );
115927
115928  /* Check to verify that it is possible to get a read lock on all
115929  ** database schemas.  The inability to get a read lock indicates that
115930  ** some other database connection is holding a write-lock, which in
115931  ** turn means that the other connection has made uncommitted changes
115932  ** to the schema.
115933  **
115934  ** Were we to proceed and prepare the statement against the uncommitted
115935  ** schema changes and if those schema changes are subsequently rolled
115936  ** back and different changes are made in their place, then when this
115937  ** prepared statement goes to run the schema cookie would fail to detect
115938  ** the schema change.  Disaster would follow.
115939  **
115940  ** This thread is currently holding mutexes on all Btrees (because
115941  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
115942  ** is not possible for another thread to start a new schema change
115943  ** while this routine is running.  Hence, we do not need to hold
115944  ** locks on the schema, we just need to make sure nobody else is
115945  ** holding them.
115946  **
115947  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
115948  ** but it does *not* override schema lock detection, so this all still
115949  ** works even if READ_UNCOMMITTED is set.
115950  */
115951  for(i=0; i<db->nDb; i++) {
115952    Btree *pBt = db->aDb[i].pBt;
115953    if( pBt ){
115954      assert( sqlite3BtreeHoldsMutex(pBt) );
115955      rc = sqlite3BtreeSchemaLocked(pBt);
115956      if( rc ){
115957        const char *zDb = db->aDb[i].zDbSName;
115958        sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
115959        testcase( db->flags & SQLITE_ReadUncommitted );
115960        goto end_prepare;
115961      }
115962    }
115963  }
115964
115965  sqlite3VtabUnlockList(db);
115966
115967  sParse.db = db;
115968  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
115969    char *zSqlCopy;
115970    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
115971    testcase( nBytes==mxLen );
115972    testcase( nBytes==mxLen+1 );
115973    if( nBytes>mxLen ){
115974      sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
115975      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
115976      goto end_prepare;
115977    }
115978    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
115979    if( zSqlCopy ){
115980      sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
115981      sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
115982      sqlite3DbFree(db, zSqlCopy);
115983    }else{
115984      sParse.zTail = &zSql[nBytes];
115985    }
115986  }else{
115987    sqlite3RunParser(&sParse, zSql, &zErrMsg);
115988  }
115989  assert( 0==sParse.nQueryLoop );
115990
115991  if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
115992  if( sParse.checkSchema ){
115993    schemaIsValid(&sParse);
115994  }
115995  if( db->mallocFailed ){
115996    sParse.rc = SQLITE_NOMEM_BKPT;
115997  }
115998  if( pzTail ){
115999    *pzTail = sParse.zTail;
116000  }
116001  rc = sParse.rc;
116002
116003#ifndef SQLITE_OMIT_EXPLAIN
116004  if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
116005    static const char * const azColName[] = {
116006       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
116007       "selectid", "order", "from", "detail"
116008    };
116009    int iFirst, mx;
116010    if( sParse.explain==2 ){
116011      sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
116012      iFirst = 8;
116013      mx = 12;
116014    }else{
116015      sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
116016      iFirst = 0;
116017      mx = 8;
116018    }
116019    for(i=iFirst; i<mx; i++){
116020      sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
116021                            azColName[i], SQLITE_STATIC);
116022    }
116023  }
116024#endif
116025
116026  if( db->init.busy==0 ){
116027    Vdbe *pVdbe = sParse.pVdbe;
116028    sqlite3VdbeSetSql(pVdbe, zSql, (int)(sParse.zTail-zSql), saveSqlFlag);
116029  }
116030  if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
116031    sqlite3VdbeFinalize(sParse.pVdbe);
116032    assert(!(*ppStmt));
116033  }else{
116034    *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
116035  }
116036
116037  if( zErrMsg ){
116038    sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
116039    sqlite3DbFree(db, zErrMsg);
116040  }else{
116041    sqlite3Error(db, rc);
116042  }
116043
116044  /* Delete any TriggerPrg structures allocated while parsing this statement. */
116045  while( sParse.pTriggerPrg ){
116046    TriggerPrg *pT = sParse.pTriggerPrg;
116047    sParse.pTriggerPrg = pT->pNext;
116048    sqlite3DbFree(db, pT);
116049  }
116050
116051end_prepare:
116052
116053  sqlite3ParserReset(&sParse);
116054  rc = sqlite3ApiExit(db, rc);
116055  assert( (rc&db->errMask)==rc );
116056  return rc;
116057}
116058static int sqlite3LockAndPrepare(
116059  sqlite3 *db,              /* Database handle. */
116060  const char *zSql,         /* UTF-8 encoded SQL statement. */
116061  int nBytes,               /* Length of zSql in bytes. */
116062  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
116063  Vdbe *pOld,               /* VM being reprepared */
116064  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
116065  const char **pzTail       /* OUT: End of parsed string */
116066){
116067  int rc;
116068
116069#ifdef SQLITE_ENABLE_API_ARMOR
116070  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
116071#endif
116072  *ppStmt = 0;
116073  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
116074    return SQLITE_MISUSE_BKPT;
116075  }
116076  sqlite3_mutex_enter(db->mutex);
116077  sqlite3BtreeEnterAll(db);
116078  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
116079  if( rc==SQLITE_SCHEMA ){
116080    sqlite3_finalize(*ppStmt);
116081    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
116082  }
116083  sqlite3BtreeLeaveAll(db);
116084  sqlite3_mutex_leave(db->mutex);
116085  assert( rc==SQLITE_OK || *ppStmt==0 );
116086  return rc;
116087}
116088
116089/*
116090** Rerun the compilation of a statement after a schema change.
116091**
116092** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
116093** if the statement cannot be recompiled because another connection has
116094** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
116095** occurs, return SQLITE_SCHEMA.
116096*/
116097SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
116098  int rc;
116099  sqlite3_stmt *pNew;
116100  const char *zSql;
116101  sqlite3 *db;
116102
116103  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
116104  zSql = sqlite3_sql((sqlite3_stmt *)p);
116105  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
116106  db = sqlite3VdbeDb(p);
116107  assert( sqlite3_mutex_held(db->mutex) );
116108  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
116109  if( rc ){
116110    if( rc==SQLITE_NOMEM ){
116111      sqlite3OomFault(db);
116112    }
116113    assert( pNew==0 );
116114    return rc;
116115  }else{
116116    assert( pNew!=0 );
116117  }
116118  sqlite3VdbeSwap((Vdbe*)pNew, p);
116119  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
116120  sqlite3VdbeResetStepResult((Vdbe*)pNew);
116121  sqlite3VdbeFinalize((Vdbe*)pNew);
116122  return SQLITE_OK;
116123}
116124
116125
116126/*
116127** Two versions of the official API.  Legacy and new use.  In the legacy
116128** version, the original SQL text is not saved in the prepared statement
116129** and so if a schema change occurs, SQLITE_SCHEMA is returned by
116130** sqlite3_step().  In the new version, the original SQL text is retained
116131** and the statement is automatically recompiled if an schema change
116132** occurs.
116133*/
116134SQLITE_API int sqlite3_prepare(
116135  sqlite3 *db,              /* Database handle. */
116136  const char *zSql,         /* UTF-8 encoded SQL statement. */
116137  int nBytes,               /* Length of zSql in bytes. */
116138  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
116139  const char **pzTail       /* OUT: End of parsed string */
116140){
116141  int rc;
116142  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
116143  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
116144  return rc;
116145}
116146SQLITE_API int sqlite3_prepare_v2(
116147  sqlite3 *db,              /* Database handle. */
116148  const char *zSql,         /* UTF-8 encoded SQL statement. */
116149  int nBytes,               /* Length of zSql in bytes. */
116150  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
116151  const char **pzTail       /* OUT: End of parsed string */
116152){
116153  int rc;
116154  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
116155  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
116156  return rc;
116157}
116158
116159
116160#ifndef SQLITE_OMIT_UTF16
116161/*
116162** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
116163*/
116164static int sqlite3Prepare16(
116165  sqlite3 *db,              /* Database handle. */
116166  const void *zSql,         /* UTF-16 encoded SQL statement. */
116167  int nBytes,               /* Length of zSql in bytes. */
116168  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
116169  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
116170  const void **pzTail       /* OUT: End of parsed string */
116171){
116172  /* This function currently works by first transforming the UTF-16
116173  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
116174  ** tricky bit is figuring out the pointer to return in *pzTail.
116175  */
116176  char *zSql8;
116177  const char *zTail8 = 0;
116178  int rc = SQLITE_OK;
116179
116180#ifdef SQLITE_ENABLE_API_ARMOR
116181  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
116182#endif
116183  *ppStmt = 0;
116184  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
116185    return SQLITE_MISUSE_BKPT;
116186  }
116187  if( nBytes>=0 ){
116188    int sz;
116189    const char *z = (const char*)zSql;
116190    for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
116191    nBytes = sz;
116192  }
116193  sqlite3_mutex_enter(db->mutex);
116194  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
116195  if( zSql8 ){
116196    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
116197  }
116198
116199  if( zTail8 && pzTail ){
116200    /* If sqlite3_prepare returns a tail pointer, we calculate the
116201    ** equivalent pointer into the UTF-16 string by counting the unicode
116202    ** characters between zSql8 and zTail8, and then returning a pointer
116203    ** the same number of characters into the UTF-16 string.
116204    */
116205    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
116206    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
116207  }
116208  sqlite3DbFree(db, zSql8);
116209  rc = sqlite3ApiExit(db, rc);
116210  sqlite3_mutex_leave(db->mutex);
116211  return rc;
116212}
116213
116214/*
116215** Two versions of the official API.  Legacy and new use.  In the legacy
116216** version, the original SQL text is not saved in the prepared statement
116217** and so if a schema change occurs, SQLITE_SCHEMA is returned by
116218** sqlite3_step().  In the new version, the original SQL text is retained
116219** and the statement is automatically recompiled if an schema change
116220** occurs.
116221*/
116222SQLITE_API int sqlite3_prepare16(
116223  sqlite3 *db,              /* Database handle. */
116224  const void *zSql,         /* UTF-16 encoded SQL statement. */
116225  int nBytes,               /* Length of zSql in bytes. */
116226  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
116227  const void **pzTail       /* OUT: End of parsed string */
116228){
116229  int rc;
116230  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
116231  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
116232  return rc;
116233}
116234SQLITE_API int sqlite3_prepare16_v2(
116235  sqlite3 *db,              /* Database handle. */
116236  const void *zSql,         /* UTF-16 encoded SQL statement. */
116237  int nBytes,               /* Length of zSql in bytes. */
116238  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
116239  const void **pzTail       /* OUT: End of parsed string */
116240){
116241  int rc;
116242  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
116243  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
116244  return rc;
116245}
116246
116247#endif /* SQLITE_OMIT_UTF16 */
116248
116249/************** End of prepare.c *********************************************/
116250/************** Begin file select.c ******************************************/
116251/*
116252** 2001 September 15
116253**
116254** The author disclaims copyright to this source code.  In place of
116255** a legal notice, here is a blessing:
116256**
116257**    May you do good and not evil.
116258**    May you find forgiveness for yourself and forgive others.
116259**    May you share freely, never taking more than you give.
116260**
116261*************************************************************************
116262** This file contains C code routines that are called by the parser
116263** to handle SELECT statements in SQLite.
116264*/
116265/* #include "sqliteInt.h" */
116266
116267/*
116268** Trace output macros
116269*/
116270#if SELECTTRACE_ENABLED
116271/***/ int sqlite3SelectTrace = 0;
116272# define SELECTTRACE(K,P,S,X)  \
116273  if(sqlite3SelectTrace&(K))   \
116274    sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
116275        (S)->zSelName,(S)),\
116276    sqlite3DebugPrintf X
116277#else
116278# define SELECTTRACE(K,P,S,X)
116279#endif
116280
116281
116282/*
116283** An instance of the following object is used to record information about
116284** how to process the DISTINCT keyword, to simplify passing that information
116285** into the selectInnerLoop() routine.
116286*/
116287typedef struct DistinctCtx DistinctCtx;
116288struct DistinctCtx {
116289  u8 isTnct;      /* True if the DISTINCT keyword is present */
116290  u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
116291  int tabTnct;    /* Ephemeral table used for DISTINCT processing */
116292  int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
116293};
116294
116295/*
116296** An instance of the following object is used to record information about
116297** the ORDER BY (or GROUP BY) clause of query is being coded.
116298*/
116299typedef struct SortCtx SortCtx;
116300struct SortCtx {
116301  ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
116302  int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
116303  int iECursor;         /* Cursor number for the sorter */
116304  int regReturn;        /* Register holding block-output return address */
116305  int labelBkOut;       /* Start label for the block-output subroutine */
116306  int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
116307  int labelDone;        /* Jump here when done, ex: LIMIT reached */
116308  u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
116309  u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
116310};
116311#define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
116312
116313/*
116314** Delete all the content of a Select structure.  Deallocate the structure
116315** itself only if bFree is true.
116316*/
116317static void clearSelect(sqlite3 *db, Select *p, int bFree){
116318  while( p ){
116319    Select *pPrior = p->pPrior;
116320    sqlite3ExprListDelete(db, p->pEList);
116321    sqlite3SrcListDelete(db, p->pSrc);
116322    sqlite3ExprDelete(db, p->pWhere);
116323    sqlite3ExprListDelete(db, p->pGroupBy);
116324    sqlite3ExprDelete(db, p->pHaving);
116325    sqlite3ExprListDelete(db, p->pOrderBy);
116326    sqlite3ExprDelete(db, p->pLimit);
116327    sqlite3ExprDelete(db, p->pOffset);
116328    if( p->pWith ) sqlite3WithDelete(db, p->pWith);
116329    if( bFree ) sqlite3DbFree(db, p);
116330    p = pPrior;
116331    bFree = 1;
116332  }
116333}
116334
116335/*
116336** Initialize a SelectDest structure.
116337*/
116338SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
116339  pDest->eDest = (u8)eDest;
116340  pDest->iSDParm = iParm;
116341  pDest->zAffSdst = 0;
116342  pDest->iSdst = 0;
116343  pDest->nSdst = 0;
116344}
116345
116346
116347/*
116348** Allocate a new Select structure and return a pointer to that
116349** structure.
116350*/
116351SQLITE_PRIVATE Select *sqlite3SelectNew(
116352  Parse *pParse,        /* Parsing context */
116353  ExprList *pEList,     /* which columns to include in the result */
116354  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
116355  Expr *pWhere,         /* the WHERE clause */
116356  ExprList *pGroupBy,   /* the GROUP BY clause */
116357  Expr *pHaving,        /* the HAVING clause */
116358  ExprList *pOrderBy,   /* the ORDER BY clause */
116359  u32 selFlags,         /* Flag parameters, such as SF_Distinct */
116360  Expr *pLimit,         /* LIMIT value.  NULL means not used */
116361  Expr *pOffset         /* OFFSET value.  NULL means no offset */
116362){
116363  Select *pNew;
116364  Select standin;
116365  sqlite3 *db = pParse->db;
116366  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
116367  if( pNew==0 ){
116368    assert( db->mallocFailed );
116369    pNew = &standin;
116370  }
116371  if( pEList==0 ){
116372    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0));
116373  }
116374  pNew->pEList = pEList;
116375  pNew->op = TK_SELECT;
116376  pNew->selFlags = selFlags;
116377  pNew->iLimit = 0;
116378  pNew->iOffset = 0;
116379#if SELECTTRACE_ENABLED
116380  pNew->zSelName[0] = 0;
116381#endif
116382  pNew->addrOpenEphm[0] = -1;
116383  pNew->addrOpenEphm[1] = -1;
116384  pNew->nSelectRow = 0;
116385  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
116386  pNew->pSrc = pSrc;
116387  pNew->pWhere = pWhere;
116388  pNew->pGroupBy = pGroupBy;
116389  pNew->pHaving = pHaving;
116390  pNew->pOrderBy = pOrderBy;
116391  pNew->pPrior = 0;
116392  pNew->pNext = 0;
116393  pNew->pLimit = pLimit;
116394  pNew->pOffset = pOffset;
116395  pNew->pWith = 0;
116396  assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
116397  if( db->mallocFailed ) {
116398    clearSelect(db, pNew, pNew!=&standin);
116399    pNew = 0;
116400  }else{
116401    assert( pNew->pSrc!=0 || pParse->nErr>0 );
116402  }
116403  assert( pNew!=&standin );
116404  return pNew;
116405}
116406
116407#if SELECTTRACE_ENABLED
116408/*
116409** Set the name of a Select object
116410*/
116411SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
116412  if( p && zName ){
116413    sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
116414  }
116415}
116416#endif
116417
116418
116419/*
116420** Delete the given Select structure and all of its substructures.
116421*/
116422SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
116423  if( p ) clearSelect(db, p, 1);
116424}
116425
116426/*
116427** Return a pointer to the right-most SELECT statement in a compound.
116428*/
116429static Select *findRightmost(Select *p){
116430  while( p->pNext ) p = p->pNext;
116431  return p;
116432}
116433
116434/*
116435** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
116436** type of join.  Return an integer constant that expresses that type
116437** in terms of the following bit values:
116438**
116439**     JT_INNER
116440**     JT_CROSS
116441**     JT_OUTER
116442**     JT_NATURAL
116443**     JT_LEFT
116444**     JT_RIGHT
116445**
116446** A full outer join is the combination of JT_LEFT and JT_RIGHT.
116447**
116448** If an illegal or unsupported join type is seen, then still return
116449** a join type, but put an error in the pParse structure.
116450*/
116451SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
116452  int jointype = 0;
116453  Token *apAll[3];
116454  Token *p;
116455                             /*   0123456789 123456789 123456789 123 */
116456  static const char zKeyText[] = "naturaleftouterightfullinnercross";
116457  static const struct {
116458    u8 i;        /* Beginning of keyword text in zKeyText[] */
116459    u8 nChar;    /* Length of the keyword in characters */
116460    u8 code;     /* Join type mask */
116461  } aKeyword[] = {
116462    /* natural */ { 0,  7, JT_NATURAL                },
116463    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
116464    /* outer   */ { 10, 5, JT_OUTER                  },
116465    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
116466    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
116467    /* inner   */ { 23, 5, JT_INNER                  },
116468    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
116469  };
116470  int i, j;
116471  apAll[0] = pA;
116472  apAll[1] = pB;
116473  apAll[2] = pC;
116474  for(i=0; i<3 && apAll[i]; i++){
116475    p = apAll[i];
116476    for(j=0; j<ArraySize(aKeyword); j++){
116477      if( p->n==aKeyword[j].nChar
116478          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
116479        jointype |= aKeyword[j].code;
116480        break;
116481      }
116482    }
116483    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
116484    if( j>=ArraySize(aKeyword) ){
116485      jointype |= JT_ERROR;
116486      break;
116487    }
116488  }
116489  if(
116490     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
116491     (jointype & JT_ERROR)!=0
116492  ){
116493    const char *zSp = " ";
116494    assert( pB!=0 );
116495    if( pC==0 ){ zSp++; }
116496    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
116497       "%T %T%s%T", pA, pB, zSp, pC);
116498    jointype = JT_INNER;
116499  }else if( (jointype & JT_OUTER)!=0
116500         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
116501    sqlite3ErrorMsg(pParse,
116502      "RIGHT and FULL OUTER JOINs are not currently supported");
116503    jointype = JT_INNER;
116504  }
116505  return jointype;
116506}
116507
116508/*
116509** Return the index of a column in a table.  Return -1 if the column
116510** is not contained in the table.
116511*/
116512static int columnIndex(Table *pTab, const char *zCol){
116513  int i;
116514  for(i=0; i<pTab->nCol; i++){
116515    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
116516  }
116517  return -1;
116518}
116519
116520/*
116521** Search the first N tables in pSrc, from left to right, looking for a
116522** table that has a column named zCol.
116523**
116524** When found, set *piTab and *piCol to the table index and column index
116525** of the matching column and return TRUE.
116526**
116527** If not found, return FALSE.
116528*/
116529static int tableAndColumnIndex(
116530  SrcList *pSrc,       /* Array of tables to search */
116531  int N,               /* Number of tables in pSrc->a[] to search */
116532  const char *zCol,    /* Name of the column we are looking for */
116533  int *piTab,          /* Write index of pSrc->a[] here */
116534  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
116535){
116536  int i;               /* For looping over tables in pSrc */
116537  int iCol;            /* Index of column matching zCol */
116538
116539  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
116540  for(i=0; i<N; i++){
116541    iCol = columnIndex(pSrc->a[i].pTab, zCol);
116542    if( iCol>=0 ){
116543      if( piTab ){
116544        *piTab = i;
116545        *piCol = iCol;
116546      }
116547      return 1;
116548    }
116549  }
116550  return 0;
116551}
116552
116553/*
116554** This function is used to add terms implied by JOIN syntax to the
116555** WHERE clause expression of a SELECT statement. The new term, which
116556** is ANDed with the existing WHERE clause, is of the form:
116557**
116558**    (tab1.col1 = tab2.col2)
116559**
116560** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
116561** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
116562** column iColRight of tab2.
116563*/
116564static void addWhereTerm(
116565  Parse *pParse,                  /* Parsing context */
116566  SrcList *pSrc,                  /* List of tables in FROM clause */
116567  int iLeft,                      /* Index of first table to join in pSrc */
116568  int iColLeft,                   /* Index of column in first table */
116569  int iRight,                     /* Index of second table in pSrc */
116570  int iColRight,                  /* Index of column in second table */
116571  int isOuterJoin,                /* True if this is an OUTER join */
116572  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
116573){
116574  sqlite3 *db = pParse->db;
116575  Expr *pE1;
116576  Expr *pE2;
116577  Expr *pEq;
116578
116579  assert( iLeft<iRight );
116580  assert( pSrc->nSrc>iRight );
116581  assert( pSrc->a[iLeft].pTab );
116582  assert( pSrc->a[iRight].pTab );
116583
116584  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
116585  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
116586
116587  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
116588  if( pEq && isOuterJoin ){
116589    ExprSetProperty(pEq, EP_FromJoin);
116590    assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
116591    ExprSetVVAProperty(pEq, EP_NoReduce);
116592    pEq->iRightJoinTable = (i16)pE2->iTable;
116593  }
116594  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
116595}
116596
116597/*
116598** Set the EP_FromJoin property on all terms of the given expression.
116599** And set the Expr.iRightJoinTable to iTable for every term in the
116600** expression.
116601**
116602** The EP_FromJoin property is used on terms of an expression to tell
116603** the LEFT OUTER JOIN processing logic that this term is part of the
116604** join restriction specified in the ON or USING clause and not a part
116605** of the more general WHERE clause.  These terms are moved over to the
116606** WHERE clause during join processing but we need to remember that they
116607** originated in the ON or USING clause.
116608**
116609** The Expr.iRightJoinTable tells the WHERE clause processing that the
116610** expression depends on table iRightJoinTable even if that table is not
116611** explicitly mentioned in the expression.  That information is needed
116612** for cases like this:
116613**
116614**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
116615**
116616** The where clause needs to defer the handling of the t1.x=5
116617** term until after the t2 loop of the join.  In that way, a
116618** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
116619** defer the handling of t1.x=5, it will be processed immediately
116620** after the t1 loop and rows with t1.x!=5 will never appear in
116621** the output, which is incorrect.
116622*/
116623static void setJoinExpr(Expr *p, int iTable){
116624  while( p ){
116625    ExprSetProperty(p, EP_FromJoin);
116626    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
116627    ExprSetVVAProperty(p, EP_NoReduce);
116628    p->iRightJoinTable = (i16)iTable;
116629    if( p->op==TK_FUNCTION && p->x.pList ){
116630      int i;
116631      for(i=0; i<p->x.pList->nExpr; i++){
116632        setJoinExpr(p->x.pList->a[i].pExpr, iTable);
116633      }
116634    }
116635    setJoinExpr(p->pLeft, iTable);
116636    p = p->pRight;
116637  }
116638}
116639
116640/*
116641** This routine processes the join information for a SELECT statement.
116642** ON and USING clauses are converted into extra terms of the WHERE clause.
116643** NATURAL joins also create extra WHERE clause terms.
116644**
116645** The terms of a FROM clause are contained in the Select.pSrc structure.
116646** The left most table is the first entry in Select.pSrc.  The right-most
116647** table is the last entry.  The join operator is held in the entry to
116648** the left.  Thus entry 0 contains the join operator for the join between
116649** entries 0 and 1.  Any ON or USING clauses associated with the join are
116650** also attached to the left entry.
116651**
116652** This routine returns the number of errors encountered.
116653*/
116654static int sqliteProcessJoin(Parse *pParse, Select *p){
116655  SrcList *pSrc;                  /* All tables in the FROM clause */
116656  int i, j;                       /* Loop counters */
116657  struct SrcList_item *pLeft;     /* Left table being joined */
116658  struct SrcList_item *pRight;    /* Right table being joined */
116659
116660  pSrc = p->pSrc;
116661  pLeft = &pSrc->a[0];
116662  pRight = &pLeft[1];
116663  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
116664    Table *pLeftTab = pLeft->pTab;
116665    Table *pRightTab = pRight->pTab;
116666    int isOuter;
116667
116668    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
116669    isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
116670
116671    /* When the NATURAL keyword is present, add WHERE clause terms for
116672    ** every column that the two tables have in common.
116673    */
116674    if( pRight->fg.jointype & JT_NATURAL ){
116675      if( pRight->pOn || pRight->pUsing ){
116676        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
116677           "an ON or USING clause", 0);
116678        return 1;
116679      }
116680      for(j=0; j<pRightTab->nCol; j++){
116681        char *zName;   /* Name of column in the right table */
116682        int iLeft;     /* Matching left table */
116683        int iLeftCol;  /* Matching column in the left table */
116684
116685        zName = pRightTab->aCol[j].zName;
116686        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
116687          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
116688                       isOuter, &p->pWhere);
116689        }
116690      }
116691    }
116692
116693    /* Disallow both ON and USING clauses in the same join
116694    */
116695    if( pRight->pOn && pRight->pUsing ){
116696      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
116697        "clauses in the same join");
116698      return 1;
116699    }
116700
116701    /* Add the ON clause to the end of the WHERE clause, connected by
116702    ** an AND operator.
116703    */
116704    if( pRight->pOn ){
116705      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
116706      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
116707      pRight->pOn = 0;
116708    }
116709
116710    /* Create extra terms on the WHERE clause for each column named
116711    ** in the USING clause.  Example: If the two tables to be joined are
116712    ** A and B and the USING clause names X, Y, and Z, then add this
116713    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
116714    ** Report an error if any column mentioned in the USING clause is
116715    ** not contained in both tables to be joined.
116716    */
116717    if( pRight->pUsing ){
116718      IdList *pList = pRight->pUsing;
116719      for(j=0; j<pList->nId; j++){
116720        char *zName;     /* Name of the term in the USING clause */
116721        int iLeft;       /* Table on the left with matching column name */
116722        int iLeftCol;    /* Column number of matching column on the left */
116723        int iRightCol;   /* Column number of matching column on the right */
116724
116725        zName = pList->a[j].zName;
116726        iRightCol = columnIndex(pRightTab, zName);
116727        if( iRightCol<0
116728         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
116729        ){
116730          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
116731            "not present in both tables", zName);
116732          return 1;
116733        }
116734        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
116735                     isOuter, &p->pWhere);
116736      }
116737    }
116738  }
116739  return 0;
116740}
116741
116742/* Forward reference */
116743static KeyInfo *keyInfoFromExprList(
116744  Parse *pParse,       /* Parsing context */
116745  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
116746  int iStart,          /* Begin with this column of pList */
116747  int nExtra           /* Add this many extra columns to the end */
116748);
116749
116750/*
116751** Generate code that will push the record in registers regData
116752** through regData+nData-1 onto the sorter.
116753*/
116754static void pushOntoSorter(
116755  Parse *pParse,         /* Parser context */
116756  SortCtx *pSort,        /* Information about the ORDER BY clause */
116757  Select *pSelect,       /* The whole SELECT statement */
116758  int regData,           /* First register holding data to be sorted */
116759  int regOrigData,       /* First register holding data before packing */
116760  int nData,             /* Number of elements in the data array */
116761  int nPrefixReg         /* No. of reg prior to regData available for use */
116762){
116763  Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
116764  int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
116765  int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
116766  int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
116767  int regBase;                                     /* Regs for sorter record */
116768  int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
116769  int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
116770  int op;                            /* Opcode to add sorter record to sorter */
116771  int iLimit;                        /* LIMIT counter */
116772
116773  assert( bSeq==0 || bSeq==1 );
116774  assert( nData==1 || regData==regOrigData || regOrigData==0 );
116775  if( nPrefixReg ){
116776    assert( nPrefixReg==nExpr+bSeq );
116777    regBase = regData - nExpr - bSeq;
116778  }else{
116779    regBase = pParse->nMem + 1;
116780    pParse->nMem += nBase;
116781  }
116782  assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
116783  iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
116784  pSort->labelDone = sqlite3VdbeMakeLabel(v);
116785  sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
116786                          SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
116787  if( bSeq ){
116788    sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
116789  }
116790  if( nPrefixReg==0 && nData>0 ){
116791    sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
116792  }
116793  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
116794  if( nOBSat>0 ){
116795    int regPrevKey;   /* The first nOBSat columns of the previous row */
116796    int addrFirst;    /* Address of the OP_IfNot opcode */
116797    int addrJmp;      /* Address of the OP_Jump opcode */
116798    VdbeOp *pOp;      /* Opcode that opens the sorter */
116799    int nKey;         /* Number of sorting key columns, including OP_Sequence */
116800    KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
116801
116802    regPrevKey = pParse->nMem+1;
116803    pParse->nMem += pSort->nOBSat;
116804    nKey = nExpr - pSort->nOBSat + bSeq;
116805    if( bSeq ){
116806      addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
116807    }else{
116808      addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
116809    }
116810    VdbeCoverage(v);
116811    sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
116812    pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
116813    if( pParse->db->mallocFailed ) return;
116814    pOp->p2 = nKey + nData;
116815    pKI = pOp->p4.pKeyInfo;
116816    memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
116817    sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
116818    testcase( pKI->nXField>2 );
116819    pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
116820                                           pKI->nXField-1);
116821    addrJmp = sqlite3VdbeCurrentAddr(v);
116822    sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
116823    pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
116824    pSort->regReturn = ++pParse->nMem;
116825    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
116826    sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
116827    if( iLimit ){
116828      sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
116829      VdbeCoverage(v);
116830    }
116831    sqlite3VdbeJumpHere(v, addrFirst);
116832    sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
116833    sqlite3VdbeJumpHere(v, addrJmp);
116834  }
116835  if( pSort->sortFlags & SORTFLAG_UseSorter ){
116836    op = OP_SorterInsert;
116837  }else{
116838    op = OP_IdxInsert;
116839  }
116840  sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
116841                       regBase+nOBSat, nBase-nOBSat);
116842  if( iLimit ){
116843    int addr;
116844    int r1 = 0;
116845    /* Fill the sorter until it contains LIMIT+OFFSET entries.  (The iLimit
116846    ** register is initialized with value of LIMIT+OFFSET.)  After the sorter
116847    ** fills up, delete the least entry in the sorter after each insert.
116848    ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
116849    addr = sqlite3VdbeAddOp1(v, OP_IfNotZero, iLimit); VdbeCoverage(v);
116850    sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
116851    if( pSort->bOrderedInnerLoop ){
116852      r1 = ++pParse->nMem;
116853      sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
116854      VdbeComment((v, "seq"));
116855    }
116856    sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
116857    if( pSort->bOrderedInnerLoop ){
116858      /* If the inner loop is driven by an index such that values from
116859      ** the same iteration of the inner loop are in sorted order, then
116860      ** immediately jump to the next iteration of an inner loop if the
116861      ** entry from the current iteration does not fit into the top
116862      ** LIMIT+OFFSET entries of the sorter. */
116863      int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
116864      sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
116865      sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
116866      VdbeCoverage(v);
116867    }
116868    sqlite3VdbeJumpHere(v, addr);
116869  }
116870}
116871
116872/*
116873** Add code to implement the OFFSET
116874*/
116875static void codeOffset(
116876  Vdbe *v,          /* Generate code into this VM */
116877  int iOffset,      /* Register holding the offset counter */
116878  int iContinue     /* Jump here to skip the current record */
116879){
116880  if( iOffset>0 ){
116881    sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
116882    VdbeComment((v, "OFFSET"));
116883  }
116884}
116885
116886/*
116887** Add code that will check to make sure the N registers starting at iMem
116888** form a distinct entry.  iTab is a sorting index that holds previously
116889** seen combinations of the N values.  A new entry is made in iTab
116890** if the current N values are new.
116891**
116892** A jump to addrRepeat is made and the N+1 values are popped from the
116893** stack if the top N elements are not distinct.
116894*/
116895static void codeDistinct(
116896  Parse *pParse,     /* Parsing and code generating context */
116897  int iTab,          /* A sorting index used to test for distinctness */
116898  int addrRepeat,    /* Jump to here if not distinct */
116899  int N,             /* Number of elements */
116900  int iMem           /* First element */
116901){
116902  Vdbe *v;
116903  int r1;
116904
116905  v = pParse->pVdbe;
116906  r1 = sqlite3GetTempReg(pParse);
116907  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
116908  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
116909  sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
116910  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
116911  sqlite3ReleaseTempReg(pParse, r1);
116912}
116913
116914/*
116915** This routine generates the code for the inside of the inner loop
116916** of a SELECT.
116917**
116918** If srcTab is negative, then the pEList expressions
116919** are evaluated in order to get the data for this row.  If srcTab is
116920** zero or more, then data is pulled from srcTab and pEList is used only
116921** to get the number of columns and the collation sequence for each column.
116922*/
116923static void selectInnerLoop(
116924  Parse *pParse,          /* The parser context */
116925  Select *p,              /* The complete select statement being coded */
116926  ExprList *pEList,       /* List of values being extracted */
116927  int srcTab,             /* Pull data from this table */
116928  SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
116929  DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
116930  SelectDest *pDest,      /* How to dispose of the results */
116931  int iContinue,          /* Jump here to continue with next row */
116932  int iBreak              /* Jump here to break out of the inner loop */
116933){
116934  Vdbe *v = pParse->pVdbe;
116935  int i;
116936  int hasDistinct;            /* True if the DISTINCT keyword is present */
116937  int eDest = pDest->eDest;   /* How to dispose of results */
116938  int iParm = pDest->iSDParm; /* First argument to disposal method */
116939  int nResultCol;             /* Number of result columns */
116940  int nPrefixReg = 0;         /* Number of extra registers before regResult */
116941
116942  /* Usually, regResult is the first cell in an array of memory cells
116943  ** containing the current result row. In this case regOrig is set to the
116944  ** same value. However, if the results are being sent to the sorter, the
116945  ** values for any expressions that are also part of the sort-key are omitted
116946  ** from this array. In this case regOrig is set to zero.  */
116947  int regResult;              /* Start of memory holding current results */
116948  int regOrig;                /* Start of memory holding full result (or 0) */
116949
116950  assert( v );
116951  assert( pEList!=0 );
116952  hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
116953  if( pSort && pSort->pOrderBy==0 ) pSort = 0;
116954  if( pSort==0 && !hasDistinct ){
116955    assert( iContinue!=0 );
116956    codeOffset(v, p->iOffset, iContinue);
116957  }
116958
116959  /* Pull the requested columns.
116960  */
116961  nResultCol = pEList->nExpr;
116962
116963  if( pDest->iSdst==0 ){
116964    if( pSort ){
116965      nPrefixReg = pSort->pOrderBy->nExpr;
116966      if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
116967      pParse->nMem += nPrefixReg;
116968    }
116969    pDest->iSdst = pParse->nMem+1;
116970    pParse->nMem += nResultCol;
116971  }else if( pDest->iSdst+nResultCol > pParse->nMem ){
116972    /* This is an error condition that can result, for example, when a SELECT
116973    ** on the right-hand side of an INSERT contains more result columns than
116974    ** there are columns in the table on the left.  The error will be caught
116975    ** and reported later.  But we need to make sure enough memory is allocated
116976    ** to avoid other spurious errors in the meantime. */
116977    pParse->nMem += nResultCol;
116978  }
116979  pDest->nSdst = nResultCol;
116980  regOrig = regResult = pDest->iSdst;
116981  if( srcTab>=0 ){
116982    for(i=0; i<nResultCol; i++){
116983      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
116984      VdbeComment((v, "%s", pEList->a[i].zName));
116985    }
116986  }else if( eDest!=SRT_Exists ){
116987    /* If the destination is an EXISTS(...) expression, the actual
116988    ** values returned by the SELECT are not required.
116989    */
116990    u8 ecelFlags;
116991    if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
116992      ecelFlags = SQLITE_ECEL_DUP;
116993    }else{
116994      ecelFlags = 0;
116995    }
116996    if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
116997      /* For each expression in pEList that is a copy of an expression in
116998      ** the ORDER BY clause (pSort->pOrderBy), set the associated
116999      ** iOrderByCol value to one more than the index of the ORDER BY
117000      ** expression within the sort-key that pushOntoSorter() will generate.
117001      ** This allows the pEList field to be omitted from the sorted record,
117002      ** saving space and CPU cycles.  */
117003      ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
117004      for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
117005        int j;
117006        if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
117007          pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
117008        }
117009      }
117010      regOrig = 0;
117011      assert( eDest==SRT_Set || eDest==SRT_Mem
117012           || eDest==SRT_Coroutine || eDest==SRT_Output );
117013    }
117014    nResultCol = sqlite3ExprCodeExprList(pParse,pEList,regResult,0,ecelFlags);
117015  }
117016
117017  /* If the DISTINCT keyword was present on the SELECT statement
117018  ** and this row has been seen before, then do not make this row
117019  ** part of the result.
117020  */
117021  if( hasDistinct ){
117022    switch( pDistinct->eTnctType ){
117023      case WHERE_DISTINCT_ORDERED: {
117024        VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
117025        int iJump;              /* Jump destination */
117026        int regPrev;            /* Previous row content */
117027
117028        /* Allocate space for the previous row */
117029        regPrev = pParse->nMem+1;
117030        pParse->nMem += nResultCol;
117031
117032        /* Change the OP_OpenEphemeral coded earlier to an OP_Null
117033        ** sets the MEM_Cleared bit on the first register of the
117034        ** previous value.  This will cause the OP_Ne below to always
117035        ** fail on the first iteration of the loop even if the first
117036        ** row is all NULLs.
117037        */
117038        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
117039        pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
117040        pOp->opcode = OP_Null;
117041        pOp->p1 = 1;
117042        pOp->p2 = regPrev;
117043
117044        iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
117045        for(i=0; i<nResultCol; i++){
117046          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
117047          if( i<nResultCol-1 ){
117048            sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
117049            VdbeCoverage(v);
117050          }else{
117051            sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
117052            VdbeCoverage(v);
117053           }
117054          sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
117055          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
117056        }
117057        assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
117058        sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
117059        break;
117060      }
117061
117062      case WHERE_DISTINCT_UNIQUE: {
117063        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
117064        break;
117065      }
117066
117067      default: {
117068        assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
117069        codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
117070                     regResult);
117071        break;
117072      }
117073    }
117074    if( pSort==0 ){
117075      codeOffset(v, p->iOffset, iContinue);
117076    }
117077  }
117078
117079  switch( eDest ){
117080    /* In this mode, write each query result to the key of the temporary
117081    ** table iParm.
117082    */
117083#ifndef SQLITE_OMIT_COMPOUND_SELECT
117084    case SRT_Union: {
117085      int r1;
117086      r1 = sqlite3GetTempReg(pParse);
117087      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
117088      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
117089      sqlite3ReleaseTempReg(pParse, r1);
117090      break;
117091    }
117092
117093    /* Construct a record from the query result, but instead of
117094    ** saving that record, use it as a key to delete elements from
117095    ** the temporary table iParm.
117096    */
117097    case SRT_Except: {
117098      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
117099      break;
117100    }
117101#endif /* SQLITE_OMIT_COMPOUND_SELECT */
117102
117103    /* Store the result as data using a unique key.
117104    */
117105    case SRT_Fifo:
117106    case SRT_DistFifo:
117107    case SRT_Table:
117108    case SRT_EphemTab: {
117109      int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
117110      testcase( eDest==SRT_Table );
117111      testcase( eDest==SRT_EphemTab );
117112      testcase( eDest==SRT_Fifo );
117113      testcase( eDest==SRT_DistFifo );
117114      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
117115#ifndef SQLITE_OMIT_CTE
117116      if( eDest==SRT_DistFifo ){
117117        /* If the destination is DistFifo, then cursor (iParm+1) is open
117118        ** on an ephemeral index. If the current row is already present
117119        ** in the index, do not write it to the output. If not, add the
117120        ** current row to the index and proceed with writing it to the
117121        ** output table as well.  */
117122        int addr = sqlite3VdbeCurrentAddr(v) + 4;
117123        sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
117124        VdbeCoverage(v);
117125        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
117126        assert( pSort==0 );
117127      }
117128#endif
117129      if( pSort ){
117130        pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
117131      }else{
117132        int r2 = sqlite3GetTempReg(pParse);
117133        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
117134        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
117135        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
117136        sqlite3ReleaseTempReg(pParse, r2);
117137      }
117138      sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
117139      break;
117140    }
117141
117142#ifndef SQLITE_OMIT_SUBQUERY
117143    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
117144    ** then there should be a single item on the stack.  Write this
117145    ** item into the set table with bogus data.
117146    */
117147    case SRT_Set: {
117148      if( pSort ){
117149        /* At first glance you would think we could optimize out the
117150        ** ORDER BY in this case since the order of entries in the set
117151        ** does not matter.  But there might be a LIMIT clause, in which
117152        ** case the order does matter */
117153        pushOntoSorter(
117154            pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
117155      }else{
117156        int r1 = sqlite3GetTempReg(pParse);
117157        assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
117158        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
117159            r1, pDest->zAffSdst, nResultCol);
117160        sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
117161        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
117162        sqlite3ReleaseTempReg(pParse, r1);
117163      }
117164      break;
117165    }
117166
117167    /* If any row exist in the result set, record that fact and abort.
117168    */
117169    case SRT_Exists: {
117170      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
117171      /* The LIMIT clause will terminate the loop for us */
117172      break;
117173    }
117174
117175    /* If this is a scalar select that is part of an expression, then
117176    ** store the results in the appropriate memory cell or array of
117177    ** memory cells and break out of the scan loop.
117178    */
117179    case SRT_Mem: {
117180      if( pSort ){
117181        assert( nResultCol<=pDest->nSdst );
117182        pushOntoSorter(
117183            pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
117184      }else{
117185        assert( nResultCol==pDest->nSdst );
117186        assert( regResult==iParm );
117187        /* The LIMIT clause will jump out of the loop for us */
117188      }
117189      break;
117190    }
117191#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
117192
117193    case SRT_Coroutine:       /* Send data to a co-routine */
117194    case SRT_Output: {        /* Return the results */
117195      testcase( eDest==SRT_Coroutine );
117196      testcase( eDest==SRT_Output );
117197      if( pSort ){
117198        pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
117199                       nPrefixReg);
117200      }else if( eDest==SRT_Coroutine ){
117201        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
117202      }else{
117203        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
117204        sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
117205      }
117206      break;
117207    }
117208
117209#ifndef SQLITE_OMIT_CTE
117210    /* Write the results into a priority queue that is order according to
117211    ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
117212    ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
117213    ** pSO->nExpr columns, then make sure all keys are unique by adding a
117214    ** final OP_Sequence column.  The last column is the record as a blob.
117215    */
117216    case SRT_DistQueue:
117217    case SRT_Queue: {
117218      int nKey;
117219      int r1, r2, r3;
117220      int addrTest = 0;
117221      ExprList *pSO;
117222      pSO = pDest->pOrderBy;
117223      assert( pSO );
117224      nKey = pSO->nExpr;
117225      r1 = sqlite3GetTempReg(pParse);
117226      r2 = sqlite3GetTempRange(pParse, nKey+2);
117227      r3 = r2+nKey+1;
117228      if( eDest==SRT_DistQueue ){
117229        /* If the destination is DistQueue, then cursor (iParm+1) is open
117230        ** on a second ephemeral index that holds all values every previously
117231        ** added to the queue. */
117232        addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
117233                                        regResult, nResultCol);
117234        VdbeCoverage(v);
117235      }
117236      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
117237      if( eDest==SRT_DistQueue ){
117238        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
117239        sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
117240      }
117241      for(i=0; i<nKey; i++){
117242        sqlite3VdbeAddOp2(v, OP_SCopy,
117243                          regResult + pSO->a[i].u.x.iOrderByCol - 1,
117244                          r2+i);
117245      }
117246      sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
117247      sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
117248      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
117249      if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
117250      sqlite3ReleaseTempReg(pParse, r1);
117251      sqlite3ReleaseTempRange(pParse, r2, nKey+2);
117252      break;
117253    }
117254#endif /* SQLITE_OMIT_CTE */
117255
117256
117257
117258#if !defined(SQLITE_OMIT_TRIGGER)
117259    /* Discard the results.  This is used for SELECT statements inside
117260    ** the body of a TRIGGER.  The purpose of such selects is to call
117261    ** user-defined functions that have side effects.  We do not care
117262    ** about the actual results of the select.
117263    */
117264    default: {
117265      assert( eDest==SRT_Discard );
117266      break;
117267    }
117268#endif
117269  }
117270
117271  /* Jump to the end of the loop if the LIMIT is reached.  Except, if
117272  ** there is a sorter, in which case the sorter has already limited
117273  ** the output for us.
117274  */
117275  if( pSort==0 && p->iLimit ){
117276    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
117277  }
117278}
117279
117280/*
117281** Allocate a KeyInfo object sufficient for an index of N key columns and
117282** X extra columns.
117283*/
117284SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
117285  int nExtra = (N+X)*(sizeof(CollSeq*)+1);
117286  KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
117287  if( p ){
117288    p->aSortOrder = (u8*)&p->aColl[N+X];
117289    p->nField = (u16)N;
117290    p->nXField = (u16)X;
117291    p->enc = ENC(db);
117292    p->db = db;
117293    p->nRef = 1;
117294    memset(&p[1], 0, nExtra);
117295  }else{
117296    sqlite3OomFault(db);
117297  }
117298  return p;
117299}
117300
117301/*
117302** Deallocate a KeyInfo object
117303*/
117304SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
117305  if( p ){
117306    assert( p->nRef>0 );
117307    p->nRef--;
117308    if( p->nRef==0 ) sqlite3DbFree(p->db, p);
117309  }
117310}
117311
117312/*
117313** Make a new pointer to a KeyInfo object
117314*/
117315SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
117316  if( p ){
117317    assert( p->nRef>0 );
117318    p->nRef++;
117319  }
117320  return p;
117321}
117322
117323#ifdef SQLITE_DEBUG
117324/*
117325** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
117326** can only be changed if this is just a single reference to the object.
117327**
117328** This routine is used only inside of assert() statements.
117329*/
117330SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
117331#endif /* SQLITE_DEBUG */
117332
117333/*
117334** Given an expression list, generate a KeyInfo structure that records
117335** the collating sequence for each expression in that expression list.
117336**
117337** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
117338** KeyInfo structure is appropriate for initializing a virtual index to
117339** implement that clause.  If the ExprList is the result set of a SELECT
117340** then the KeyInfo structure is appropriate for initializing a virtual
117341** index to implement a DISTINCT test.
117342**
117343** Space to hold the KeyInfo structure is obtained from malloc.  The calling
117344** function is responsible for seeing that this structure is eventually
117345** freed.
117346*/
117347static KeyInfo *keyInfoFromExprList(
117348  Parse *pParse,       /* Parsing context */
117349  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
117350  int iStart,          /* Begin with this column of pList */
117351  int nExtra           /* Add this many extra columns to the end */
117352){
117353  int nExpr;
117354  KeyInfo *pInfo;
117355  struct ExprList_item *pItem;
117356  sqlite3 *db = pParse->db;
117357  int i;
117358
117359  nExpr = pList->nExpr;
117360  pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
117361  if( pInfo ){
117362    assert( sqlite3KeyInfoIsWriteable(pInfo) );
117363    for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
117364      CollSeq *pColl;
117365      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
117366      if( !pColl ) pColl = db->pDfltColl;
117367      pInfo->aColl[i-iStart] = pColl;
117368      pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
117369    }
117370  }
117371  return pInfo;
117372}
117373
117374/*
117375** Name of the connection operator, used for error messages.
117376*/
117377static const char *selectOpName(int id){
117378  char *z;
117379  switch( id ){
117380    case TK_ALL:       z = "UNION ALL";   break;
117381    case TK_INTERSECT: z = "INTERSECT";   break;
117382    case TK_EXCEPT:    z = "EXCEPT";      break;
117383    default:           z = "UNION";       break;
117384  }
117385  return z;
117386}
117387
117388#ifndef SQLITE_OMIT_EXPLAIN
117389/*
117390** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
117391** is a no-op. Otherwise, it adds a single row of output to the EQP result,
117392** where the caption is of the form:
117393**
117394**   "USE TEMP B-TREE FOR xxx"
117395**
117396** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
117397** is determined by the zUsage argument.
117398*/
117399static void explainTempTable(Parse *pParse, const char *zUsage){
117400  if( pParse->explain==2 ){
117401    Vdbe *v = pParse->pVdbe;
117402    char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
117403    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
117404  }
117405}
117406
117407/*
117408** Assign expression b to lvalue a. A second, no-op, version of this macro
117409** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
117410** in sqlite3Select() to assign values to structure member variables that
117411** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
117412** code with #ifndef directives.
117413*/
117414# define explainSetInteger(a, b) a = b
117415
117416#else
117417/* No-op versions of the explainXXX() functions and macros. */
117418# define explainTempTable(y,z)
117419# define explainSetInteger(y,z)
117420#endif
117421
117422#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
117423/*
117424** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
117425** is a no-op. Otherwise, it adds a single row of output to the EQP result,
117426** where the caption is of one of the two forms:
117427**
117428**   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
117429**   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
117430**
117431** where iSub1 and iSub2 are the integers passed as the corresponding
117432** function parameters, and op is the text representation of the parameter
117433** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
117434** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
117435** false, or the second form if it is true.
117436*/
117437static void explainComposite(
117438  Parse *pParse,                  /* Parse context */
117439  int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
117440  int iSub1,                      /* Subquery id 1 */
117441  int iSub2,                      /* Subquery id 2 */
117442  int bUseTmp                     /* True if a temp table was used */
117443){
117444  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
117445  if( pParse->explain==2 ){
117446    Vdbe *v = pParse->pVdbe;
117447    char *zMsg = sqlite3MPrintf(
117448        pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
117449        bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
117450    );
117451    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
117452  }
117453}
117454#else
117455/* No-op versions of the explainXXX() functions and macros. */
117456# define explainComposite(v,w,x,y,z)
117457#endif
117458
117459/*
117460** If the inner loop was generated using a non-null pOrderBy argument,
117461** then the results were placed in a sorter.  After the loop is terminated
117462** we need to run the sorter and output the results.  The following
117463** routine generates the code needed to do that.
117464*/
117465static void generateSortTail(
117466  Parse *pParse,    /* Parsing context */
117467  Select *p,        /* The SELECT statement */
117468  SortCtx *pSort,   /* Information on the ORDER BY clause */
117469  int nColumn,      /* Number of columns of data */
117470  SelectDest *pDest /* Write the sorted results here */
117471){
117472  Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
117473  int addrBreak = pSort->labelDone;            /* Jump here to exit loop */
117474  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
117475  int addr;
117476  int addrOnce = 0;
117477  int iTab;
117478  ExprList *pOrderBy = pSort->pOrderBy;
117479  int eDest = pDest->eDest;
117480  int iParm = pDest->iSDParm;
117481  int regRow;
117482  int regRowid;
117483  int iCol;
117484  int nKey;
117485  int iSortTab;                   /* Sorter cursor to read from */
117486  int nSortData;                  /* Trailing values to read from sorter */
117487  int i;
117488  int bSeq;                       /* True if sorter record includes seq. no. */
117489  struct ExprList_item *aOutEx = p->pEList->a;
117490
117491  assert( addrBreak<0 );
117492  if( pSort->labelBkOut ){
117493    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
117494    sqlite3VdbeGoto(v, addrBreak);
117495    sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
117496  }
117497  iTab = pSort->iECursor;
117498  if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
117499    regRowid = 0;
117500    regRow = pDest->iSdst;
117501    nSortData = nColumn;
117502  }else{
117503    regRowid = sqlite3GetTempReg(pParse);
117504    regRow = sqlite3GetTempRange(pParse, nColumn);
117505    nSortData = nColumn;
117506  }
117507  nKey = pOrderBy->nExpr - pSort->nOBSat;
117508  if( pSort->sortFlags & SORTFLAG_UseSorter ){
117509    int regSortOut = ++pParse->nMem;
117510    iSortTab = pParse->nTab++;
117511    if( pSort->labelBkOut ){
117512      addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
117513    }
117514    sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
117515    if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
117516    addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
117517    VdbeCoverage(v);
117518    codeOffset(v, p->iOffset, addrContinue);
117519    sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
117520    bSeq = 0;
117521  }else{
117522    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
117523    codeOffset(v, p->iOffset, addrContinue);
117524    iSortTab = iTab;
117525    bSeq = 1;
117526  }
117527  for(i=0, iCol=nKey+bSeq; i<nSortData; i++){
117528    int iRead;
117529    if( aOutEx[i].u.x.iOrderByCol ){
117530      iRead = aOutEx[i].u.x.iOrderByCol-1;
117531    }else{
117532      iRead = iCol++;
117533    }
117534    sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
117535    VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
117536  }
117537  switch( eDest ){
117538    case SRT_Table:
117539    case SRT_EphemTab: {
117540      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
117541      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
117542      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
117543      break;
117544    }
117545#ifndef SQLITE_OMIT_SUBQUERY
117546    case SRT_Set: {
117547      assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
117548      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
117549                        pDest->zAffSdst, nColumn);
117550      sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn);
117551      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
117552      break;
117553    }
117554    case SRT_Mem: {
117555      /* The LIMIT clause will terminate the loop for us */
117556      break;
117557    }
117558#endif
117559    default: {
117560      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
117561      testcase( eDest==SRT_Output );
117562      testcase( eDest==SRT_Coroutine );
117563      if( eDest==SRT_Output ){
117564        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
117565        sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
117566      }else{
117567        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
117568      }
117569      break;
117570    }
117571  }
117572  if( regRowid ){
117573    if( eDest==SRT_Set ){
117574      sqlite3ReleaseTempRange(pParse, regRow, nColumn);
117575    }else{
117576      sqlite3ReleaseTempReg(pParse, regRow);
117577    }
117578    sqlite3ReleaseTempReg(pParse, regRowid);
117579  }
117580  /* The bottom of the loop
117581  */
117582  sqlite3VdbeResolveLabel(v, addrContinue);
117583  if( pSort->sortFlags & SORTFLAG_UseSorter ){
117584    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
117585  }else{
117586    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
117587  }
117588  if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
117589  sqlite3VdbeResolveLabel(v, addrBreak);
117590}
117591
117592/*
117593** Return a pointer to a string containing the 'declaration type' of the
117594** expression pExpr. The string may be treated as static by the caller.
117595**
117596** Also try to estimate the size of the returned value and return that
117597** result in *pEstWidth.
117598**
117599** The declaration type is the exact datatype definition extracted from the
117600** original CREATE TABLE statement if the expression is a column. The
117601** declaration type for a ROWID field is INTEGER. Exactly when an expression
117602** is considered a column can be complex in the presence of subqueries. The
117603** result-set expression in all of the following SELECT statements is
117604** considered a column by this function.
117605**
117606**   SELECT col FROM tbl;
117607**   SELECT (SELECT col FROM tbl;
117608**   SELECT (SELECT col FROM tbl);
117609**   SELECT abc FROM (SELECT col AS abc FROM tbl);
117610**
117611** The declaration type for any expression other than a column is NULL.
117612**
117613** This routine has either 3 or 6 parameters depending on whether or not
117614** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
117615*/
117616#ifdef SQLITE_ENABLE_COLUMN_METADATA
117617# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
117618#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
117619# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
117620#endif
117621static const char *columnTypeImpl(
117622  NameContext *pNC,
117623  Expr *pExpr,
117624#ifdef SQLITE_ENABLE_COLUMN_METADATA
117625  const char **pzOrigDb,
117626  const char **pzOrigTab,
117627  const char **pzOrigCol,
117628#endif
117629  u8 *pEstWidth
117630){
117631  char const *zType = 0;
117632  int j;
117633  u8 estWidth = 1;
117634#ifdef SQLITE_ENABLE_COLUMN_METADATA
117635  char const *zOrigDb = 0;
117636  char const *zOrigTab = 0;
117637  char const *zOrigCol = 0;
117638#endif
117639
117640  assert( pExpr!=0 );
117641  assert( pNC->pSrcList!=0 );
117642  switch( pExpr->op ){
117643    case TK_AGG_COLUMN:
117644    case TK_COLUMN: {
117645      /* The expression is a column. Locate the table the column is being
117646      ** extracted from in NameContext.pSrcList. This table may be real
117647      ** database table or a subquery.
117648      */
117649      Table *pTab = 0;            /* Table structure column is extracted from */
117650      Select *pS = 0;             /* Select the column is extracted from */
117651      int iCol = pExpr->iColumn;  /* Index of column in pTab */
117652      testcase( pExpr->op==TK_AGG_COLUMN );
117653      testcase( pExpr->op==TK_COLUMN );
117654      while( pNC && !pTab ){
117655        SrcList *pTabList = pNC->pSrcList;
117656        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
117657        if( j<pTabList->nSrc ){
117658          pTab = pTabList->a[j].pTab;
117659          pS = pTabList->a[j].pSelect;
117660        }else{
117661          pNC = pNC->pNext;
117662        }
117663      }
117664
117665      if( pTab==0 ){
117666        /* At one time, code such as "SELECT new.x" within a trigger would
117667        ** cause this condition to run.  Since then, we have restructured how
117668        ** trigger code is generated and so this condition is no longer
117669        ** possible. However, it can still be true for statements like
117670        ** the following:
117671        **
117672        **   CREATE TABLE t1(col INTEGER);
117673        **   SELECT (SELECT t1.col) FROM FROM t1;
117674        **
117675        ** when columnType() is called on the expression "t1.col" in the
117676        ** sub-select. In this case, set the column type to NULL, even
117677        ** though it should really be "INTEGER".
117678        **
117679        ** This is not a problem, as the column type of "t1.col" is never
117680        ** used. When columnType() is called on the expression
117681        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
117682        ** branch below.  */
117683        break;
117684      }
117685
117686      assert( pTab && pExpr->pTab==pTab );
117687      if( pS ){
117688        /* The "table" is actually a sub-select or a view in the FROM clause
117689        ** of the SELECT statement. Return the declaration type and origin
117690        ** data for the result-set column of the sub-select.
117691        */
117692        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
117693          /* If iCol is less than zero, then the expression requests the
117694          ** rowid of the sub-select or view. This expression is legal (see
117695          ** test case misc2.2.2) - it always evaluates to NULL.
117696          **
117697          ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
117698          ** caught already by name resolution.
117699          */
117700          NameContext sNC;
117701          Expr *p = pS->pEList->a[iCol].pExpr;
117702          sNC.pSrcList = pS->pSrc;
117703          sNC.pNext = pNC;
117704          sNC.pParse = pNC->pParse;
117705          zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
117706        }
117707      }else if( pTab->pSchema ){
117708        /* A real table */
117709        assert( !pS );
117710        if( iCol<0 ) iCol = pTab->iPKey;
117711        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
117712#ifdef SQLITE_ENABLE_COLUMN_METADATA
117713        if( iCol<0 ){
117714          zType = "INTEGER";
117715          zOrigCol = "rowid";
117716        }else{
117717          zOrigCol = pTab->aCol[iCol].zName;
117718          zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
117719          estWidth = pTab->aCol[iCol].szEst;
117720        }
117721        zOrigTab = pTab->zName;
117722        if( pNC->pParse ){
117723          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
117724          zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
117725        }
117726#else
117727        if( iCol<0 ){
117728          zType = "INTEGER";
117729        }else{
117730          zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
117731          estWidth = pTab->aCol[iCol].szEst;
117732        }
117733#endif
117734      }
117735      break;
117736    }
117737#ifndef SQLITE_OMIT_SUBQUERY
117738    case TK_SELECT: {
117739      /* The expression is a sub-select. Return the declaration type and
117740      ** origin info for the single column in the result set of the SELECT
117741      ** statement.
117742      */
117743      NameContext sNC;
117744      Select *pS = pExpr->x.pSelect;
117745      Expr *p = pS->pEList->a[0].pExpr;
117746      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
117747      sNC.pSrcList = pS->pSrc;
117748      sNC.pNext = pNC;
117749      sNC.pParse = pNC->pParse;
117750      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
117751      break;
117752    }
117753#endif
117754  }
117755
117756#ifdef SQLITE_ENABLE_COLUMN_METADATA
117757  if( pzOrigDb ){
117758    assert( pzOrigTab && pzOrigCol );
117759    *pzOrigDb = zOrigDb;
117760    *pzOrigTab = zOrigTab;
117761    *pzOrigCol = zOrigCol;
117762  }
117763#endif
117764  if( pEstWidth ) *pEstWidth = estWidth;
117765  return zType;
117766}
117767
117768/*
117769** Generate code that will tell the VDBE the declaration types of columns
117770** in the result set.
117771*/
117772static void generateColumnTypes(
117773  Parse *pParse,      /* Parser context */
117774  SrcList *pTabList,  /* List of tables */
117775  ExprList *pEList    /* Expressions defining the result set */
117776){
117777#ifndef SQLITE_OMIT_DECLTYPE
117778  Vdbe *v = pParse->pVdbe;
117779  int i;
117780  NameContext sNC;
117781  sNC.pSrcList = pTabList;
117782  sNC.pParse = pParse;
117783  for(i=0; i<pEList->nExpr; i++){
117784    Expr *p = pEList->a[i].pExpr;
117785    const char *zType;
117786#ifdef SQLITE_ENABLE_COLUMN_METADATA
117787    const char *zOrigDb = 0;
117788    const char *zOrigTab = 0;
117789    const char *zOrigCol = 0;
117790    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
117791
117792    /* The vdbe must make its own copy of the column-type and other
117793    ** column specific strings, in case the schema is reset before this
117794    ** virtual machine is deleted.
117795    */
117796    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
117797    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
117798    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
117799#else
117800    zType = columnType(&sNC, p, 0, 0, 0, 0);
117801#endif
117802    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
117803  }
117804#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
117805}
117806
117807/*
117808** Generate code that will tell the VDBE the names of columns
117809** in the result set.  This information is used to provide the
117810** azCol[] values in the callback.
117811*/
117812static void generateColumnNames(
117813  Parse *pParse,      /* Parser context */
117814  SrcList *pTabList,  /* List of tables */
117815  ExprList *pEList    /* Expressions defining the result set */
117816){
117817  Vdbe *v = pParse->pVdbe;
117818  int i, j;
117819  sqlite3 *db = pParse->db;
117820  int fullNames, shortNames;
117821
117822#ifndef SQLITE_OMIT_EXPLAIN
117823  /* If this is an EXPLAIN, skip this step */
117824  if( pParse->explain ){
117825    return;
117826  }
117827#endif
117828
117829  if( pParse->colNamesSet || db->mallocFailed ) return;
117830  assert( v!=0 );
117831  assert( pTabList!=0 );
117832  pParse->colNamesSet = 1;
117833  fullNames = (db->flags & SQLITE_FullColNames)!=0;
117834  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
117835  sqlite3VdbeSetNumCols(v, pEList->nExpr);
117836  for(i=0; i<pEList->nExpr; i++){
117837    Expr *p;
117838    p = pEList->a[i].pExpr;
117839    if( NEVER(p==0) ) continue;
117840    if( pEList->a[i].zName ){
117841      char *zName = pEList->a[i].zName;
117842      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
117843    }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){
117844      Table *pTab;
117845      char *zCol;
117846      int iCol = p->iColumn;
117847      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
117848        if( pTabList->a[j].iCursor==p->iTable ) break;
117849      }
117850      assert( j<pTabList->nSrc );
117851      pTab = pTabList->a[j].pTab;
117852      if( iCol<0 ) iCol = pTab->iPKey;
117853      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
117854      if( iCol<0 ){
117855        zCol = "rowid";
117856      }else{
117857        zCol = pTab->aCol[iCol].zName;
117858      }
117859      if( !shortNames && !fullNames ){
117860        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
117861            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
117862      }else if( fullNames ){
117863        char *zName = 0;
117864        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
117865        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
117866      }else{
117867        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
117868      }
117869    }else{
117870      const char *z = pEList->a[i].zSpan;
117871      z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
117872      sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
117873    }
117874  }
117875  generateColumnTypes(pParse, pTabList, pEList);
117876}
117877
117878/*
117879** Given an expression list (which is really the list of expressions
117880** that form the result set of a SELECT statement) compute appropriate
117881** column names for a table that would hold the expression list.
117882**
117883** All column names will be unique.
117884**
117885** Only the column names are computed.  Column.zType, Column.zColl,
117886** and other fields of Column are zeroed.
117887**
117888** Return SQLITE_OK on success.  If a memory allocation error occurs,
117889** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
117890*/
117891SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
117892  Parse *pParse,          /* Parsing context */
117893  ExprList *pEList,       /* Expr list from which to derive column names */
117894  i16 *pnCol,             /* Write the number of columns here */
117895  Column **paCol          /* Write the new column list here */
117896){
117897  sqlite3 *db = pParse->db;   /* Database connection */
117898  int i, j;                   /* Loop counters */
117899  u32 cnt;                    /* Index added to make the name unique */
117900  Column *aCol, *pCol;        /* For looping over result columns */
117901  int nCol;                   /* Number of columns in the result set */
117902  Expr *p;                    /* Expression for a single result column */
117903  char *zName;                /* Column name */
117904  int nName;                  /* Size of name in zName[] */
117905  Hash ht;                    /* Hash table of column names */
117906
117907  sqlite3HashInit(&ht);
117908  if( pEList ){
117909    nCol = pEList->nExpr;
117910    aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
117911    testcase( aCol==0 );
117912  }else{
117913    nCol = 0;
117914    aCol = 0;
117915  }
117916  assert( nCol==(i16)nCol );
117917  *pnCol = nCol;
117918  *paCol = aCol;
117919
117920  for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
117921    /* Get an appropriate name for the column
117922    */
117923    p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
117924    if( (zName = pEList->a[i].zName)!=0 ){
117925      /* If the column contains an "AS <name>" phrase, use <name> as the name */
117926    }else{
117927      Expr *pColExpr = p;  /* The expression that is the result column name */
117928      Table *pTab;         /* Table associated with this expression */
117929      while( pColExpr->op==TK_DOT ){
117930        pColExpr = pColExpr->pRight;
117931        assert( pColExpr!=0 );
117932      }
117933      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
117934        /* For columns use the column name name */
117935        int iCol = pColExpr->iColumn;
117936        pTab = pColExpr->pTab;
117937        if( iCol<0 ) iCol = pTab->iPKey;
117938        zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
117939      }else if( pColExpr->op==TK_ID ){
117940        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
117941        zName = pColExpr->u.zToken;
117942      }else{
117943        /* Use the original text of the column expression as its name */
117944        zName = pEList->a[i].zSpan;
117945      }
117946    }
117947    zName = sqlite3MPrintf(db, "%s", zName);
117948
117949    /* Make sure the column name is unique.  If the name is not unique,
117950    ** append an integer to the name so that it becomes unique.
117951    */
117952    cnt = 0;
117953    while( zName && sqlite3HashFind(&ht, zName)!=0 ){
117954      nName = sqlite3Strlen30(zName);
117955      if( nName>0 ){
117956        for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
117957        if( zName[j]==':' ) nName = j;
117958      }
117959      zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
117960      if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
117961    }
117962    pCol->zName = zName;
117963    sqlite3ColumnPropertiesFromName(0, pCol);
117964    if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
117965      sqlite3OomFault(db);
117966    }
117967  }
117968  sqlite3HashClear(&ht);
117969  if( db->mallocFailed ){
117970    for(j=0; j<i; j++){
117971      sqlite3DbFree(db, aCol[j].zName);
117972    }
117973    sqlite3DbFree(db, aCol);
117974    *paCol = 0;
117975    *pnCol = 0;
117976    return SQLITE_NOMEM_BKPT;
117977  }
117978  return SQLITE_OK;
117979}
117980
117981/*
117982** Add type and collation information to a column list based on
117983** a SELECT statement.
117984**
117985** The column list presumably came from selectColumnNamesFromExprList().
117986** The column list has only names, not types or collations.  This
117987** routine goes through and adds the types and collations.
117988**
117989** This routine requires that all identifiers in the SELECT
117990** statement be resolved.
117991*/
117992SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
117993  Parse *pParse,        /* Parsing contexts */
117994  Table *pTab,          /* Add column type information to this table */
117995  Select *pSelect       /* SELECT used to determine types and collations */
117996){
117997  sqlite3 *db = pParse->db;
117998  NameContext sNC;
117999  Column *pCol;
118000  CollSeq *pColl;
118001  int i;
118002  Expr *p;
118003  struct ExprList_item *a;
118004  u64 szAll = 0;
118005
118006  assert( pSelect!=0 );
118007  assert( (pSelect->selFlags & SF_Resolved)!=0 );
118008  assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
118009  if( db->mallocFailed ) return;
118010  memset(&sNC, 0, sizeof(sNC));
118011  sNC.pSrcList = pSelect->pSrc;
118012  a = pSelect->pEList->a;
118013  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
118014    const char *zType;
118015    int n, m;
118016    p = a[i].pExpr;
118017    zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst);
118018    szAll += pCol->szEst;
118019    pCol->affinity = sqlite3ExprAffinity(p);
118020    if( zType && (m = sqlite3Strlen30(zType))>0 ){
118021      n = sqlite3Strlen30(pCol->zName);
118022      pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
118023      if( pCol->zName ){
118024        memcpy(&pCol->zName[n+1], zType, m+1);
118025        pCol->colFlags |= COLFLAG_HASTYPE;
118026      }
118027    }
118028    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
118029    pColl = sqlite3ExprCollSeq(pParse, p);
118030    if( pColl && pCol->zColl==0 ){
118031      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
118032    }
118033  }
118034  pTab->szTabRow = sqlite3LogEst(szAll*4);
118035}
118036
118037/*
118038** Given a SELECT statement, generate a Table structure that describes
118039** the result set of that SELECT.
118040*/
118041SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
118042  Table *pTab;
118043  sqlite3 *db = pParse->db;
118044  int savedFlags;
118045
118046  savedFlags = db->flags;
118047  db->flags &= ~SQLITE_FullColNames;
118048  db->flags |= SQLITE_ShortColNames;
118049  sqlite3SelectPrep(pParse, pSelect, 0);
118050  if( pParse->nErr ) return 0;
118051  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
118052  db->flags = savedFlags;
118053  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
118054  if( pTab==0 ){
118055    return 0;
118056  }
118057  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
118058  ** is disabled */
118059  assert( db->lookaside.bDisable );
118060  pTab->nTabRef = 1;
118061  pTab->zName = 0;
118062  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
118063  sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
118064  sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
118065  pTab->iPKey = -1;
118066  if( db->mallocFailed ){
118067    sqlite3DeleteTable(db, pTab);
118068    return 0;
118069  }
118070  return pTab;
118071}
118072
118073/*
118074** Get a VDBE for the given parser context.  Create a new one if necessary.
118075** If an error occurs, return NULL and leave a message in pParse.
118076*/
118077static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){
118078  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
118079  if( v ) sqlite3VdbeAddOp2(v, OP_Init, 0, 1);
118080  if( pParse->pToplevel==0
118081   && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
118082  ){
118083    pParse->okConstFactor = 1;
118084  }
118085  return v;
118086}
118087SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
118088  Vdbe *v = pParse->pVdbe;
118089  return v ? v : allocVdbe(pParse);
118090}
118091
118092
118093/*
118094** Compute the iLimit and iOffset fields of the SELECT based on the
118095** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
118096** that appear in the original SQL statement after the LIMIT and OFFSET
118097** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
118098** are the integer memory register numbers for counters used to compute
118099** the limit and offset.  If there is no limit and/or offset, then
118100** iLimit and iOffset are negative.
118101**
118102** This routine changes the values of iLimit and iOffset only if
118103** a limit or offset is defined by pLimit and pOffset.  iLimit and
118104** iOffset should have been preset to appropriate default values (zero)
118105** prior to calling this routine.
118106**
118107** The iOffset register (if it exists) is initialized to the value
118108** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
118109** iOffset+1 is initialized to LIMIT+OFFSET.
118110**
118111** Only if pLimit!=0 or pOffset!=0 do the limit registers get
118112** redefined.  The UNION ALL operator uses this property to force
118113** the reuse of the same limit and offset registers across multiple
118114** SELECT statements.
118115*/
118116static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
118117  Vdbe *v = 0;
118118  int iLimit = 0;
118119  int iOffset;
118120  int n;
118121  if( p->iLimit ) return;
118122
118123  /*
118124  ** "LIMIT -1" always shows all rows.  There is some
118125  ** controversy about what the correct behavior should be.
118126  ** The current implementation interprets "LIMIT 0" to mean
118127  ** no rows.
118128  */
118129  sqlite3ExprCacheClear(pParse);
118130  assert( p->pOffset==0 || p->pLimit!=0 );
118131  if( p->pLimit ){
118132    p->iLimit = iLimit = ++pParse->nMem;
118133    v = sqlite3GetVdbe(pParse);
118134    assert( v!=0 );
118135    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
118136      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
118137      VdbeComment((v, "LIMIT counter"));
118138      if( n==0 ){
118139        sqlite3VdbeGoto(v, iBreak);
118140      }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
118141        p->nSelectRow = sqlite3LogEst((u64)n);
118142        p->selFlags |= SF_FixedLimit;
118143      }
118144    }else{
118145      sqlite3ExprCode(pParse, p->pLimit, iLimit);
118146      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
118147      VdbeComment((v, "LIMIT counter"));
118148      sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
118149    }
118150    if( p->pOffset ){
118151      p->iOffset = iOffset = ++pParse->nMem;
118152      pParse->nMem++;   /* Allocate an extra register for limit+offset */
118153      sqlite3ExprCode(pParse, p->pOffset, iOffset);
118154      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
118155      VdbeComment((v, "OFFSET counter"));
118156      sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
118157      VdbeComment((v, "LIMIT+OFFSET"));
118158    }
118159  }
118160}
118161
118162#ifndef SQLITE_OMIT_COMPOUND_SELECT
118163/*
118164** Return the appropriate collating sequence for the iCol-th column of
118165** the result set for the compound-select statement "p".  Return NULL if
118166** the column has no default collating sequence.
118167**
118168** The collating sequence for the compound select is taken from the
118169** left-most term of the select that has a collating sequence.
118170*/
118171static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
118172  CollSeq *pRet;
118173  if( p->pPrior ){
118174    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
118175  }else{
118176    pRet = 0;
118177  }
118178  assert( iCol>=0 );
118179  /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
118180  ** have been thrown during name resolution and we would not have gotten
118181  ** this far */
118182  if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
118183    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
118184  }
118185  return pRet;
118186}
118187
118188/*
118189** The select statement passed as the second parameter is a compound SELECT
118190** with an ORDER BY clause. This function allocates and returns a KeyInfo
118191** structure suitable for implementing the ORDER BY.
118192**
118193** Space to hold the KeyInfo structure is obtained from malloc. The calling
118194** function is responsible for ensuring that this structure is eventually
118195** freed.
118196*/
118197static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
118198  ExprList *pOrderBy = p->pOrderBy;
118199  int nOrderBy = p->pOrderBy->nExpr;
118200  sqlite3 *db = pParse->db;
118201  KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
118202  if( pRet ){
118203    int i;
118204    for(i=0; i<nOrderBy; i++){
118205      struct ExprList_item *pItem = &pOrderBy->a[i];
118206      Expr *pTerm = pItem->pExpr;
118207      CollSeq *pColl;
118208
118209      if( pTerm->flags & EP_Collate ){
118210        pColl = sqlite3ExprCollSeq(pParse, pTerm);
118211      }else{
118212        pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
118213        if( pColl==0 ) pColl = db->pDfltColl;
118214        pOrderBy->a[i].pExpr =
118215          sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
118216      }
118217      assert( sqlite3KeyInfoIsWriteable(pRet) );
118218      pRet->aColl[i] = pColl;
118219      pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
118220    }
118221  }
118222
118223  return pRet;
118224}
118225
118226#ifndef SQLITE_OMIT_CTE
118227/*
118228** This routine generates VDBE code to compute the content of a WITH RECURSIVE
118229** query of the form:
118230**
118231**   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
118232**                         \___________/             \_______________/
118233**                           p->pPrior                      p
118234**
118235**
118236** There is exactly one reference to the recursive-table in the FROM clause
118237** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
118238**
118239** The setup-query runs once to generate an initial set of rows that go
118240** into a Queue table.  Rows are extracted from the Queue table one by
118241** one.  Each row extracted from Queue is output to pDest.  Then the single
118242** extracted row (now in the iCurrent table) becomes the content of the
118243** recursive-table for a recursive-query run.  The output of the recursive-query
118244** is added back into the Queue table.  Then another row is extracted from Queue
118245** and the iteration continues until the Queue table is empty.
118246**
118247** If the compound query operator is UNION then no duplicate rows are ever
118248** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
118249** that have ever been inserted into Queue and causes duplicates to be
118250** discarded.  If the operator is UNION ALL, then duplicates are allowed.
118251**
118252** If the query has an ORDER BY, then entries in the Queue table are kept in
118253** ORDER BY order and the first entry is extracted for each cycle.  Without
118254** an ORDER BY, the Queue table is just a FIFO.
118255**
118256** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
118257** have been output to pDest.  A LIMIT of zero means to output no rows and a
118258** negative LIMIT means to output all rows.  If there is also an OFFSET clause
118259** with a positive value, then the first OFFSET outputs are discarded rather
118260** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
118261** rows have been skipped.
118262*/
118263static void generateWithRecursiveQuery(
118264  Parse *pParse,        /* Parsing context */
118265  Select *p,            /* The recursive SELECT to be coded */
118266  SelectDest *pDest     /* What to do with query results */
118267){
118268  SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
118269  int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
118270  Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
118271  Select *pSetup = p->pPrior;   /* The setup query */
118272  int addrTop;                  /* Top of the loop */
118273  int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
118274  int iCurrent = 0;             /* The Current table */
118275  int regCurrent;               /* Register holding Current table */
118276  int iQueue;                   /* The Queue table */
118277  int iDistinct = 0;            /* To ensure unique results if UNION */
118278  int eDest = SRT_Fifo;         /* How to write to Queue */
118279  SelectDest destQueue;         /* SelectDest targetting the Queue table */
118280  int i;                        /* Loop counter */
118281  int rc;                       /* Result code */
118282  ExprList *pOrderBy;           /* The ORDER BY clause */
118283  Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
118284  int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
118285
118286  /* Obtain authorization to do a recursive query */
118287  if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
118288
118289  /* Process the LIMIT and OFFSET clauses, if they exist */
118290  addrBreak = sqlite3VdbeMakeLabel(v);
118291  p->nSelectRow = 320;  /* 4 billion rows */
118292  computeLimitRegisters(pParse, p, addrBreak);
118293  pLimit = p->pLimit;
118294  pOffset = p->pOffset;
118295  regLimit = p->iLimit;
118296  regOffset = p->iOffset;
118297  p->pLimit = p->pOffset = 0;
118298  p->iLimit = p->iOffset = 0;
118299  pOrderBy = p->pOrderBy;
118300
118301  /* Locate the cursor number of the Current table */
118302  for(i=0; ALWAYS(i<pSrc->nSrc); i++){
118303    if( pSrc->a[i].fg.isRecursive ){
118304      iCurrent = pSrc->a[i].iCursor;
118305      break;
118306    }
118307  }
118308
118309  /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
118310  ** the Distinct table must be exactly one greater than Queue in order
118311  ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
118312  iQueue = pParse->nTab++;
118313  if( p->op==TK_UNION ){
118314    eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
118315    iDistinct = pParse->nTab++;
118316  }else{
118317    eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
118318  }
118319  sqlite3SelectDestInit(&destQueue, eDest, iQueue);
118320
118321  /* Allocate cursors for Current, Queue, and Distinct. */
118322  regCurrent = ++pParse->nMem;
118323  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
118324  if( pOrderBy ){
118325    KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
118326    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
118327                      (char*)pKeyInfo, P4_KEYINFO);
118328    destQueue.pOrderBy = pOrderBy;
118329  }else{
118330    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
118331  }
118332  VdbeComment((v, "Queue table"));
118333  if( iDistinct ){
118334    p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
118335    p->selFlags |= SF_UsesEphemeral;
118336  }
118337
118338  /* Detach the ORDER BY clause from the compound SELECT */
118339  p->pOrderBy = 0;
118340
118341  /* Store the results of the setup-query in Queue. */
118342  pSetup->pNext = 0;
118343  rc = sqlite3Select(pParse, pSetup, &destQueue);
118344  pSetup->pNext = p;
118345  if( rc ) goto end_of_recursive_query;
118346
118347  /* Find the next row in the Queue and output that row */
118348  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
118349
118350  /* Transfer the next row in Queue over to Current */
118351  sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
118352  if( pOrderBy ){
118353    sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
118354  }else{
118355    sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
118356  }
118357  sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
118358
118359  /* Output the single row in Current */
118360  addrCont = sqlite3VdbeMakeLabel(v);
118361  codeOffset(v, regOffset, addrCont);
118362  selectInnerLoop(pParse, p, p->pEList, iCurrent,
118363      0, 0, pDest, addrCont, addrBreak);
118364  if( regLimit ){
118365    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
118366    VdbeCoverage(v);
118367  }
118368  sqlite3VdbeResolveLabel(v, addrCont);
118369
118370  /* Execute the recursive SELECT taking the single row in Current as
118371  ** the value for the recursive-table. Store the results in the Queue.
118372  */
118373  if( p->selFlags & SF_Aggregate ){
118374    sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
118375  }else{
118376    p->pPrior = 0;
118377    sqlite3Select(pParse, p, &destQueue);
118378    assert( p->pPrior==0 );
118379    p->pPrior = pSetup;
118380  }
118381
118382  /* Keep running the loop until the Queue is empty */
118383  sqlite3VdbeGoto(v, addrTop);
118384  sqlite3VdbeResolveLabel(v, addrBreak);
118385
118386end_of_recursive_query:
118387  sqlite3ExprListDelete(pParse->db, p->pOrderBy);
118388  p->pOrderBy = pOrderBy;
118389  p->pLimit = pLimit;
118390  p->pOffset = pOffset;
118391  return;
118392}
118393#endif /* SQLITE_OMIT_CTE */
118394
118395/* Forward references */
118396static int multiSelectOrderBy(
118397  Parse *pParse,        /* Parsing context */
118398  Select *p,            /* The right-most of SELECTs to be coded */
118399  SelectDest *pDest     /* What to do with query results */
118400);
118401
118402/*
118403** Handle the special case of a compound-select that originates from a
118404** VALUES clause.  By handling this as a special case, we avoid deep
118405** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
118406** on a VALUES clause.
118407**
118408** Because the Select object originates from a VALUES clause:
118409**   (1) It has no LIMIT or OFFSET
118410**   (2) All terms are UNION ALL
118411**   (3) There is no ORDER BY clause
118412*/
118413static int multiSelectValues(
118414  Parse *pParse,        /* Parsing context */
118415  Select *p,            /* The right-most of SELECTs to be coded */
118416  SelectDest *pDest     /* What to do with query results */
118417){
118418  Select *pPrior;
118419  int nRow = 1;
118420  int rc = 0;
118421  assert( p->selFlags & SF_MultiValue );
118422  do{
118423    assert( p->selFlags & SF_Values );
118424    assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
118425    assert( p->pLimit==0 );
118426    assert( p->pOffset==0 );
118427    assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
118428    if( p->pPrior==0 ) break;
118429    assert( p->pPrior->pNext==p );
118430    p = p->pPrior;
118431    nRow++;
118432  }while(1);
118433  while( p ){
118434    pPrior = p->pPrior;
118435    p->pPrior = 0;
118436    rc = sqlite3Select(pParse, p, pDest);
118437    p->pPrior = pPrior;
118438    if( rc ) break;
118439    p->nSelectRow = nRow;
118440    p = p->pNext;
118441  }
118442  return rc;
118443}
118444
118445/*
118446** This routine is called to process a compound query form from
118447** two or more separate queries using UNION, UNION ALL, EXCEPT, or
118448** INTERSECT
118449**
118450** "p" points to the right-most of the two queries.  the query on the
118451** left is p->pPrior.  The left query could also be a compound query
118452** in which case this routine will be called recursively.
118453**
118454** The results of the total query are to be written into a destination
118455** of type eDest with parameter iParm.
118456**
118457** Example 1:  Consider a three-way compound SQL statement.
118458**
118459**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
118460**
118461** This statement is parsed up as follows:
118462**
118463**     SELECT c FROM t3
118464**      |
118465**      `----->  SELECT b FROM t2
118466**                |
118467**                `------>  SELECT a FROM t1
118468**
118469** The arrows in the diagram above represent the Select.pPrior pointer.
118470** So if this routine is called with p equal to the t3 query, then
118471** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
118472**
118473** Notice that because of the way SQLite parses compound SELECTs, the
118474** individual selects always group from left to right.
118475*/
118476static int multiSelect(
118477  Parse *pParse,        /* Parsing context */
118478  Select *p,            /* The right-most of SELECTs to be coded */
118479  SelectDest *pDest     /* What to do with query results */
118480){
118481  int rc = SQLITE_OK;   /* Success code from a subroutine */
118482  Select *pPrior;       /* Another SELECT immediately to our left */
118483  Vdbe *v;              /* Generate code to this VDBE */
118484  SelectDest dest;      /* Alternative data destination */
118485  Select *pDelete = 0;  /* Chain of simple selects to delete */
118486  sqlite3 *db;          /* Database connection */
118487#ifndef SQLITE_OMIT_EXPLAIN
118488  int iSub1 = 0;        /* EQP id of left-hand query */
118489  int iSub2 = 0;        /* EQP id of right-hand query */
118490#endif
118491
118492  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
118493  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
118494  */
118495  assert( p && p->pPrior );  /* Calling function guarantees this much */
118496  assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
118497  db = pParse->db;
118498  pPrior = p->pPrior;
118499  dest = *pDest;
118500  if( pPrior->pOrderBy ){
118501    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
118502      selectOpName(p->op));
118503    rc = 1;
118504    goto multi_select_end;
118505  }
118506  if( pPrior->pLimit ){
118507    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
118508      selectOpName(p->op));
118509    rc = 1;
118510    goto multi_select_end;
118511  }
118512
118513  v = sqlite3GetVdbe(pParse);
118514  assert( v!=0 );  /* The VDBE already created by calling function */
118515
118516  /* Create the destination temporary table if necessary
118517  */
118518  if( dest.eDest==SRT_EphemTab ){
118519    assert( p->pEList );
118520    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
118521    dest.eDest = SRT_Table;
118522  }
118523
118524  /* Special handling for a compound-select that originates as a VALUES clause.
118525  */
118526  if( p->selFlags & SF_MultiValue ){
118527    rc = multiSelectValues(pParse, p, &dest);
118528    goto multi_select_end;
118529  }
118530
118531  /* Make sure all SELECTs in the statement have the same number of elements
118532  ** in their result sets.
118533  */
118534  assert( p->pEList && pPrior->pEList );
118535  assert( p->pEList->nExpr==pPrior->pEList->nExpr );
118536
118537#ifndef SQLITE_OMIT_CTE
118538  if( p->selFlags & SF_Recursive ){
118539    generateWithRecursiveQuery(pParse, p, &dest);
118540  }else
118541#endif
118542
118543  /* Compound SELECTs that have an ORDER BY clause are handled separately.
118544  */
118545  if( p->pOrderBy ){
118546    return multiSelectOrderBy(pParse, p, pDest);
118547  }else
118548
118549  /* Generate code for the left and right SELECT statements.
118550  */
118551  switch( p->op ){
118552    case TK_ALL: {
118553      int addr = 0;
118554      int nLimit;
118555      assert( !pPrior->pLimit );
118556      pPrior->iLimit = p->iLimit;
118557      pPrior->iOffset = p->iOffset;
118558      pPrior->pLimit = p->pLimit;
118559      pPrior->pOffset = p->pOffset;
118560      explainSetInteger(iSub1, pParse->iNextSelectId);
118561      rc = sqlite3Select(pParse, pPrior, &dest);
118562      p->pLimit = 0;
118563      p->pOffset = 0;
118564      if( rc ){
118565        goto multi_select_end;
118566      }
118567      p->pPrior = 0;
118568      p->iLimit = pPrior->iLimit;
118569      p->iOffset = pPrior->iOffset;
118570      if( p->iLimit ){
118571        addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
118572        VdbeComment((v, "Jump ahead if LIMIT reached"));
118573        if( p->iOffset ){
118574          sqlite3VdbeAddOp3(v, OP_OffsetLimit,
118575                            p->iLimit, p->iOffset+1, p->iOffset);
118576        }
118577      }
118578      explainSetInteger(iSub2, pParse->iNextSelectId);
118579      rc = sqlite3Select(pParse, p, &dest);
118580      testcase( rc!=SQLITE_OK );
118581      pDelete = p->pPrior;
118582      p->pPrior = pPrior;
118583      p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
118584      if( pPrior->pLimit
118585       && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
118586       && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
118587      ){
118588        p->nSelectRow = sqlite3LogEst((u64)nLimit);
118589      }
118590      if( addr ){
118591        sqlite3VdbeJumpHere(v, addr);
118592      }
118593      break;
118594    }
118595    case TK_EXCEPT:
118596    case TK_UNION: {
118597      int unionTab;    /* Cursor number of the temporary table holding result */
118598      u8 op = 0;       /* One of the SRT_ operations to apply to self */
118599      int priorOp;     /* The SRT_ operation to apply to prior selects */
118600      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
118601      int addr;
118602      SelectDest uniondest;
118603
118604      testcase( p->op==TK_EXCEPT );
118605      testcase( p->op==TK_UNION );
118606      priorOp = SRT_Union;
118607      if( dest.eDest==priorOp ){
118608        /* We can reuse a temporary table generated by a SELECT to our
118609        ** right.
118610        */
118611        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
118612        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
118613        unionTab = dest.iSDParm;
118614      }else{
118615        /* We will need to create our own temporary table to hold the
118616        ** intermediate results.
118617        */
118618        unionTab = pParse->nTab++;
118619        assert( p->pOrderBy==0 );
118620        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
118621        assert( p->addrOpenEphm[0] == -1 );
118622        p->addrOpenEphm[0] = addr;
118623        findRightmost(p)->selFlags |= SF_UsesEphemeral;
118624        assert( p->pEList );
118625      }
118626
118627      /* Code the SELECT statements to our left
118628      */
118629      assert( !pPrior->pOrderBy );
118630      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
118631      explainSetInteger(iSub1, pParse->iNextSelectId);
118632      rc = sqlite3Select(pParse, pPrior, &uniondest);
118633      if( rc ){
118634        goto multi_select_end;
118635      }
118636
118637      /* Code the current SELECT statement
118638      */
118639      if( p->op==TK_EXCEPT ){
118640        op = SRT_Except;
118641      }else{
118642        assert( p->op==TK_UNION );
118643        op = SRT_Union;
118644      }
118645      p->pPrior = 0;
118646      pLimit = p->pLimit;
118647      p->pLimit = 0;
118648      pOffset = p->pOffset;
118649      p->pOffset = 0;
118650      uniondest.eDest = op;
118651      explainSetInteger(iSub2, pParse->iNextSelectId);
118652      rc = sqlite3Select(pParse, p, &uniondest);
118653      testcase( rc!=SQLITE_OK );
118654      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
118655      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
118656      sqlite3ExprListDelete(db, p->pOrderBy);
118657      pDelete = p->pPrior;
118658      p->pPrior = pPrior;
118659      p->pOrderBy = 0;
118660      if( p->op==TK_UNION ){
118661        p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
118662      }
118663      sqlite3ExprDelete(db, p->pLimit);
118664      p->pLimit = pLimit;
118665      p->pOffset = pOffset;
118666      p->iLimit = 0;
118667      p->iOffset = 0;
118668
118669      /* Convert the data in the temporary table into whatever form
118670      ** it is that we currently need.
118671      */
118672      assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
118673      if( dest.eDest!=priorOp ){
118674        int iCont, iBreak, iStart;
118675        assert( p->pEList );
118676        if( dest.eDest==SRT_Output ){
118677          Select *pFirst = p;
118678          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
118679          generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
118680        }
118681        iBreak = sqlite3VdbeMakeLabel(v);
118682        iCont = sqlite3VdbeMakeLabel(v);
118683        computeLimitRegisters(pParse, p, iBreak);
118684        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
118685        iStart = sqlite3VdbeCurrentAddr(v);
118686        selectInnerLoop(pParse, p, p->pEList, unionTab,
118687                        0, 0, &dest, iCont, iBreak);
118688        sqlite3VdbeResolveLabel(v, iCont);
118689        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
118690        sqlite3VdbeResolveLabel(v, iBreak);
118691        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
118692      }
118693      break;
118694    }
118695    default: assert( p->op==TK_INTERSECT ); {
118696      int tab1, tab2;
118697      int iCont, iBreak, iStart;
118698      Expr *pLimit, *pOffset;
118699      int addr;
118700      SelectDest intersectdest;
118701      int r1;
118702
118703      /* INTERSECT is different from the others since it requires
118704      ** two temporary tables.  Hence it has its own case.  Begin
118705      ** by allocating the tables we will need.
118706      */
118707      tab1 = pParse->nTab++;
118708      tab2 = pParse->nTab++;
118709      assert( p->pOrderBy==0 );
118710
118711      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
118712      assert( p->addrOpenEphm[0] == -1 );
118713      p->addrOpenEphm[0] = addr;
118714      findRightmost(p)->selFlags |= SF_UsesEphemeral;
118715      assert( p->pEList );
118716
118717      /* Code the SELECTs to our left into temporary table "tab1".
118718      */
118719      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
118720      explainSetInteger(iSub1, pParse->iNextSelectId);
118721      rc = sqlite3Select(pParse, pPrior, &intersectdest);
118722      if( rc ){
118723        goto multi_select_end;
118724      }
118725
118726      /* Code the current SELECT into temporary table "tab2"
118727      */
118728      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
118729      assert( p->addrOpenEphm[1] == -1 );
118730      p->addrOpenEphm[1] = addr;
118731      p->pPrior = 0;
118732      pLimit = p->pLimit;
118733      p->pLimit = 0;
118734      pOffset = p->pOffset;
118735      p->pOffset = 0;
118736      intersectdest.iSDParm = tab2;
118737      explainSetInteger(iSub2, pParse->iNextSelectId);
118738      rc = sqlite3Select(pParse, p, &intersectdest);
118739      testcase( rc!=SQLITE_OK );
118740      pDelete = p->pPrior;
118741      p->pPrior = pPrior;
118742      if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
118743      sqlite3ExprDelete(db, p->pLimit);
118744      p->pLimit = pLimit;
118745      p->pOffset = pOffset;
118746
118747      /* Generate code to take the intersection of the two temporary
118748      ** tables.
118749      */
118750      assert( p->pEList );
118751      if( dest.eDest==SRT_Output ){
118752        Select *pFirst = p;
118753        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
118754        generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
118755      }
118756      iBreak = sqlite3VdbeMakeLabel(v);
118757      iCont = sqlite3VdbeMakeLabel(v);
118758      computeLimitRegisters(pParse, p, iBreak);
118759      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
118760      r1 = sqlite3GetTempReg(pParse);
118761      iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
118762      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
118763      sqlite3ReleaseTempReg(pParse, r1);
118764      selectInnerLoop(pParse, p, p->pEList, tab1,
118765                      0, 0, &dest, iCont, iBreak);
118766      sqlite3VdbeResolveLabel(v, iCont);
118767      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
118768      sqlite3VdbeResolveLabel(v, iBreak);
118769      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
118770      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
118771      break;
118772    }
118773  }
118774
118775  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
118776
118777  /* Compute collating sequences used by
118778  ** temporary tables needed to implement the compound select.
118779  ** Attach the KeyInfo structure to all temporary tables.
118780  **
118781  ** This section is run by the right-most SELECT statement only.
118782  ** SELECT statements to the left always skip this part.  The right-most
118783  ** SELECT might also skip this part if it has no ORDER BY clause and
118784  ** no temp tables are required.
118785  */
118786  if( p->selFlags & SF_UsesEphemeral ){
118787    int i;                        /* Loop counter */
118788    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
118789    Select *pLoop;                /* For looping through SELECT statements */
118790    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
118791    int nCol;                     /* Number of columns in result set */
118792
118793    assert( p->pNext==0 );
118794    nCol = p->pEList->nExpr;
118795    pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
118796    if( !pKeyInfo ){
118797      rc = SQLITE_NOMEM_BKPT;
118798      goto multi_select_end;
118799    }
118800    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
118801      *apColl = multiSelectCollSeq(pParse, p, i);
118802      if( 0==*apColl ){
118803        *apColl = db->pDfltColl;
118804      }
118805    }
118806
118807    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
118808      for(i=0; i<2; i++){
118809        int addr = pLoop->addrOpenEphm[i];
118810        if( addr<0 ){
118811          /* If [0] is unused then [1] is also unused.  So we can
118812          ** always safely abort as soon as the first unused slot is found */
118813          assert( pLoop->addrOpenEphm[1]<0 );
118814          break;
118815        }
118816        sqlite3VdbeChangeP2(v, addr, nCol);
118817        sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
118818                            P4_KEYINFO);
118819        pLoop->addrOpenEphm[i] = -1;
118820      }
118821    }
118822    sqlite3KeyInfoUnref(pKeyInfo);
118823  }
118824
118825multi_select_end:
118826  pDest->iSdst = dest.iSdst;
118827  pDest->nSdst = dest.nSdst;
118828  sqlite3SelectDelete(db, pDelete);
118829  return rc;
118830}
118831#endif /* SQLITE_OMIT_COMPOUND_SELECT */
118832
118833/*
118834** Error message for when two or more terms of a compound select have different
118835** size result sets.
118836*/
118837SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
118838  if( p->selFlags & SF_Values ){
118839    sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
118840  }else{
118841    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
118842      " do not have the same number of result columns", selectOpName(p->op));
118843  }
118844}
118845
118846/*
118847** Code an output subroutine for a coroutine implementation of a
118848** SELECT statment.
118849**
118850** The data to be output is contained in pIn->iSdst.  There are
118851** pIn->nSdst columns to be output.  pDest is where the output should
118852** be sent.
118853**
118854** regReturn is the number of the register holding the subroutine
118855** return address.
118856**
118857** If regPrev>0 then it is the first register in a vector that
118858** records the previous output.  mem[regPrev] is a flag that is false
118859** if there has been no previous output.  If regPrev>0 then code is
118860** generated to suppress duplicates.  pKeyInfo is used for comparing
118861** keys.
118862**
118863** If the LIMIT found in p->iLimit is reached, jump immediately to
118864** iBreak.
118865*/
118866static int generateOutputSubroutine(
118867  Parse *pParse,          /* Parsing context */
118868  Select *p,              /* The SELECT statement */
118869  SelectDest *pIn,        /* Coroutine supplying data */
118870  SelectDest *pDest,      /* Where to send the data */
118871  int regReturn,          /* The return address register */
118872  int regPrev,            /* Previous result register.  No uniqueness if 0 */
118873  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
118874  int iBreak              /* Jump here if we hit the LIMIT */
118875){
118876  Vdbe *v = pParse->pVdbe;
118877  int iContinue;
118878  int addr;
118879
118880  addr = sqlite3VdbeCurrentAddr(v);
118881  iContinue = sqlite3VdbeMakeLabel(v);
118882
118883  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
118884  */
118885  if( regPrev ){
118886    int addr1, addr2;
118887    addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
118888    addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
118889                              (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
118890    sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
118891    sqlite3VdbeJumpHere(v, addr1);
118892    sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
118893    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
118894  }
118895  if( pParse->db->mallocFailed ) return 0;
118896
118897  /* Suppress the first OFFSET entries if there is an OFFSET clause
118898  */
118899  codeOffset(v, p->iOffset, iContinue);
118900
118901  assert( pDest->eDest!=SRT_Exists );
118902  assert( pDest->eDest!=SRT_Table );
118903  switch( pDest->eDest ){
118904    /* Store the result as data using a unique key.
118905    */
118906    case SRT_EphemTab: {
118907      int r1 = sqlite3GetTempReg(pParse);
118908      int r2 = sqlite3GetTempReg(pParse);
118909      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
118910      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
118911      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
118912      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
118913      sqlite3ReleaseTempReg(pParse, r2);
118914      sqlite3ReleaseTempReg(pParse, r1);
118915      break;
118916    }
118917
118918#ifndef SQLITE_OMIT_SUBQUERY
118919    /* If we are creating a set for an "expr IN (SELECT ...)".
118920    */
118921    case SRT_Set: {
118922      int r1;
118923      testcase( pIn->nSdst>1 );
118924      r1 = sqlite3GetTempReg(pParse);
118925      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
118926          r1, pDest->zAffSdst, pIn->nSdst);
118927      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
118928      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
118929                           pIn->iSdst, pIn->nSdst);
118930      sqlite3ReleaseTempReg(pParse, r1);
118931      break;
118932    }
118933
118934    /* If this is a scalar select that is part of an expression, then
118935    ** store the results in the appropriate memory cell and break out
118936    ** of the scan loop.
118937    */
118938    case SRT_Mem: {
118939      assert( pIn->nSdst==1 || pParse->nErr>0 );  testcase( pIn->nSdst!=1 );
118940      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
118941      /* The LIMIT clause will jump out of the loop for us */
118942      break;
118943    }
118944#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
118945
118946    /* The results are stored in a sequence of registers
118947    ** starting at pDest->iSdst.  Then the co-routine yields.
118948    */
118949    case SRT_Coroutine: {
118950      if( pDest->iSdst==0 ){
118951        pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
118952        pDest->nSdst = pIn->nSdst;
118953      }
118954      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
118955      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
118956      break;
118957    }
118958
118959    /* If none of the above, then the result destination must be
118960    ** SRT_Output.  This routine is never called with any other
118961    ** destination other than the ones handled above or SRT_Output.
118962    **
118963    ** For SRT_Output, results are stored in a sequence of registers.
118964    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
118965    ** return the next row of result.
118966    */
118967    default: {
118968      assert( pDest->eDest==SRT_Output );
118969      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
118970      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
118971      break;
118972    }
118973  }
118974
118975  /* Jump to the end of the loop if the LIMIT is reached.
118976  */
118977  if( p->iLimit ){
118978    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
118979  }
118980
118981  /* Generate the subroutine return
118982  */
118983  sqlite3VdbeResolveLabel(v, iContinue);
118984  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
118985
118986  return addr;
118987}
118988
118989/*
118990** Alternative compound select code generator for cases when there
118991** is an ORDER BY clause.
118992**
118993** We assume a query of the following form:
118994**
118995**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
118996**
118997** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
118998** is to code both <selectA> and <selectB> with the ORDER BY clause as
118999** co-routines.  Then run the co-routines in parallel and merge the results
119000** into the output.  In addition to the two coroutines (called selectA and
119001** selectB) there are 7 subroutines:
119002**
119003**    outA:    Move the output of the selectA coroutine into the output
119004**             of the compound query.
119005**
119006**    outB:    Move the output of the selectB coroutine into the output
119007**             of the compound query.  (Only generated for UNION and
119008**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
119009**             appears only in B.)
119010**
119011**    AltB:    Called when there is data from both coroutines and A<B.
119012**
119013**    AeqB:    Called when there is data from both coroutines and A==B.
119014**
119015**    AgtB:    Called when there is data from both coroutines and A>B.
119016**
119017**    EofA:    Called when data is exhausted from selectA.
119018**
119019**    EofB:    Called when data is exhausted from selectB.
119020**
119021** The implementation of the latter five subroutines depend on which
119022** <operator> is used:
119023**
119024**
119025**             UNION ALL         UNION            EXCEPT          INTERSECT
119026**          -------------  -----------------  --------------  -----------------
119027**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
119028**
119029**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
119030**
119031**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
119032**
119033**   EofA:   outB, nextB      outB, nextB          halt             halt
119034**
119035**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
119036**
119037** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
119038** causes an immediate jump to EofA and an EOF on B following nextB causes
119039** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
119040** following nextX causes a jump to the end of the select processing.
119041**
119042** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
119043** within the output subroutine.  The regPrev register set holds the previously
119044** output value.  A comparison is made against this value and the output
119045** is skipped if the next results would be the same as the previous.
119046**
119047** The implementation plan is to implement the two coroutines and seven
119048** subroutines first, then put the control logic at the bottom.  Like this:
119049**
119050**          goto Init
119051**     coA: coroutine for left query (A)
119052**     coB: coroutine for right query (B)
119053**    outA: output one row of A
119054**    outB: output one row of B (UNION and UNION ALL only)
119055**    EofA: ...
119056**    EofB: ...
119057**    AltB: ...
119058**    AeqB: ...
119059**    AgtB: ...
119060**    Init: initialize coroutine registers
119061**          yield coA
119062**          if eof(A) goto EofA
119063**          yield coB
119064**          if eof(B) goto EofB
119065**    Cmpr: Compare A, B
119066**          Jump AltB, AeqB, AgtB
119067**     End: ...
119068**
119069** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
119070** actually called using Gosub and they do not Return.  EofA and EofB loop
119071** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
119072** and AgtB jump to either L2 or to one of EofA or EofB.
119073*/
119074#ifndef SQLITE_OMIT_COMPOUND_SELECT
119075static int multiSelectOrderBy(
119076  Parse *pParse,        /* Parsing context */
119077  Select *p,            /* The right-most of SELECTs to be coded */
119078  SelectDest *pDest     /* What to do with query results */
119079){
119080  int i, j;             /* Loop counters */
119081  Select *pPrior;       /* Another SELECT immediately to our left */
119082  Vdbe *v;              /* Generate code to this VDBE */
119083  SelectDest destA;     /* Destination for coroutine A */
119084  SelectDest destB;     /* Destination for coroutine B */
119085  int regAddrA;         /* Address register for select-A coroutine */
119086  int regAddrB;         /* Address register for select-B coroutine */
119087  int addrSelectA;      /* Address of the select-A coroutine */
119088  int addrSelectB;      /* Address of the select-B coroutine */
119089  int regOutA;          /* Address register for the output-A subroutine */
119090  int regOutB;          /* Address register for the output-B subroutine */
119091  int addrOutA;         /* Address of the output-A subroutine */
119092  int addrOutB = 0;     /* Address of the output-B subroutine */
119093  int addrEofA;         /* Address of the select-A-exhausted subroutine */
119094  int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
119095  int addrEofB;         /* Address of the select-B-exhausted subroutine */
119096  int addrAltB;         /* Address of the A<B subroutine */
119097  int addrAeqB;         /* Address of the A==B subroutine */
119098  int addrAgtB;         /* Address of the A>B subroutine */
119099  int regLimitA;        /* Limit register for select-A */
119100  int regLimitB;        /* Limit register for select-A */
119101  int regPrev;          /* A range of registers to hold previous output */
119102  int savedLimit;       /* Saved value of p->iLimit */
119103  int savedOffset;      /* Saved value of p->iOffset */
119104  int labelCmpr;        /* Label for the start of the merge algorithm */
119105  int labelEnd;         /* Label for the end of the overall SELECT stmt */
119106  int addr1;            /* Jump instructions that get retargetted */
119107  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
119108  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
119109  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
119110  sqlite3 *db;          /* Database connection */
119111  ExprList *pOrderBy;   /* The ORDER BY clause */
119112  int nOrderBy;         /* Number of terms in the ORDER BY clause */
119113  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
119114#ifndef SQLITE_OMIT_EXPLAIN
119115  int iSub1;            /* EQP id of left-hand query */
119116  int iSub2;            /* EQP id of right-hand query */
119117#endif
119118
119119  assert( p->pOrderBy!=0 );
119120  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
119121  db = pParse->db;
119122  v = pParse->pVdbe;
119123  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
119124  labelEnd = sqlite3VdbeMakeLabel(v);
119125  labelCmpr = sqlite3VdbeMakeLabel(v);
119126
119127
119128  /* Patch up the ORDER BY clause
119129  */
119130  op = p->op;
119131  pPrior = p->pPrior;
119132  assert( pPrior->pOrderBy==0 );
119133  pOrderBy = p->pOrderBy;
119134  assert( pOrderBy );
119135  nOrderBy = pOrderBy->nExpr;
119136
119137  /* For operators other than UNION ALL we have to make sure that
119138  ** the ORDER BY clause covers every term of the result set.  Add
119139  ** terms to the ORDER BY clause as necessary.
119140  */
119141  if( op!=TK_ALL ){
119142    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
119143      struct ExprList_item *pItem;
119144      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
119145        assert( pItem->u.x.iOrderByCol>0 );
119146        if( pItem->u.x.iOrderByCol==i ) break;
119147      }
119148      if( j==nOrderBy ){
119149        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
119150        if( pNew==0 ) return SQLITE_NOMEM_BKPT;
119151        pNew->flags |= EP_IntValue;
119152        pNew->u.iValue = i;
119153        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
119154        if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
119155      }
119156    }
119157  }
119158
119159  /* Compute the comparison permutation and keyinfo that is used with
119160  ** the permutation used to determine if the next
119161  ** row of results comes from selectA or selectB.  Also add explicit
119162  ** collations to the ORDER BY clause terms so that when the subqueries
119163  ** to the right and the left are evaluated, they use the correct
119164  ** collation.
119165  */
119166  aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
119167  if( aPermute ){
119168    struct ExprList_item *pItem;
119169    aPermute[0] = nOrderBy;
119170    for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
119171      assert( pItem->u.x.iOrderByCol>0 );
119172      assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
119173      aPermute[i] = pItem->u.x.iOrderByCol - 1;
119174    }
119175    pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
119176  }else{
119177    pKeyMerge = 0;
119178  }
119179
119180  /* Reattach the ORDER BY clause to the query.
119181  */
119182  p->pOrderBy = pOrderBy;
119183  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
119184
119185  /* Allocate a range of temporary registers and the KeyInfo needed
119186  ** for the logic that removes duplicate result rows when the
119187  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
119188  */
119189  if( op==TK_ALL ){
119190    regPrev = 0;
119191  }else{
119192    int nExpr = p->pEList->nExpr;
119193    assert( nOrderBy>=nExpr || db->mallocFailed );
119194    regPrev = pParse->nMem+1;
119195    pParse->nMem += nExpr+1;
119196    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
119197    pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
119198    if( pKeyDup ){
119199      assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
119200      for(i=0; i<nExpr; i++){
119201        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
119202        pKeyDup->aSortOrder[i] = 0;
119203      }
119204    }
119205  }
119206
119207  /* Separate the left and the right query from one another
119208  */
119209  p->pPrior = 0;
119210  pPrior->pNext = 0;
119211  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
119212  if( pPrior->pPrior==0 ){
119213    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
119214  }
119215
119216  /* Compute the limit registers */
119217  computeLimitRegisters(pParse, p, labelEnd);
119218  if( p->iLimit && op==TK_ALL ){
119219    regLimitA = ++pParse->nMem;
119220    regLimitB = ++pParse->nMem;
119221    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
119222                                  regLimitA);
119223    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
119224  }else{
119225    regLimitA = regLimitB = 0;
119226  }
119227  sqlite3ExprDelete(db, p->pLimit);
119228  p->pLimit = 0;
119229  sqlite3ExprDelete(db, p->pOffset);
119230  p->pOffset = 0;
119231
119232  regAddrA = ++pParse->nMem;
119233  regAddrB = ++pParse->nMem;
119234  regOutA = ++pParse->nMem;
119235  regOutB = ++pParse->nMem;
119236  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
119237  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
119238
119239  /* Generate a coroutine to evaluate the SELECT statement to the
119240  ** left of the compound operator - the "A" select.
119241  */
119242  addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
119243  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
119244  VdbeComment((v, "left SELECT"));
119245  pPrior->iLimit = regLimitA;
119246  explainSetInteger(iSub1, pParse->iNextSelectId);
119247  sqlite3Select(pParse, pPrior, &destA);
119248  sqlite3VdbeEndCoroutine(v, regAddrA);
119249  sqlite3VdbeJumpHere(v, addr1);
119250
119251  /* Generate a coroutine to evaluate the SELECT statement on
119252  ** the right - the "B" select
119253  */
119254  addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
119255  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
119256  VdbeComment((v, "right SELECT"));
119257  savedLimit = p->iLimit;
119258  savedOffset = p->iOffset;
119259  p->iLimit = regLimitB;
119260  p->iOffset = 0;
119261  explainSetInteger(iSub2, pParse->iNextSelectId);
119262  sqlite3Select(pParse, p, &destB);
119263  p->iLimit = savedLimit;
119264  p->iOffset = savedOffset;
119265  sqlite3VdbeEndCoroutine(v, regAddrB);
119266
119267  /* Generate a subroutine that outputs the current row of the A
119268  ** select as the next output row of the compound select.
119269  */
119270  VdbeNoopComment((v, "Output routine for A"));
119271  addrOutA = generateOutputSubroutine(pParse,
119272                 p, &destA, pDest, regOutA,
119273                 regPrev, pKeyDup, labelEnd);
119274
119275  /* Generate a subroutine that outputs the current row of the B
119276  ** select as the next output row of the compound select.
119277  */
119278  if( op==TK_ALL || op==TK_UNION ){
119279    VdbeNoopComment((v, "Output routine for B"));
119280    addrOutB = generateOutputSubroutine(pParse,
119281                 p, &destB, pDest, regOutB,
119282                 regPrev, pKeyDup, labelEnd);
119283  }
119284  sqlite3KeyInfoUnref(pKeyDup);
119285
119286  /* Generate a subroutine to run when the results from select A
119287  ** are exhausted and only data in select B remains.
119288  */
119289  if( op==TK_EXCEPT || op==TK_INTERSECT ){
119290    addrEofA_noB = addrEofA = labelEnd;
119291  }else{
119292    VdbeNoopComment((v, "eof-A subroutine"));
119293    addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
119294    addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
119295                                     VdbeCoverage(v);
119296    sqlite3VdbeGoto(v, addrEofA);
119297    p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
119298  }
119299
119300  /* Generate a subroutine to run when the results from select B
119301  ** are exhausted and only data in select A remains.
119302  */
119303  if( op==TK_INTERSECT ){
119304    addrEofB = addrEofA;
119305    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
119306  }else{
119307    VdbeNoopComment((v, "eof-B subroutine"));
119308    addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
119309    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
119310    sqlite3VdbeGoto(v, addrEofB);
119311  }
119312
119313  /* Generate code to handle the case of A<B
119314  */
119315  VdbeNoopComment((v, "A-lt-B subroutine"));
119316  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
119317  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
119318  sqlite3VdbeGoto(v, labelCmpr);
119319
119320  /* Generate code to handle the case of A==B
119321  */
119322  if( op==TK_ALL ){
119323    addrAeqB = addrAltB;
119324  }else if( op==TK_INTERSECT ){
119325    addrAeqB = addrAltB;
119326    addrAltB++;
119327  }else{
119328    VdbeNoopComment((v, "A-eq-B subroutine"));
119329    addrAeqB =
119330    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
119331    sqlite3VdbeGoto(v, labelCmpr);
119332  }
119333
119334  /* Generate code to handle the case of A>B
119335  */
119336  VdbeNoopComment((v, "A-gt-B subroutine"));
119337  addrAgtB = sqlite3VdbeCurrentAddr(v);
119338  if( op==TK_ALL || op==TK_UNION ){
119339    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
119340  }
119341  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
119342  sqlite3VdbeGoto(v, labelCmpr);
119343
119344  /* This code runs once to initialize everything.
119345  */
119346  sqlite3VdbeJumpHere(v, addr1);
119347  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
119348  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
119349
119350  /* Implement the main merge loop
119351  */
119352  sqlite3VdbeResolveLabel(v, labelCmpr);
119353  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
119354  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
119355                         (char*)pKeyMerge, P4_KEYINFO);
119356  sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
119357  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
119358
119359  /* Jump to the this point in order to terminate the query.
119360  */
119361  sqlite3VdbeResolveLabel(v, labelEnd);
119362
119363  /* Set the number of output columns
119364  */
119365  if( pDest->eDest==SRT_Output ){
119366    Select *pFirst = pPrior;
119367    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
119368    generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
119369  }
119370
119371  /* Reassembly the compound query so that it will be freed correctly
119372  ** by the calling function */
119373  if( p->pPrior ){
119374    sqlite3SelectDelete(db, p->pPrior);
119375  }
119376  p->pPrior = pPrior;
119377  pPrior->pNext = p;
119378
119379  /*** TBD:  Insert subroutine calls to close cursors on incomplete
119380  **** subqueries ****/
119381  explainComposite(pParse, p->op, iSub1, iSub2, 0);
119382  return pParse->nErr!=0;
119383}
119384#endif
119385
119386#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
119387/* Forward Declarations */
119388static void substExprList(Parse*, ExprList*, int, ExprList*);
119389static void substSelect(Parse*, Select *, int, ExprList*, int);
119390
119391/*
119392** Scan through the expression pExpr.  Replace every reference to
119393** a column in table number iTable with a copy of the iColumn-th
119394** entry in pEList.  (But leave references to the ROWID column
119395** unchanged.)
119396**
119397** This routine is part of the flattening procedure.  A subquery
119398** whose result set is defined by pEList appears as entry in the
119399** FROM clause of a SELECT such that the VDBE cursor assigned to that
119400** FORM clause entry is iTable.  This routine make the necessary
119401** changes to pExpr so that it refers directly to the source table
119402** of the subquery rather the result set of the subquery.
119403*/
119404static Expr *substExpr(
119405  Parse *pParse,      /* Report errors here */
119406  Expr *pExpr,        /* Expr in which substitution occurs */
119407  int iTable,         /* Table to be substituted */
119408  ExprList *pEList    /* Substitute expressions */
119409){
119410  sqlite3 *db = pParse->db;
119411  if( pExpr==0 ) return 0;
119412  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
119413    if( pExpr->iColumn<0 ){
119414      pExpr->op = TK_NULL;
119415    }else{
119416      Expr *pNew;
119417      Expr *pCopy = pEList->a[pExpr->iColumn].pExpr;
119418      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
119419      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
119420      if( sqlite3ExprIsVector(pCopy) ){
119421        sqlite3VectorErrorMsg(pParse, pCopy);
119422      }else{
119423        pNew = sqlite3ExprDup(db, pCopy, 0);
119424        if( pNew && (pExpr->flags & EP_FromJoin) ){
119425          pNew->iRightJoinTable = pExpr->iRightJoinTable;
119426          pNew->flags |= EP_FromJoin;
119427        }
119428        sqlite3ExprDelete(db, pExpr);
119429        pExpr = pNew;
119430      }
119431    }
119432  }else{
119433    pExpr->pLeft = substExpr(pParse, pExpr->pLeft, iTable, pEList);
119434    pExpr->pRight = substExpr(pParse, pExpr->pRight, iTable, pEList);
119435    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
119436      substSelect(pParse, pExpr->x.pSelect, iTable, pEList, 1);
119437    }else{
119438      substExprList(pParse, pExpr->x.pList, iTable, pEList);
119439    }
119440  }
119441  return pExpr;
119442}
119443static void substExprList(
119444  Parse *pParse,       /* Report errors here */
119445  ExprList *pList,     /* List to scan and in which to make substitutes */
119446  int iTable,          /* Table to be substituted */
119447  ExprList *pEList     /* Substitute values */
119448){
119449  int i;
119450  if( pList==0 ) return;
119451  for(i=0; i<pList->nExpr; i++){
119452    pList->a[i].pExpr = substExpr(pParse, pList->a[i].pExpr, iTable, pEList);
119453  }
119454}
119455static void substSelect(
119456  Parse *pParse,       /* Report errors here */
119457  Select *p,           /* SELECT statement in which to make substitutions */
119458  int iTable,          /* Table to be replaced */
119459  ExprList *pEList,    /* Substitute values */
119460  int doPrior          /* Do substitutes on p->pPrior too */
119461){
119462  SrcList *pSrc;
119463  struct SrcList_item *pItem;
119464  int i;
119465  if( !p ) return;
119466  do{
119467    substExprList(pParse, p->pEList, iTable, pEList);
119468    substExprList(pParse, p->pGroupBy, iTable, pEList);
119469    substExprList(pParse, p->pOrderBy, iTable, pEList);
119470    p->pHaving = substExpr(pParse, p->pHaving, iTable, pEList);
119471    p->pWhere = substExpr(pParse, p->pWhere, iTable, pEList);
119472    pSrc = p->pSrc;
119473    assert( pSrc!=0 );
119474    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
119475      substSelect(pParse, pItem->pSelect, iTable, pEList, 1);
119476      if( pItem->fg.isTabFunc ){
119477        substExprList(pParse, pItem->u1.pFuncArg, iTable, pEList);
119478      }
119479    }
119480  }while( doPrior && (p = p->pPrior)!=0 );
119481}
119482#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
119483
119484#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
119485/*
119486** This routine attempts to flatten subqueries as a performance optimization.
119487** This routine returns 1 if it makes changes and 0 if no flattening occurs.
119488**
119489** To understand the concept of flattening, consider the following
119490** query:
119491**
119492**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
119493**
119494** The default way of implementing this query is to execute the
119495** subquery first and store the results in a temporary table, then
119496** run the outer query on that temporary table.  This requires two
119497** passes over the data.  Furthermore, because the temporary table
119498** has no indices, the WHERE clause on the outer query cannot be
119499** optimized.
119500**
119501** This routine attempts to rewrite queries such as the above into
119502** a single flat select, like this:
119503**
119504**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
119505**
119506** The code generated for this simplification gives the same result
119507** but only has to scan the data once.  And because indices might
119508** exist on the table t1, a complete scan of the data might be
119509** avoided.
119510**
119511** Flattening is only attempted if all of the following are true:
119512**
119513**   (1)  The subquery and the outer query do not both use aggregates.
119514**
119515**   (2)  The subquery is not an aggregate or (2a) the outer query is not a join
119516**        and (2b) the outer query does not use subqueries other than the one
119517**        FROM-clause subquery that is a candidate for flattening.  (2b is
119518**        due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
119519**
119520**   (3)  The subquery is not the right operand of a left outer join
119521**        (Originally ticket #306.  Strengthened by ticket #3300)
119522**
119523**   (4)  The subquery is not DISTINCT.
119524**
119525**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
119526**        sub-queries that were excluded from this optimization. Restriction
119527**        (4) has since been expanded to exclude all DISTINCT subqueries.
119528**
119529**   (6)  The subquery does not use aggregates or the outer query is not
119530**        DISTINCT.
119531**
119532**   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
119533**        A FROM clause, consider adding a FROM close with the special
119534**        table sqlite_once that consists of a single row containing a
119535**        single NULL.
119536**
119537**   (8)  The subquery does not use LIMIT or the outer query is not a join.
119538**
119539**   (9)  The subquery does not use LIMIT or the outer query does not use
119540**        aggregates.
119541**
119542**  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
119543**        accidently carried the comment forward until 2014-09-15.  Original
119544**        text: "The subquery does not use aggregates or the outer query
119545**        does not use LIMIT."
119546**
119547**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
119548**
119549**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
119550**        a separate restriction deriving from ticket #350.
119551**
119552**  (13)  The subquery and outer query do not both use LIMIT.
119553**
119554**  (14)  The subquery does not use OFFSET.
119555**
119556**  (15)  The outer query is not part of a compound select or the
119557**        subquery does not have a LIMIT clause.
119558**        (See ticket #2339 and ticket [02a8e81d44]).
119559**
119560**  (16)  The outer query is not an aggregate or the subquery does
119561**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
119562**        until we introduced the group_concat() function.
119563**
119564**  (17)  The sub-query is not a compound select, or it is a UNION ALL
119565**        compound clause made up entirely of non-aggregate queries, and
119566**        the parent query:
119567**
119568**          * is not itself part of a compound select,
119569**          * is not an aggregate or DISTINCT query, and
119570**          * is not a join
119571**
119572**        The parent and sub-query may contain WHERE clauses. Subject to
119573**        rules (11), (13) and (14), they may also contain ORDER BY,
119574**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
119575**        operator other than UNION ALL because all the other compound
119576**        operators have an implied DISTINCT which is disallowed by
119577**        restriction (4).
119578**
119579**        Also, each component of the sub-query must return the same number
119580**        of result columns. This is actually a requirement for any compound
119581**        SELECT statement, but all the code here does is make sure that no
119582**        such (illegal) sub-query is flattened. The caller will detect the
119583**        syntax error and return a detailed message.
119584**
119585**  (18)  If the sub-query is a compound select, then all terms of the
119586**        ORDER by clause of the parent must be simple references to
119587**        columns of the sub-query.
119588**
119589**  (19)  The subquery does not use LIMIT or the outer query does not
119590**        have a WHERE clause.
119591**
119592**  (20)  If the sub-query is a compound select, then it must not use
119593**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
119594**        somewhat by saying that the terms of the ORDER BY clause must
119595**        appear as unmodified result columns in the outer query.  But we
119596**        have other optimizations in mind to deal with that case.
119597**
119598**  (21)  The subquery does not use LIMIT or the outer query is not
119599**        DISTINCT.  (See ticket [752e1646fc]).
119600**
119601**  (22)  The subquery is not a recursive CTE.
119602**
119603**  (23)  The parent is not a recursive CTE, or the sub-query is not a
119604**        compound query. This restriction is because transforming the
119605**        parent to a compound query confuses the code that handles
119606**        recursive queries in multiSelect().
119607**
119608**  (24)  The subquery is not an aggregate that uses the built-in min() or
119609**        or max() functions.  (Without this restriction, a query like:
119610**        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
119611**        return the value X for which Y was maximal.)
119612**
119613**
119614** In this routine, the "p" parameter is a pointer to the outer query.
119615** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
119616** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
119617**
119618** If flattening is not attempted, this routine is a no-op and returns 0.
119619** If flattening is attempted this routine returns 1.
119620**
119621** All of the expression analysis must occur on both the outer query and
119622** the subquery before this routine runs.
119623*/
119624static int flattenSubquery(
119625  Parse *pParse,       /* Parsing context */
119626  Select *p,           /* The parent or outer SELECT statement */
119627  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
119628  int isAgg,           /* True if outer SELECT uses aggregate functions */
119629  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
119630){
119631  const char *zSavedAuthContext = pParse->zAuthContext;
119632  Select *pParent;    /* Current UNION ALL term of the other query */
119633  Select *pSub;       /* The inner query or "subquery" */
119634  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
119635  SrcList *pSrc;      /* The FROM clause of the outer query */
119636  SrcList *pSubSrc;   /* The FROM clause of the subquery */
119637  ExprList *pList;    /* The result set of the outer query */
119638  int iParent;        /* VDBE cursor number of the pSub result set temp table */
119639  int i;              /* Loop counter */
119640  Expr *pWhere;                    /* The WHERE clause */
119641  struct SrcList_item *pSubitem;   /* The subquery */
119642  sqlite3 *db = pParse->db;
119643
119644  /* Check to see if flattening is permitted.  Return 0 if not.
119645  */
119646  assert( p!=0 );
119647  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
119648  if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
119649  pSrc = p->pSrc;
119650  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
119651  pSubitem = &pSrc->a[iFrom];
119652  iParent = pSubitem->iCursor;
119653  pSub = pSubitem->pSelect;
119654  assert( pSub!=0 );
119655  if( subqueryIsAgg ){
119656    if( isAgg ) return 0;                                /* Restriction (1)   */
119657    if( pSrc->nSrc>1 ) return 0;                         /* Restriction (2a)  */
119658    if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
119659     || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
119660     || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
119661    ){
119662      return 0;                                          /* Restriction (2b)  */
119663    }
119664  }
119665
119666  pSubSrc = pSub->pSrc;
119667  assert( pSubSrc );
119668  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
119669  ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
119670  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
119671  ** became arbitrary expressions, we were forced to add restrictions (13)
119672  ** and (14). */
119673  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
119674  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
119675  if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
119676    return 0;                                            /* Restriction (15) */
119677  }
119678  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
119679  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
119680  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
119681     return 0;         /* Restrictions (8)(9) */
119682  }
119683  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
119684     return 0;         /* Restriction (6)  */
119685  }
119686  if( p->pOrderBy && pSub->pOrderBy ){
119687     return 0;                                           /* Restriction (11) */
119688  }
119689  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
119690  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
119691  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
119692     return 0;         /* Restriction (21) */
119693  }
119694  testcase( pSub->selFlags & SF_Recursive );
119695  testcase( pSub->selFlags & SF_MinMaxAgg );
119696  if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
119697    return 0; /* Restrictions (22) and (24) */
119698  }
119699  if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
119700    return 0; /* Restriction (23) */
119701  }
119702
119703  /* OBSOLETE COMMENT 1:
119704  ** Restriction 3:  If the subquery is a join, make sure the subquery is
119705  ** not used as the right operand of an outer join.  Examples of why this
119706  ** is not allowed:
119707  **
119708  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
119709  **
119710  ** If we flatten the above, we would get
119711  **
119712  **         (t1 LEFT OUTER JOIN t2) JOIN t3
119713  **
119714  ** which is not at all the same thing.
119715  **
119716  ** OBSOLETE COMMENT 2:
119717  ** Restriction 12:  If the subquery is the right operand of a left outer
119718  ** join, make sure the subquery has no WHERE clause.
119719  ** An examples of why this is not allowed:
119720  **
119721  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
119722  **
119723  ** If we flatten the above, we would get
119724  **
119725  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
119726  **
119727  ** But the t2.x>0 test will always fail on a NULL row of t2, which
119728  ** effectively converts the OUTER JOIN into an INNER JOIN.
119729  **
119730  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
119731  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
119732  ** is fraught with danger.  Best to avoid the whole thing.  If the
119733  ** subquery is the right term of a LEFT JOIN, then do not flatten.
119734  */
119735  if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
119736    return 0;
119737  }
119738
119739  /* Restriction 17: If the sub-query is a compound SELECT, then it must
119740  ** use only the UNION ALL operator. And none of the simple select queries
119741  ** that make up the compound SELECT are allowed to be aggregate or distinct
119742  ** queries.
119743  */
119744  if( pSub->pPrior ){
119745    if( pSub->pOrderBy ){
119746      return 0;  /* Restriction 20 */
119747    }
119748    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
119749      return 0;
119750    }
119751    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
119752      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
119753      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
119754      assert( pSub->pSrc!=0 );
119755      assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
119756      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
119757       || (pSub1->pPrior && pSub1->op!=TK_ALL)
119758       || pSub1->pSrc->nSrc<1
119759      ){
119760        return 0;
119761      }
119762      testcase( pSub1->pSrc->nSrc>1 );
119763    }
119764
119765    /* Restriction 18. */
119766    if( p->pOrderBy ){
119767      int ii;
119768      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
119769        if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
119770      }
119771    }
119772  }
119773
119774  /***** If we reach this point, flattening is permitted. *****/
119775  SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
119776                   pSub->zSelName, pSub, iFrom));
119777
119778  /* Authorize the subquery */
119779  pParse->zAuthContext = pSubitem->zName;
119780  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
119781  testcase( i==SQLITE_DENY );
119782  pParse->zAuthContext = zSavedAuthContext;
119783
119784  /* If the sub-query is a compound SELECT statement, then (by restrictions
119785  ** 17 and 18 above) it must be a UNION ALL and the parent query must
119786  ** be of the form:
119787  **
119788  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
119789  **
119790  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
119791  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
119792  ** OFFSET clauses and joins them to the left-hand-side of the original
119793  ** using UNION ALL operators. In this case N is the number of simple
119794  ** select statements in the compound sub-query.
119795  **
119796  ** Example:
119797  **
119798  **     SELECT a+1 FROM (
119799  **        SELECT x FROM tab
119800  **        UNION ALL
119801  **        SELECT y FROM tab
119802  **        UNION ALL
119803  **        SELECT abs(z*2) FROM tab2
119804  **     ) WHERE a!=5 ORDER BY 1
119805  **
119806  ** Transformed into:
119807  **
119808  **     SELECT x+1 FROM tab WHERE x+1!=5
119809  **     UNION ALL
119810  **     SELECT y+1 FROM tab WHERE y+1!=5
119811  **     UNION ALL
119812  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
119813  **     ORDER BY 1
119814  **
119815  ** We call this the "compound-subquery flattening".
119816  */
119817  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
119818    Select *pNew;
119819    ExprList *pOrderBy = p->pOrderBy;
119820    Expr *pLimit = p->pLimit;
119821    Expr *pOffset = p->pOffset;
119822    Select *pPrior = p->pPrior;
119823    p->pOrderBy = 0;
119824    p->pSrc = 0;
119825    p->pPrior = 0;
119826    p->pLimit = 0;
119827    p->pOffset = 0;
119828    pNew = sqlite3SelectDup(db, p, 0);
119829    sqlite3SelectSetName(pNew, pSub->zSelName);
119830    p->pOffset = pOffset;
119831    p->pLimit = pLimit;
119832    p->pOrderBy = pOrderBy;
119833    p->pSrc = pSrc;
119834    p->op = TK_ALL;
119835    if( pNew==0 ){
119836      p->pPrior = pPrior;
119837    }else{
119838      pNew->pPrior = pPrior;
119839      if( pPrior ) pPrior->pNext = pNew;
119840      pNew->pNext = p;
119841      p->pPrior = pNew;
119842      SELECTTRACE(2,pParse,p,
119843         ("compound-subquery flattener creates %s.%p as peer\n",
119844         pNew->zSelName, pNew));
119845    }
119846    if( db->mallocFailed ) return 1;
119847  }
119848
119849  /* Begin flattening the iFrom-th entry of the FROM clause
119850  ** in the outer query.
119851  */
119852  pSub = pSub1 = pSubitem->pSelect;
119853
119854  /* Delete the transient table structure associated with the
119855  ** subquery
119856  */
119857  sqlite3DbFree(db, pSubitem->zDatabase);
119858  sqlite3DbFree(db, pSubitem->zName);
119859  sqlite3DbFree(db, pSubitem->zAlias);
119860  pSubitem->zDatabase = 0;
119861  pSubitem->zName = 0;
119862  pSubitem->zAlias = 0;
119863  pSubitem->pSelect = 0;
119864
119865  /* Defer deleting the Table object associated with the
119866  ** subquery until code generation is
119867  ** complete, since there may still exist Expr.pTab entries that
119868  ** refer to the subquery even after flattening.  Ticket #3346.
119869  **
119870  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
119871  */
119872  if( ALWAYS(pSubitem->pTab!=0) ){
119873    Table *pTabToDel = pSubitem->pTab;
119874    if( pTabToDel->nTabRef==1 ){
119875      Parse *pToplevel = sqlite3ParseToplevel(pParse);
119876      pTabToDel->pNextZombie = pToplevel->pZombieTab;
119877      pToplevel->pZombieTab = pTabToDel;
119878    }else{
119879      pTabToDel->nTabRef--;
119880    }
119881    pSubitem->pTab = 0;
119882  }
119883
119884  /* The following loop runs once for each term in a compound-subquery
119885  ** flattening (as described above).  If we are doing a different kind
119886  ** of flattening - a flattening other than a compound-subquery flattening -
119887  ** then this loop only runs once.
119888  **
119889  ** This loop moves all of the FROM elements of the subquery into the
119890  ** the FROM clause of the outer query.  Before doing this, remember
119891  ** the cursor number for the original outer query FROM element in
119892  ** iParent.  The iParent cursor will never be used.  Subsequent code
119893  ** will scan expressions looking for iParent references and replace
119894  ** those references with expressions that resolve to the subquery FROM
119895  ** elements we are now copying in.
119896  */
119897  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
119898    int nSubSrc;
119899    u8 jointype = 0;
119900    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
119901    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
119902    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
119903
119904    if( pSrc ){
119905      assert( pParent==p );  /* First time through the loop */
119906      jointype = pSubitem->fg.jointype;
119907    }else{
119908      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
119909      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
119910      if( pSrc==0 ){
119911        assert( db->mallocFailed );
119912        break;
119913      }
119914    }
119915
119916    /* The subquery uses a single slot of the FROM clause of the outer
119917    ** query.  If the subquery has more than one element in its FROM clause,
119918    ** then expand the outer query to make space for it to hold all elements
119919    ** of the subquery.
119920    **
119921    ** Example:
119922    **
119923    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
119924    **
119925    ** The outer query has 3 slots in its FROM clause.  One slot of the
119926    ** outer query (the middle slot) is used by the subquery.  The next
119927    ** block of code will expand the outer query FROM clause to 4 slots.
119928    ** The middle slot is expanded to two slots in order to make space
119929    ** for the two elements in the FROM clause of the subquery.
119930    */
119931    if( nSubSrc>1 ){
119932      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
119933      if( db->mallocFailed ){
119934        break;
119935      }
119936    }
119937
119938    /* Transfer the FROM clause terms from the subquery into the
119939    ** outer query.
119940    */
119941    for(i=0; i<nSubSrc; i++){
119942      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
119943      assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
119944      pSrc->a[i+iFrom] = pSubSrc->a[i];
119945      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
119946    }
119947    pSrc->a[iFrom].fg.jointype = jointype;
119948
119949    /* Now begin substituting subquery result set expressions for
119950    ** references to the iParent in the outer query.
119951    **
119952    ** Example:
119953    **
119954    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
119955    **   \                     \_____________ subquery __________/          /
119956    **    \_____________________ outer query ______________________________/
119957    **
119958    ** We look at every expression in the outer query and every place we see
119959    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
119960    */
119961    pList = pParent->pEList;
119962    for(i=0; i<pList->nExpr; i++){
119963      if( pList->a[i].zName==0 ){
119964        char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
119965        sqlite3Dequote(zName);
119966        pList->a[i].zName = zName;
119967      }
119968    }
119969    if( pSub->pOrderBy ){
119970      /* At this point, any non-zero iOrderByCol values indicate that the
119971      ** ORDER BY column expression is identical to the iOrderByCol'th
119972      ** expression returned by SELECT statement pSub. Since these values
119973      ** do not necessarily correspond to columns in SELECT statement pParent,
119974      ** zero them before transfering the ORDER BY clause.
119975      **
119976      ** Not doing this may cause an error if a subsequent call to this
119977      ** function attempts to flatten a compound sub-query into pParent
119978      ** (the only way this can happen is if the compound sub-query is
119979      ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
119980      ExprList *pOrderBy = pSub->pOrderBy;
119981      for(i=0; i<pOrderBy->nExpr; i++){
119982        pOrderBy->a[i].u.x.iOrderByCol = 0;
119983      }
119984      assert( pParent->pOrderBy==0 );
119985      assert( pSub->pPrior==0 );
119986      pParent->pOrderBy = pOrderBy;
119987      pSub->pOrderBy = 0;
119988    }
119989    pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
119990    if( subqueryIsAgg ){
119991      assert( pParent->pHaving==0 );
119992      pParent->pHaving = pParent->pWhere;
119993      pParent->pWhere = pWhere;
119994      pParent->pHaving = sqlite3ExprAnd(db,
119995          sqlite3ExprDup(db, pSub->pHaving, 0), pParent->pHaving
119996      );
119997      assert( pParent->pGroupBy==0 );
119998      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
119999    }else{
120000      pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
120001    }
120002    if( db->mallocFailed==0 ){
120003      substSelect(pParse, pParent, iParent, pSub->pEList, 0);
120004    }
120005
120006    /* The flattened query is distinct if either the inner or the
120007    ** outer query is distinct.
120008    */
120009    pParent->selFlags |= pSub->selFlags & SF_Distinct;
120010
120011    /*
120012    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
120013    **
120014    ** One is tempted to try to add a and b to combine the limits.  But this
120015    ** does not work if either limit is negative.
120016    */
120017    if( pSub->pLimit ){
120018      pParent->pLimit = pSub->pLimit;
120019      pSub->pLimit = 0;
120020    }
120021  }
120022
120023  /* Finially, delete what is left of the subquery and return
120024  ** success.
120025  */
120026  sqlite3SelectDelete(db, pSub1);
120027
120028#if SELECTTRACE_ENABLED
120029  if( sqlite3SelectTrace & 0x100 ){
120030    SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
120031    sqlite3TreeViewSelect(0, p, 0);
120032  }
120033#endif
120034
120035  return 1;
120036}
120037#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
120038
120039
120040
120041#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
120042/*
120043** Make copies of relevant WHERE clause terms of the outer query into
120044** the WHERE clause of subquery.  Example:
120045**
120046**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
120047**
120048** Transformed into:
120049**
120050**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
120051**     WHERE x=5 AND y=10;
120052**
120053** The hope is that the terms added to the inner query will make it more
120054** efficient.
120055**
120056** Do not attempt this optimization if:
120057**
120058**   (1) The inner query is an aggregate.  (In that case, we'd really want
120059**       to copy the outer WHERE-clause terms onto the HAVING clause of the
120060**       inner query.  But they probably won't help there so do not bother.)
120061**
120062**   (2) The inner query is the recursive part of a common table expression.
120063**
120064**   (3) The inner query has a LIMIT clause (since the changes to the WHERE
120065**       close would change the meaning of the LIMIT).
120066**
120067**   (4) The inner query is the right operand of a LEFT JOIN.  (The caller
120068**       enforces this restriction since this routine does not have enough
120069**       information to know.)
120070**
120071**   (5) The WHERE clause expression originates in the ON or USING clause
120072**       of a LEFT JOIN.
120073**
120074** Return 0 if no changes are made and non-zero if one or more WHERE clause
120075** terms are duplicated into the subquery.
120076*/
120077static int pushDownWhereTerms(
120078  Parse *pParse,        /* Parse context (for malloc() and error reporting) */
120079  Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
120080  Expr *pWhere,         /* The WHERE clause of the outer query */
120081  int iCursor           /* Cursor number of the subquery */
120082){
120083  Expr *pNew;
120084  int nChng = 0;
120085  Select *pX;           /* For looping over compound SELECTs in pSubq */
120086  if( pWhere==0 ) return 0;
120087  for(pX=pSubq; pX; pX=pX->pPrior){
120088    if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
120089      testcase( pX->selFlags & SF_Aggregate );
120090      testcase( pX->selFlags & SF_Recursive );
120091      testcase( pX!=pSubq );
120092      return 0; /* restrictions (1) and (2) */
120093    }
120094  }
120095  if( pSubq->pLimit!=0 ){
120096    return 0; /* restriction (3) */
120097  }
120098  while( pWhere->op==TK_AND ){
120099    nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, iCursor);
120100    pWhere = pWhere->pLeft;
120101  }
120102  if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
120103  if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
120104    nChng++;
120105    while( pSubq ){
120106      pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
120107      pNew = substExpr(pParse, pNew, iCursor, pSubq->pEList);
120108      pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew);
120109      pSubq = pSubq->pPrior;
120110    }
120111  }
120112  return nChng;
120113}
120114#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
120115
120116/*
120117** Based on the contents of the AggInfo structure indicated by the first
120118** argument, this function checks if the following are true:
120119**
120120**    * the query contains just a single aggregate function,
120121**    * the aggregate function is either min() or max(), and
120122**    * the argument to the aggregate function is a column value.
120123**
120124** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
120125** is returned as appropriate. Also, *ppMinMax is set to point to the
120126** list of arguments passed to the aggregate before returning.
120127**
120128** Or, if the conditions above are not met, *ppMinMax is set to 0 and
120129** WHERE_ORDERBY_NORMAL is returned.
120130*/
120131static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
120132  int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
120133
120134  *ppMinMax = 0;
120135  if( pAggInfo->nFunc==1 ){
120136    Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
120137    ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
120138
120139    assert( pExpr->op==TK_AGG_FUNCTION );
120140    if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
120141      const char *zFunc = pExpr->u.zToken;
120142      if( sqlite3StrICmp(zFunc, "min")==0 ){
120143        eRet = WHERE_ORDERBY_MIN;
120144        *ppMinMax = pEList;
120145      }else if( sqlite3StrICmp(zFunc, "max")==0 ){
120146        eRet = WHERE_ORDERBY_MAX;
120147        *ppMinMax = pEList;
120148      }
120149    }
120150  }
120151
120152  assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
120153  return eRet;
120154}
120155
120156/*
120157** The select statement passed as the first argument is an aggregate query.
120158** The second argument is the associated aggregate-info object. This
120159** function tests if the SELECT is of the form:
120160**
120161**   SELECT count(*) FROM <tbl>
120162**
120163** where table is a database table, not a sub-select or view. If the query
120164** does match this pattern, then a pointer to the Table object representing
120165** <tbl> is returned. Otherwise, 0 is returned.
120166*/
120167static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
120168  Table *pTab;
120169  Expr *pExpr;
120170
120171  assert( !p->pGroupBy );
120172
120173  if( p->pWhere || p->pEList->nExpr!=1
120174   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
120175  ){
120176    return 0;
120177  }
120178  pTab = p->pSrc->a[0].pTab;
120179  pExpr = p->pEList->a[0].pExpr;
120180  assert( pTab && !pTab->pSelect && pExpr );
120181
120182  if( IsVirtual(pTab) ) return 0;
120183  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
120184  if( NEVER(pAggInfo->nFunc==0) ) return 0;
120185  if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
120186  if( pExpr->flags&EP_Distinct ) return 0;
120187
120188  return pTab;
120189}
120190
120191/*
120192** If the source-list item passed as an argument was augmented with an
120193** INDEXED BY clause, then try to locate the specified index. If there
120194** was such a clause and the named index cannot be found, return
120195** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
120196** pFrom->pIndex and return SQLITE_OK.
120197*/
120198SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
120199  if( pFrom->pTab && pFrom->fg.isIndexedBy ){
120200    Table *pTab = pFrom->pTab;
120201    char *zIndexedBy = pFrom->u1.zIndexedBy;
120202    Index *pIdx;
120203    for(pIdx=pTab->pIndex;
120204        pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
120205        pIdx=pIdx->pNext
120206    );
120207    if( !pIdx ){
120208      sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
120209      pParse->checkSchema = 1;
120210      return SQLITE_ERROR;
120211    }
120212    pFrom->pIBIndex = pIdx;
120213  }
120214  return SQLITE_OK;
120215}
120216/*
120217** Detect compound SELECT statements that use an ORDER BY clause with
120218** an alternative collating sequence.
120219**
120220**    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
120221**
120222** These are rewritten as a subquery:
120223**
120224**    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
120225**     ORDER BY ... COLLATE ...
120226**
120227** This transformation is necessary because the multiSelectOrderBy() routine
120228** above that generates the code for a compound SELECT with an ORDER BY clause
120229** uses a merge algorithm that requires the same collating sequence on the
120230** result columns as on the ORDER BY clause.  See ticket
120231** http://www.sqlite.org/src/info/6709574d2a
120232**
120233** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
120234** The UNION ALL operator works fine with multiSelectOrderBy() even when
120235** there are COLLATE terms in the ORDER BY.
120236*/
120237static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
120238  int i;
120239  Select *pNew;
120240  Select *pX;
120241  sqlite3 *db;
120242  struct ExprList_item *a;
120243  SrcList *pNewSrc;
120244  Parse *pParse;
120245  Token dummy;
120246
120247  if( p->pPrior==0 ) return WRC_Continue;
120248  if( p->pOrderBy==0 ) return WRC_Continue;
120249  for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
120250  if( pX==0 ) return WRC_Continue;
120251  a = p->pOrderBy->a;
120252  for(i=p->pOrderBy->nExpr-1; i>=0; i--){
120253    if( a[i].pExpr->flags & EP_Collate ) break;
120254  }
120255  if( i<0 ) return WRC_Continue;
120256
120257  /* If we reach this point, that means the transformation is required. */
120258
120259  pParse = pWalker->pParse;
120260  db = pParse->db;
120261  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
120262  if( pNew==0 ) return WRC_Abort;
120263  memset(&dummy, 0, sizeof(dummy));
120264  pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
120265  if( pNewSrc==0 ) return WRC_Abort;
120266  *pNew = *p;
120267  p->pSrc = pNewSrc;
120268  p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
120269  p->op = TK_SELECT;
120270  p->pWhere = 0;
120271  pNew->pGroupBy = 0;
120272  pNew->pHaving = 0;
120273  pNew->pOrderBy = 0;
120274  p->pPrior = 0;
120275  p->pNext = 0;
120276  p->pWith = 0;
120277  p->selFlags &= ~SF_Compound;
120278  assert( (p->selFlags & SF_Converted)==0 );
120279  p->selFlags |= SF_Converted;
120280  assert( pNew->pPrior!=0 );
120281  pNew->pPrior->pNext = pNew;
120282  pNew->pLimit = 0;
120283  pNew->pOffset = 0;
120284  return WRC_Continue;
120285}
120286
120287/*
120288** Check to see if the FROM clause term pFrom has table-valued function
120289** arguments.  If it does, leave an error message in pParse and return
120290** non-zero, since pFrom is not allowed to be a table-valued function.
120291*/
120292static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
120293  if( pFrom->fg.isTabFunc ){
120294    sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
120295    return 1;
120296  }
120297  return 0;
120298}
120299
120300#ifndef SQLITE_OMIT_CTE
120301/*
120302** Argument pWith (which may be NULL) points to a linked list of nested
120303** WITH contexts, from inner to outermost. If the table identified by
120304** FROM clause element pItem is really a common-table-expression (CTE)
120305** then return a pointer to the CTE definition for that table. Otherwise
120306** return NULL.
120307**
120308** If a non-NULL value is returned, set *ppContext to point to the With
120309** object that the returned CTE belongs to.
120310*/
120311static struct Cte *searchWith(
120312  With *pWith,                    /* Current innermost WITH clause */
120313  struct SrcList_item *pItem,     /* FROM clause element to resolve */
120314  With **ppContext                /* OUT: WITH clause return value belongs to */
120315){
120316  const char *zName;
120317  if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
120318    With *p;
120319    for(p=pWith; p; p=p->pOuter){
120320      int i;
120321      for(i=0; i<p->nCte; i++){
120322        if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
120323          *ppContext = p;
120324          return &p->a[i];
120325        }
120326      }
120327    }
120328  }
120329  return 0;
120330}
120331
120332/* The code generator maintains a stack of active WITH clauses
120333** with the inner-most WITH clause being at the top of the stack.
120334**
120335** This routine pushes the WITH clause passed as the second argument
120336** onto the top of the stack. If argument bFree is true, then this
120337** WITH clause will never be popped from the stack. In this case it
120338** should be freed along with the Parse object. In other cases, when
120339** bFree==0, the With object will be freed along with the SELECT
120340** statement with which it is associated.
120341*/
120342SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
120343  assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
120344  if( pWith ){
120345    assert( pParse->pWith!=pWith );
120346    pWith->pOuter = pParse->pWith;
120347    pParse->pWith = pWith;
120348    if( bFree ) pParse->pWithToFree = pWith;
120349  }
120350}
120351
120352/*
120353** This function checks if argument pFrom refers to a CTE declared by
120354** a WITH clause on the stack currently maintained by the parser. And,
120355** if currently processing a CTE expression, if it is a recursive
120356** reference to the current CTE.
120357**
120358** If pFrom falls into either of the two categories above, pFrom->pTab
120359** and other fields are populated accordingly. The caller should check
120360** (pFrom->pTab!=0) to determine whether or not a successful match
120361** was found.
120362**
120363** Whether or not a match is found, SQLITE_OK is returned if no error
120364** occurs. If an error does occur, an error message is stored in the
120365** parser and some error code other than SQLITE_OK returned.
120366*/
120367static int withExpand(
120368  Walker *pWalker,
120369  struct SrcList_item *pFrom
120370){
120371  Parse *pParse = pWalker->pParse;
120372  sqlite3 *db = pParse->db;
120373  struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
120374  With *pWith;                    /* WITH clause that pCte belongs to */
120375
120376  assert( pFrom->pTab==0 );
120377
120378  pCte = searchWith(pParse->pWith, pFrom, &pWith);
120379  if( pCte ){
120380    Table *pTab;
120381    ExprList *pEList;
120382    Select *pSel;
120383    Select *pLeft;                /* Left-most SELECT statement */
120384    int bMayRecursive;            /* True if compound joined by UNION [ALL] */
120385    With *pSavedWith;             /* Initial value of pParse->pWith */
120386
120387    /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
120388    ** recursive reference to CTE pCte. Leave an error in pParse and return
120389    ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
120390    ** In this case, proceed.  */
120391    if( pCte->zCteErr ){
120392      sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
120393      return SQLITE_ERROR;
120394    }
120395    if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
120396
120397    assert( pFrom->pTab==0 );
120398    pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
120399    if( pTab==0 ) return WRC_Abort;
120400    pTab->nTabRef = 1;
120401    pTab->zName = sqlite3DbStrDup(db, pCte->zName);
120402    pTab->iPKey = -1;
120403    pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
120404    pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
120405    pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
120406    if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
120407    assert( pFrom->pSelect );
120408
120409    /* Check if this is a recursive CTE. */
120410    pSel = pFrom->pSelect;
120411    bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
120412    if( bMayRecursive ){
120413      int i;
120414      SrcList *pSrc = pFrom->pSelect->pSrc;
120415      for(i=0; i<pSrc->nSrc; i++){
120416        struct SrcList_item *pItem = &pSrc->a[i];
120417        if( pItem->zDatabase==0
120418         && pItem->zName!=0
120419         && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
120420          ){
120421          pItem->pTab = pTab;
120422          pItem->fg.isRecursive = 1;
120423          pTab->nTabRef++;
120424          pSel->selFlags |= SF_Recursive;
120425        }
120426      }
120427    }
120428
120429    /* Only one recursive reference is permitted. */
120430    if( pTab->nTabRef>2 ){
120431      sqlite3ErrorMsg(
120432          pParse, "multiple references to recursive table: %s", pCte->zName
120433      );
120434      return SQLITE_ERROR;
120435    }
120436    assert( pTab->nTabRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
120437
120438    pCte->zCteErr = "circular reference: %s";
120439    pSavedWith = pParse->pWith;
120440    pParse->pWith = pWith;
120441    if( bMayRecursive ){
120442      Select *pPrior = pSel->pPrior;
120443      assert( pPrior->pWith==0 );
120444      pPrior->pWith = pSel->pWith;
120445      sqlite3WalkSelect(pWalker, pPrior);
120446      pPrior->pWith = 0;
120447    }else{
120448      sqlite3WalkSelect(pWalker, pSel);
120449    }
120450    pParse->pWith = pWith;
120451
120452    for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
120453    pEList = pLeft->pEList;
120454    if( pCte->pCols ){
120455      if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
120456        sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
120457            pCte->zName, pEList->nExpr, pCte->pCols->nExpr
120458        );
120459        pParse->pWith = pSavedWith;
120460        return SQLITE_ERROR;
120461      }
120462      pEList = pCte->pCols;
120463    }
120464
120465    sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
120466    if( bMayRecursive ){
120467      if( pSel->selFlags & SF_Recursive ){
120468        pCte->zCteErr = "multiple recursive references: %s";
120469      }else{
120470        pCte->zCteErr = "recursive reference in a subquery: %s";
120471      }
120472      sqlite3WalkSelect(pWalker, pSel);
120473    }
120474    pCte->zCteErr = 0;
120475    pParse->pWith = pSavedWith;
120476  }
120477
120478  return SQLITE_OK;
120479}
120480#endif
120481
120482#ifndef SQLITE_OMIT_CTE
120483/*
120484** If the SELECT passed as the second argument has an associated WITH
120485** clause, pop it from the stack stored as part of the Parse object.
120486**
120487** This function is used as the xSelectCallback2() callback by
120488** sqlite3SelectExpand() when walking a SELECT tree to resolve table
120489** names and other FROM clause elements.
120490*/
120491static void selectPopWith(Walker *pWalker, Select *p){
120492  Parse *pParse = pWalker->pParse;
120493  if( pParse->pWith && p->pPrior==0 ){
120494    With *pWith = findRightmost(p)->pWith;
120495    if( pWith!=0 ){
120496      assert( pParse->pWith==pWith );
120497      pParse->pWith = pWith->pOuter;
120498    }
120499  }
120500}
120501#else
120502#define selectPopWith 0
120503#endif
120504
120505/*
120506** This routine is a Walker callback for "expanding" a SELECT statement.
120507** "Expanding" means to do the following:
120508**
120509**    (1)  Make sure VDBE cursor numbers have been assigned to every
120510**         element of the FROM clause.
120511**
120512**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
120513**         defines FROM clause.  When views appear in the FROM clause,
120514**         fill pTabList->a[].pSelect with a copy of the SELECT statement
120515**         that implements the view.  A copy is made of the view's SELECT
120516**         statement so that we can freely modify or delete that statement
120517**         without worrying about messing up the persistent representation
120518**         of the view.
120519**
120520**    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
120521**         on joins and the ON and USING clause of joins.
120522**
120523**    (4)  Scan the list of columns in the result set (pEList) looking
120524**         for instances of the "*" operator or the TABLE.* operator.
120525**         If found, expand each "*" to be every column in every table
120526**         and TABLE.* to be every column in TABLE.
120527**
120528*/
120529static int selectExpander(Walker *pWalker, Select *p){
120530  Parse *pParse = pWalker->pParse;
120531  int i, j, k;
120532  SrcList *pTabList;
120533  ExprList *pEList;
120534  struct SrcList_item *pFrom;
120535  sqlite3 *db = pParse->db;
120536  Expr *pE, *pRight, *pExpr;
120537  u16 selFlags = p->selFlags;
120538
120539  p->selFlags |= SF_Expanded;
120540  if( db->mallocFailed  ){
120541    return WRC_Abort;
120542  }
120543  if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
120544    return WRC_Prune;
120545  }
120546  pTabList = p->pSrc;
120547  pEList = p->pEList;
120548  if( p->pWith ){
120549    sqlite3WithPush(pParse, p->pWith, 0);
120550  }
120551
120552  /* Make sure cursor numbers have been assigned to all entries in
120553  ** the FROM clause of the SELECT statement.
120554  */
120555  sqlite3SrcListAssignCursors(pParse, pTabList);
120556
120557  /* Look up every table named in the FROM clause of the select.  If
120558  ** an entry of the FROM clause is a subquery instead of a table or view,
120559  ** then create a transient table structure to describe the subquery.
120560  */
120561  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
120562    Table *pTab;
120563    assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
120564    if( pFrom->fg.isRecursive ) continue;
120565    assert( pFrom->pTab==0 );
120566#ifndef SQLITE_OMIT_CTE
120567    if( withExpand(pWalker, pFrom) ) return WRC_Abort;
120568    if( pFrom->pTab ) {} else
120569#endif
120570    if( pFrom->zName==0 ){
120571#ifndef SQLITE_OMIT_SUBQUERY
120572      Select *pSel = pFrom->pSelect;
120573      /* A sub-query in the FROM clause of a SELECT */
120574      assert( pSel!=0 );
120575      assert( pFrom->pTab==0 );
120576      if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
120577      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
120578      if( pTab==0 ) return WRC_Abort;
120579      pTab->nTabRef = 1;
120580      pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
120581      while( pSel->pPrior ){ pSel = pSel->pPrior; }
120582      sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
120583      pTab->iPKey = -1;
120584      pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
120585      pTab->tabFlags |= TF_Ephemeral;
120586#endif
120587    }else{
120588      /* An ordinary table or view name in the FROM clause */
120589      assert( pFrom->pTab==0 );
120590      pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
120591      if( pTab==0 ) return WRC_Abort;
120592      if( pTab->nTabRef>=0xffff ){
120593        sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
120594           pTab->zName);
120595        pFrom->pTab = 0;
120596        return WRC_Abort;
120597      }
120598      pTab->nTabRef++;
120599      if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
120600        return WRC_Abort;
120601      }
120602#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
120603      if( IsVirtual(pTab) || pTab->pSelect ){
120604        i16 nCol;
120605        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
120606        assert( pFrom->pSelect==0 );
120607        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
120608        sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
120609        nCol = pTab->nCol;
120610        pTab->nCol = -1;
120611        sqlite3WalkSelect(pWalker, pFrom->pSelect);
120612        pTab->nCol = nCol;
120613      }
120614#endif
120615    }
120616
120617    /* Locate the index named by the INDEXED BY clause, if any. */
120618    if( sqlite3IndexedByLookup(pParse, pFrom) ){
120619      return WRC_Abort;
120620    }
120621  }
120622
120623  /* Process NATURAL keywords, and ON and USING clauses of joins.
120624  */
120625  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
120626    return WRC_Abort;
120627  }
120628
120629  /* For every "*" that occurs in the column list, insert the names of
120630  ** all columns in all tables.  And for every TABLE.* insert the names
120631  ** of all columns in TABLE.  The parser inserted a special expression
120632  ** with the TK_ASTERISK operator for each "*" that it found in the column
120633  ** list.  The following code just has to locate the TK_ASTERISK
120634  ** expressions and expand each one to the list of all columns in
120635  ** all tables.
120636  **
120637  ** The first loop just checks to see if there are any "*" operators
120638  ** that need expanding.
120639  */
120640  for(k=0; k<pEList->nExpr; k++){
120641    pE = pEList->a[k].pExpr;
120642    if( pE->op==TK_ASTERISK ) break;
120643    assert( pE->op!=TK_DOT || pE->pRight!=0 );
120644    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
120645    if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
120646  }
120647  if( k<pEList->nExpr ){
120648    /*
120649    ** If we get here it means the result set contains one or more "*"
120650    ** operators that need to be expanded.  Loop through each expression
120651    ** in the result set and expand them one by one.
120652    */
120653    struct ExprList_item *a = pEList->a;
120654    ExprList *pNew = 0;
120655    int flags = pParse->db->flags;
120656    int longNames = (flags & SQLITE_FullColNames)!=0
120657                      && (flags & SQLITE_ShortColNames)==0;
120658
120659    for(k=0; k<pEList->nExpr; k++){
120660      pE = a[k].pExpr;
120661      pRight = pE->pRight;
120662      assert( pE->op!=TK_DOT || pRight!=0 );
120663      if( pE->op!=TK_ASTERISK
120664       && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
120665      ){
120666        /* This particular expression does not need to be expanded.
120667        */
120668        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
120669        if( pNew ){
120670          pNew->a[pNew->nExpr-1].zName = a[k].zName;
120671          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
120672          a[k].zName = 0;
120673          a[k].zSpan = 0;
120674        }
120675        a[k].pExpr = 0;
120676      }else{
120677        /* This expression is a "*" or a "TABLE.*" and needs to be
120678        ** expanded. */
120679        int tableSeen = 0;      /* Set to 1 when TABLE matches */
120680        char *zTName = 0;       /* text of name of TABLE */
120681        if( pE->op==TK_DOT ){
120682          assert( pE->pLeft!=0 );
120683          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
120684          zTName = pE->pLeft->u.zToken;
120685        }
120686        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
120687          Table *pTab = pFrom->pTab;
120688          Select *pSub = pFrom->pSelect;
120689          char *zTabName = pFrom->zAlias;
120690          const char *zSchemaName = 0;
120691          int iDb;
120692          if( zTabName==0 ){
120693            zTabName = pTab->zName;
120694          }
120695          if( db->mallocFailed ) break;
120696          if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
120697            pSub = 0;
120698            if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
120699              continue;
120700            }
120701            iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
120702            zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
120703          }
120704          for(j=0; j<pTab->nCol; j++){
120705            char *zName = pTab->aCol[j].zName;
120706            char *zColname;  /* The computed column name */
120707            char *zToFree;   /* Malloced string that needs to be freed */
120708            Token sColname;  /* Computed column name as a token */
120709
120710            assert( zName );
120711            if( zTName && pSub
120712             && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
120713            ){
120714              continue;
120715            }
120716
120717            /* If a column is marked as 'hidden', omit it from the expanded
120718            ** result-set list unless the SELECT has the SF_IncludeHidden
120719            ** bit set.
120720            */
120721            if( (p->selFlags & SF_IncludeHidden)==0
120722             && IsHiddenColumn(&pTab->aCol[j])
120723            ){
120724              continue;
120725            }
120726            tableSeen = 1;
120727
120728            if( i>0 && zTName==0 ){
120729              if( (pFrom->fg.jointype & JT_NATURAL)!=0
120730                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
120731              ){
120732                /* In a NATURAL join, omit the join columns from the
120733                ** table to the right of the join */
120734                continue;
120735              }
120736              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
120737                /* In a join with a USING clause, omit columns in the
120738                ** using clause from the table on the right. */
120739                continue;
120740              }
120741            }
120742            pRight = sqlite3Expr(db, TK_ID, zName);
120743            zColname = zName;
120744            zToFree = 0;
120745            if( longNames || pTabList->nSrc>1 ){
120746              Expr *pLeft;
120747              pLeft = sqlite3Expr(db, TK_ID, zTabName);
120748              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
120749              if( zSchemaName ){
120750                pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
120751                pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
120752              }
120753              if( longNames ){
120754                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
120755                zToFree = zColname;
120756              }
120757            }else{
120758              pExpr = pRight;
120759            }
120760            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
120761            sqlite3TokenInit(&sColname, zColname);
120762            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
120763            if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
120764              struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
120765              if( pSub ){
120766                pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
120767                testcase( pX->zSpan==0 );
120768              }else{
120769                pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
120770                                           zSchemaName, zTabName, zColname);
120771                testcase( pX->zSpan==0 );
120772              }
120773              pX->bSpanIsTab = 1;
120774            }
120775            sqlite3DbFree(db, zToFree);
120776          }
120777        }
120778        if( !tableSeen ){
120779          if( zTName ){
120780            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
120781          }else{
120782            sqlite3ErrorMsg(pParse, "no tables specified");
120783          }
120784        }
120785      }
120786    }
120787    sqlite3ExprListDelete(db, pEList);
120788    p->pEList = pNew;
120789  }
120790#if SQLITE_MAX_COLUMN
120791  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
120792    sqlite3ErrorMsg(pParse, "too many columns in result set");
120793    return WRC_Abort;
120794  }
120795#endif
120796  return WRC_Continue;
120797}
120798
120799/*
120800** No-op routine for the parse-tree walker.
120801**
120802** When this routine is the Walker.xExprCallback then expression trees
120803** are walked without any actions being taken at each node.  Presumably,
120804** when this routine is used for Walker.xExprCallback then
120805** Walker.xSelectCallback is set to do something useful for every
120806** subquery in the parser tree.
120807*/
120808SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
120809  UNUSED_PARAMETER2(NotUsed, NotUsed2);
120810  return WRC_Continue;
120811}
120812
120813/*
120814** This routine "expands" a SELECT statement and all of its subqueries.
120815** For additional information on what it means to "expand" a SELECT
120816** statement, see the comment on the selectExpand worker callback above.
120817**
120818** Expanding a SELECT statement is the first step in processing a
120819** SELECT statement.  The SELECT statement must be expanded before
120820** name resolution is performed.
120821**
120822** If anything goes wrong, an error message is written into pParse.
120823** The calling function can detect the problem by looking at pParse->nErr
120824** and/or pParse->db->mallocFailed.
120825*/
120826static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
120827  Walker w;
120828  memset(&w, 0, sizeof(w));
120829  w.xExprCallback = sqlite3ExprWalkNoop;
120830  w.pParse = pParse;
120831  if( pParse->hasCompound ){
120832    w.xSelectCallback = convertCompoundSelectToSubquery;
120833    sqlite3WalkSelect(&w, pSelect);
120834  }
120835  w.xSelectCallback = selectExpander;
120836  w.xSelectCallback2 = selectPopWith;
120837  sqlite3WalkSelect(&w, pSelect);
120838}
120839
120840
120841#ifndef SQLITE_OMIT_SUBQUERY
120842/*
120843** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
120844** interface.
120845**
120846** For each FROM-clause subquery, add Column.zType and Column.zColl
120847** information to the Table structure that represents the result set
120848** of that subquery.
120849**
120850** The Table structure that represents the result set was constructed
120851** by selectExpander() but the type and collation information was omitted
120852** at that point because identifiers had not yet been resolved.  This
120853** routine is called after identifier resolution.
120854*/
120855static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
120856  Parse *pParse;
120857  int i;
120858  SrcList *pTabList;
120859  struct SrcList_item *pFrom;
120860
120861  assert( p->selFlags & SF_Resolved );
120862  assert( (p->selFlags & SF_HasTypeInfo)==0 );
120863  p->selFlags |= SF_HasTypeInfo;
120864  pParse = pWalker->pParse;
120865  pTabList = p->pSrc;
120866  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
120867    Table *pTab = pFrom->pTab;
120868    assert( pTab!=0 );
120869    if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
120870      /* A sub-query in the FROM clause of a SELECT */
120871      Select *pSel = pFrom->pSelect;
120872      if( pSel ){
120873        while( pSel->pPrior ) pSel = pSel->pPrior;
120874        sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
120875      }
120876    }
120877  }
120878}
120879#endif
120880
120881
120882/*
120883** This routine adds datatype and collating sequence information to
120884** the Table structures of all FROM-clause subqueries in a
120885** SELECT statement.
120886**
120887** Use this routine after name resolution.
120888*/
120889static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
120890#ifndef SQLITE_OMIT_SUBQUERY
120891  Walker w;
120892  memset(&w, 0, sizeof(w));
120893  w.xSelectCallback2 = selectAddSubqueryTypeInfo;
120894  w.xExprCallback = sqlite3ExprWalkNoop;
120895  w.pParse = pParse;
120896  sqlite3WalkSelect(&w, pSelect);
120897#endif
120898}
120899
120900
120901/*
120902** This routine sets up a SELECT statement for processing.  The
120903** following is accomplished:
120904**
120905**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
120906**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
120907**     *  ON and USING clauses are shifted into WHERE statements
120908**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
120909**     *  Identifiers in expression are matched to tables.
120910**
120911** This routine acts recursively on all subqueries within the SELECT.
120912*/
120913SQLITE_PRIVATE void sqlite3SelectPrep(
120914  Parse *pParse,         /* The parser context */
120915  Select *p,             /* The SELECT statement being coded. */
120916  NameContext *pOuterNC  /* Name context for container */
120917){
120918  sqlite3 *db;
120919  if( NEVER(p==0) ) return;
120920  db = pParse->db;
120921  if( db->mallocFailed ) return;
120922  if( p->selFlags & SF_HasTypeInfo ) return;
120923  sqlite3SelectExpand(pParse, p);
120924  if( pParse->nErr || db->mallocFailed ) return;
120925  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
120926  if( pParse->nErr || db->mallocFailed ) return;
120927  sqlite3SelectAddTypeInfo(pParse, p);
120928}
120929
120930/*
120931** Reset the aggregate accumulator.
120932**
120933** The aggregate accumulator is a set of memory cells that hold
120934** intermediate results while calculating an aggregate.  This
120935** routine generates code that stores NULLs in all of those memory
120936** cells.
120937*/
120938static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
120939  Vdbe *v = pParse->pVdbe;
120940  int i;
120941  struct AggInfo_func *pFunc;
120942  int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
120943  if( nReg==0 ) return;
120944#ifdef SQLITE_DEBUG
120945  /* Verify that all AggInfo registers are within the range specified by
120946  ** AggInfo.mnReg..AggInfo.mxReg */
120947  assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
120948  for(i=0; i<pAggInfo->nColumn; i++){
120949    assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
120950         && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
120951  }
120952  for(i=0; i<pAggInfo->nFunc; i++){
120953    assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
120954         && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
120955  }
120956#endif
120957  sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
120958  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
120959    if( pFunc->iDistinct>=0 ){
120960      Expr *pE = pFunc->pExpr;
120961      assert( !ExprHasProperty(pE, EP_xIsSelect) );
120962      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
120963        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
120964           "argument");
120965        pFunc->iDistinct = -1;
120966      }else{
120967        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
120968        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
120969                          (char*)pKeyInfo, P4_KEYINFO);
120970      }
120971    }
120972  }
120973}
120974
120975/*
120976** Invoke the OP_AggFinalize opcode for every aggregate function
120977** in the AggInfo structure.
120978*/
120979static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
120980  Vdbe *v = pParse->pVdbe;
120981  int i;
120982  struct AggInfo_func *pF;
120983  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
120984    ExprList *pList = pF->pExpr->x.pList;
120985    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
120986    sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
120987    sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
120988  }
120989}
120990
120991/*
120992** Update the accumulator memory cells for an aggregate based on
120993** the current cursor position.
120994*/
120995static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
120996  Vdbe *v = pParse->pVdbe;
120997  int i;
120998  int regHit = 0;
120999  int addrHitTest = 0;
121000  struct AggInfo_func *pF;
121001  struct AggInfo_col *pC;
121002
121003  pAggInfo->directMode = 1;
121004  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
121005    int nArg;
121006    int addrNext = 0;
121007    int regAgg;
121008    ExprList *pList = pF->pExpr->x.pList;
121009    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
121010    if( pList ){
121011      nArg = pList->nExpr;
121012      regAgg = sqlite3GetTempRange(pParse, nArg);
121013      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
121014    }else{
121015      nArg = 0;
121016      regAgg = 0;
121017    }
121018    if( pF->iDistinct>=0 ){
121019      addrNext = sqlite3VdbeMakeLabel(v);
121020      testcase( nArg==0 );  /* Error condition */
121021      testcase( nArg>1 );   /* Also an error */
121022      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
121023    }
121024    if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
121025      CollSeq *pColl = 0;
121026      struct ExprList_item *pItem;
121027      int j;
121028      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
121029      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
121030        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
121031      }
121032      if( !pColl ){
121033        pColl = pParse->db->pDfltColl;
121034      }
121035      if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
121036      sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
121037    }
121038    sqlite3VdbeAddOp3(v, OP_AggStep0, 0, regAgg, pF->iMem);
121039    sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
121040    sqlite3VdbeChangeP5(v, (u8)nArg);
121041    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
121042    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
121043    if( addrNext ){
121044      sqlite3VdbeResolveLabel(v, addrNext);
121045      sqlite3ExprCacheClear(pParse);
121046    }
121047  }
121048
121049  /* Before populating the accumulator registers, clear the column cache.
121050  ** Otherwise, if any of the required column values are already present
121051  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
121052  ** to pC->iMem. But by the time the value is used, the original register
121053  ** may have been used, invalidating the underlying buffer holding the
121054  ** text or blob value. See ticket [883034dcb5].
121055  **
121056  ** Another solution would be to change the OP_SCopy used to copy cached
121057  ** values to an OP_Copy.
121058  */
121059  if( regHit ){
121060    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
121061  }
121062  sqlite3ExprCacheClear(pParse);
121063  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
121064    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
121065  }
121066  pAggInfo->directMode = 0;
121067  sqlite3ExprCacheClear(pParse);
121068  if( addrHitTest ){
121069    sqlite3VdbeJumpHere(v, addrHitTest);
121070  }
121071}
121072
121073/*
121074** Add a single OP_Explain instruction to the VDBE to explain a simple
121075** count(*) query ("SELECT count(*) FROM pTab").
121076*/
121077#ifndef SQLITE_OMIT_EXPLAIN
121078static void explainSimpleCount(
121079  Parse *pParse,                  /* Parse context */
121080  Table *pTab,                    /* Table being queried */
121081  Index *pIdx                     /* Index used to optimize scan, or NULL */
121082){
121083  if( pParse->explain==2 ){
121084    int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
121085    char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
121086        pTab->zName,
121087        bCover ? " USING COVERING INDEX " : "",
121088        bCover ? pIdx->zName : ""
121089    );
121090    sqlite3VdbeAddOp4(
121091        pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
121092    );
121093  }
121094}
121095#else
121096# define explainSimpleCount(a,b,c)
121097#endif
121098
121099/*
121100** Generate code for the SELECT statement given in the p argument.
121101**
121102** The results are returned according to the SelectDest structure.
121103** See comments in sqliteInt.h for further information.
121104**
121105** This routine returns the number of errors.  If any errors are
121106** encountered, then an appropriate error message is left in
121107** pParse->zErrMsg.
121108**
121109** This routine does NOT free the Select structure passed in.  The
121110** calling function needs to do that.
121111*/
121112SQLITE_PRIVATE int sqlite3Select(
121113  Parse *pParse,         /* The parser context */
121114  Select *p,             /* The SELECT statement being coded. */
121115  SelectDest *pDest      /* What to do with the query results */
121116){
121117  int i, j;              /* Loop counters */
121118  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
121119  Vdbe *v;               /* The virtual machine under construction */
121120  int isAgg;             /* True for select lists like "count(*)" */
121121  ExprList *pEList = 0;  /* List of columns to extract. */
121122  SrcList *pTabList;     /* List of tables to select from */
121123  Expr *pWhere;          /* The WHERE clause.  May be NULL */
121124  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
121125  Expr *pHaving;         /* The HAVING clause.  May be NULL */
121126  int rc = 1;            /* Value to return from this function */
121127  DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
121128  SortCtx sSort;         /* Info on how to code the ORDER BY clause */
121129  AggInfo sAggInfo;      /* Information used by aggregate queries */
121130  int iEnd;              /* Address of the end of the query */
121131  sqlite3 *db;           /* The database connection */
121132
121133#ifndef SQLITE_OMIT_EXPLAIN
121134  int iRestoreSelectId = pParse->iSelectId;
121135  pParse->iSelectId = pParse->iNextSelectId++;
121136#endif
121137
121138  db = pParse->db;
121139  if( p==0 || db->mallocFailed || pParse->nErr ){
121140    return 1;
121141  }
121142  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
121143  memset(&sAggInfo, 0, sizeof(sAggInfo));
121144#if SELECTTRACE_ENABLED
121145  pParse->nSelectIndent++;
121146  SELECTTRACE(1,pParse,p, ("begin processing:\n"));
121147  if( sqlite3SelectTrace & 0x100 ){
121148    sqlite3TreeViewSelect(0, p, 0);
121149  }
121150#endif
121151
121152  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
121153  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
121154  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
121155  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
121156  if( IgnorableOrderby(pDest) ){
121157    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
121158           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
121159           pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
121160           pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
121161    /* If ORDER BY makes no difference in the output then neither does
121162    ** DISTINCT so it can be removed too. */
121163    sqlite3ExprListDelete(db, p->pOrderBy);
121164    p->pOrderBy = 0;
121165    p->selFlags &= ~SF_Distinct;
121166  }
121167  sqlite3SelectPrep(pParse, p, 0);
121168  memset(&sSort, 0, sizeof(sSort));
121169  sSort.pOrderBy = p->pOrderBy;
121170  pTabList = p->pSrc;
121171  if( pParse->nErr || db->mallocFailed ){
121172    goto select_end;
121173  }
121174  assert( p->pEList!=0 );
121175  isAgg = (p->selFlags & SF_Aggregate)!=0;
121176#if SELECTTRACE_ENABLED
121177  if( sqlite3SelectTrace & 0x100 ){
121178    SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
121179    sqlite3TreeViewSelect(0, p, 0);
121180  }
121181#endif
121182
121183  /* Try to flatten subqueries in the FROM clause up into the main query
121184  */
121185#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
121186  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
121187    struct SrcList_item *pItem = &pTabList->a[i];
121188    Select *pSub = pItem->pSelect;
121189    int isAggSub;
121190    Table *pTab = pItem->pTab;
121191    if( pSub==0 ) continue;
121192
121193    /* Catch mismatch in the declared columns of a view and the number of
121194    ** columns in the SELECT on the RHS */
121195    if( pTab->nCol!=pSub->pEList->nExpr ){
121196      sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
121197                      pTab->nCol, pTab->zName, pSub->pEList->nExpr);
121198      goto select_end;
121199    }
121200
121201    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
121202    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
121203      /* This subquery can be absorbed into its parent. */
121204      if( isAggSub ){
121205        isAgg = 1;
121206        p->selFlags |= SF_Aggregate;
121207      }
121208      i = -1;
121209    }
121210    pTabList = p->pSrc;
121211    if( db->mallocFailed ) goto select_end;
121212    if( !IgnorableOrderby(pDest) ){
121213      sSort.pOrderBy = p->pOrderBy;
121214    }
121215  }
121216#endif
121217
121218  /* Get a pointer the VDBE under construction, allocating a new VDBE if one
121219  ** does not already exist */
121220  v = sqlite3GetVdbe(pParse);
121221  if( v==0 ) goto select_end;
121222
121223#ifndef SQLITE_OMIT_COMPOUND_SELECT
121224  /* Handle compound SELECT statements using the separate multiSelect()
121225  ** procedure.
121226  */
121227  if( p->pPrior ){
121228    rc = multiSelect(pParse, p, pDest);
121229    explainSetInteger(pParse->iSelectId, iRestoreSelectId);
121230#if SELECTTRACE_ENABLED
121231    SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
121232    pParse->nSelectIndent--;
121233#endif
121234    return rc;
121235  }
121236#endif
121237
121238  /* Generate code for all sub-queries in the FROM clause
121239  */
121240#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
121241  for(i=0; i<pTabList->nSrc; i++){
121242    struct SrcList_item *pItem = &pTabList->a[i];
121243    SelectDest dest;
121244    Select *pSub = pItem->pSelect;
121245    if( pSub==0 ) continue;
121246
121247    /* Sometimes the code for a subquery will be generated more than
121248    ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
121249    ** for example.  In that case, do not regenerate the code to manifest
121250    ** a view or the co-routine to implement a view.  The first instance
121251    ** is sufficient, though the subroutine to manifest the view does need
121252    ** to be invoked again. */
121253    if( pItem->addrFillSub ){
121254      if( pItem->fg.viaCoroutine==0 ){
121255        sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
121256      }
121257      continue;
121258    }
121259
121260    /* Increment Parse.nHeight by the height of the largest expression
121261    ** tree referred to by this, the parent select. The child select
121262    ** may contain expression trees of at most
121263    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
121264    ** more conservative than necessary, but much easier than enforcing
121265    ** an exact limit.
121266    */
121267    pParse->nHeight += sqlite3SelectExprHeight(p);
121268
121269    /* Make copies of constant WHERE-clause terms in the outer query down
121270    ** inside the subquery.  This can help the subquery to run more efficiently.
121271    */
121272    if( (pItem->fg.jointype & JT_OUTER)==0
121273     && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor)
121274    ){
121275#if SELECTTRACE_ENABLED
121276      if( sqlite3SelectTrace & 0x100 ){
121277        SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
121278        sqlite3TreeViewSelect(0, p, 0);
121279      }
121280#endif
121281    }
121282
121283    /* Generate code to implement the subquery
121284    **
121285    ** The subquery is implemented as a co-routine if all of these are true:
121286    **   (1)  The subquery is guaranteed to be the outer loop (so that it
121287    **        does not need to be computed more than once)
121288    **   (2)  The ALL keyword after SELECT is omitted.  (Applications are
121289    **        allowed to say "SELECT ALL" instead of just "SELECT" to disable
121290    **        the use of co-routines.)
121291    **   (3)  Co-routines are not disabled using sqlite3_test_control()
121292    **        with SQLITE_TESTCTRL_OPTIMIZATIONS.
121293    **
121294    ** TODO: Are there other reasons beside (1) to use a co-routine
121295    ** implementation?
121296    */
121297    if( i==0
121298     && (pTabList->nSrc==1
121299            || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)  /* (1) */
121300     && (p->selFlags & SF_All)==0                                   /* (2) */
121301     && OptimizationEnabled(db, SQLITE_SubqCoroutine)               /* (3) */
121302    ){
121303      /* Implement a co-routine that will return a single row of the result
121304      ** set on each invocation.
121305      */
121306      int addrTop = sqlite3VdbeCurrentAddr(v)+1;
121307      pItem->regReturn = ++pParse->nMem;
121308      sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
121309      VdbeComment((v, "%s", pItem->pTab->zName));
121310      pItem->addrFillSub = addrTop;
121311      sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
121312      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
121313      sqlite3Select(pParse, pSub, &dest);
121314      pItem->pTab->nRowLogEst = pSub->nSelectRow;
121315      pItem->fg.viaCoroutine = 1;
121316      pItem->regResult = dest.iSdst;
121317      sqlite3VdbeEndCoroutine(v, pItem->regReturn);
121318      sqlite3VdbeJumpHere(v, addrTop-1);
121319      sqlite3ClearTempRegCache(pParse);
121320    }else{
121321      /* Generate a subroutine that will fill an ephemeral table with
121322      ** the content of this subquery.  pItem->addrFillSub will point
121323      ** to the address of the generated subroutine.  pItem->regReturn
121324      ** is a register allocated to hold the subroutine return address
121325      */
121326      int topAddr;
121327      int onceAddr = 0;
121328      int retAddr;
121329      assert( pItem->addrFillSub==0 );
121330      pItem->regReturn = ++pParse->nMem;
121331      topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
121332      pItem->addrFillSub = topAddr+1;
121333      if( pItem->fg.isCorrelated==0 ){
121334        /* If the subquery is not correlated and if we are not inside of
121335        ** a trigger, then we only need to compute the value of the subquery
121336        ** once. */
121337        onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
121338        VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
121339      }else{
121340        VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
121341      }
121342      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
121343      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
121344      sqlite3Select(pParse, pSub, &dest);
121345      pItem->pTab->nRowLogEst = pSub->nSelectRow;
121346      if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
121347      retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
121348      VdbeComment((v, "end %s", pItem->pTab->zName));
121349      sqlite3VdbeChangeP1(v, topAddr, retAddr);
121350      sqlite3ClearTempRegCache(pParse);
121351    }
121352    if( db->mallocFailed ) goto select_end;
121353    pParse->nHeight -= sqlite3SelectExprHeight(p);
121354  }
121355#endif
121356
121357  /* Various elements of the SELECT copied into local variables for
121358  ** convenience */
121359  pEList = p->pEList;
121360  pWhere = p->pWhere;
121361  pGroupBy = p->pGroupBy;
121362  pHaving = p->pHaving;
121363  sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
121364
121365#if SELECTTRACE_ENABLED
121366  if( sqlite3SelectTrace & 0x400 ){
121367    SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
121368    sqlite3TreeViewSelect(0, p, 0);
121369  }
121370#endif
121371
121372  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
121373  ** if the select-list is the same as the ORDER BY list, then this query
121374  ** can be rewritten as a GROUP BY. In other words, this:
121375  **
121376  **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
121377  **
121378  ** is transformed to:
121379  **
121380  **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
121381  **
121382  ** The second form is preferred as a single index (or temp-table) may be
121383  ** used for both the ORDER BY and DISTINCT processing. As originally
121384  ** written the query must use a temp-table for at least one of the ORDER
121385  ** BY and DISTINCT, and an index or separate temp-table for the other.
121386  */
121387  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
121388   && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
121389  ){
121390    p->selFlags &= ~SF_Distinct;
121391    pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
121392    /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
121393    ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
121394    ** original setting of the SF_Distinct flag, not the current setting */
121395    assert( sDistinct.isTnct );
121396
121397#if SELECTTRACE_ENABLED
121398    if( sqlite3SelectTrace & 0x400 ){
121399      SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
121400      sqlite3TreeViewSelect(0, p, 0);
121401    }
121402#endif
121403  }
121404
121405  /* If there is an ORDER BY clause, then create an ephemeral index to
121406  ** do the sorting.  But this sorting ephemeral index might end up
121407  ** being unused if the data can be extracted in pre-sorted order.
121408  ** If that is the case, then the OP_OpenEphemeral instruction will be
121409  ** changed to an OP_Noop once we figure out that the sorting index is
121410  ** not needed.  The sSort.addrSortIndex variable is used to facilitate
121411  ** that change.
121412  */
121413  if( sSort.pOrderBy ){
121414    KeyInfo *pKeyInfo;
121415    pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
121416    sSort.iECursor = pParse->nTab++;
121417    sSort.addrSortIndex =
121418      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
121419          sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
121420          (char*)pKeyInfo, P4_KEYINFO
121421      );
121422  }else{
121423    sSort.addrSortIndex = -1;
121424  }
121425
121426  /* If the output is destined for a temporary table, open that table.
121427  */
121428  if( pDest->eDest==SRT_EphemTab ){
121429    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
121430  }
121431
121432  /* Set the limiter.
121433  */
121434  iEnd = sqlite3VdbeMakeLabel(v);
121435  if( (p->selFlags & SF_FixedLimit)==0 ){
121436    p->nSelectRow = 320;  /* 4 billion rows */
121437  }
121438  computeLimitRegisters(pParse, p, iEnd);
121439  if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
121440    sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
121441    sSort.sortFlags |= SORTFLAG_UseSorter;
121442  }
121443
121444  /* Open an ephemeral index to use for the distinct set.
121445  */
121446  if( p->selFlags & SF_Distinct ){
121447    sDistinct.tabTnct = pParse->nTab++;
121448    sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
121449                             sDistinct.tabTnct, 0, 0,
121450                             (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
121451                             P4_KEYINFO);
121452    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
121453    sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
121454  }else{
121455    sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
121456  }
121457
121458  if( !isAgg && pGroupBy==0 ){
121459    /* No aggregate functions and no GROUP BY clause */
121460    u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
121461    assert( WHERE_USE_LIMIT==SF_FixedLimit );
121462    wctrlFlags |= p->selFlags & SF_FixedLimit;
121463
121464    /* Begin the database scan. */
121465    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
121466                               p->pEList, wctrlFlags, p->nSelectRow);
121467    if( pWInfo==0 ) goto select_end;
121468    if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
121469      p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
121470    }
121471    if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
121472      sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
121473    }
121474    if( sSort.pOrderBy ){
121475      sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
121476      sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
121477      if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
121478        sSort.pOrderBy = 0;
121479      }
121480    }
121481
121482    /* If sorting index that was created by a prior OP_OpenEphemeral
121483    ** instruction ended up not being needed, then change the OP_OpenEphemeral
121484    ** into an OP_Noop.
121485    */
121486    if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
121487      sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
121488    }
121489
121490    /* Use the standard inner loop. */
121491    selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
121492                    sqlite3WhereContinueLabel(pWInfo),
121493                    sqlite3WhereBreakLabel(pWInfo));
121494
121495    /* End the database scan loop.
121496    */
121497    sqlite3WhereEnd(pWInfo);
121498  }else{
121499    /* This case when there exist aggregate functions or a GROUP BY clause
121500    ** or both */
121501    NameContext sNC;    /* Name context for processing aggregate information */
121502    int iAMem;          /* First Mem address for storing current GROUP BY */
121503    int iBMem;          /* First Mem address for previous GROUP BY */
121504    int iUseFlag;       /* Mem address holding flag indicating that at least
121505                        ** one row of the input to the aggregator has been
121506                        ** processed */
121507    int iAbortFlag;     /* Mem address which causes query abort if positive */
121508    int groupBySort;    /* Rows come from source in GROUP BY order */
121509    int addrEnd;        /* End of processing for this SELECT */
121510    int sortPTab = 0;   /* Pseudotable used to decode sorting results */
121511    int sortOut = 0;    /* Output register from the sorter */
121512    int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
121513
121514    /* Remove any and all aliases between the result set and the
121515    ** GROUP BY clause.
121516    */
121517    if( pGroupBy ){
121518      int k;                        /* Loop counter */
121519      struct ExprList_item *pItem;  /* For looping over expression in a list */
121520
121521      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
121522        pItem->u.x.iAlias = 0;
121523      }
121524      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
121525        pItem->u.x.iAlias = 0;
121526      }
121527      assert( 66==sqlite3LogEst(100) );
121528      if( p->nSelectRow>66 ) p->nSelectRow = 66;
121529    }else{
121530      assert( 0==sqlite3LogEst(1) );
121531      p->nSelectRow = 0;
121532    }
121533
121534    /* If there is both a GROUP BY and an ORDER BY clause and they are
121535    ** identical, then it may be possible to disable the ORDER BY clause
121536    ** on the grounds that the GROUP BY will cause elements to come out
121537    ** in the correct order. It also may not - the GROUP BY might use a
121538    ** database index that causes rows to be grouped together as required
121539    ** but not actually sorted. Either way, record the fact that the
121540    ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
121541    ** variable.  */
121542    if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
121543      orderByGrp = 1;
121544    }
121545
121546    /* Create a label to jump to when we want to abort the query */
121547    addrEnd = sqlite3VdbeMakeLabel(v);
121548
121549    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
121550    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
121551    ** SELECT statement.
121552    */
121553    memset(&sNC, 0, sizeof(sNC));
121554    sNC.pParse = pParse;
121555    sNC.pSrcList = pTabList;
121556    sNC.pAggInfo = &sAggInfo;
121557    sAggInfo.mnReg = pParse->nMem+1;
121558    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
121559    sAggInfo.pGroupBy = pGroupBy;
121560    sqlite3ExprAnalyzeAggList(&sNC, pEList);
121561    sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
121562    if( pHaving ){
121563      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
121564    }
121565    sAggInfo.nAccumulator = sAggInfo.nColumn;
121566    for(i=0; i<sAggInfo.nFunc; i++){
121567      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
121568      sNC.ncFlags |= NC_InAggFunc;
121569      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
121570      sNC.ncFlags &= ~NC_InAggFunc;
121571    }
121572    sAggInfo.mxReg = pParse->nMem;
121573    if( db->mallocFailed ) goto select_end;
121574
121575    /* Processing for aggregates with GROUP BY is very different and
121576    ** much more complex than aggregates without a GROUP BY.
121577    */
121578    if( pGroupBy ){
121579      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
121580      int addr1;          /* A-vs-B comparision jump */
121581      int addrOutputRow;  /* Start of subroutine that outputs a result row */
121582      int regOutputRow;   /* Return address register for output subroutine */
121583      int addrSetAbort;   /* Set the abort flag and return */
121584      int addrTopOfLoop;  /* Top of the input loop */
121585      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
121586      int addrReset;      /* Subroutine for resetting the accumulator */
121587      int regReset;       /* Return address register for reset subroutine */
121588
121589      /* If there is a GROUP BY clause we might need a sorting index to
121590      ** implement it.  Allocate that sorting index now.  If it turns out
121591      ** that we do not need it after all, the OP_SorterOpen instruction
121592      ** will be converted into a Noop.
121593      */
121594      sAggInfo.sortingIdx = pParse->nTab++;
121595      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
121596      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
121597          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
121598          0, (char*)pKeyInfo, P4_KEYINFO);
121599
121600      /* Initialize memory locations used by GROUP BY aggregate processing
121601      */
121602      iUseFlag = ++pParse->nMem;
121603      iAbortFlag = ++pParse->nMem;
121604      regOutputRow = ++pParse->nMem;
121605      addrOutputRow = sqlite3VdbeMakeLabel(v);
121606      regReset = ++pParse->nMem;
121607      addrReset = sqlite3VdbeMakeLabel(v);
121608      iAMem = pParse->nMem + 1;
121609      pParse->nMem += pGroupBy->nExpr;
121610      iBMem = pParse->nMem + 1;
121611      pParse->nMem += pGroupBy->nExpr;
121612      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
121613      VdbeComment((v, "clear abort flag"));
121614      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
121615      VdbeComment((v, "indicate accumulator empty"));
121616      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
121617
121618      /* Begin a loop that will extract all source rows in GROUP BY order.
121619      ** This might involve two separate loops with an OP_Sort in between, or
121620      ** it might be a single loop that uses an index to extract information
121621      ** in the right order to begin with.
121622      */
121623      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
121624      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
121625          WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
121626      );
121627      if( pWInfo==0 ) goto select_end;
121628      if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
121629        /* The optimizer is able to deliver rows in group by order so
121630        ** we do not have to sort.  The OP_OpenEphemeral table will be
121631        ** cancelled later because we still need to use the pKeyInfo
121632        */
121633        groupBySort = 0;
121634      }else{
121635        /* Rows are coming out in undetermined order.  We have to push
121636        ** each row into a sorting index, terminate the first loop,
121637        ** then loop over the sorting index in order to get the output
121638        ** in sorted order
121639        */
121640        int regBase;
121641        int regRecord;
121642        int nCol;
121643        int nGroupBy;
121644
121645        explainTempTable(pParse,
121646            (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
121647                    "DISTINCT" : "GROUP BY");
121648
121649        groupBySort = 1;
121650        nGroupBy = pGroupBy->nExpr;
121651        nCol = nGroupBy;
121652        j = nGroupBy;
121653        for(i=0; i<sAggInfo.nColumn; i++){
121654          if( sAggInfo.aCol[i].iSorterColumn>=j ){
121655            nCol++;
121656            j++;
121657          }
121658        }
121659        regBase = sqlite3GetTempRange(pParse, nCol);
121660        sqlite3ExprCacheClear(pParse);
121661        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
121662        j = nGroupBy;
121663        for(i=0; i<sAggInfo.nColumn; i++){
121664          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
121665          if( pCol->iSorterColumn>=j ){
121666            int r1 = j + regBase;
121667            sqlite3ExprCodeGetColumnToReg(pParse,
121668                               pCol->pTab, pCol->iColumn, pCol->iTable, r1);
121669            j++;
121670          }
121671        }
121672        regRecord = sqlite3GetTempReg(pParse);
121673        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
121674        sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
121675        sqlite3ReleaseTempReg(pParse, regRecord);
121676        sqlite3ReleaseTempRange(pParse, regBase, nCol);
121677        sqlite3WhereEnd(pWInfo);
121678        sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
121679        sortOut = sqlite3GetTempReg(pParse);
121680        sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
121681        sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
121682        VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
121683        sAggInfo.useSortingIdx = 1;
121684        sqlite3ExprCacheClear(pParse);
121685
121686      }
121687
121688      /* If the index or temporary table used by the GROUP BY sort
121689      ** will naturally deliver rows in the order required by the ORDER BY
121690      ** clause, cancel the ephemeral table open coded earlier.
121691      **
121692      ** This is an optimization - the correct answer should result regardless.
121693      ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
121694      ** disable this optimization for testing purposes.  */
121695      if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
121696       && (groupBySort || sqlite3WhereIsSorted(pWInfo))
121697      ){
121698        sSort.pOrderBy = 0;
121699        sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
121700      }
121701
121702      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
121703      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
121704      ** Then compare the current GROUP BY terms against the GROUP BY terms
121705      ** from the previous row currently stored in a0, a1, a2...
121706      */
121707      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
121708      sqlite3ExprCacheClear(pParse);
121709      if( groupBySort ){
121710        sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
121711                          sortOut, sortPTab);
121712      }
121713      for(j=0; j<pGroupBy->nExpr; j++){
121714        if( groupBySort ){
121715          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
121716        }else{
121717          sAggInfo.directMode = 1;
121718          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
121719        }
121720      }
121721      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
121722                          (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
121723      addr1 = sqlite3VdbeCurrentAddr(v);
121724      sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
121725
121726      /* Generate code that runs whenever the GROUP BY changes.
121727      ** Changes in the GROUP BY are detected by the previous code
121728      ** block.  If there were no changes, this block is skipped.
121729      **
121730      ** This code copies current group by terms in b0,b1,b2,...
121731      ** over to a0,a1,a2.  It then calls the output subroutine
121732      ** and resets the aggregate accumulator registers in preparation
121733      ** for the next GROUP BY batch.
121734      */
121735      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
121736      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
121737      VdbeComment((v, "output one row"));
121738      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
121739      VdbeComment((v, "check abort flag"));
121740      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
121741      VdbeComment((v, "reset accumulator"));
121742
121743      /* Update the aggregate accumulators based on the content of
121744      ** the current row
121745      */
121746      sqlite3VdbeJumpHere(v, addr1);
121747      updateAccumulator(pParse, &sAggInfo);
121748      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
121749      VdbeComment((v, "indicate data in accumulator"));
121750
121751      /* End of the loop
121752      */
121753      if( groupBySort ){
121754        sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
121755        VdbeCoverage(v);
121756      }else{
121757        sqlite3WhereEnd(pWInfo);
121758        sqlite3VdbeChangeToNoop(v, addrSortingIdx);
121759      }
121760
121761      /* Output the final row of result
121762      */
121763      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
121764      VdbeComment((v, "output final row"));
121765
121766      /* Jump over the subroutines
121767      */
121768      sqlite3VdbeGoto(v, addrEnd);
121769
121770      /* Generate a subroutine that outputs a single row of the result
121771      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
121772      ** is less than or equal to zero, the subroutine is a no-op.  If
121773      ** the processing calls for the query to abort, this subroutine
121774      ** increments the iAbortFlag memory location before returning in
121775      ** order to signal the caller to abort.
121776      */
121777      addrSetAbort = sqlite3VdbeCurrentAddr(v);
121778      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
121779      VdbeComment((v, "set abort flag"));
121780      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
121781      sqlite3VdbeResolveLabel(v, addrOutputRow);
121782      addrOutputRow = sqlite3VdbeCurrentAddr(v);
121783      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
121784      VdbeCoverage(v);
121785      VdbeComment((v, "Groupby result generator entry point"));
121786      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
121787      finalizeAggFunctions(pParse, &sAggInfo);
121788      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
121789      selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
121790                      &sDistinct, pDest,
121791                      addrOutputRow+1, addrSetAbort);
121792      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
121793      VdbeComment((v, "end groupby result generator"));
121794
121795      /* Generate a subroutine that will reset the group-by accumulator
121796      */
121797      sqlite3VdbeResolveLabel(v, addrReset);
121798      resetAccumulator(pParse, &sAggInfo);
121799      sqlite3VdbeAddOp1(v, OP_Return, regReset);
121800
121801    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
121802    else {
121803      ExprList *pDel = 0;
121804#ifndef SQLITE_OMIT_BTREECOUNT
121805      Table *pTab;
121806      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
121807        /* If isSimpleCount() returns a pointer to a Table structure, then
121808        ** the SQL statement is of the form:
121809        **
121810        **   SELECT count(*) FROM <tbl>
121811        **
121812        ** where the Table structure returned represents table <tbl>.
121813        **
121814        ** This statement is so common that it is optimized specially. The
121815        ** OP_Count instruction is executed either on the intkey table that
121816        ** contains the data for table <tbl> or on one of its indexes. It
121817        ** is better to execute the op on an index, as indexes are almost
121818        ** always spread across less pages than their corresponding tables.
121819        */
121820        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
121821        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
121822        Index *pIdx;                         /* Iterator variable */
121823        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
121824        Index *pBest = 0;                    /* Best index found so far */
121825        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
121826
121827        sqlite3CodeVerifySchema(pParse, iDb);
121828        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
121829
121830        /* Search for the index that has the lowest scan cost.
121831        **
121832        ** (2011-04-15) Do not do a full scan of an unordered index.
121833        **
121834        ** (2013-10-03) Do not count the entries in a partial index.
121835        **
121836        ** In practice the KeyInfo structure will not be used. It is only
121837        ** passed to keep OP_OpenRead happy.
121838        */
121839        if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
121840        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
121841          if( pIdx->bUnordered==0
121842           && pIdx->szIdxRow<pTab->szTabRow
121843           && pIdx->pPartIdxWhere==0
121844           && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
121845          ){
121846            pBest = pIdx;
121847          }
121848        }
121849        if( pBest ){
121850          iRoot = pBest->tnum;
121851          pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
121852        }
121853
121854        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
121855        sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
121856        if( pKeyInfo ){
121857          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
121858        }
121859        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
121860        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
121861        explainSimpleCount(pParse, pTab, pBest);
121862      }else
121863#endif /* SQLITE_OMIT_BTREECOUNT */
121864      {
121865        /* Check if the query is of one of the following forms:
121866        **
121867        **   SELECT min(x) FROM ...
121868        **   SELECT max(x) FROM ...
121869        **
121870        ** If it is, then ask the code in where.c to attempt to sort results
121871        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
121872        ** If where.c is able to produce results sorted in this order, then
121873        ** add vdbe code to break out of the processing loop after the
121874        ** first iteration (since the first iteration of the loop is
121875        ** guaranteed to operate on the row with the minimum or maximum
121876        ** value of x, the only row required).
121877        **
121878        ** A special flag must be passed to sqlite3WhereBegin() to slightly
121879        ** modify behavior as follows:
121880        **
121881        **   + If the query is a "SELECT min(x)", then the loop coded by
121882        **     where.c should not iterate over any values with a NULL value
121883        **     for x.
121884        **
121885        **   + The optimizer code in where.c (the thing that decides which
121886        **     index or indices to use) should place a different priority on
121887        **     satisfying the 'ORDER BY' clause than it does in other cases.
121888        **     Refer to code and comments in where.c for details.
121889        */
121890        ExprList *pMinMax = 0;
121891        u8 flag = WHERE_ORDERBY_NORMAL;
121892
121893        assert( p->pGroupBy==0 );
121894        assert( flag==0 );
121895        if( p->pHaving==0 ){
121896          flag = minMaxQuery(&sAggInfo, &pMinMax);
121897        }
121898        assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
121899
121900        if( flag ){
121901          pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
121902          pDel = pMinMax;
121903          assert( db->mallocFailed || pMinMax!=0 );
121904          if( !db->mallocFailed ){
121905            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
121906            pMinMax->a[0].pExpr->op = TK_COLUMN;
121907          }
121908        }
121909
121910        /* This case runs if the aggregate has no GROUP BY clause.  The
121911        ** processing is much simpler since there is only a single row
121912        ** of output.
121913        */
121914        resetAccumulator(pParse, &sAggInfo);
121915        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax, 0,flag,0);
121916        if( pWInfo==0 ){
121917          sqlite3ExprListDelete(db, pDel);
121918          goto select_end;
121919        }
121920        updateAccumulator(pParse, &sAggInfo);
121921        assert( pMinMax==0 || pMinMax->nExpr==1 );
121922        if( sqlite3WhereIsOrdered(pWInfo)>0 ){
121923          sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
121924          VdbeComment((v, "%s() by index",
121925                (flag==WHERE_ORDERBY_MIN?"min":"max")));
121926        }
121927        sqlite3WhereEnd(pWInfo);
121928        finalizeAggFunctions(pParse, &sAggInfo);
121929      }
121930
121931      sSort.pOrderBy = 0;
121932      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
121933      selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
121934                      pDest, addrEnd, addrEnd);
121935      sqlite3ExprListDelete(db, pDel);
121936    }
121937    sqlite3VdbeResolveLabel(v, addrEnd);
121938
121939  } /* endif aggregate query */
121940
121941  if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
121942    explainTempTable(pParse, "DISTINCT");
121943  }
121944
121945  /* If there is an ORDER BY clause, then we need to sort the results
121946  ** and send them to the callback one by one.
121947  */
121948  if( sSort.pOrderBy ){
121949    explainTempTable(pParse,
121950                     sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
121951    generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
121952  }
121953
121954  /* Jump here to skip this query
121955  */
121956  sqlite3VdbeResolveLabel(v, iEnd);
121957
121958  /* The SELECT has been coded. If there is an error in the Parse structure,
121959  ** set the return code to 1. Otherwise 0. */
121960  rc = (pParse->nErr>0);
121961
121962  /* Control jumps to here if an error is encountered above, or upon
121963  ** successful coding of the SELECT.
121964  */
121965select_end:
121966  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
121967
121968  /* Identify column names if results of the SELECT are to be output.
121969  */
121970  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
121971    generateColumnNames(pParse, pTabList, pEList);
121972  }
121973
121974  sqlite3DbFree(db, sAggInfo.aCol);
121975  sqlite3DbFree(db, sAggInfo.aFunc);
121976#if SELECTTRACE_ENABLED
121977  SELECTTRACE(1,pParse,p,("end processing\n"));
121978  pParse->nSelectIndent--;
121979#endif
121980  return rc;
121981}
121982
121983/************** End of select.c **********************************************/
121984/************** Begin file table.c *******************************************/
121985/*
121986** 2001 September 15
121987**
121988** The author disclaims copyright to this source code.  In place of
121989** a legal notice, here is a blessing:
121990**
121991**    May you do good and not evil.
121992**    May you find forgiveness for yourself and forgive others.
121993**    May you share freely, never taking more than you give.
121994**
121995*************************************************************************
121996** This file contains the sqlite3_get_table() and sqlite3_free_table()
121997** interface routines.  These are just wrappers around the main
121998** interface routine of sqlite3_exec().
121999**
122000** These routines are in a separate files so that they will not be linked
122001** if they are not used.
122002*/
122003/* #include "sqliteInt.h" */
122004
122005#ifndef SQLITE_OMIT_GET_TABLE
122006
122007/*
122008** This structure is used to pass data from sqlite3_get_table() through
122009** to the callback function is uses to build the result.
122010*/
122011typedef struct TabResult {
122012  char **azResult;   /* Accumulated output */
122013  char *zErrMsg;     /* Error message text, if an error occurs */
122014  u32 nAlloc;        /* Slots allocated for azResult[] */
122015  u32 nRow;          /* Number of rows in the result */
122016  u32 nColumn;       /* Number of columns in the result */
122017  u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
122018  int rc;            /* Return code from sqlite3_exec() */
122019} TabResult;
122020
122021/*
122022** This routine is called once for each row in the result table.  Its job
122023** is to fill in the TabResult structure appropriately, allocating new
122024** memory as necessary.
122025*/
122026static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
122027  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
122028  int need;                         /* Slots needed in p->azResult[] */
122029  int i;                            /* Loop counter */
122030  char *z;                          /* A single column of result */
122031
122032  /* Make sure there is enough space in p->azResult to hold everything
122033  ** we need to remember from this invocation of the callback.
122034  */
122035  if( p->nRow==0 && argv!=0 ){
122036    need = nCol*2;
122037  }else{
122038    need = nCol;
122039  }
122040  if( p->nData + need > p->nAlloc ){
122041    char **azNew;
122042    p->nAlloc = p->nAlloc*2 + need;
122043    azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
122044    if( azNew==0 ) goto malloc_failed;
122045    p->azResult = azNew;
122046  }
122047
122048  /* If this is the first row, then generate an extra row containing
122049  ** the names of all columns.
122050  */
122051  if( p->nRow==0 ){
122052    p->nColumn = nCol;
122053    for(i=0; i<nCol; i++){
122054      z = sqlite3_mprintf("%s", colv[i]);
122055      if( z==0 ) goto malloc_failed;
122056      p->azResult[p->nData++] = z;
122057    }
122058  }else if( (int)p->nColumn!=nCol ){
122059    sqlite3_free(p->zErrMsg);
122060    p->zErrMsg = sqlite3_mprintf(
122061       "sqlite3_get_table() called with two or more incompatible queries"
122062    );
122063    p->rc = SQLITE_ERROR;
122064    return 1;
122065  }
122066
122067  /* Copy over the row data
122068  */
122069  if( argv!=0 ){
122070    for(i=0; i<nCol; i++){
122071      if( argv[i]==0 ){
122072        z = 0;
122073      }else{
122074        int n = sqlite3Strlen30(argv[i])+1;
122075        z = sqlite3_malloc64( n );
122076        if( z==0 ) goto malloc_failed;
122077        memcpy(z, argv[i], n);
122078      }
122079      p->azResult[p->nData++] = z;
122080    }
122081    p->nRow++;
122082  }
122083  return 0;
122084
122085malloc_failed:
122086  p->rc = SQLITE_NOMEM_BKPT;
122087  return 1;
122088}
122089
122090/*
122091** Query the database.  But instead of invoking a callback for each row,
122092** malloc() for space to hold the result and return the entire results
122093** at the conclusion of the call.
122094**
122095** The result that is written to ***pazResult is held in memory obtained
122096** from malloc().  But the caller cannot free this memory directly.
122097** Instead, the entire table should be passed to sqlite3_free_table() when
122098** the calling procedure is finished using it.
122099*/
122100SQLITE_API int sqlite3_get_table(
122101  sqlite3 *db,                /* The database on which the SQL executes */
122102  const char *zSql,           /* The SQL to be executed */
122103  char ***pazResult,          /* Write the result table here */
122104  int *pnRow,                 /* Write the number of rows in the result here */
122105  int *pnColumn,              /* Write the number of columns of result here */
122106  char **pzErrMsg             /* Write error messages here */
122107){
122108  int rc;
122109  TabResult res;
122110
122111#ifdef SQLITE_ENABLE_API_ARMOR
122112  if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
122113#endif
122114  *pazResult = 0;
122115  if( pnColumn ) *pnColumn = 0;
122116  if( pnRow ) *pnRow = 0;
122117  if( pzErrMsg ) *pzErrMsg = 0;
122118  res.zErrMsg = 0;
122119  res.nRow = 0;
122120  res.nColumn = 0;
122121  res.nData = 1;
122122  res.nAlloc = 20;
122123  res.rc = SQLITE_OK;
122124  res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
122125  if( res.azResult==0 ){
122126     db->errCode = SQLITE_NOMEM;
122127     return SQLITE_NOMEM_BKPT;
122128  }
122129  res.azResult[0] = 0;
122130  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
122131  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
122132  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
122133  if( (rc&0xff)==SQLITE_ABORT ){
122134    sqlite3_free_table(&res.azResult[1]);
122135    if( res.zErrMsg ){
122136      if( pzErrMsg ){
122137        sqlite3_free(*pzErrMsg);
122138        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
122139      }
122140      sqlite3_free(res.zErrMsg);
122141    }
122142    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
122143    return res.rc;
122144  }
122145  sqlite3_free(res.zErrMsg);
122146  if( rc!=SQLITE_OK ){
122147    sqlite3_free_table(&res.azResult[1]);
122148    return rc;
122149  }
122150  if( res.nAlloc>res.nData ){
122151    char **azNew;
122152    azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
122153    if( azNew==0 ){
122154      sqlite3_free_table(&res.azResult[1]);
122155      db->errCode = SQLITE_NOMEM;
122156      return SQLITE_NOMEM_BKPT;
122157    }
122158    res.azResult = azNew;
122159  }
122160  *pazResult = &res.azResult[1];
122161  if( pnColumn ) *pnColumn = res.nColumn;
122162  if( pnRow ) *pnRow = res.nRow;
122163  return rc;
122164}
122165
122166/*
122167** This routine frees the space the sqlite3_get_table() malloced.
122168*/
122169SQLITE_API void sqlite3_free_table(
122170  char **azResult            /* Result returned from sqlite3_get_table() */
122171){
122172  if( azResult ){
122173    int i, n;
122174    azResult--;
122175    assert( azResult!=0 );
122176    n = SQLITE_PTR_TO_INT(azResult[0]);
122177    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
122178    sqlite3_free(azResult);
122179  }
122180}
122181
122182#endif /* SQLITE_OMIT_GET_TABLE */
122183
122184/************** End of table.c ***********************************************/
122185/************** Begin file trigger.c *****************************************/
122186/*
122187**
122188** The author disclaims copyright to this source code.  In place of
122189** a legal notice, here is a blessing:
122190**
122191**    May you do good and not evil.
122192**    May you find forgiveness for yourself and forgive others.
122193**    May you share freely, never taking more than you give.
122194**
122195*************************************************************************
122196** This file contains the implementation for TRIGGERs
122197*/
122198/* #include "sqliteInt.h" */
122199
122200#ifndef SQLITE_OMIT_TRIGGER
122201/*
122202** Delete a linked list of TriggerStep structures.
122203*/
122204SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
122205  while( pTriggerStep ){
122206    TriggerStep * pTmp = pTriggerStep;
122207    pTriggerStep = pTriggerStep->pNext;
122208
122209    sqlite3ExprDelete(db, pTmp->pWhere);
122210    sqlite3ExprListDelete(db, pTmp->pExprList);
122211    sqlite3SelectDelete(db, pTmp->pSelect);
122212    sqlite3IdListDelete(db, pTmp->pIdList);
122213
122214    sqlite3DbFree(db, pTmp);
122215  }
122216}
122217
122218/*
122219** Given table pTab, return a list of all the triggers attached to
122220** the table. The list is connected by Trigger.pNext pointers.
122221**
122222** All of the triggers on pTab that are in the same database as pTab
122223** are already attached to pTab->pTrigger.  But there might be additional
122224** triggers on pTab in the TEMP schema.  This routine prepends all
122225** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
122226** and returns the combined list.
122227**
122228** To state it another way:  This routine returns a list of all triggers
122229** that fire off of pTab.  The list will include any TEMP triggers on
122230** pTab as well as the triggers lised in pTab->pTrigger.
122231*/
122232SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
122233  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
122234  Trigger *pList = 0;                  /* List of triggers to return */
122235
122236  if( pParse->disableTriggers ){
122237    return 0;
122238  }
122239
122240  if( pTmpSchema!=pTab->pSchema ){
122241    HashElem *p;
122242    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
122243    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
122244      Trigger *pTrig = (Trigger *)sqliteHashData(p);
122245      if( pTrig->pTabSchema==pTab->pSchema
122246       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
122247      ){
122248        pTrig->pNext = (pList ? pList : pTab->pTrigger);
122249        pList = pTrig;
122250      }
122251    }
122252  }
122253
122254  return (pList ? pList : pTab->pTrigger);
122255}
122256
122257/*
122258** This is called by the parser when it sees a CREATE TRIGGER statement
122259** up to the point of the BEGIN before the trigger actions.  A Trigger
122260** structure is generated based on the information available and stored
122261** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
122262** sqlite3FinishTrigger() function is called to complete the trigger
122263** construction process.
122264*/
122265SQLITE_PRIVATE void sqlite3BeginTrigger(
122266  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
122267  Token *pName1,      /* The name of the trigger */
122268  Token *pName2,      /* The name of the trigger */
122269  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
122270  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
122271  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
122272  SrcList *pTableName,/* The name of the table/view the trigger applies to */
122273  Expr *pWhen,        /* WHEN clause */
122274  int isTemp,         /* True if the TEMPORARY keyword is present */
122275  int noErr           /* Suppress errors if the trigger already exists */
122276){
122277  Trigger *pTrigger = 0;  /* The new trigger */
122278  Table *pTab;            /* Table that the trigger fires off of */
122279  char *zName = 0;        /* Name of the trigger */
122280  sqlite3 *db = pParse->db;  /* The database connection */
122281  int iDb;                /* The database to store the trigger in */
122282  Token *pName;           /* The unqualified db name */
122283  DbFixer sFix;           /* State vector for the DB fixer */
122284
122285  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
122286  assert( pName2!=0 );
122287  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
122288  assert( op>0 && op<0xff );
122289  if( isTemp ){
122290    /* If TEMP was specified, then the trigger name may not be qualified. */
122291    if( pName2->n>0 ){
122292      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
122293      goto trigger_cleanup;
122294    }
122295    iDb = 1;
122296    pName = pName1;
122297  }else{
122298    /* Figure out the db that the trigger will be created in */
122299    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
122300    if( iDb<0 ){
122301      goto trigger_cleanup;
122302    }
122303  }
122304  if( !pTableName || db->mallocFailed ){
122305    goto trigger_cleanup;
122306  }
122307
122308  /* A long-standing parser bug is that this syntax was allowed:
122309  **
122310  **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
122311  **                                                 ^^^^^^^^
122312  **
122313  ** To maintain backwards compatibility, ignore the database
122314  ** name on pTableName if we are reparsing out of SQLITE_MASTER.
122315  */
122316  if( db->init.busy && iDb!=1 ){
122317    sqlite3DbFree(db, pTableName->a[0].zDatabase);
122318    pTableName->a[0].zDatabase = 0;
122319  }
122320
122321  /* If the trigger name was unqualified, and the table is a temp table,
122322  ** then set iDb to 1 to create the trigger in the temporary database.
122323  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
122324  ** exist, the error is caught by the block below.
122325  */
122326  pTab = sqlite3SrcListLookup(pParse, pTableName);
122327  if( db->init.busy==0 && pName2->n==0 && pTab
122328        && pTab->pSchema==db->aDb[1].pSchema ){
122329    iDb = 1;
122330  }
122331
122332  /* Ensure the table name matches database name and that the table exists */
122333  if( db->mallocFailed ) goto trigger_cleanup;
122334  assert( pTableName->nSrc==1 );
122335  sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
122336  if( sqlite3FixSrcList(&sFix, pTableName) ){
122337    goto trigger_cleanup;
122338  }
122339  pTab = sqlite3SrcListLookup(pParse, pTableName);
122340  if( !pTab ){
122341    /* The table does not exist. */
122342    if( db->init.iDb==1 ){
122343      /* Ticket #3810.
122344      ** Normally, whenever a table is dropped, all associated triggers are
122345      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
122346      ** and the table is dropped by a different database connection, the
122347      ** trigger is not visible to the database connection that does the
122348      ** drop so the trigger cannot be dropped.  This results in an
122349      ** "orphaned trigger" - a trigger whose associated table is missing.
122350      */
122351      db->init.orphanTrigger = 1;
122352    }
122353    goto trigger_cleanup;
122354  }
122355  if( IsVirtual(pTab) ){
122356    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
122357    goto trigger_cleanup;
122358  }
122359
122360  /* Check that the trigger name is not reserved and that no trigger of the
122361  ** specified name exists */
122362  zName = sqlite3NameFromToken(db, pName);
122363  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
122364    goto trigger_cleanup;
122365  }
122366  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
122367  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
122368    if( !noErr ){
122369      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
122370    }else{
122371      assert( !db->init.busy );
122372      sqlite3CodeVerifySchema(pParse, iDb);
122373    }
122374    goto trigger_cleanup;
122375  }
122376
122377  /* Do not create a trigger on a system table */
122378  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
122379    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
122380    goto trigger_cleanup;
122381  }
122382
122383  /* INSTEAD of triggers are only for views and views only support INSTEAD
122384  ** of triggers.
122385  */
122386  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
122387    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
122388        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
122389    goto trigger_cleanup;
122390  }
122391  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
122392    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
122393        " trigger on table: %S", pTableName, 0);
122394    goto trigger_cleanup;
122395  }
122396
122397#ifndef SQLITE_OMIT_AUTHORIZATION
122398  {
122399    int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
122400    int code = SQLITE_CREATE_TRIGGER;
122401    const char *zDb = db->aDb[iTabDb].zDbSName;
122402    const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
122403    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
122404    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
122405      goto trigger_cleanup;
122406    }
122407    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
122408      goto trigger_cleanup;
122409    }
122410  }
122411#endif
122412
122413  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
122414  ** cannot appear on views.  So we might as well translate every
122415  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
122416  ** elsewhere.
122417  */
122418  if (tr_tm == TK_INSTEAD){
122419    tr_tm = TK_BEFORE;
122420  }
122421
122422  /* Build the Trigger object */
122423  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
122424  if( pTrigger==0 ) goto trigger_cleanup;
122425  pTrigger->zName = zName;
122426  zName = 0;
122427  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
122428  pTrigger->pSchema = db->aDb[iDb].pSchema;
122429  pTrigger->pTabSchema = pTab->pSchema;
122430  pTrigger->op = (u8)op;
122431  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
122432  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
122433  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
122434  assert( pParse->pNewTrigger==0 );
122435  pParse->pNewTrigger = pTrigger;
122436
122437trigger_cleanup:
122438  sqlite3DbFree(db, zName);
122439  sqlite3SrcListDelete(db, pTableName);
122440  sqlite3IdListDelete(db, pColumns);
122441  sqlite3ExprDelete(db, pWhen);
122442  if( !pParse->pNewTrigger ){
122443    sqlite3DeleteTrigger(db, pTrigger);
122444  }else{
122445    assert( pParse->pNewTrigger==pTrigger );
122446  }
122447}
122448
122449/*
122450** This routine is called after all of the trigger actions have been parsed
122451** in order to complete the process of building the trigger.
122452*/
122453SQLITE_PRIVATE void sqlite3FinishTrigger(
122454  Parse *pParse,          /* Parser context */
122455  TriggerStep *pStepList, /* The triggered program */
122456  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
122457){
122458  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
122459  char *zName;                            /* Name of trigger */
122460  sqlite3 *db = pParse->db;               /* The database */
122461  DbFixer sFix;                           /* Fixer object */
122462  int iDb;                                /* Database containing the trigger */
122463  Token nameToken;                        /* Trigger name for error reporting */
122464
122465  pParse->pNewTrigger = 0;
122466  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
122467  zName = pTrig->zName;
122468  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
122469  pTrig->step_list = pStepList;
122470  while( pStepList ){
122471    pStepList->pTrig = pTrig;
122472    pStepList = pStepList->pNext;
122473  }
122474  sqlite3TokenInit(&nameToken, pTrig->zName);
122475  sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
122476  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
122477   || sqlite3FixExpr(&sFix, pTrig->pWhen)
122478  ){
122479    goto triggerfinish_cleanup;
122480  }
122481
122482  /* if we are not initializing,
122483  ** build the sqlite_master entry
122484  */
122485  if( !db->init.busy ){
122486    Vdbe *v;
122487    char *z;
122488
122489    /* Make an entry in the sqlite_master table */
122490    v = sqlite3GetVdbe(pParse);
122491    if( v==0 ) goto triggerfinish_cleanup;
122492    sqlite3BeginWriteOperation(pParse, 0, iDb);
122493    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
122494    sqlite3NestedParse(pParse,
122495       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
122496       db->aDb[iDb].zDbSName, MASTER_NAME, zName,
122497       pTrig->table, z);
122498    sqlite3DbFree(db, z);
122499    sqlite3ChangeCookie(pParse, iDb);
122500    sqlite3VdbeAddParseSchemaOp(v, iDb,
122501        sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
122502  }
122503
122504  if( db->init.busy ){
122505    Trigger *pLink = pTrig;
122506    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
122507    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
122508    pTrig = sqlite3HashInsert(pHash, zName, pTrig);
122509    if( pTrig ){
122510      sqlite3OomFault(db);
122511    }else if( pLink->pSchema==pLink->pTabSchema ){
122512      Table *pTab;
122513      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
122514      assert( pTab!=0 );
122515      pLink->pNext = pTab->pTrigger;
122516      pTab->pTrigger = pLink;
122517    }
122518  }
122519
122520triggerfinish_cleanup:
122521  sqlite3DeleteTrigger(db, pTrig);
122522  assert( !pParse->pNewTrigger );
122523  sqlite3DeleteTriggerStep(db, pStepList);
122524}
122525
122526/*
122527** Turn a SELECT statement (that the pSelect parameter points to) into
122528** a trigger step.  Return a pointer to a TriggerStep structure.
122529**
122530** The parser calls this routine when it finds a SELECT statement in
122531** body of a TRIGGER.
122532*/
122533SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
122534  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
122535  if( pTriggerStep==0 ) {
122536    sqlite3SelectDelete(db, pSelect);
122537    return 0;
122538  }
122539  pTriggerStep->op = TK_SELECT;
122540  pTriggerStep->pSelect = pSelect;
122541  pTriggerStep->orconf = OE_Default;
122542  return pTriggerStep;
122543}
122544
122545/*
122546** Allocate space to hold a new trigger step.  The allocated space
122547** holds both the TriggerStep object and the TriggerStep.target.z string.
122548**
122549** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
122550*/
122551static TriggerStep *triggerStepAllocate(
122552  sqlite3 *db,                /* Database connection */
122553  u8 op,                      /* Trigger opcode */
122554  Token *pName                /* The target name */
122555){
122556  TriggerStep *pTriggerStep;
122557
122558  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
122559  if( pTriggerStep ){
122560    char *z = (char*)&pTriggerStep[1];
122561    memcpy(z, pName->z, pName->n);
122562    sqlite3Dequote(z);
122563    pTriggerStep->zTarget = z;
122564    pTriggerStep->op = op;
122565  }
122566  return pTriggerStep;
122567}
122568
122569/*
122570** Build a trigger step out of an INSERT statement.  Return a pointer
122571** to the new trigger step.
122572**
122573** The parser calls this routine when it sees an INSERT inside the
122574** body of a trigger.
122575*/
122576SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
122577  sqlite3 *db,        /* The database connection */
122578  Token *pTableName,  /* Name of the table into which we insert */
122579  IdList *pColumn,    /* List of columns in pTableName to insert into */
122580  Select *pSelect,    /* A SELECT statement that supplies values */
122581  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
122582){
122583  TriggerStep *pTriggerStep;
122584
122585  assert(pSelect != 0 || db->mallocFailed);
122586
122587  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
122588  if( pTriggerStep ){
122589    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
122590    pTriggerStep->pIdList = pColumn;
122591    pTriggerStep->orconf = orconf;
122592  }else{
122593    sqlite3IdListDelete(db, pColumn);
122594  }
122595  sqlite3SelectDelete(db, pSelect);
122596
122597  return pTriggerStep;
122598}
122599
122600/*
122601** Construct a trigger step that implements an UPDATE statement and return
122602** a pointer to that trigger step.  The parser calls this routine when it
122603** sees an UPDATE statement inside the body of a CREATE TRIGGER.
122604*/
122605SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
122606  sqlite3 *db,         /* The database connection */
122607  Token *pTableName,   /* Name of the table to be updated */
122608  ExprList *pEList,    /* The SET clause: list of column and new values */
122609  Expr *pWhere,        /* The WHERE clause */
122610  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
122611){
122612  TriggerStep *pTriggerStep;
122613
122614  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
122615  if( pTriggerStep ){
122616    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
122617    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
122618    pTriggerStep->orconf = orconf;
122619  }
122620  sqlite3ExprListDelete(db, pEList);
122621  sqlite3ExprDelete(db, pWhere);
122622  return pTriggerStep;
122623}
122624
122625/*
122626** Construct a trigger step that implements a DELETE statement and return
122627** a pointer to that trigger step.  The parser calls this routine when it
122628** sees a DELETE statement inside the body of a CREATE TRIGGER.
122629*/
122630SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
122631  sqlite3 *db,            /* Database connection */
122632  Token *pTableName,      /* The table from which rows are deleted */
122633  Expr *pWhere            /* The WHERE clause */
122634){
122635  TriggerStep *pTriggerStep;
122636
122637  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
122638  if( pTriggerStep ){
122639    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
122640    pTriggerStep->orconf = OE_Default;
122641  }
122642  sqlite3ExprDelete(db, pWhere);
122643  return pTriggerStep;
122644}
122645
122646/*
122647** Recursively delete a Trigger structure
122648*/
122649SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
122650  if( pTrigger==0 ) return;
122651  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
122652  sqlite3DbFree(db, pTrigger->zName);
122653  sqlite3DbFree(db, pTrigger->table);
122654  sqlite3ExprDelete(db, pTrigger->pWhen);
122655  sqlite3IdListDelete(db, pTrigger->pColumns);
122656  sqlite3DbFree(db, pTrigger);
122657}
122658
122659/*
122660** This function is called to drop a trigger from the database schema.
122661**
122662** This may be called directly from the parser and therefore identifies
122663** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
122664** same job as this routine except it takes a pointer to the trigger
122665** instead of the trigger name.
122666**/
122667SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
122668  Trigger *pTrigger = 0;
122669  int i;
122670  const char *zDb;
122671  const char *zName;
122672  sqlite3 *db = pParse->db;
122673
122674  if( db->mallocFailed ) goto drop_trigger_cleanup;
122675  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
122676    goto drop_trigger_cleanup;
122677  }
122678
122679  assert( pName->nSrc==1 );
122680  zDb = pName->a[0].zDatabase;
122681  zName = pName->a[0].zName;
122682  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
122683  for(i=OMIT_TEMPDB; i<db->nDb; i++){
122684    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
122685    if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
122686    assert( sqlite3SchemaMutexHeld(db, j, 0) );
122687    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
122688    if( pTrigger ) break;
122689  }
122690  if( !pTrigger ){
122691    if( !noErr ){
122692      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
122693    }else{
122694      sqlite3CodeVerifyNamedSchema(pParse, zDb);
122695    }
122696    pParse->checkSchema = 1;
122697    goto drop_trigger_cleanup;
122698  }
122699  sqlite3DropTriggerPtr(pParse, pTrigger);
122700
122701drop_trigger_cleanup:
122702  sqlite3SrcListDelete(db, pName);
122703}
122704
122705/*
122706** Return a pointer to the Table structure for the table that a trigger
122707** is set on.
122708*/
122709static Table *tableOfTrigger(Trigger *pTrigger){
122710  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
122711}
122712
122713
122714/*
122715** Drop a trigger given a pointer to that trigger.
122716*/
122717SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
122718  Table   *pTable;
122719  Vdbe *v;
122720  sqlite3 *db = pParse->db;
122721  int iDb;
122722
122723  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
122724  assert( iDb>=0 && iDb<db->nDb );
122725  pTable = tableOfTrigger(pTrigger);
122726  assert( pTable );
122727  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
122728#ifndef SQLITE_OMIT_AUTHORIZATION
122729  {
122730    int code = SQLITE_DROP_TRIGGER;
122731    const char *zDb = db->aDb[iDb].zDbSName;
122732    const char *zTab = SCHEMA_TABLE(iDb);
122733    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
122734    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
122735      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
122736      return;
122737    }
122738  }
122739#endif
122740
122741  /* Generate code to destroy the database record of the trigger.
122742  */
122743  assert( pTable!=0 );
122744  if( (v = sqlite3GetVdbe(pParse))!=0 ){
122745    sqlite3NestedParse(pParse,
122746       "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
122747       db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
122748    );
122749    sqlite3ChangeCookie(pParse, iDb);
122750    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
122751  }
122752}
122753
122754/*
122755** Remove a trigger from the hash tables of the sqlite* pointer.
122756*/
122757SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
122758  Trigger *pTrigger;
122759  Hash *pHash;
122760
122761  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
122762  pHash = &(db->aDb[iDb].pSchema->trigHash);
122763  pTrigger = sqlite3HashInsert(pHash, zName, 0);
122764  if( ALWAYS(pTrigger) ){
122765    if( pTrigger->pSchema==pTrigger->pTabSchema ){
122766      Table *pTab = tableOfTrigger(pTrigger);
122767      Trigger **pp;
122768      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
122769      *pp = (*pp)->pNext;
122770    }
122771    sqlite3DeleteTrigger(db, pTrigger);
122772    db->flags |= SQLITE_InternChanges;
122773  }
122774}
122775
122776/*
122777** pEList is the SET clause of an UPDATE statement.  Each entry
122778** in pEList is of the format <id>=<expr>.  If any of the entries
122779** in pEList have an <id> which matches an identifier in pIdList,
122780** then return TRUE.  If pIdList==NULL, then it is considered a
122781** wildcard that matches anything.  Likewise if pEList==NULL then
122782** it matches anything so always return true.  Return false only
122783** if there is no match.
122784*/
122785static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
122786  int e;
122787  if( pIdList==0 || NEVER(pEList==0) ) return 1;
122788  for(e=0; e<pEList->nExpr; e++){
122789    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
122790  }
122791  return 0;
122792}
122793
122794/*
122795** Return a list of all triggers on table pTab if there exists at least
122796** one trigger that must be fired when an operation of type 'op' is
122797** performed on the table, and, if that operation is an UPDATE, if at
122798** least one of the columns in pChanges is being modified.
122799*/
122800SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
122801  Parse *pParse,          /* Parse context */
122802  Table *pTab,            /* The table the contains the triggers */
122803  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
122804  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
122805  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
122806){
122807  int mask = 0;
122808  Trigger *pList = 0;
122809  Trigger *p;
122810
122811  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
122812    pList = sqlite3TriggerList(pParse, pTab);
122813  }
122814  assert( pList==0 || IsVirtual(pTab)==0 );
122815  for(p=pList; p; p=p->pNext){
122816    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
122817      mask |= p->tr_tm;
122818    }
122819  }
122820  if( pMask ){
122821    *pMask = mask;
122822  }
122823  return (mask ? pList : 0);
122824}
122825
122826/*
122827** Convert the pStep->zTarget string into a SrcList and return a pointer
122828** to that SrcList.
122829**
122830** This routine adds a specific database name, if needed, to the target when
122831** forming the SrcList.  This prevents a trigger in one database from
122832** referring to a target in another database.  An exception is when the
122833** trigger is in TEMP in which case it can refer to any other database it
122834** wants.
122835*/
122836static SrcList *targetSrcList(
122837  Parse *pParse,       /* The parsing context */
122838  TriggerStep *pStep   /* The trigger containing the target token */
122839){
122840  sqlite3 *db = pParse->db;
122841  int iDb;             /* Index of the database to use */
122842  SrcList *pSrc;       /* SrcList to be returned */
122843
122844  pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
122845  if( pSrc ){
122846    assert( pSrc->nSrc>0 );
122847    pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
122848    iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
122849    if( iDb==0 || iDb>=2 ){
122850      const char *zDb;
122851      assert( iDb<db->nDb );
122852      zDb = db->aDb[iDb].zDbSName;
122853      pSrc->a[pSrc->nSrc-1].zDatabase =  sqlite3DbStrDup(db, zDb);
122854    }
122855  }
122856  return pSrc;
122857}
122858
122859/*
122860** Generate VDBE code for the statements inside the body of a single
122861** trigger.
122862*/
122863static int codeTriggerProgram(
122864  Parse *pParse,            /* The parser context */
122865  TriggerStep *pStepList,   /* List of statements inside the trigger body */
122866  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
122867){
122868  TriggerStep *pStep;
122869  Vdbe *v = pParse->pVdbe;
122870  sqlite3 *db = pParse->db;
122871
122872  assert( pParse->pTriggerTab && pParse->pToplevel );
122873  assert( pStepList );
122874  assert( v!=0 );
122875  for(pStep=pStepList; pStep; pStep=pStep->pNext){
122876    /* Figure out the ON CONFLICT policy that will be used for this step
122877    ** of the trigger program. If the statement that caused this trigger
122878    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
122879    ** the ON CONFLICT policy that was specified as part of the trigger
122880    ** step statement. Example:
122881    **
122882    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
122883    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
122884    **   END;
122885    **
122886    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
122887    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
122888    */
122889    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
122890    assert( pParse->okConstFactor==0 );
122891
122892    switch( pStep->op ){
122893      case TK_UPDATE: {
122894        sqlite3Update(pParse,
122895          targetSrcList(pParse, pStep),
122896          sqlite3ExprListDup(db, pStep->pExprList, 0),
122897          sqlite3ExprDup(db, pStep->pWhere, 0),
122898          pParse->eOrconf
122899        );
122900        break;
122901      }
122902      case TK_INSERT: {
122903        sqlite3Insert(pParse,
122904          targetSrcList(pParse, pStep),
122905          sqlite3SelectDup(db, pStep->pSelect, 0),
122906          sqlite3IdListDup(db, pStep->pIdList),
122907          pParse->eOrconf
122908        );
122909        break;
122910      }
122911      case TK_DELETE: {
122912        sqlite3DeleteFrom(pParse,
122913          targetSrcList(pParse, pStep),
122914          sqlite3ExprDup(db, pStep->pWhere, 0)
122915        );
122916        break;
122917      }
122918      default: assert( pStep->op==TK_SELECT ); {
122919        SelectDest sDest;
122920        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
122921        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
122922        sqlite3Select(pParse, pSelect, &sDest);
122923        sqlite3SelectDelete(db, pSelect);
122924        break;
122925      }
122926    }
122927    if( pStep->op!=TK_SELECT ){
122928      sqlite3VdbeAddOp0(v, OP_ResetCount);
122929    }
122930  }
122931
122932  return 0;
122933}
122934
122935#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
122936/*
122937** This function is used to add VdbeComment() annotations to a VDBE
122938** program. It is not used in production code, only for debugging.
122939*/
122940static const char *onErrorText(int onError){
122941  switch( onError ){
122942    case OE_Abort:    return "abort";
122943    case OE_Rollback: return "rollback";
122944    case OE_Fail:     return "fail";
122945    case OE_Replace:  return "replace";
122946    case OE_Ignore:   return "ignore";
122947    case OE_Default:  return "default";
122948  }
122949  return "n/a";
122950}
122951#endif
122952
122953/*
122954** Parse context structure pFrom has just been used to create a sub-vdbe
122955** (trigger program). If an error has occurred, transfer error information
122956** from pFrom to pTo.
122957*/
122958static void transferParseError(Parse *pTo, Parse *pFrom){
122959  assert( pFrom->zErrMsg==0 || pFrom->nErr );
122960  assert( pTo->zErrMsg==0 || pTo->nErr );
122961  if( pTo->nErr==0 ){
122962    pTo->zErrMsg = pFrom->zErrMsg;
122963    pTo->nErr = pFrom->nErr;
122964    pTo->rc = pFrom->rc;
122965  }else{
122966    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
122967  }
122968}
122969
122970/*
122971** Create and populate a new TriggerPrg object with a sub-program
122972** implementing trigger pTrigger with ON CONFLICT policy orconf.
122973*/
122974static TriggerPrg *codeRowTrigger(
122975  Parse *pParse,       /* Current parse context */
122976  Trigger *pTrigger,   /* Trigger to code */
122977  Table *pTab,         /* The table pTrigger is attached to */
122978  int orconf           /* ON CONFLICT policy to code trigger program with */
122979){
122980  Parse *pTop = sqlite3ParseToplevel(pParse);
122981  sqlite3 *db = pParse->db;   /* Database handle */
122982  TriggerPrg *pPrg;           /* Value to return */
122983  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
122984  Vdbe *v;                    /* Temporary VM */
122985  NameContext sNC;            /* Name context for sub-vdbe */
122986  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
122987  Parse *pSubParse;           /* Parse context for sub-vdbe */
122988  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
122989
122990  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
122991  assert( pTop->pVdbe );
122992
122993  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
122994  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
122995  ** list of the top-level Parse object sooner rather than later.  */
122996  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
122997  if( !pPrg ) return 0;
122998  pPrg->pNext = pTop->pTriggerPrg;
122999  pTop->pTriggerPrg = pPrg;
123000  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
123001  if( !pProgram ) return 0;
123002  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
123003  pPrg->pTrigger = pTrigger;
123004  pPrg->orconf = orconf;
123005  pPrg->aColmask[0] = 0xffffffff;
123006  pPrg->aColmask[1] = 0xffffffff;
123007
123008  /* Allocate and populate a new Parse context to use for coding the
123009  ** trigger sub-program.  */
123010  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
123011  if( !pSubParse ) return 0;
123012  memset(&sNC, 0, sizeof(sNC));
123013  sNC.pParse = pSubParse;
123014  pSubParse->db = db;
123015  pSubParse->pTriggerTab = pTab;
123016  pSubParse->pToplevel = pTop;
123017  pSubParse->zAuthContext = pTrigger->zName;
123018  pSubParse->eTriggerOp = pTrigger->op;
123019  pSubParse->nQueryLoop = pParse->nQueryLoop;
123020
123021  v = sqlite3GetVdbe(pSubParse);
123022  if( v ){
123023    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
123024      pTrigger->zName, onErrorText(orconf),
123025      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
123026        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
123027        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
123028        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
123029      pTab->zName
123030    ));
123031#ifndef SQLITE_OMIT_TRACE
123032    sqlite3VdbeChangeP4(v, -1,
123033      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
123034    );
123035#endif
123036
123037    /* If one was specified, code the WHEN clause. If it evaluates to false
123038    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
123039    ** OP_Halt inserted at the end of the program.  */
123040    if( pTrigger->pWhen ){
123041      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
123042      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
123043       && db->mallocFailed==0
123044      ){
123045        iEndTrigger = sqlite3VdbeMakeLabel(v);
123046        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
123047      }
123048      sqlite3ExprDelete(db, pWhen);
123049    }
123050
123051    /* Code the trigger program into the sub-vdbe. */
123052    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
123053
123054    /* Insert an OP_Halt at the end of the sub-program. */
123055    if( iEndTrigger ){
123056      sqlite3VdbeResolveLabel(v, iEndTrigger);
123057    }
123058    sqlite3VdbeAddOp0(v, OP_Halt);
123059    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
123060
123061    transferParseError(pParse, pSubParse);
123062    if( db->mallocFailed==0 ){
123063      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
123064    }
123065    pProgram->nMem = pSubParse->nMem;
123066    pProgram->nCsr = pSubParse->nTab;
123067    pProgram->token = (void *)pTrigger;
123068    pPrg->aColmask[0] = pSubParse->oldmask;
123069    pPrg->aColmask[1] = pSubParse->newmask;
123070    sqlite3VdbeDelete(v);
123071  }
123072
123073  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
123074  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
123075  sqlite3ParserReset(pSubParse);
123076  sqlite3StackFree(db, pSubParse);
123077
123078  return pPrg;
123079}
123080
123081/*
123082** Return a pointer to a TriggerPrg object containing the sub-program for
123083** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
123084** TriggerPrg object exists, a new object is allocated and populated before
123085** being returned.
123086*/
123087static TriggerPrg *getRowTrigger(
123088  Parse *pParse,       /* Current parse context */
123089  Trigger *pTrigger,   /* Trigger to code */
123090  Table *pTab,         /* The table trigger pTrigger is attached to */
123091  int orconf           /* ON CONFLICT algorithm. */
123092){
123093  Parse *pRoot = sqlite3ParseToplevel(pParse);
123094  TriggerPrg *pPrg;
123095
123096  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
123097
123098  /* It may be that this trigger has already been coded (or is in the
123099  ** process of being coded). If this is the case, then an entry with
123100  ** a matching TriggerPrg.pTrigger field will be present somewhere
123101  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
123102  for(pPrg=pRoot->pTriggerPrg;
123103      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
123104      pPrg=pPrg->pNext
123105  );
123106
123107  /* If an existing TriggerPrg could not be located, create a new one. */
123108  if( !pPrg ){
123109    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
123110  }
123111
123112  return pPrg;
123113}
123114
123115/*
123116** Generate code for the trigger program associated with trigger p on
123117** table pTab. The reg, orconf and ignoreJump parameters passed to this
123118** function are the same as those described in the header function for
123119** sqlite3CodeRowTrigger()
123120*/
123121SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
123122  Parse *pParse,       /* Parse context */
123123  Trigger *p,          /* Trigger to code */
123124  Table *pTab,         /* The table to code triggers from */
123125  int reg,             /* Reg array containing OLD.* and NEW.* values */
123126  int orconf,          /* ON CONFLICT policy */
123127  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
123128){
123129  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
123130  TriggerPrg *pPrg;
123131  pPrg = getRowTrigger(pParse, p, pTab, orconf);
123132  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
123133
123134  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
123135  ** is a pointer to the sub-vdbe containing the trigger program.  */
123136  if( pPrg ){
123137    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
123138
123139    sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
123140                      (const char *)pPrg->pProgram, P4_SUBPROGRAM);
123141    VdbeComment(
123142        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
123143
123144    /* Set the P5 operand of the OP_Program instruction to non-zero if
123145    ** recursive invocation of this trigger program is disallowed. Recursive
123146    ** invocation is disallowed if (a) the sub-program is really a trigger,
123147    ** not a foreign key action, and (b) the flag to enable recursive triggers
123148    ** is clear.  */
123149    sqlite3VdbeChangeP5(v, (u8)bRecursive);
123150  }
123151}
123152
123153/*
123154** This is called to code the required FOR EACH ROW triggers for an operation
123155** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
123156** is given by the op parameter. The tr_tm parameter determines whether the
123157** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
123158** parameter pChanges is passed the list of columns being modified.
123159**
123160** If there are no triggers that fire at the specified time for the specified
123161** operation on pTab, this function is a no-op.
123162**
123163** The reg argument is the address of the first in an array of registers
123164** that contain the values substituted for the new.* and old.* references
123165** in the trigger program. If N is the number of columns in table pTab
123166** (a copy of pTab->nCol), then registers are populated as follows:
123167**
123168**   Register       Contains
123169**   ------------------------------------------------------
123170**   reg+0          OLD.rowid
123171**   reg+1          OLD.* value of left-most column of pTab
123172**   ...            ...
123173**   reg+N          OLD.* value of right-most column of pTab
123174**   reg+N+1        NEW.rowid
123175**   reg+N+2        OLD.* value of left-most column of pTab
123176**   ...            ...
123177**   reg+N+N+1      NEW.* value of right-most column of pTab
123178**
123179** For ON DELETE triggers, the registers containing the NEW.* values will
123180** never be accessed by the trigger program, so they are not allocated or
123181** populated by the caller (there is no data to populate them with anyway).
123182** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
123183** are never accessed, and so are not allocated by the caller. So, for an
123184** ON INSERT trigger, the value passed to this function as parameter reg
123185** is not a readable register, although registers (reg+N) through
123186** (reg+N+N+1) are.
123187**
123188** Parameter orconf is the default conflict resolution algorithm for the
123189** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
123190** is the instruction that control should jump to if a trigger program
123191** raises an IGNORE exception.
123192*/
123193SQLITE_PRIVATE void sqlite3CodeRowTrigger(
123194  Parse *pParse,       /* Parse context */
123195  Trigger *pTrigger,   /* List of triggers on table pTab */
123196  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
123197  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
123198  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
123199  Table *pTab,         /* The table to code triggers from */
123200  int reg,             /* The first in an array of registers (see above) */
123201  int orconf,          /* ON CONFLICT policy */
123202  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
123203){
123204  Trigger *p;          /* Used to iterate through pTrigger list */
123205
123206  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
123207  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
123208  assert( (op==TK_UPDATE)==(pChanges!=0) );
123209
123210  for(p=pTrigger; p; p=p->pNext){
123211
123212    /* Sanity checking:  The schema for the trigger and for the table are
123213    ** always defined.  The trigger must be in the same schema as the table
123214    ** or else it must be a TEMP trigger. */
123215    assert( p->pSchema!=0 );
123216    assert( p->pTabSchema!=0 );
123217    assert( p->pSchema==p->pTabSchema
123218         || p->pSchema==pParse->db->aDb[1].pSchema );
123219
123220    /* Determine whether we should code this trigger */
123221    if( p->op==op
123222     && p->tr_tm==tr_tm
123223     && checkColumnOverlap(p->pColumns, pChanges)
123224    ){
123225      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
123226    }
123227  }
123228}
123229
123230/*
123231** Triggers may access values stored in the old.* or new.* pseudo-table.
123232** This function returns a 32-bit bitmask indicating which columns of the
123233** old.* or new.* tables actually are used by triggers. This information
123234** may be used by the caller, for example, to avoid having to load the entire
123235** old.* record into memory when executing an UPDATE or DELETE command.
123236**
123237** Bit 0 of the returned mask is set if the left-most column of the
123238** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
123239** the second leftmost column value is required, and so on. If there
123240** are more than 32 columns in the table, and at least one of the columns
123241** with an index greater than 32 may be accessed, 0xffffffff is returned.
123242**
123243** It is not possible to determine if the old.rowid or new.rowid column is
123244** accessed by triggers. The caller must always assume that it is.
123245**
123246** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
123247** applies to the old.* table. If 1, the new.* table.
123248**
123249** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
123250** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
123251** included in the returned mask if the TRIGGER_BEFORE bit is set in the
123252** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
123253** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
123254*/
123255SQLITE_PRIVATE u32 sqlite3TriggerColmask(
123256  Parse *pParse,       /* Parse context */
123257  Trigger *pTrigger,   /* List of triggers on table pTab */
123258  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
123259  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
123260  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
123261  Table *pTab,         /* The table to code triggers from */
123262  int orconf           /* Default ON CONFLICT policy for trigger steps */
123263){
123264  const int op = pChanges ? TK_UPDATE : TK_DELETE;
123265  u32 mask = 0;
123266  Trigger *p;
123267
123268  assert( isNew==1 || isNew==0 );
123269  for(p=pTrigger; p; p=p->pNext){
123270    if( p->op==op && (tr_tm&p->tr_tm)
123271     && checkColumnOverlap(p->pColumns,pChanges)
123272    ){
123273      TriggerPrg *pPrg;
123274      pPrg = getRowTrigger(pParse, p, pTab, orconf);
123275      if( pPrg ){
123276        mask |= pPrg->aColmask[isNew];
123277      }
123278    }
123279  }
123280
123281  return mask;
123282}
123283
123284#endif /* !defined(SQLITE_OMIT_TRIGGER) */
123285
123286/************** End of trigger.c *********************************************/
123287/************** Begin file update.c ******************************************/
123288/*
123289** 2001 September 15
123290**
123291** The author disclaims copyright to this source code.  In place of
123292** a legal notice, here is a blessing:
123293**
123294**    May you do good and not evil.
123295**    May you find forgiveness for yourself and forgive others.
123296**    May you share freely, never taking more than you give.
123297**
123298*************************************************************************
123299** This file contains C code routines that are called by the parser
123300** to handle UPDATE statements.
123301*/
123302/* #include "sqliteInt.h" */
123303
123304#ifndef SQLITE_OMIT_VIRTUALTABLE
123305/* Forward declaration */
123306static void updateVirtualTable(
123307  Parse *pParse,       /* The parsing context */
123308  SrcList *pSrc,       /* The virtual table to be modified */
123309  Table *pTab,         /* The virtual table */
123310  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
123311  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
123312  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
123313  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
123314  int onError          /* ON CONFLICT strategy */
123315);
123316#endif /* SQLITE_OMIT_VIRTUALTABLE */
123317
123318/*
123319** The most recently coded instruction was an OP_Column to retrieve the
123320** i-th column of table pTab. This routine sets the P4 parameter of the
123321** OP_Column to the default value, if any.
123322**
123323** The default value of a column is specified by a DEFAULT clause in the
123324** column definition. This was either supplied by the user when the table
123325** was created, or added later to the table definition by an ALTER TABLE
123326** command. If the latter, then the row-records in the table btree on disk
123327** may not contain a value for the column and the default value, taken
123328** from the P4 parameter of the OP_Column instruction, is returned instead.
123329** If the former, then all row-records are guaranteed to include a value
123330** for the column and the P4 value is not required.
123331**
123332** Column definitions created by an ALTER TABLE command may only have
123333** literal default values specified: a number, null or a string. (If a more
123334** complicated default expression value was provided, it is evaluated
123335** when the ALTER TABLE is executed and one of the literal values written
123336** into the sqlite_master table.)
123337**
123338** Therefore, the P4 parameter is only required if the default value for
123339** the column is a literal number, string or null. The sqlite3ValueFromExpr()
123340** function is capable of transforming these types of expressions into
123341** sqlite3_value objects.
123342**
123343** If parameter iReg is not negative, code an OP_RealAffinity instruction
123344** on register iReg. This is used when an equivalent integer value is
123345** stored in place of an 8-byte floating point value in order to save
123346** space.
123347*/
123348SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
123349  assert( pTab!=0 );
123350  if( !pTab->pSelect ){
123351    sqlite3_value *pValue = 0;
123352    u8 enc = ENC(sqlite3VdbeDb(v));
123353    Column *pCol = &pTab->aCol[i];
123354    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
123355    assert( i<pTab->nCol );
123356    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
123357                         pCol->affinity, &pValue);
123358    if( pValue ){
123359      sqlite3VdbeAppendP4(v, pValue, P4_MEM);
123360    }
123361  }
123362#ifndef SQLITE_OMIT_FLOATING_POINT
123363  if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
123364    sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
123365  }
123366#endif
123367}
123368
123369/*
123370** Process an UPDATE statement.
123371**
123372**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
123373**          \_______/ \________/     \______/       \________________/
123374*            onError   pTabList      pChanges             pWhere
123375*/
123376SQLITE_PRIVATE void sqlite3Update(
123377  Parse *pParse,         /* The parser context */
123378  SrcList *pTabList,     /* The table in which we should change things */
123379  ExprList *pChanges,    /* Things to be changed */
123380  Expr *pWhere,          /* The WHERE clause.  May be null */
123381  int onError            /* How to handle constraint errors */
123382){
123383  int i, j;              /* Loop counters */
123384  Table *pTab;           /* The table to be updated */
123385  int addrTop = 0;       /* VDBE instruction address of the start of the loop */
123386  WhereInfo *pWInfo;     /* Information about the WHERE clause */
123387  Vdbe *v;               /* The virtual database engine */
123388  Index *pIdx;           /* For looping over indices */
123389  Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
123390  int nIdx;              /* Number of indices that need updating */
123391  int iBaseCur;          /* Base cursor number */
123392  int iDataCur;          /* Cursor for the canonical data btree */
123393  int iIdxCur;           /* Cursor for the first index */
123394  sqlite3 *db;           /* The database structure */
123395  int *aRegIdx = 0;      /* First register in array assigned to each index */
123396  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
123397                         ** an expression for the i-th column of the table.
123398                         ** aXRef[i]==-1 if the i-th column is not changed. */
123399  u8 *aToOpen;           /* 1 for tables and indices to be opened */
123400  u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
123401  u8 chngRowid;          /* Rowid changed in a normal table */
123402  u8 chngKey;            /* Either chngPk or chngRowid */
123403  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
123404  AuthContext sContext;  /* The authorization context */
123405  NameContext sNC;       /* The name-context to resolve expressions in */
123406  int iDb;               /* Database containing the table being updated */
123407  int eOnePass;          /* ONEPASS_XXX value from where.c */
123408  int hasFK;             /* True if foreign key processing is required */
123409  int labelBreak;        /* Jump here to break out of UPDATE loop */
123410  int labelContinue;     /* Jump here to continue next step of UPDATE loop */
123411  int flags;             /* Flags for sqlite3WhereBegin() */
123412
123413#ifndef SQLITE_OMIT_TRIGGER
123414  int isView;            /* True when updating a view (INSTEAD OF trigger) */
123415  Trigger *pTrigger;     /* List of triggers on pTab, if required */
123416  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
123417#endif
123418  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
123419  int iEph = 0;          /* Ephemeral table holding all primary key values */
123420  int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
123421  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
123422  int addrOpen = 0;      /* Address of OP_OpenEphemeral */
123423  int iPk = 0;           /* First of nPk cells holding PRIMARY KEY value */
123424  i16 nPk = 0;           /* Number of components of the PRIMARY KEY */
123425  int bReplace = 0;      /* True if REPLACE conflict resolution might happen */
123426
123427  /* Register Allocations */
123428  int regRowCount = 0;   /* A count of rows changed */
123429  int regOldRowid = 0;   /* The old rowid */
123430  int regNewRowid = 0;   /* The new rowid */
123431  int regNew = 0;        /* Content of the NEW.* table in triggers */
123432  int regOld = 0;        /* Content of OLD.* table in triggers */
123433  int regRowSet = 0;     /* Rowset of rows to be updated */
123434  int regKey = 0;        /* composite PRIMARY KEY value */
123435
123436  memset(&sContext, 0, sizeof(sContext));
123437  db = pParse->db;
123438  if( pParse->nErr || db->mallocFailed ){
123439    goto update_cleanup;
123440  }
123441  assert( pTabList->nSrc==1 );
123442
123443  /* Locate the table which we want to update.
123444  */
123445  pTab = sqlite3SrcListLookup(pParse, pTabList);
123446  if( pTab==0 ) goto update_cleanup;
123447  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
123448
123449  /* Figure out if we have any triggers and if the table being
123450  ** updated is a view.
123451  */
123452#ifndef SQLITE_OMIT_TRIGGER
123453  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
123454  isView = pTab->pSelect!=0;
123455  assert( pTrigger || tmask==0 );
123456#else
123457# define pTrigger 0
123458# define isView 0
123459# define tmask 0
123460#endif
123461#ifdef SQLITE_OMIT_VIEW
123462# undef isView
123463# define isView 0
123464#endif
123465
123466  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
123467    goto update_cleanup;
123468  }
123469  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
123470    goto update_cleanup;
123471  }
123472
123473  /* Allocate a cursors for the main database table and for all indices.
123474  ** The index cursors might not be used, but if they are used they
123475  ** need to occur right after the database cursor.  So go ahead and
123476  ** allocate enough space, just in case.
123477  */
123478  pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
123479  iIdxCur = iDataCur+1;
123480  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
123481  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
123482    if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
123483      iDataCur = pParse->nTab;
123484      pTabList->a[0].iCursor = iDataCur;
123485    }
123486    pParse->nTab++;
123487  }
123488
123489  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
123490  ** Initialize aXRef[] and aToOpen[] to their default values.
123491  */
123492  aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
123493  if( aXRef==0 ) goto update_cleanup;
123494  aRegIdx = aXRef+pTab->nCol;
123495  aToOpen = (u8*)(aRegIdx+nIdx);
123496  memset(aToOpen, 1, nIdx+1);
123497  aToOpen[nIdx+1] = 0;
123498  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
123499
123500  /* Initialize the name-context */
123501  memset(&sNC, 0, sizeof(sNC));
123502  sNC.pParse = pParse;
123503  sNC.pSrcList = pTabList;
123504
123505  /* Resolve the column names in all the expressions of the
123506  ** of the UPDATE statement.  Also find the column index
123507  ** for each column to be updated in the pChanges array.  For each
123508  ** column to be updated, make sure we have authorization to change
123509  ** that column.
123510  */
123511  chngRowid = chngPk = 0;
123512  for(i=0; i<pChanges->nExpr; i++){
123513    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
123514      goto update_cleanup;
123515    }
123516    for(j=0; j<pTab->nCol; j++){
123517      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
123518        if( j==pTab->iPKey ){
123519          chngRowid = 1;
123520          pRowidExpr = pChanges->a[i].pExpr;
123521        }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
123522          chngPk = 1;
123523        }
123524        aXRef[j] = i;
123525        break;
123526      }
123527    }
123528    if( j>=pTab->nCol ){
123529      if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
123530        j = -1;
123531        chngRowid = 1;
123532        pRowidExpr = pChanges->a[i].pExpr;
123533      }else{
123534        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
123535        pParse->checkSchema = 1;
123536        goto update_cleanup;
123537      }
123538    }
123539#ifndef SQLITE_OMIT_AUTHORIZATION
123540    {
123541      int rc;
123542      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
123543                            j<0 ? "ROWID" : pTab->aCol[j].zName,
123544                            db->aDb[iDb].zDbSName);
123545      if( rc==SQLITE_DENY ){
123546        goto update_cleanup;
123547      }else if( rc==SQLITE_IGNORE ){
123548        aXRef[j] = -1;
123549      }
123550    }
123551#endif
123552  }
123553  assert( (chngRowid & chngPk)==0 );
123554  assert( chngRowid==0 || chngRowid==1 );
123555  assert( chngPk==0 || chngPk==1 );
123556  chngKey = chngRowid + chngPk;
123557
123558  /* The SET expressions are not actually used inside the WHERE loop.
123559  ** So reset the colUsed mask. Unless this is a virtual table. In that
123560  ** case, set all bits of the colUsed mask (to ensure that the virtual
123561  ** table implementation makes all columns available).
123562  */
123563  pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
123564
123565  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
123566
123567  /* There is one entry in the aRegIdx[] array for each index on the table
123568  ** being updated.  Fill in aRegIdx[] with a register number that will hold
123569  ** the key for accessing each index.
123570  **
123571  ** FIXME:  Be smarter about omitting indexes that use expressions.
123572  */
123573  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
123574    int reg;
123575    if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
123576      reg = ++pParse->nMem;
123577      pParse->nMem += pIdx->nColumn;
123578    }else{
123579      reg = 0;
123580      for(i=0; i<pIdx->nKeyCol; i++){
123581        i16 iIdxCol = pIdx->aiColumn[i];
123582        if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
123583          reg = ++pParse->nMem;
123584          pParse->nMem += pIdx->nColumn;
123585          if( (onError==OE_Replace)
123586           || (onError==OE_Default && pIdx->onError==OE_Replace)
123587          ){
123588            bReplace = 1;
123589          }
123590          break;
123591        }
123592      }
123593    }
123594    if( reg==0 ) aToOpen[j+1] = 0;
123595    aRegIdx[j] = reg;
123596  }
123597  if( bReplace ){
123598    /* If REPLACE conflict resolution might be invoked, open cursors on all
123599    ** indexes in case they are needed to delete records.  */
123600    memset(aToOpen, 1, nIdx+1);
123601  }
123602
123603  /* Begin generating code. */
123604  v = sqlite3GetVdbe(pParse);
123605  if( v==0 ) goto update_cleanup;
123606  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
123607  sqlite3BeginWriteOperation(pParse, 1, iDb);
123608
123609  /* Allocate required registers. */
123610  if( !IsVirtual(pTab) ){
123611    regRowSet = ++pParse->nMem;
123612    regOldRowid = regNewRowid = ++pParse->nMem;
123613    if( chngPk || pTrigger || hasFK ){
123614      regOld = pParse->nMem + 1;
123615      pParse->nMem += pTab->nCol;
123616    }
123617    if( chngKey || pTrigger || hasFK ){
123618      regNewRowid = ++pParse->nMem;
123619    }
123620    regNew = pParse->nMem + 1;
123621    pParse->nMem += pTab->nCol;
123622  }
123623
123624  /* Start the view context. */
123625  if( isView ){
123626    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
123627  }
123628
123629  /* If we are trying to update a view, realize that view into
123630  ** an ephemeral table.
123631  */
123632#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
123633  if( isView ){
123634    sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
123635  }
123636#endif
123637
123638  /* Resolve the column names in all the expressions in the
123639  ** WHERE clause.
123640  */
123641  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
123642    goto update_cleanup;
123643  }
123644
123645#ifndef SQLITE_OMIT_VIRTUALTABLE
123646  /* Virtual tables must be handled separately */
123647  if( IsVirtual(pTab) ){
123648    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
123649                       pWhere, onError);
123650    goto update_cleanup;
123651  }
123652#endif
123653
123654  /* Initialize the count of updated rows */
123655  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
123656    regRowCount = ++pParse->nMem;
123657    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
123658  }
123659
123660  if( HasRowid(pTab) ){
123661    sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
123662  }else{
123663    assert( pPk!=0 );
123664    nPk = pPk->nKeyCol;
123665    iPk = pParse->nMem+1;
123666    pParse->nMem += nPk;
123667    regKey = ++pParse->nMem;
123668    iEph = pParse->nTab++;
123669
123670    sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
123671    addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
123672    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
123673  }
123674
123675  /* Begin the database scan.
123676  **
123677  ** Do not consider a single-pass strategy for a multi-row update if
123678  ** there are any triggers or foreign keys to process, or rows may
123679  ** be deleted as a result of REPLACE conflict handling. Any of these
123680  ** things might disturb a cursor being used to scan through the table
123681  ** or index, causing a single-pass approach to malfunction.  */
123682  flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
123683  if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
123684    flags |= WHERE_ONEPASS_MULTIROW;
123685  }
123686  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
123687  if( pWInfo==0 ) goto update_cleanup;
123688
123689  /* A one-pass strategy that might update more than one row may not
123690  ** be used if any column of the index used for the scan is being
123691  ** updated. Otherwise, if there is an index on "b", statements like
123692  ** the following could create an infinite loop:
123693  **
123694  **   UPDATE t1 SET b=b+1 WHERE b>?
123695  **
123696  ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
123697  ** strategy that uses an index for which one or more columns are being
123698  ** updated.  */
123699  eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
123700  if( eOnePass==ONEPASS_MULTI ){
123701    int iCur = aiCurOnePass[1];
123702    if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
123703      eOnePass = ONEPASS_OFF;
123704    }
123705    assert( iCur!=iDataCur || !HasRowid(pTab) );
123706  }
123707
123708  if( HasRowid(pTab) ){
123709    /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
123710    ** mode, write the rowid into the FIFO. In either of the one-pass modes,
123711    ** leave it in register regOldRowid.  */
123712    sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
123713    if( eOnePass==ONEPASS_OFF ){
123714      sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
123715    }
123716  }else{
123717    /* Read the PK of the current row into an array of registers. In
123718    ** ONEPASS_OFF mode, serialize the array into a record and store it in
123719    ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
123720    ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
123721    ** is not required) and leave the PK fields in the array of registers.  */
123722    for(i=0; i<nPk; i++){
123723      assert( pPk->aiColumn[i]>=0 );
123724      sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
123725    }
123726    if( eOnePass ){
123727      sqlite3VdbeChangeToNoop(v, addrOpen);
123728      nKey = nPk;
123729      regKey = iPk;
123730    }else{
123731      sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
123732                        sqlite3IndexAffinityStr(db, pPk), nPk);
123733      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
123734    }
123735  }
123736
123737  if( eOnePass!=ONEPASS_MULTI ){
123738    sqlite3WhereEnd(pWInfo);
123739  }
123740
123741  labelBreak = sqlite3VdbeMakeLabel(v);
123742  if( !isView ){
123743    int addrOnce = 0;
123744
123745    /* Open every index that needs updating. */
123746    if( eOnePass!=ONEPASS_OFF ){
123747      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
123748      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
123749    }
123750
123751    if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
123752      addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
123753    }
123754    sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
123755                               0, 0);
123756    if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
123757  }
123758
123759  /* Top of the update loop */
123760  if( eOnePass!=ONEPASS_OFF ){
123761    if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
123762      assert( pPk );
123763      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
123764      VdbeCoverageNeverTaken(v);
123765    }
123766    if( eOnePass==ONEPASS_SINGLE ){
123767      labelContinue = labelBreak;
123768    }else{
123769      labelContinue = sqlite3VdbeMakeLabel(v);
123770    }
123771    sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
123772    VdbeCoverageIf(v, pPk==0);
123773    VdbeCoverageIf(v, pPk!=0);
123774  }else if( pPk ){
123775    labelContinue = sqlite3VdbeMakeLabel(v);
123776    sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
123777    addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
123778    sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
123779    VdbeCoverage(v);
123780  }else{
123781    labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
123782                             regOldRowid);
123783    VdbeCoverage(v);
123784    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
123785    VdbeCoverage(v);
123786  }
123787
123788  /* If the record number will change, set register regNewRowid to
123789  ** contain the new value. If the record number is not being modified,
123790  ** then regNewRowid is the same register as regOldRowid, which is
123791  ** already populated.  */
123792  assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
123793  if( chngRowid ){
123794    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
123795    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
123796  }
123797
123798  /* Compute the old pre-UPDATE content of the row being changed, if that
123799  ** information is needed */
123800  if( chngPk || hasFK || pTrigger ){
123801    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
123802    oldmask |= sqlite3TriggerColmask(pParse,
123803        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
123804    );
123805    for(i=0; i<pTab->nCol; i++){
123806      if( oldmask==0xffffffff
123807       || (i<32 && (oldmask & MASKBIT32(i))!=0)
123808       || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
123809      ){
123810        testcase(  oldmask!=0xffffffff && i==31 );
123811        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
123812      }else{
123813        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
123814      }
123815    }
123816    if( chngRowid==0 && pPk==0 ){
123817      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
123818    }
123819  }
123820
123821  /* Populate the array of registers beginning at regNew with the new
123822  ** row data. This array is used to check constants, create the new
123823  ** table and index records, and as the values for any new.* references
123824  ** made by triggers.
123825  **
123826  ** If there are one or more BEFORE triggers, then do not populate the
123827  ** registers associated with columns that are (a) not modified by
123828  ** this UPDATE statement and (b) not accessed by new.* references. The
123829  ** values for registers not modified by the UPDATE must be reloaded from
123830  ** the database after the BEFORE triggers are fired anyway (as the trigger
123831  ** may have modified them). So not loading those that are not going to
123832  ** be used eliminates some redundant opcodes.
123833  */
123834  newmask = sqlite3TriggerColmask(
123835      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
123836  );
123837  for(i=0; i<pTab->nCol; i++){
123838    if( i==pTab->iPKey ){
123839      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
123840    }else{
123841      j = aXRef[i];
123842      if( j>=0 ){
123843        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
123844      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
123845        /* This branch loads the value of a column that will not be changed
123846        ** into a register. This is done if there are no BEFORE triggers, or
123847        ** if there are one or more BEFORE triggers that use this value via
123848        ** a new.* reference in a trigger program.
123849        */
123850        testcase( i==31 );
123851        testcase( i==32 );
123852        sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
123853      }else{
123854        sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
123855      }
123856    }
123857  }
123858
123859  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
123860  ** verified. One could argue that this is wrong.
123861  */
123862  if( tmask&TRIGGER_BEFORE ){
123863    sqlite3TableAffinity(v, pTab, regNew);
123864    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
123865        TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
123866
123867    /* The row-trigger may have deleted the row being updated. In this
123868    ** case, jump to the next row. No updates or AFTER triggers are
123869    ** required. This behavior - what happens when the row being updated
123870    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
123871    ** documentation.
123872    */
123873    if( pPk ){
123874      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
123875      VdbeCoverage(v);
123876    }else{
123877      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
123878      VdbeCoverage(v);
123879    }
123880
123881    /* If it did not delete it, the row-trigger may still have modified
123882    ** some of the columns of the row being updated. Load the values for
123883    ** all columns not modified by the update statement into their
123884    ** registers in case this has happened.
123885    */
123886    for(i=0; i<pTab->nCol; i++){
123887      if( aXRef[i]<0 && i!=pTab->iPKey ){
123888        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
123889      }
123890    }
123891  }
123892
123893  if( !isView ){
123894    int addr1 = 0;        /* Address of jump instruction */
123895
123896    /* Do constraint checks. */
123897    assert( regOldRowid>0 );
123898    sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
123899        regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
123900        aXRef);
123901
123902    /* Do FK constraint checks. */
123903    if( hasFK ){
123904      sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
123905    }
123906
123907    /* Delete the index entries associated with the current record.  */
123908    if( bReplace || chngKey ){
123909      if( pPk ){
123910        addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
123911      }else{
123912        addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
123913      }
123914      VdbeCoverageNeverTaken(v);
123915    }
123916    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
123917
123918    /* If changing the rowid value, or if there are foreign key constraints
123919    ** to process, delete the old record. Otherwise, add a noop OP_Delete
123920    ** to invoke the pre-update hook.
123921    **
123922    ** That (regNew==regnewRowid+1) is true is also important for the
123923    ** pre-update hook. If the caller invokes preupdate_new(), the returned
123924    ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
123925    ** is the column index supplied by the user.
123926    */
123927    assert( regNew==regNewRowid+1 );
123928#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
123929    sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
123930        OPFLAG_ISUPDATE | ((hasFK || chngKey) ? 0 : OPFLAG_ISNOOP),
123931        regNewRowid
123932    );
123933    if( eOnePass==ONEPASS_MULTI ){
123934      assert( hasFK==0 && chngKey==0 );
123935      sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
123936    }
123937    if( !pParse->nested ){
123938      sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
123939    }
123940#else
123941    if( hasFK || chngKey ){
123942      sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
123943    }
123944#endif
123945    if( bReplace || chngKey ){
123946      sqlite3VdbeJumpHere(v, addr1);
123947    }
123948
123949    if( hasFK ){
123950      sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
123951    }
123952
123953    /* Insert the new index entries and the new record. */
123954    sqlite3CompleteInsertion(
123955        pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
123956        OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
123957        0, 0
123958    );
123959
123960    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
123961    ** handle rows (possibly in other tables) that refer via a foreign key
123962    ** to the row just updated. */
123963    if( hasFK ){
123964      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
123965    }
123966  }
123967
123968  /* Increment the row counter
123969  */
123970  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
123971    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
123972  }
123973
123974  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
123975      TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
123976
123977  /* Repeat the above with the next record to be updated, until
123978  ** all record selected by the WHERE clause have been updated.
123979  */
123980  if( eOnePass==ONEPASS_SINGLE ){
123981    /* Nothing to do at end-of-loop for a single-pass */
123982  }else if( eOnePass==ONEPASS_MULTI ){
123983    sqlite3VdbeResolveLabel(v, labelContinue);
123984    sqlite3WhereEnd(pWInfo);
123985  }else if( pPk ){
123986    sqlite3VdbeResolveLabel(v, labelContinue);
123987    sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
123988  }else{
123989    sqlite3VdbeGoto(v, labelContinue);
123990  }
123991  sqlite3VdbeResolveLabel(v, labelBreak);
123992
123993  /* Update the sqlite_sequence table by storing the content of the
123994  ** maximum rowid counter values recorded while inserting into
123995  ** autoincrement tables.
123996  */
123997  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
123998    sqlite3AutoincrementEnd(pParse);
123999  }
124000
124001  /*
124002  ** Return the number of rows that were changed. If this routine is
124003  ** generating code because of a call to sqlite3NestedParse(), do not
124004  ** invoke the callback function.
124005  */
124006  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
124007    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
124008    sqlite3VdbeSetNumCols(v, 1);
124009    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
124010  }
124011
124012update_cleanup:
124013  sqlite3AuthContextPop(&sContext);
124014  sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
124015  sqlite3SrcListDelete(db, pTabList);
124016  sqlite3ExprListDelete(db, pChanges);
124017  sqlite3ExprDelete(db, pWhere);
124018  return;
124019}
124020/* Make sure "isView" and other macros defined above are undefined. Otherwise
124021** they may interfere with compilation of other functions in this file
124022** (or in another file, if this file becomes part of the amalgamation).  */
124023#ifdef isView
124024 #undef isView
124025#endif
124026#ifdef pTrigger
124027 #undef pTrigger
124028#endif
124029
124030#ifndef SQLITE_OMIT_VIRTUALTABLE
124031/*
124032** Generate code for an UPDATE of a virtual table.
124033**
124034** There are two possible strategies - the default and the special
124035** "onepass" strategy. Onepass is only used if the virtual table
124036** implementation indicates that pWhere may match at most one row.
124037**
124038** The default strategy is to create an ephemeral table that contains
124039** for each row to be changed:
124040**
124041**   (A)  The original rowid of that row.
124042**   (B)  The revised rowid for the row.
124043**   (C)  The content of every column in the row.
124044**
124045** Then loop through the contents of this ephemeral table executing a
124046** VUpdate for each row. When finished, drop the ephemeral table.
124047**
124048** The "onepass" strategy does not use an ephemeral table. Instead, it
124049** stores the same values (A, B and C above) in a register array and
124050** makes a single invocation of VUpdate.
124051*/
124052static void updateVirtualTable(
124053  Parse *pParse,       /* The parsing context */
124054  SrcList *pSrc,       /* The virtual table to be modified */
124055  Table *pTab,         /* The virtual table */
124056  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
124057  Expr *pRowid,        /* Expression used to recompute the rowid */
124058  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
124059  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
124060  int onError          /* ON CONFLICT strategy */
124061){
124062  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
124063  int ephemTab;             /* Table holding the result of the SELECT */
124064  int i;                    /* Loop counter */
124065  sqlite3 *db = pParse->db; /* Database connection */
124066  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
124067  WhereInfo *pWInfo;
124068  int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
124069  int regArg;                     /* First register in VUpdate arg array */
124070  int regRec;                     /* Register in which to assemble record */
124071  int regRowid;                   /* Register for ephem table rowid */
124072  int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
124073  int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
124074  int bOnePass;                   /* True to use onepass strategy */
124075  int addr;                       /* Address of OP_OpenEphemeral */
124076
124077  /* Allocate nArg registers to martial the arguments to VUpdate. Then
124078  ** create and open the ephemeral table in which the records created from
124079  ** these arguments will be temporarily stored. */
124080  assert( v );
124081  ephemTab = pParse->nTab++;
124082  addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
124083  regArg = pParse->nMem + 1;
124084  pParse->nMem += nArg;
124085  regRec = ++pParse->nMem;
124086  regRowid = ++pParse->nMem;
124087
124088  /* Start scanning the virtual table */
124089  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
124090  if( pWInfo==0 ) return;
124091
124092  /* Populate the argument registers. */
124093  sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
124094  if( pRowid ){
124095    sqlite3ExprCode(pParse, pRowid, regArg+1);
124096  }else{
124097    sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
124098  }
124099  for(i=0; i<pTab->nCol; i++){
124100    if( aXRef[i]>=0 ){
124101      sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
124102    }else{
124103      sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
124104    }
124105  }
124106
124107  bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
124108
124109  if( bOnePass ){
124110    /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
124111    ** above. Also, if this is a top-level parse (not a trigger), clear the
124112    ** multi-write flag so that the VM does not open a statement journal */
124113    sqlite3VdbeChangeToNoop(v, addr);
124114    if( sqlite3IsToplevel(pParse) ){
124115      pParse->isMultiWrite = 0;
124116    }
124117  }else{
124118    /* Create a record from the argument register contents and insert it into
124119    ** the ephemeral table. */
124120    sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
124121    sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
124122    sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
124123  }
124124
124125
124126  if( bOnePass==0 ){
124127    /* End the virtual table scan */
124128    sqlite3WhereEnd(pWInfo);
124129
124130    /* Begin scannning through the ephemeral table. */
124131    addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
124132
124133    /* Extract arguments from the current row of the ephemeral table and
124134    ** invoke the VUpdate method.  */
124135    for(i=0; i<nArg; i++){
124136      sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
124137    }
124138  }
124139  sqlite3VtabMakeWritable(pParse, pTab);
124140  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
124141  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
124142  sqlite3MayAbort(pParse);
124143
124144  /* End of the ephemeral table scan. Or, if using the onepass strategy,
124145  ** jump to here if the scan visited zero rows. */
124146  if( bOnePass==0 ){
124147    sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
124148    sqlite3VdbeJumpHere(v, addr);
124149    sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
124150  }else{
124151    sqlite3WhereEnd(pWInfo);
124152  }
124153}
124154#endif /* SQLITE_OMIT_VIRTUALTABLE */
124155
124156/************** End of update.c **********************************************/
124157/************** Begin file vacuum.c ******************************************/
124158/*
124159** 2003 April 6
124160**
124161** The author disclaims copyright to this source code.  In place of
124162** a legal notice, here is a blessing:
124163**
124164**    May you do good and not evil.
124165**    May you find forgiveness for yourself and forgive others.
124166**    May you share freely, never taking more than you give.
124167**
124168*************************************************************************
124169** This file contains code used to implement the VACUUM command.
124170**
124171** Most of the code in this file may be omitted by defining the
124172** SQLITE_OMIT_VACUUM macro.
124173*/
124174/* #include "sqliteInt.h" */
124175/* #include "vdbeInt.h" */
124176
124177#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
124178
124179/*
124180** Execute zSql on database db.
124181**
124182** If zSql returns rows, then each row will have exactly one
124183** column.  (This will only happen if zSql begins with "SELECT".)
124184** Take each row of result and call execSql() again recursively.
124185**
124186** The execSqlF() routine does the same thing, except it accepts
124187** a format string as its third argument
124188*/
124189static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
124190  sqlite3_stmt *pStmt;
124191  int rc;
124192
124193  /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
124194  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
124195  if( rc!=SQLITE_OK ) return rc;
124196  while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
124197    const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
124198    assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
124199    if( zSubSql ){
124200      assert( zSubSql[0]!='S' );
124201      rc = execSql(db, pzErrMsg, zSubSql);
124202      if( rc!=SQLITE_OK ) break;
124203    }
124204  }
124205  assert( rc!=SQLITE_ROW );
124206  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
124207  if( rc ){
124208    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
124209  }
124210  (void)sqlite3_finalize(pStmt);
124211  return rc;
124212}
124213static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
124214  char *z;
124215  va_list ap;
124216  int rc;
124217  va_start(ap, zSql);
124218  z = sqlite3VMPrintf(db, zSql, ap);
124219  va_end(ap);
124220  if( z==0 ) return SQLITE_NOMEM;
124221  rc = execSql(db, pzErrMsg, z);
124222  sqlite3DbFree(db, z);
124223  return rc;
124224}
124225
124226/*
124227** The VACUUM command is used to clean up the database,
124228** collapse free space, etc.  It is modelled after the VACUUM command
124229** in PostgreSQL.  The VACUUM command works as follows:
124230**
124231**   (1)  Create a new transient database file
124232**   (2)  Copy all content from the database being vacuumed into
124233**        the new transient database file
124234**   (3)  Copy content from the transient database back into the
124235**        original database.
124236**
124237** The transient database requires temporary disk space approximately
124238** equal to the size of the original database.  The copy operation of
124239** step (3) requires additional temporary disk space approximately equal
124240** to the size of the original database for the rollback journal.
124241** Hence, temporary disk space that is approximately 2x the size of the
124242** original database is required.  Every page of the database is written
124243** approximately 3 times:  Once for step (2) and twice for step (3).
124244** Two writes per page are required in step (3) because the original
124245** database content must be written into the rollback journal prior to
124246** overwriting the database with the vacuumed content.
124247**
124248** Only 1x temporary space and only 1x writes would be required if
124249** the copy of step (3) were replaced by deleting the original database
124250** and renaming the transient database as the original.  But that will
124251** not work if other processes are attached to the original database.
124252** And a power loss in between deleting the original and renaming the
124253** transient would cause the database file to appear to be deleted
124254** following reboot.
124255*/
124256SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm){
124257  Vdbe *v = sqlite3GetVdbe(pParse);
124258  int iDb = 0;
124259  if( v==0 ) return;
124260  if( pNm ){
124261#ifndef SQLITE_BUG_COMPATIBLE_20160819
124262    /* Default behavior:  Report an error if the argument to VACUUM is
124263    ** not recognized */
124264    iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
124265    if( iDb<0 ) return;
124266#else
124267    /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
124268    ** to VACUUM are silently ignored.  This is a back-out of a bug fix that
124269    ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
124270    ** The buggy behavior is required for binary compatibility with some
124271    ** legacy applications. */
124272    iDb = sqlite3FindDb(pParse->db, pNm);
124273    if( iDb<0 ) iDb = 0;
124274#endif
124275  }
124276  if( iDb!=1 ){
124277    sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
124278    sqlite3VdbeUsesBtree(v, iDb);
124279  }
124280  return;
124281}
124282
124283/*
124284** This routine implements the OP_Vacuum opcode of the VDBE.
124285*/
124286SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
124287  int rc = SQLITE_OK;     /* Return code from service routines */
124288  Btree *pMain;           /* The database being vacuumed */
124289  Btree *pTemp;           /* The temporary database we vacuum into */
124290  int saved_flags;        /* Saved value of the db->flags */
124291  int saved_nChange;      /* Saved value of db->nChange */
124292  int saved_nTotalChange; /* Saved value of db->nTotalChange */
124293  u8 saved_mTrace;        /* Saved trace settings */
124294  Db *pDb = 0;            /* Database to detach at end of vacuum */
124295  int isMemDb;            /* True if vacuuming a :memory: database */
124296  int nRes;               /* Bytes of reserved space at the end of each page */
124297  int nDb;                /* Number of attached databases */
124298  const char *zDbMain;    /* Schema name of database to vacuum */
124299
124300  if( !db->autoCommit ){
124301    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
124302    return SQLITE_ERROR;
124303  }
124304  if( db->nVdbeActive>1 ){
124305    sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
124306    return SQLITE_ERROR;
124307  }
124308
124309  /* Save the current value of the database flags so that it can be
124310  ** restored before returning. Then set the writable-schema flag, and
124311  ** disable CHECK and foreign key constraints.  */
124312  saved_flags = db->flags;
124313  saved_nChange = db->nChange;
124314  saved_nTotalChange = db->nTotalChange;
124315  saved_mTrace = db->mTrace;
124316  db->flags |= (SQLITE_WriteSchema | SQLITE_IgnoreChecks
124317                 | SQLITE_PreferBuiltin | SQLITE_Vacuum);
124318  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows);
124319  db->mTrace = 0;
124320
124321  zDbMain = db->aDb[iDb].zDbSName;
124322  pMain = db->aDb[iDb].pBt;
124323  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
124324
124325  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
124326  ** can be set to 'off' for this file, as it is not recovered if a crash
124327  ** occurs anyway. The integrity of the database is maintained by a
124328  ** (possibly synchronous) transaction opened on the main database before
124329  ** sqlite3BtreeCopyFile() is called.
124330  **
124331  ** An optimisation would be to use a non-journaled pager.
124332  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
124333  ** that actually made the VACUUM run slower.  Very little journalling
124334  ** actually occurs when doing a vacuum since the vacuum_db is initially
124335  ** empty.  Only the journal header is written.  Apparently it takes more
124336  ** time to parse and run the PRAGMA to turn journalling off than it does
124337  ** to write the journal header file.
124338  */
124339  nDb = db->nDb;
124340  rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
124341  if( rc!=SQLITE_OK ) goto end_of_vacuum;
124342  assert( (db->nDb-1)==nDb );
124343  pDb = &db->aDb[nDb];
124344  assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
124345  pTemp = pDb->pBt;
124346
124347  /* The call to execSql() to attach the temp database has left the file
124348  ** locked (as there was more than one active statement when the transaction
124349  ** to read the schema was concluded. Unlock it here so that this doesn't
124350  ** cause problems for the call to BtreeSetPageSize() below.  */
124351  sqlite3BtreeCommit(pTemp);
124352
124353  nRes = sqlite3BtreeGetOptimalReserve(pMain);
124354
124355  /* A VACUUM cannot change the pagesize of an encrypted database. */
124356#ifdef SQLITE_HAS_CODEC
124357  if( db->nextPagesize ){
124358    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
124359    int nKey;
124360    char *zKey;
124361    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
124362    if( nKey ) db->nextPagesize = 0;
124363  }
124364#endif
124365
124366  sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
124367  sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
124368  sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
124369
124370  /* Begin a transaction and take an exclusive lock on the main database
124371  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
124372  ** to ensure that we do not try to change the page-size on a WAL database.
124373  */
124374  rc = execSql(db, pzErrMsg, "BEGIN");
124375  if( rc!=SQLITE_OK ) goto end_of_vacuum;
124376  rc = sqlite3BtreeBeginTrans(pMain, 2);
124377  if( rc!=SQLITE_OK ) goto end_of_vacuum;
124378
124379  /* Do not attempt to change the page size for a WAL database */
124380  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
124381                                               ==PAGER_JOURNALMODE_WAL ){
124382    db->nextPagesize = 0;
124383  }
124384
124385  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
124386   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
124387   || NEVER(db->mallocFailed)
124388  ){
124389    rc = SQLITE_NOMEM_BKPT;
124390    goto end_of_vacuum;
124391  }
124392
124393#ifndef SQLITE_OMIT_AUTOVACUUM
124394  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
124395                                           sqlite3BtreeGetAutoVacuum(pMain));
124396#endif
124397
124398  /* Query the schema of the main database. Create a mirror schema
124399  ** in the temporary database.
124400  */
124401  db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
124402  rc = execSqlF(db, pzErrMsg,
124403      "SELECT sql FROM \"%w\".sqlite_master"
124404      " WHERE type='table'AND name<>'sqlite_sequence'"
124405      " AND coalesce(rootpage,1)>0",
124406      zDbMain
124407  );
124408  if( rc!=SQLITE_OK ) goto end_of_vacuum;
124409  rc = execSqlF(db, pzErrMsg,
124410      "SELECT sql FROM \"%w\".sqlite_master"
124411      " WHERE type='index' AND length(sql)>10",
124412      zDbMain
124413  );
124414  if( rc!=SQLITE_OK ) goto end_of_vacuum;
124415  db->init.iDb = 0;
124416
124417  /* Loop through the tables in the main database. For each, do
124418  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
124419  ** the contents to the temporary database.
124420  */
124421  rc = execSqlF(db, pzErrMsg,
124422      "SELECT'INSERT INTO vacuum_db.'||quote(name)"
124423      "||' SELECT*FROM\"%w\".'||quote(name)"
124424      "FROM vacuum_db.sqlite_master "
124425      "WHERE type='table'AND coalesce(rootpage,1)>0",
124426      zDbMain
124427  );
124428  assert( (db->flags & SQLITE_Vacuum)!=0 );
124429  db->flags &= ~SQLITE_Vacuum;
124430  if( rc!=SQLITE_OK ) goto end_of_vacuum;
124431
124432  /* Copy the triggers, views, and virtual tables from the main database
124433  ** over to the temporary database.  None of these objects has any
124434  ** associated storage, so all we have to do is copy their entries
124435  ** from the SQLITE_MASTER table.
124436  */
124437  rc = execSqlF(db, pzErrMsg,
124438      "INSERT INTO vacuum_db.sqlite_master"
124439      " SELECT*FROM \"%w\".sqlite_master"
124440      " WHERE type IN('view','trigger')"
124441      " OR(type='table'AND rootpage=0)",
124442      zDbMain
124443  );
124444  if( rc ) goto end_of_vacuum;
124445
124446  /* At this point, there is a write transaction open on both the
124447  ** vacuum database and the main database. Assuming no error occurs,
124448  ** both transactions are closed by this block - the main database
124449  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
124450  ** call to sqlite3BtreeCommit().
124451  */
124452  {
124453    u32 meta;
124454    int i;
124455
124456    /* This array determines which meta meta values are preserved in the
124457    ** vacuum.  Even entries are the meta value number and odd entries
124458    ** are an increment to apply to the meta value after the vacuum.
124459    ** The increment is used to increase the schema cookie so that other
124460    ** connections to the same database will know to reread the schema.
124461    */
124462    static const unsigned char aCopy[] = {
124463       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
124464       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
124465       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
124466       BTREE_USER_VERSION,       0,  /* Preserve the user version */
124467       BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
124468    };
124469
124470    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
124471    assert( 1==sqlite3BtreeIsInTrans(pMain) );
124472
124473    /* Copy Btree meta values */
124474    for(i=0; i<ArraySize(aCopy); i+=2){
124475      /* GetMeta() and UpdateMeta() cannot fail in this context because
124476      ** we already have page 1 loaded into cache and marked dirty. */
124477      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
124478      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
124479      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
124480    }
124481
124482    rc = sqlite3BtreeCopyFile(pMain, pTemp);
124483    if( rc!=SQLITE_OK ) goto end_of_vacuum;
124484    rc = sqlite3BtreeCommit(pTemp);
124485    if( rc!=SQLITE_OK ) goto end_of_vacuum;
124486#ifndef SQLITE_OMIT_AUTOVACUUM
124487    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
124488#endif
124489  }
124490
124491  assert( rc==SQLITE_OK );
124492  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
124493
124494end_of_vacuum:
124495  /* Restore the original value of db->flags */
124496  db->init.iDb = 0;
124497  db->flags = saved_flags;
124498  db->nChange = saved_nChange;
124499  db->nTotalChange = saved_nTotalChange;
124500  db->mTrace = saved_mTrace;
124501  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
124502
124503  /* Currently there is an SQL level transaction open on the vacuum
124504  ** database. No locks are held on any other files (since the main file
124505  ** was committed at the btree level). So it safe to end the transaction
124506  ** by manually setting the autoCommit flag to true and detaching the
124507  ** vacuum database. The vacuum_db journal file is deleted when the pager
124508  ** is closed by the DETACH.
124509  */
124510  db->autoCommit = 1;
124511
124512  if( pDb ){
124513    sqlite3BtreeClose(pDb->pBt);
124514    pDb->pBt = 0;
124515    pDb->pSchema = 0;
124516  }
124517
124518  /* This both clears the schemas and reduces the size of the db->aDb[]
124519  ** array. */
124520  sqlite3ResetAllSchemasOfConnection(db);
124521
124522  return rc;
124523}
124524
124525#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
124526
124527/************** End of vacuum.c **********************************************/
124528/************** Begin file vtab.c ********************************************/
124529/*
124530** 2006 June 10
124531**
124532** The author disclaims copyright to this source code.  In place of
124533** a legal notice, here is a blessing:
124534**
124535**    May you do good and not evil.
124536**    May you find forgiveness for yourself and forgive others.
124537**    May you share freely, never taking more than you give.
124538**
124539*************************************************************************
124540** This file contains code used to help implement virtual tables.
124541*/
124542#ifndef SQLITE_OMIT_VIRTUALTABLE
124543/* #include "sqliteInt.h" */
124544
124545/*
124546** Before a virtual table xCreate() or xConnect() method is invoked, the
124547** sqlite3.pVtabCtx member variable is set to point to an instance of
124548** this struct allocated on the stack. It is used by the implementation of
124549** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
124550** are invoked only from within xCreate and xConnect methods.
124551*/
124552struct VtabCtx {
124553  VTable *pVTable;    /* The virtual table being constructed */
124554  Table *pTab;        /* The Table object to which the virtual table belongs */
124555  VtabCtx *pPrior;    /* Parent context (if any) */
124556  int bDeclared;      /* True after sqlite3_declare_vtab() is called */
124557};
124558
124559/*
124560** Construct and install a Module object for a virtual table.  When this
124561** routine is called, it is guaranteed that all appropriate locks are held
124562** and the module is not already part of the connection.
124563*/
124564SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
124565  sqlite3 *db,                    /* Database in which module is registered */
124566  const char *zName,              /* Name assigned to this module */
124567  const sqlite3_module *pModule,  /* The definition of the module */
124568  void *pAux,                     /* Context pointer for xCreate/xConnect */
124569  void (*xDestroy)(void *)        /* Module destructor function */
124570){
124571  Module *pMod;
124572  int nName = sqlite3Strlen30(zName);
124573  pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1);
124574  if( pMod ){
124575    Module *pDel;
124576    char *zCopy = (char *)(&pMod[1]);
124577    memcpy(zCopy, zName, nName+1);
124578    pMod->zName = zCopy;
124579    pMod->pModule = pModule;
124580    pMod->pAux = pAux;
124581    pMod->xDestroy = xDestroy;
124582    pMod->pEpoTab = 0;
124583    pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
124584    assert( pDel==0 || pDel==pMod );
124585    if( pDel ){
124586      sqlite3OomFault(db);
124587      sqlite3DbFree(db, pDel);
124588      pMod = 0;
124589    }
124590  }
124591  return pMod;
124592}
124593
124594/*
124595** The actual function that does the work of creating a new module.
124596** This function implements the sqlite3_create_module() and
124597** sqlite3_create_module_v2() interfaces.
124598*/
124599static int createModule(
124600  sqlite3 *db,                    /* Database in which module is registered */
124601  const char *zName,              /* Name assigned to this module */
124602  const sqlite3_module *pModule,  /* The definition of the module */
124603  void *pAux,                     /* Context pointer for xCreate/xConnect */
124604  void (*xDestroy)(void *)        /* Module destructor function */
124605){
124606  int rc = SQLITE_OK;
124607
124608  sqlite3_mutex_enter(db->mutex);
124609  if( sqlite3HashFind(&db->aModule, zName) ){
124610    rc = SQLITE_MISUSE_BKPT;
124611  }else{
124612    (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
124613  }
124614  rc = sqlite3ApiExit(db, rc);
124615  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
124616  sqlite3_mutex_leave(db->mutex);
124617  return rc;
124618}
124619
124620
124621/*
124622** External API function used to create a new virtual-table module.
124623*/
124624SQLITE_API int sqlite3_create_module(
124625  sqlite3 *db,                    /* Database in which module is registered */
124626  const char *zName,              /* Name assigned to this module */
124627  const sqlite3_module *pModule,  /* The definition of the module */
124628  void *pAux                      /* Context pointer for xCreate/xConnect */
124629){
124630#ifdef SQLITE_ENABLE_API_ARMOR
124631  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
124632#endif
124633  return createModule(db, zName, pModule, pAux, 0);
124634}
124635
124636/*
124637** External API function used to create a new virtual-table module.
124638*/
124639SQLITE_API int sqlite3_create_module_v2(
124640  sqlite3 *db,                    /* Database in which module is registered */
124641  const char *zName,              /* Name assigned to this module */
124642  const sqlite3_module *pModule,  /* The definition of the module */
124643  void *pAux,                     /* Context pointer for xCreate/xConnect */
124644  void (*xDestroy)(void *)        /* Module destructor function */
124645){
124646#ifdef SQLITE_ENABLE_API_ARMOR
124647  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
124648#endif
124649  return createModule(db, zName, pModule, pAux, xDestroy);
124650}
124651
124652/*
124653** Lock the virtual table so that it cannot be disconnected.
124654** Locks nest.  Every lock should have a corresponding unlock.
124655** If an unlock is omitted, resources leaks will occur.
124656**
124657** If a disconnect is attempted while a virtual table is locked,
124658** the disconnect is deferred until all locks have been removed.
124659*/
124660SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
124661  pVTab->nRef++;
124662}
124663
124664
124665/*
124666** pTab is a pointer to a Table structure representing a virtual-table.
124667** Return a pointer to the VTable object used by connection db to access
124668** this virtual-table, if one has been created, or NULL otherwise.
124669*/
124670SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
124671  VTable *pVtab;
124672  assert( IsVirtual(pTab) );
124673  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
124674  return pVtab;
124675}
124676
124677/*
124678** Decrement the ref-count on a virtual table object. When the ref-count
124679** reaches zero, call the xDisconnect() method to delete the object.
124680*/
124681SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
124682  sqlite3 *db = pVTab->db;
124683
124684  assert( db );
124685  assert( pVTab->nRef>0 );
124686  assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
124687
124688  pVTab->nRef--;
124689  if( pVTab->nRef==0 ){
124690    sqlite3_vtab *p = pVTab->pVtab;
124691    if( p ){
124692      p->pModule->xDisconnect(p);
124693    }
124694    sqlite3DbFree(db, pVTab);
124695  }
124696}
124697
124698/*
124699** Table p is a virtual table. This function moves all elements in the
124700** p->pVTable list to the sqlite3.pDisconnect lists of their associated
124701** database connections to be disconnected at the next opportunity.
124702** Except, if argument db is not NULL, then the entry associated with
124703** connection db is left in the p->pVTable list.
124704*/
124705static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
124706  VTable *pRet = 0;
124707  VTable *pVTable = p->pVTable;
124708  p->pVTable = 0;
124709
124710  /* Assert that the mutex (if any) associated with the BtShared database
124711  ** that contains table p is held by the caller. See header comments
124712  ** above function sqlite3VtabUnlockList() for an explanation of why
124713  ** this makes it safe to access the sqlite3.pDisconnect list of any
124714  ** database connection that may have an entry in the p->pVTable list.
124715  */
124716  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
124717
124718  while( pVTable ){
124719    sqlite3 *db2 = pVTable->db;
124720    VTable *pNext = pVTable->pNext;
124721    assert( db2 );
124722    if( db2==db ){
124723      pRet = pVTable;
124724      p->pVTable = pRet;
124725      pRet->pNext = 0;
124726    }else{
124727      pVTable->pNext = db2->pDisconnect;
124728      db2->pDisconnect = pVTable;
124729    }
124730    pVTable = pNext;
124731  }
124732
124733  assert( !db || pRet );
124734  return pRet;
124735}
124736
124737/*
124738** Table *p is a virtual table. This function removes the VTable object
124739** for table *p associated with database connection db from the linked
124740** list in p->pVTab. It also decrements the VTable ref count. This is
124741** used when closing database connection db to free all of its VTable
124742** objects without disturbing the rest of the Schema object (which may
124743** be being used by other shared-cache connections).
124744*/
124745SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
124746  VTable **ppVTab;
124747
124748  assert( IsVirtual(p) );
124749  assert( sqlite3BtreeHoldsAllMutexes(db) );
124750  assert( sqlite3_mutex_held(db->mutex) );
124751
124752  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
124753    if( (*ppVTab)->db==db  ){
124754      VTable *pVTab = *ppVTab;
124755      *ppVTab = pVTab->pNext;
124756      sqlite3VtabUnlock(pVTab);
124757      break;
124758    }
124759  }
124760}
124761
124762
124763/*
124764** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
124765**
124766** This function may only be called when the mutexes associated with all
124767** shared b-tree databases opened using connection db are held by the
124768** caller. This is done to protect the sqlite3.pDisconnect list. The
124769** sqlite3.pDisconnect list is accessed only as follows:
124770**
124771**   1) By this function. In this case, all BtShared mutexes and the mutex
124772**      associated with the database handle itself must be held.
124773**
124774**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
124775**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
124776**      associated with the database the virtual table is stored in is held
124777**      or, if the virtual table is stored in a non-sharable database, then
124778**      the database handle mutex is held.
124779**
124780** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
124781** by multiple threads. It is thread-safe.
124782*/
124783SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
124784  VTable *p = db->pDisconnect;
124785  db->pDisconnect = 0;
124786
124787  assert( sqlite3BtreeHoldsAllMutexes(db) );
124788  assert( sqlite3_mutex_held(db->mutex) );
124789
124790  if( p ){
124791    sqlite3ExpirePreparedStatements(db);
124792    do {
124793      VTable *pNext = p->pNext;
124794      sqlite3VtabUnlock(p);
124795      p = pNext;
124796    }while( p );
124797  }
124798}
124799
124800/*
124801** Clear any and all virtual-table information from the Table record.
124802** This routine is called, for example, just before deleting the Table
124803** record.
124804**
124805** Since it is a virtual-table, the Table structure contains a pointer
124806** to the head of a linked list of VTable structures. Each VTable
124807** structure is associated with a single sqlite3* user of the schema.
124808** The reference count of the VTable structure associated with database
124809** connection db is decremented immediately (which may lead to the
124810** structure being xDisconnected and free). Any other VTable structures
124811** in the list are moved to the sqlite3.pDisconnect list of the associated
124812** database connection.
124813*/
124814SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
124815  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
124816  if( p->azModuleArg ){
124817    int i;
124818    for(i=0; i<p->nModuleArg; i++){
124819      if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
124820    }
124821    sqlite3DbFree(db, p->azModuleArg);
124822  }
124823}
124824
124825/*
124826** Add a new module argument to pTable->azModuleArg[].
124827** The string is not copied - the pointer is stored.  The
124828** string will be freed automatically when the table is
124829** deleted.
124830*/
124831static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
124832  int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
124833  char **azModuleArg;
124834  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
124835  if( azModuleArg==0 ){
124836    sqlite3DbFree(db, zArg);
124837  }else{
124838    int i = pTable->nModuleArg++;
124839    azModuleArg[i] = zArg;
124840    azModuleArg[i+1] = 0;
124841    pTable->azModuleArg = azModuleArg;
124842  }
124843}
124844
124845/*
124846** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
124847** statement.  The module name has been parsed, but the optional list
124848** of parameters that follow the module name are still pending.
124849*/
124850SQLITE_PRIVATE void sqlite3VtabBeginParse(
124851  Parse *pParse,        /* Parsing context */
124852  Token *pName1,        /* Name of new table, or database name */
124853  Token *pName2,        /* Name of new table or NULL */
124854  Token *pModuleName,   /* Name of the module for the virtual table */
124855  int ifNotExists       /* No error if the table already exists */
124856){
124857  int iDb;              /* The database the table is being created in */
124858  Table *pTable;        /* The new virtual table */
124859  sqlite3 *db;          /* Database connection */
124860
124861  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
124862  pTable = pParse->pNewTable;
124863  if( pTable==0 ) return;
124864  assert( 0==pTable->pIndex );
124865
124866  db = pParse->db;
124867  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
124868  assert( iDb>=0 );
124869
124870  assert( pTable->nModuleArg==0 );
124871  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
124872  addModuleArgument(db, pTable, 0);
124873  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
124874  assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
124875       || (pParse->sNameToken.z==pName1->z && pName2->z==0)
124876  );
124877  pParse->sNameToken.n = (int)(
124878      &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
124879  );
124880
124881#ifndef SQLITE_OMIT_AUTHORIZATION
124882  /* Creating a virtual table invokes the authorization callback twice.
124883  ** The first invocation, to obtain permission to INSERT a row into the
124884  ** sqlite_master table, has already been made by sqlite3StartTable().
124885  ** The second call, to obtain permission to create the table, is made now.
124886  */
124887  if( pTable->azModuleArg ){
124888    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
124889            pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
124890  }
124891#endif
124892}
124893
124894/*
124895** This routine takes the module argument that has been accumulating
124896** in pParse->zArg[] and appends it to the list of arguments on the
124897** virtual table currently under construction in pParse->pTable.
124898*/
124899static void addArgumentToVtab(Parse *pParse){
124900  if( pParse->sArg.z && pParse->pNewTable ){
124901    const char *z = (const char*)pParse->sArg.z;
124902    int n = pParse->sArg.n;
124903    sqlite3 *db = pParse->db;
124904    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
124905  }
124906}
124907
124908/*
124909** The parser calls this routine after the CREATE VIRTUAL TABLE statement
124910** has been completely parsed.
124911*/
124912SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
124913  Table *pTab = pParse->pNewTable;  /* The table being constructed */
124914  sqlite3 *db = pParse->db;         /* The database connection */
124915
124916  if( pTab==0 ) return;
124917  addArgumentToVtab(pParse);
124918  pParse->sArg.z = 0;
124919  if( pTab->nModuleArg<1 ) return;
124920
124921  /* If the CREATE VIRTUAL TABLE statement is being entered for the
124922  ** first time (in other words if the virtual table is actually being
124923  ** created now instead of just being read out of sqlite_master) then
124924  ** do additional initialization work and store the statement text
124925  ** in the sqlite_master table.
124926  */
124927  if( !db->init.busy ){
124928    char *zStmt;
124929    char *zWhere;
124930    int iDb;
124931    int iReg;
124932    Vdbe *v;
124933
124934    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
124935    if( pEnd ){
124936      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
124937    }
124938    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
124939
124940    /* A slot for the record has already been allocated in the
124941    ** SQLITE_MASTER table.  We just need to update that slot with all
124942    ** the information we've collected.
124943    **
124944    ** The VM register number pParse->regRowid holds the rowid of an
124945    ** entry in the sqlite_master table tht was created for this vtab
124946    ** by sqlite3StartTable().
124947    */
124948    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
124949    sqlite3NestedParse(pParse,
124950      "UPDATE %Q.%s "
124951         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
124952       "WHERE rowid=#%d",
124953      db->aDb[iDb].zDbSName, MASTER_NAME,
124954      pTab->zName,
124955      pTab->zName,
124956      zStmt,
124957      pParse->regRowid
124958    );
124959    sqlite3DbFree(db, zStmt);
124960    v = sqlite3GetVdbe(pParse);
124961    sqlite3ChangeCookie(pParse, iDb);
124962
124963    sqlite3VdbeAddOp0(v, OP_Expire);
124964    zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
124965    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
124966
124967    iReg = ++pParse->nMem;
124968    sqlite3VdbeLoadString(v, iReg, pTab->zName);
124969    sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
124970  }
124971
124972  /* If we are rereading the sqlite_master table create the in-memory
124973  ** record of the table. The xConnect() method is not called until
124974  ** the first time the virtual table is used in an SQL statement. This
124975  ** allows a schema that contains virtual tables to be loaded before
124976  ** the required virtual table implementations are registered.  */
124977  else {
124978    Table *pOld;
124979    Schema *pSchema = pTab->pSchema;
124980    const char *zName = pTab->zName;
124981    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
124982    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
124983    if( pOld ){
124984      sqlite3OomFault(db);
124985      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
124986      return;
124987    }
124988    pParse->pNewTable = 0;
124989  }
124990}
124991
124992/*
124993** The parser calls this routine when it sees the first token
124994** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
124995*/
124996SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
124997  addArgumentToVtab(pParse);
124998  pParse->sArg.z = 0;
124999  pParse->sArg.n = 0;
125000}
125001
125002/*
125003** The parser calls this routine for each token after the first token
125004** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
125005*/
125006SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
125007  Token *pArg = &pParse->sArg;
125008  if( pArg->z==0 ){
125009    pArg->z = p->z;
125010    pArg->n = p->n;
125011  }else{
125012    assert(pArg->z <= p->z);
125013    pArg->n = (int)(&p->z[p->n] - pArg->z);
125014  }
125015}
125016
125017/*
125018** Invoke a virtual table constructor (either xCreate or xConnect). The
125019** pointer to the function to invoke is passed as the fourth parameter
125020** to this procedure.
125021*/
125022static int vtabCallConstructor(
125023  sqlite3 *db,
125024  Table *pTab,
125025  Module *pMod,
125026  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
125027  char **pzErr
125028){
125029  VtabCtx sCtx;
125030  VTable *pVTable;
125031  int rc;
125032  const char *const*azArg = (const char *const*)pTab->azModuleArg;
125033  int nArg = pTab->nModuleArg;
125034  char *zErr = 0;
125035  char *zModuleName;
125036  int iDb;
125037  VtabCtx *pCtx;
125038
125039  /* Check that the virtual-table is not already being initialized */
125040  for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
125041    if( pCtx->pTab==pTab ){
125042      *pzErr = sqlite3MPrintf(db,
125043          "vtable constructor called recursively: %s", pTab->zName
125044      );
125045      return SQLITE_LOCKED;
125046    }
125047  }
125048
125049  zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
125050  if( !zModuleName ){
125051    return SQLITE_NOMEM_BKPT;
125052  }
125053
125054  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
125055  if( !pVTable ){
125056    sqlite3DbFree(db, zModuleName);
125057    return SQLITE_NOMEM_BKPT;
125058  }
125059  pVTable->db = db;
125060  pVTable->pMod = pMod;
125061
125062  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
125063  pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
125064
125065  /* Invoke the virtual table constructor */
125066  assert( &db->pVtabCtx );
125067  assert( xConstruct );
125068  sCtx.pTab = pTab;
125069  sCtx.pVTable = pVTable;
125070  sCtx.pPrior = db->pVtabCtx;
125071  sCtx.bDeclared = 0;
125072  db->pVtabCtx = &sCtx;
125073  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
125074  db->pVtabCtx = sCtx.pPrior;
125075  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
125076  assert( sCtx.pTab==pTab );
125077
125078  if( SQLITE_OK!=rc ){
125079    if( zErr==0 ){
125080      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
125081    }else {
125082      *pzErr = sqlite3MPrintf(db, "%s", zErr);
125083      sqlite3_free(zErr);
125084    }
125085    sqlite3DbFree(db, pVTable);
125086  }else if( ALWAYS(pVTable->pVtab) ){
125087    /* Justification of ALWAYS():  A correct vtab constructor must allocate
125088    ** the sqlite3_vtab object if successful.  */
125089    memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
125090    pVTable->pVtab->pModule = pMod->pModule;
125091    pVTable->nRef = 1;
125092    if( sCtx.bDeclared==0 ){
125093      const char *zFormat = "vtable constructor did not declare schema: %s";
125094      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
125095      sqlite3VtabUnlock(pVTable);
125096      rc = SQLITE_ERROR;
125097    }else{
125098      int iCol;
125099      u8 oooHidden = 0;
125100      /* If everything went according to plan, link the new VTable structure
125101      ** into the linked list headed by pTab->pVTable. Then loop through the
125102      ** columns of the table to see if any of them contain the token "hidden".
125103      ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
125104      ** the type string.  */
125105      pVTable->pNext = pTab->pVTable;
125106      pTab->pVTable = pVTable;
125107
125108      for(iCol=0; iCol<pTab->nCol; iCol++){
125109        char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
125110        int nType;
125111        int i = 0;
125112        nType = sqlite3Strlen30(zType);
125113        for(i=0; i<nType; i++){
125114          if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
125115           && (i==0 || zType[i-1]==' ')
125116           && (zType[i+6]=='\0' || zType[i+6]==' ')
125117          ){
125118            break;
125119          }
125120        }
125121        if( i<nType ){
125122          int j;
125123          int nDel = 6 + (zType[i+6] ? 1 : 0);
125124          for(j=i; (j+nDel)<=nType; j++){
125125            zType[j] = zType[j+nDel];
125126          }
125127          if( zType[i]=='\0' && i>0 ){
125128            assert(zType[i-1]==' ');
125129            zType[i-1] = '\0';
125130          }
125131          pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
125132          oooHidden = TF_OOOHidden;
125133        }else{
125134          pTab->tabFlags |= oooHidden;
125135        }
125136      }
125137    }
125138  }
125139
125140  sqlite3DbFree(db, zModuleName);
125141  return rc;
125142}
125143
125144/*
125145** This function is invoked by the parser to call the xConnect() method
125146** of the virtual table pTab. If an error occurs, an error code is returned
125147** and an error left in pParse.
125148**
125149** This call is a no-op if table pTab is not a virtual table.
125150*/
125151SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
125152  sqlite3 *db = pParse->db;
125153  const char *zMod;
125154  Module *pMod;
125155  int rc;
125156
125157  assert( pTab );
125158  if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
125159    return SQLITE_OK;
125160  }
125161
125162  /* Locate the required virtual table module */
125163  zMod = pTab->azModuleArg[0];
125164  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
125165
125166  if( !pMod ){
125167    const char *zModule = pTab->azModuleArg[0];
125168    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
125169    rc = SQLITE_ERROR;
125170  }else{
125171    char *zErr = 0;
125172    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
125173    if( rc!=SQLITE_OK ){
125174      sqlite3ErrorMsg(pParse, "%s", zErr);
125175    }
125176    sqlite3DbFree(db, zErr);
125177  }
125178
125179  return rc;
125180}
125181/*
125182** Grow the db->aVTrans[] array so that there is room for at least one
125183** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
125184*/
125185static int growVTrans(sqlite3 *db){
125186  const int ARRAY_INCR = 5;
125187
125188  /* Grow the sqlite3.aVTrans array if required */
125189  if( (db->nVTrans%ARRAY_INCR)==0 ){
125190    VTable **aVTrans;
125191    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
125192    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
125193    if( !aVTrans ){
125194      return SQLITE_NOMEM_BKPT;
125195    }
125196    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
125197    db->aVTrans = aVTrans;
125198  }
125199
125200  return SQLITE_OK;
125201}
125202
125203/*
125204** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
125205** have already been reserved using growVTrans().
125206*/
125207static void addToVTrans(sqlite3 *db, VTable *pVTab){
125208  /* Add pVtab to the end of sqlite3.aVTrans */
125209  db->aVTrans[db->nVTrans++] = pVTab;
125210  sqlite3VtabLock(pVTab);
125211}
125212
125213/*
125214** This function is invoked by the vdbe to call the xCreate method
125215** of the virtual table named zTab in database iDb.
125216**
125217** If an error occurs, *pzErr is set to point to an English language
125218** description of the error and an SQLITE_XXX error code is returned.
125219** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
125220*/
125221SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
125222  int rc = SQLITE_OK;
125223  Table *pTab;
125224  Module *pMod;
125225  const char *zMod;
125226
125227  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
125228  assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
125229
125230  /* Locate the required virtual table module */
125231  zMod = pTab->azModuleArg[0];
125232  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
125233
125234  /* If the module has been registered and includes a Create method,
125235  ** invoke it now. If the module has not been registered, return an
125236  ** error. Otherwise, do nothing.
125237  */
125238  if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
125239    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
125240    rc = SQLITE_ERROR;
125241  }else{
125242    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
125243  }
125244
125245  /* Justification of ALWAYS():  The xConstructor method is required to
125246  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
125247  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
125248    rc = growVTrans(db);
125249    if( rc==SQLITE_OK ){
125250      addToVTrans(db, sqlite3GetVTable(db, pTab));
125251    }
125252  }
125253
125254  return rc;
125255}
125256
125257/*
125258** This function is used to set the schema of a virtual table.  It is only
125259** valid to call this function from within the xCreate() or xConnect() of a
125260** virtual table module.
125261*/
125262SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
125263  VtabCtx *pCtx;
125264  Parse *pParse;
125265  int rc = SQLITE_OK;
125266  Table *pTab;
125267  char *zErr = 0;
125268
125269#ifdef SQLITE_ENABLE_API_ARMOR
125270  if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
125271    return SQLITE_MISUSE_BKPT;
125272  }
125273#endif
125274  sqlite3_mutex_enter(db->mutex);
125275  pCtx = db->pVtabCtx;
125276  if( !pCtx || pCtx->bDeclared ){
125277    sqlite3Error(db, SQLITE_MISUSE);
125278    sqlite3_mutex_leave(db->mutex);
125279    return SQLITE_MISUSE_BKPT;
125280  }
125281  pTab = pCtx->pTab;
125282  assert( IsVirtual(pTab) );
125283
125284  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
125285  if( pParse==0 ){
125286    rc = SQLITE_NOMEM_BKPT;
125287  }else{
125288    pParse->declareVtab = 1;
125289    pParse->db = db;
125290    pParse->nQueryLoop = 1;
125291
125292    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
125293     && pParse->pNewTable
125294     && !db->mallocFailed
125295     && !pParse->pNewTable->pSelect
125296     && !IsVirtual(pParse->pNewTable)
125297    ){
125298      if( !pTab->aCol ){
125299        Table *pNew = pParse->pNewTable;
125300        Index *pIdx;
125301        pTab->aCol = pNew->aCol;
125302        pTab->nCol = pNew->nCol;
125303        pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
125304        pNew->nCol = 0;
125305        pNew->aCol = 0;
125306        assert( pTab->pIndex==0 );
125307        if( !HasRowid(pNew) && pCtx->pVTable->pMod->pModule->xUpdate!=0 ){
125308          rc = SQLITE_ERROR;
125309        }
125310        pIdx = pNew->pIndex;
125311        if( pIdx ){
125312          assert( pIdx->pNext==0 );
125313          pTab->pIndex = pIdx;
125314          pNew->pIndex = 0;
125315          pIdx->pTable = pTab;
125316        }
125317      }
125318      pCtx->bDeclared = 1;
125319    }else{
125320      sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
125321      sqlite3DbFree(db, zErr);
125322      rc = SQLITE_ERROR;
125323    }
125324    pParse->declareVtab = 0;
125325
125326    if( pParse->pVdbe ){
125327      sqlite3VdbeFinalize(pParse->pVdbe);
125328    }
125329    sqlite3DeleteTable(db, pParse->pNewTable);
125330    sqlite3ParserReset(pParse);
125331    sqlite3StackFree(db, pParse);
125332  }
125333
125334  assert( (rc&0xff)==rc );
125335  rc = sqlite3ApiExit(db, rc);
125336  sqlite3_mutex_leave(db->mutex);
125337  return rc;
125338}
125339
125340/*
125341** This function is invoked by the vdbe to call the xDestroy method
125342** of the virtual table named zTab in database iDb. This occurs
125343** when a DROP TABLE is mentioned.
125344**
125345** This call is a no-op if zTab is not a virtual table.
125346*/
125347SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
125348  int rc = SQLITE_OK;
125349  Table *pTab;
125350
125351  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
125352  if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
125353    VTable *p;
125354    int (*xDestroy)(sqlite3_vtab *);
125355    for(p=pTab->pVTable; p; p=p->pNext){
125356      assert( p->pVtab );
125357      if( p->pVtab->nRef>0 ){
125358        return SQLITE_LOCKED;
125359      }
125360    }
125361    p = vtabDisconnectAll(db, pTab);
125362    xDestroy = p->pMod->pModule->xDestroy;
125363    assert( xDestroy!=0 );  /* Checked before the virtual table is created */
125364    rc = xDestroy(p->pVtab);
125365    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
125366    if( rc==SQLITE_OK ){
125367      assert( pTab->pVTable==p && p->pNext==0 );
125368      p->pVtab = 0;
125369      pTab->pVTable = 0;
125370      sqlite3VtabUnlock(p);
125371    }
125372  }
125373
125374  return rc;
125375}
125376
125377/*
125378** This function invokes either the xRollback or xCommit method
125379** of each of the virtual tables in the sqlite3.aVTrans array. The method
125380** called is identified by the second argument, "offset", which is
125381** the offset of the method to call in the sqlite3_module structure.
125382**
125383** The array is cleared after invoking the callbacks.
125384*/
125385static void callFinaliser(sqlite3 *db, int offset){
125386  int i;
125387  if( db->aVTrans ){
125388    VTable **aVTrans = db->aVTrans;
125389    db->aVTrans = 0;
125390    for(i=0; i<db->nVTrans; i++){
125391      VTable *pVTab = aVTrans[i];
125392      sqlite3_vtab *p = pVTab->pVtab;
125393      if( p ){
125394        int (*x)(sqlite3_vtab *);
125395        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
125396        if( x ) x(p);
125397      }
125398      pVTab->iSavepoint = 0;
125399      sqlite3VtabUnlock(pVTab);
125400    }
125401    sqlite3DbFree(db, aVTrans);
125402    db->nVTrans = 0;
125403  }
125404}
125405
125406/*
125407** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
125408** array. Return the error code for the first error that occurs, or
125409** SQLITE_OK if all xSync operations are successful.
125410**
125411** If an error message is available, leave it in p->zErrMsg.
125412*/
125413SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
125414  int i;
125415  int rc = SQLITE_OK;
125416  VTable **aVTrans = db->aVTrans;
125417
125418  db->aVTrans = 0;
125419  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
125420    int (*x)(sqlite3_vtab *);
125421    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
125422    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
125423      rc = x(pVtab);
125424      sqlite3VtabImportErrmsg(p, pVtab);
125425    }
125426  }
125427  db->aVTrans = aVTrans;
125428  return rc;
125429}
125430
125431/*
125432** Invoke the xRollback method of all virtual tables in the
125433** sqlite3.aVTrans array. Then clear the array itself.
125434*/
125435SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
125436  callFinaliser(db, offsetof(sqlite3_module,xRollback));
125437  return SQLITE_OK;
125438}
125439
125440/*
125441** Invoke the xCommit method of all virtual tables in the
125442** sqlite3.aVTrans array. Then clear the array itself.
125443*/
125444SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
125445  callFinaliser(db, offsetof(sqlite3_module,xCommit));
125446  return SQLITE_OK;
125447}
125448
125449/*
125450** If the virtual table pVtab supports the transaction interface
125451** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
125452** not currently open, invoke the xBegin method now.
125453**
125454** If the xBegin call is successful, place the sqlite3_vtab pointer
125455** in the sqlite3.aVTrans array.
125456*/
125457SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
125458  int rc = SQLITE_OK;
125459  const sqlite3_module *pModule;
125460
125461  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
125462  ** than zero, then this function is being called from within a
125463  ** virtual module xSync() callback. It is illegal to write to
125464  ** virtual module tables in this case, so return SQLITE_LOCKED.
125465  */
125466  if( sqlite3VtabInSync(db) ){
125467    return SQLITE_LOCKED;
125468  }
125469  if( !pVTab ){
125470    return SQLITE_OK;
125471  }
125472  pModule = pVTab->pVtab->pModule;
125473
125474  if( pModule->xBegin ){
125475    int i;
125476
125477    /* If pVtab is already in the aVTrans array, return early */
125478    for(i=0; i<db->nVTrans; i++){
125479      if( db->aVTrans[i]==pVTab ){
125480        return SQLITE_OK;
125481      }
125482    }
125483
125484    /* Invoke the xBegin method. If successful, add the vtab to the
125485    ** sqlite3.aVTrans[] array. */
125486    rc = growVTrans(db);
125487    if( rc==SQLITE_OK ){
125488      rc = pModule->xBegin(pVTab->pVtab);
125489      if( rc==SQLITE_OK ){
125490        int iSvpt = db->nStatement + db->nSavepoint;
125491        addToVTrans(db, pVTab);
125492        if( iSvpt && pModule->xSavepoint ){
125493          pVTab->iSavepoint = iSvpt;
125494          rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
125495        }
125496      }
125497    }
125498  }
125499  return rc;
125500}
125501
125502/*
125503** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
125504** virtual tables that currently have an open transaction. Pass iSavepoint
125505** as the second argument to the virtual table method invoked.
125506**
125507** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
125508** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
125509** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
125510** an open transaction is invoked.
125511**
125512** If any virtual table method returns an error code other than SQLITE_OK,
125513** processing is abandoned and the error returned to the caller of this
125514** function immediately. If all calls to virtual table methods are successful,
125515** SQLITE_OK is returned.
125516*/
125517SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
125518  int rc = SQLITE_OK;
125519
125520  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
125521  assert( iSavepoint>=-1 );
125522  if( db->aVTrans ){
125523    int i;
125524    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
125525      VTable *pVTab = db->aVTrans[i];
125526      const sqlite3_module *pMod = pVTab->pMod->pModule;
125527      if( pVTab->pVtab && pMod->iVersion>=2 ){
125528        int (*xMethod)(sqlite3_vtab *, int);
125529        switch( op ){
125530          case SAVEPOINT_BEGIN:
125531            xMethod = pMod->xSavepoint;
125532            pVTab->iSavepoint = iSavepoint+1;
125533            break;
125534          case SAVEPOINT_ROLLBACK:
125535            xMethod = pMod->xRollbackTo;
125536            break;
125537          default:
125538            xMethod = pMod->xRelease;
125539            break;
125540        }
125541        if( xMethod && pVTab->iSavepoint>iSavepoint ){
125542          rc = xMethod(pVTab->pVtab, iSavepoint);
125543        }
125544      }
125545    }
125546  }
125547  return rc;
125548}
125549
125550/*
125551** The first parameter (pDef) is a function implementation.  The
125552** second parameter (pExpr) is the first argument to this function.
125553** If pExpr is a column in a virtual table, then let the virtual
125554** table implementation have an opportunity to overload the function.
125555**
125556** This routine is used to allow virtual table implementations to
125557** overload MATCH, LIKE, GLOB, and REGEXP operators.
125558**
125559** Return either the pDef argument (indicating no change) or a
125560** new FuncDef structure that is marked as ephemeral using the
125561** SQLITE_FUNC_EPHEM flag.
125562*/
125563SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
125564  sqlite3 *db,    /* Database connection for reporting malloc problems */
125565  FuncDef *pDef,  /* Function to possibly overload */
125566  int nArg,       /* Number of arguments to the function */
125567  Expr *pExpr     /* First argument to the function */
125568){
125569  Table *pTab;
125570  sqlite3_vtab *pVtab;
125571  sqlite3_module *pMod;
125572  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
125573  void *pArg = 0;
125574  FuncDef *pNew;
125575  int rc = 0;
125576  char *zLowerName;
125577  unsigned char *z;
125578
125579
125580  /* Check to see the left operand is a column in a virtual table */
125581  if( NEVER(pExpr==0) ) return pDef;
125582  if( pExpr->op!=TK_COLUMN ) return pDef;
125583  pTab = pExpr->pTab;
125584  if( NEVER(pTab==0) ) return pDef;
125585  if( !IsVirtual(pTab) ) return pDef;
125586  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
125587  assert( pVtab!=0 );
125588  assert( pVtab->pModule!=0 );
125589  pMod = (sqlite3_module *)pVtab->pModule;
125590  if( pMod->xFindFunction==0 ) return pDef;
125591
125592  /* Call the xFindFunction method on the virtual table implementation
125593  ** to see if the implementation wants to overload this function
125594  */
125595  zLowerName = sqlite3DbStrDup(db, pDef->zName);
125596  if( zLowerName ){
125597    for(z=(unsigned char*)zLowerName; *z; z++){
125598      *z = sqlite3UpperToLower[*z];
125599    }
125600    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
125601    sqlite3DbFree(db, zLowerName);
125602  }
125603  if( rc==0 ){
125604    return pDef;
125605  }
125606
125607  /* Create a new ephemeral function definition for the overloaded
125608  ** function */
125609  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
125610                             + sqlite3Strlen30(pDef->zName) + 1);
125611  if( pNew==0 ){
125612    return pDef;
125613  }
125614  *pNew = *pDef;
125615  pNew->zName = (const char*)&pNew[1];
125616  memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
125617  pNew->xSFunc = xSFunc;
125618  pNew->pUserData = pArg;
125619  pNew->funcFlags |= SQLITE_FUNC_EPHEM;
125620  return pNew;
125621}
125622
125623/*
125624** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
125625** array so that an OP_VBegin will get generated for it.  Add pTab to the
125626** array if it is missing.  If pTab is already in the array, this routine
125627** is a no-op.
125628*/
125629SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
125630  Parse *pToplevel = sqlite3ParseToplevel(pParse);
125631  int i, n;
125632  Table **apVtabLock;
125633
125634  assert( IsVirtual(pTab) );
125635  for(i=0; i<pToplevel->nVtabLock; i++){
125636    if( pTab==pToplevel->apVtabLock[i] ) return;
125637  }
125638  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
125639  apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
125640  if( apVtabLock ){
125641    pToplevel->apVtabLock = apVtabLock;
125642    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
125643  }else{
125644    sqlite3OomFault(pToplevel->db);
125645  }
125646}
125647
125648/*
125649** Check to see if virtual table module pMod can be have an eponymous
125650** virtual table instance.  If it can, create one if one does not already
125651** exist. Return non-zero if the eponymous virtual table instance exists
125652** when this routine returns, and return zero if it does not exist.
125653**
125654** An eponymous virtual table instance is one that is named after its
125655** module, and more importantly, does not require a CREATE VIRTUAL TABLE
125656** statement in order to come into existance.  Eponymous virtual table
125657** instances always exist.  They cannot be DROP-ed.
125658**
125659** Any virtual table module for which xConnect and xCreate are the same
125660** method can have an eponymous virtual table instance.
125661*/
125662SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
125663  const sqlite3_module *pModule = pMod->pModule;
125664  Table *pTab;
125665  char *zErr = 0;
125666  int rc;
125667  sqlite3 *db = pParse->db;
125668  if( pMod->pEpoTab ) return 1;
125669  if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
125670  pTab = sqlite3DbMallocZero(db, sizeof(Table));
125671  if( pTab==0 ) return 0;
125672  pTab->zName = sqlite3DbStrDup(db, pMod->zName);
125673  if( pTab->zName==0 ){
125674    sqlite3DbFree(db, pTab);
125675    return 0;
125676  }
125677  pMod->pEpoTab = pTab;
125678  pTab->nTabRef = 1;
125679  pTab->pSchema = db->aDb[0].pSchema;
125680  assert( pTab->nModuleArg==0 );
125681  pTab->iPKey = -1;
125682  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
125683  addModuleArgument(db, pTab, 0);
125684  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
125685  rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
125686  if( rc ){
125687    sqlite3ErrorMsg(pParse, "%s", zErr);
125688    sqlite3DbFree(db, zErr);
125689    sqlite3VtabEponymousTableClear(db, pMod);
125690    return 0;
125691  }
125692  return 1;
125693}
125694
125695/*
125696** Erase the eponymous virtual table instance associated with
125697** virtual table module pMod, if it exists.
125698*/
125699SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
125700  Table *pTab = pMod->pEpoTab;
125701  if( pTab!=0 ){
125702    /* Mark the table as Ephemeral prior to deleting it, so that the
125703    ** sqlite3DeleteTable() routine will know that it is not stored in
125704    ** the schema. */
125705    pTab->tabFlags |= TF_Ephemeral;
125706    sqlite3DeleteTable(db, pTab);
125707    pMod->pEpoTab = 0;
125708  }
125709}
125710
125711/*
125712** Return the ON CONFLICT resolution mode in effect for the virtual
125713** table update operation currently in progress.
125714**
125715** The results of this routine are undefined unless it is called from
125716** within an xUpdate method.
125717*/
125718SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
125719  static const unsigned char aMap[] = {
125720    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
125721  };
125722#ifdef SQLITE_ENABLE_API_ARMOR
125723  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
125724#endif
125725  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
125726  assert( OE_Ignore==4 && OE_Replace==5 );
125727  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
125728  return (int)aMap[db->vtabOnConflict-1];
125729}
125730
125731/*
125732** Call from within the xCreate() or xConnect() methods to provide
125733** the SQLite core with additional information about the behavior
125734** of the virtual table being implemented.
125735*/
125736SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
125737  va_list ap;
125738  int rc = SQLITE_OK;
125739
125740#ifdef SQLITE_ENABLE_API_ARMOR
125741  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
125742#endif
125743  sqlite3_mutex_enter(db->mutex);
125744  va_start(ap, op);
125745  switch( op ){
125746    case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
125747      VtabCtx *p = db->pVtabCtx;
125748      if( !p ){
125749        rc = SQLITE_MISUSE_BKPT;
125750      }else{
125751        assert( p->pTab==0 || IsVirtual(p->pTab) );
125752        p->pVTable->bConstraint = (u8)va_arg(ap, int);
125753      }
125754      break;
125755    }
125756    default:
125757      rc = SQLITE_MISUSE_BKPT;
125758      break;
125759  }
125760  va_end(ap);
125761
125762  if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
125763  sqlite3_mutex_leave(db->mutex);
125764  return rc;
125765}
125766
125767#endif /* SQLITE_OMIT_VIRTUALTABLE */
125768
125769/************** End of vtab.c ************************************************/
125770/************** Begin file wherecode.c ***************************************/
125771/*
125772** 2015-06-06
125773**
125774** The author disclaims copyright to this source code.  In place of
125775** a legal notice, here is a blessing:
125776**
125777**    May you do good and not evil.
125778**    May you find forgiveness for yourself and forgive others.
125779**    May you share freely, never taking more than you give.
125780**
125781*************************************************************************
125782** This module contains C code that generates VDBE code used to process
125783** the WHERE clause of SQL statements.
125784**
125785** This file was split off from where.c on 2015-06-06 in order to reduce the
125786** size of where.c and make it easier to edit.  This file contains the routines
125787** that actually generate the bulk of the WHERE loop code.  The original where.c
125788** file retains the code that does query planning and analysis.
125789*/
125790/* #include "sqliteInt.h" */
125791/************** Include whereInt.h in the middle of wherecode.c **************/
125792/************** Begin file whereInt.h ****************************************/
125793/*
125794** 2013-11-12
125795**
125796** The author disclaims copyright to this source code.  In place of
125797** a legal notice, here is a blessing:
125798**
125799**    May you do good and not evil.
125800**    May you find forgiveness for yourself and forgive others.
125801**    May you share freely, never taking more than you give.
125802**
125803*************************************************************************
125804**
125805** This file contains structure and macro definitions for the query
125806** planner logic in "where.c".  These definitions are broken out into
125807** a separate source file for easier editing.
125808*/
125809
125810/*
125811** Trace output macros
125812*/
125813#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
125814/***/ int sqlite3WhereTrace;
125815#endif
125816#if defined(SQLITE_DEBUG) \
125817    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
125818# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
125819# define WHERETRACE_ENABLED 1
125820#else
125821# define WHERETRACE(K,X)
125822#endif
125823
125824/* Forward references
125825*/
125826typedef struct WhereClause WhereClause;
125827typedef struct WhereMaskSet WhereMaskSet;
125828typedef struct WhereOrInfo WhereOrInfo;
125829typedef struct WhereAndInfo WhereAndInfo;
125830typedef struct WhereLevel WhereLevel;
125831typedef struct WhereLoop WhereLoop;
125832typedef struct WherePath WherePath;
125833typedef struct WhereTerm WhereTerm;
125834typedef struct WhereLoopBuilder WhereLoopBuilder;
125835typedef struct WhereScan WhereScan;
125836typedef struct WhereOrCost WhereOrCost;
125837typedef struct WhereOrSet WhereOrSet;
125838
125839/*
125840** This object contains information needed to implement a single nested
125841** loop in WHERE clause.
125842**
125843** Contrast this object with WhereLoop.  This object describes the
125844** implementation of the loop.  WhereLoop describes the algorithm.
125845** This object contains a pointer to the WhereLoop algorithm as one of
125846** its elements.
125847**
125848** The WhereInfo object contains a single instance of this object for
125849** each term in the FROM clause (which is to say, for each of the
125850** nested loops as implemented).  The order of WhereLevel objects determines
125851** the loop nested order, with WhereInfo.a[0] being the outer loop and
125852** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
125853*/
125854struct WhereLevel {
125855  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
125856  int iTabCur;          /* The VDBE cursor used to access the table */
125857  int iIdxCur;          /* The VDBE cursor used to access pIdx */
125858  int addrBrk;          /* Jump here to break out of the loop */
125859  int addrNxt;          /* Jump here to start the next IN combination */
125860  int addrSkip;         /* Jump here for next iteration of skip-scan */
125861  int addrCont;         /* Jump here to continue with the next loop cycle */
125862  int addrFirst;        /* First instruction of interior of the loop */
125863  int addrBody;         /* Beginning of the body of this loop */
125864#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
125865  u32 iLikeRepCntr;     /* LIKE range processing counter register (times 2) */
125866  int addrLikeRep;      /* LIKE range processing address */
125867#endif
125868  u8 iFrom;             /* Which entry in the FROM clause */
125869  u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
125870  int p1, p2;           /* Operands of the opcode used to ends the loop */
125871  union {               /* Information that depends on pWLoop->wsFlags */
125872    struct {
125873      int nIn;              /* Number of entries in aInLoop[] */
125874      struct InLoop {
125875        int iCur;              /* The VDBE cursor used by this IN operator */
125876        int addrInTop;         /* Top of the IN loop */
125877        u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
125878      } *aInLoop;           /* Information about each nested IN operator */
125879    } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
125880    Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
125881  } u;
125882  struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
125883  Bitmask notReady;          /* FROM entries not usable at this level */
125884#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
125885  int addrVisit;        /* Address at which row is visited */
125886#endif
125887};
125888
125889/*
125890** Each instance of this object represents an algorithm for evaluating one
125891** term of a join.  Every term of the FROM clause will have at least
125892** one corresponding WhereLoop object (unless INDEXED BY constraints
125893** prevent a query solution - which is an error) and many terms of the
125894** FROM clause will have multiple WhereLoop objects, each describing a
125895** potential way of implementing that FROM-clause term, together with
125896** dependencies and cost estimates for using the chosen algorithm.
125897**
125898** Query planning consists of building up a collection of these WhereLoop
125899** objects, then computing a particular sequence of WhereLoop objects, with
125900** one WhereLoop object per FROM clause term, that satisfy all dependencies
125901** and that minimize the overall cost.
125902*/
125903struct WhereLoop {
125904  Bitmask prereq;       /* Bitmask of other loops that must run first */
125905  Bitmask maskSelf;     /* Bitmask identifying table iTab */
125906#ifdef SQLITE_DEBUG
125907  char cId;             /* Symbolic ID of this loop for debugging use */
125908#endif
125909  u8 iTab;              /* Position in FROM clause of table for this loop */
125910  u8 iSortIdx;          /* Sorting index number.  0==None */
125911  LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
125912  LogEst rRun;          /* Cost of running each loop */
125913  LogEst nOut;          /* Estimated number of output rows */
125914  union {
125915    struct {               /* Information for internal btree tables */
125916      u16 nEq;               /* Number of equality constraints */
125917      u16 nBtm;              /* Size of BTM vector */
125918      u16 nTop;              /* Size of TOP vector */
125919      Index *pIndex;         /* Index used, or NULL */
125920    } btree;
125921    struct {               /* Information for virtual tables */
125922      int idxNum;            /* Index number */
125923      u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
125924      i8 isOrdered;          /* True if satisfies ORDER BY */
125925      u16 omitMask;          /* Terms that may be omitted */
125926      char *idxStr;          /* Index identifier string */
125927    } vtab;
125928  } u;
125929  u32 wsFlags;          /* WHERE_* flags describing the plan */
125930  u16 nLTerm;           /* Number of entries in aLTerm[] */
125931  u16 nSkip;            /* Number of NULL aLTerm[] entries */
125932  /**** whereLoopXfer() copies fields above ***********************/
125933# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
125934  u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
125935  WhereTerm **aLTerm;   /* WhereTerms used */
125936  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
125937  WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
125938};
125939
125940/* This object holds the prerequisites and the cost of running a
125941** subquery on one operand of an OR operator in the WHERE clause.
125942** See WhereOrSet for additional information
125943*/
125944struct WhereOrCost {
125945  Bitmask prereq;     /* Prerequisites */
125946  LogEst rRun;        /* Cost of running this subquery */
125947  LogEst nOut;        /* Number of outputs for this subquery */
125948};
125949
125950/* The WhereOrSet object holds a set of possible WhereOrCosts that
125951** correspond to the subquery(s) of OR-clause processing.  Only the
125952** best N_OR_COST elements are retained.
125953*/
125954#define N_OR_COST 3
125955struct WhereOrSet {
125956  u16 n;                      /* Number of valid a[] entries */
125957  WhereOrCost a[N_OR_COST];   /* Set of best costs */
125958};
125959
125960/*
125961** Each instance of this object holds a sequence of WhereLoop objects
125962** that implement some or all of a query plan.
125963**
125964** Think of each WhereLoop object as a node in a graph with arcs
125965** showing dependencies and costs for travelling between nodes.  (That is
125966** not a completely accurate description because WhereLoop costs are a
125967** vector, not a scalar, and because dependencies are many-to-one, not
125968** one-to-one as are graph nodes.  But it is a useful visualization aid.)
125969** Then a WherePath object is a path through the graph that visits some
125970** or all of the WhereLoop objects once.
125971**
125972** The "solver" works by creating the N best WherePath objects of length
125973** 1.  Then using those as a basis to compute the N best WherePath objects
125974** of length 2.  And so forth until the length of WherePaths equals the
125975** number of nodes in the FROM clause.  The best (lowest cost) WherePath
125976** at the end is the chosen query plan.
125977*/
125978struct WherePath {
125979  Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
125980  Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
125981  LogEst nRow;          /* Estimated number of rows generated by this path */
125982  LogEst rCost;         /* Total cost of this path */
125983  LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
125984  i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
125985  WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
125986};
125987
125988/*
125989** The query generator uses an array of instances of this structure to
125990** help it analyze the subexpressions of the WHERE clause.  Each WHERE
125991** clause subexpression is separated from the others by AND operators,
125992** usually, or sometimes subexpressions separated by OR.
125993**
125994** All WhereTerms are collected into a single WhereClause structure.
125995** The following identity holds:
125996**
125997**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
125998**
125999** When a term is of the form:
126000**
126001**              X <op> <expr>
126002**
126003** where X is a column name and <op> is one of certain operators,
126004** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
126005** cursor number and column number for X.  WhereTerm.eOperator records
126006** the <op> using a bitmask encoding defined by WO_xxx below.  The
126007** use of a bitmask encoding for the operator allows us to search
126008** quickly for terms that match any of several different operators.
126009**
126010** A WhereTerm might also be two or more subterms connected by OR:
126011**
126012**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
126013**
126014** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
126015** and the WhereTerm.u.pOrInfo field points to auxiliary information that
126016** is collected about the OR clause.
126017**
126018** If a term in the WHERE clause does not match either of the two previous
126019** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
126020** to the original subexpression content and wtFlags is set up appropriately
126021** but no other fields in the WhereTerm object are meaningful.
126022**
126023** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
126024** but they do so indirectly.  A single WhereMaskSet structure translates
126025** cursor number into bits and the translated bit is stored in the prereq
126026** fields.  The translation is used in order to maximize the number of
126027** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
126028** spread out over the non-negative integers.  For example, the cursor
126029** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
126030** translates these sparse cursor numbers into consecutive integers
126031** beginning with 0 in order to make the best possible use of the available
126032** bits in the Bitmask.  So, in the example above, the cursor numbers
126033** would be mapped into integers 0 through 7.
126034**
126035** The number of terms in a join is limited by the number of bits
126036** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
126037** is only able to process joins with 64 or fewer tables.
126038*/
126039struct WhereTerm {
126040  Expr *pExpr;            /* Pointer to the subexpression that is this term */
126041  WhereClause *pWC;       /* The clause this term is part of */
126042  LogEst truthProb;       /* Probability of truth for this expression */
126043  u16 wtFlags;            /* TERM_xxx bit flags.  See below */
126044  u16 eOperator;          /* A WO_xx value describing <op> */
126045  u8 nChild;              /* Number of children that must disable us */
126046  u8 eMatchOp;            /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
126047  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
126048  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
126049  int iField;             /* Field in (?,?,?) IN (SELECT...) vector */
126050  union {
126051    int leftColumn;         /* Column number of X in "X <op> <expr>" */
126052    WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
126053    WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
126054  } u;
126055  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
126056  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
126057};
126058
126059/*
126060** Allowed values of WhereTerm.wtFlags
126061*/
126062#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
126063#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
126064#define TERM_CODED      0x04   /* This term is already coded */
126065#define TERM_COPIED     0x08   /* Has a child */
126066#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
126067#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
126068#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
126069#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
126070#  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
126071#else
126072#  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
126073#endif
126074#define TERM_LIKEOPT    0x100  /* Virtual terms from the LIKE optimization */
126075#define TERM_LIKECOND   0x200  /* Conditionally this LIKE operator term */
126076#define TERM_LIKE       0x400  /* The original LIKE operator */
126077#define TERM_IS         0x800  /* Term.pExpr is an IS operator */
126078
126079/*
126080** An instance of the WhereScan object is used as an iterator for locating
126081** terms in the WHERE clause that are useful to the query planner.
126082*/
126083struct WhereScan {
126084  WhereClause *pOrigWC;      /* Original, innermost WhereClause */
126085  WhereClause *pWC;          /* WhereClause currently being scanned */
126086  const char *zCollName;     /* Required collating sequence, if not NULL */
126087  Expr *pIdxExpr;            /* Search for this index expression */
126088  char idxaff;               /* Must match this affinity, if zCollName!=NULL */
126089  unsigned char nEquiv;      /* Number of entries in aEquiv[] */
126090  unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
126091  u32 opMask;                /* Acceptable operators */
126092  int k;                     /* Resume scanning at this->pWC->a[this->k] */
126093  int aiCur[11];             /* Cursors in the equivalence class */
126094  i16 aiColumn[11];          /* Corresponding column number in the eq-class */
126095};
126096
126097/*
126098** An instance of the following structure holds all information about a
126099** WHERE clause.  Mostly this is a container for one or more WhereTerms.
126100**
126101** Explanation of pOuter:  For a WHERE clause of the form
126102**
126103**           a AND ((b AND c) OR (d AND e)) AND f
126104**
126105** There are separate WhereClause objects for the whole clause and for
126106** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
126107** subclauses points to the WhereClause object for the whole clause.
126108*/
126109struct WhereClause {
126110  WhereInfo *pWInfo;       /* WHERE clause processing context */
126111  WhereClause *pOuter;     /* Outer conjunction */
126112  u8 op;                   /* Split operator.  TK_AND or TK_OR */
126113  int nTerm;               /* Number of terms */
126114  int nSlot;               /* Number of entries in a[] */
126115  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
126116#if defined(SQLITE_SMALL_STACK)
126117  WhereTerm aStatic[1];    /* Initial static space for a[] */
126118#else
126119  WhereTerm aStatic[8];    /* Initial static space for a[] */
126120#endif
126121};
126122
126123/*
126124** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
126125** a dynamically allocated instance of the following structure.
126126*/
126127struct WhereOrInfo {
126128  WhereClause wc;          /* Decomposition into subterms */
126129  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
126130};
126131
126132/*
126133** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
126134** a dynamically allocated instance of the following structure.
126135*/
126136struct WhereAndInfo {
126137  WhereClause wc;          /* The subexpression broken out */
126138};
126139
126140/*
126141** An instance of the following structure keeps track of a mapping
126142** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
126143**
126144** The VDBE cursor numbers are small integers contained in
126145** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
126146** clause, the cursor numbers might not begin with 0 and they might
126147** contain gaps in the numbering sequence.  But we want to make maximum
126148** use of the bits in our bitmasks.  This structure provides a mapping
126149** from the sparse cursor numbers into consecutive integers beginning
126150** with 0.
126151**
126152** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
126153** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
126154**
126155** For example, if the WHERE clause expression used these VDBE
126156** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
126157** would map those cursor numbers into bits 0 through 5.
126158**
126159** Note that the mapping is not necessarily ordered.  In the example
126160** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
126161** 57->5, 73->4.  Or one of 719 other combinations might be used. It
126162** does not really matter.  What is important is that sparse cursor
126163** numbers all get mapped into bit numbers that begin with 0 and contain
126164** no gaps.
126165*/
126166struct WhereMaskSet {
126167  int n;                        /* Number of assigned cursor values */
126168  int ix[BMS];                  /* Cursor assigned to each bit */
126169};
126170
126171/*
126172** Initialize a WhereMaskSet object
126173*/
126174#define initMaskSet(P)  (P)->n=0
126175
126176/*
126177** This object is a convenience wrapper holding all information needed
126178** to construct WhereLoop objects for a particular query.
126179*/
126180struct WhereLoopBuilder {
126181  WhereInfo *pWInfo;        /* Information about this WHERE */
126182  WhereClause *pWC;         /* WHERE clause terms */
126183  ExprList *pOrderBy;       /* ORDER BY clause */
126184  WhereLoop *pNew;          /* Template WhereLoop */
126185  WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
126186#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
126187  UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
126188  int nRecValid;            /* Number of valid fields currently in pRec */
126189#endif
126190  unsigned int bldFlags;    /* SQLITE_BLDF_* flags */
126191};
126192
126193/* Allowed values for WhereLoopBuider.bldFlags */
126194#define SQLITE_BLDF_INDEXED  0x0001   /* An index is used */
126195#define SQLITE_BLDF_UNIQUE   0x0002   /* All keys of a UNIQUE index used */
126196
126197/*
126198** The WHERE clause processing routine has two halves.  The
126199** first part does the start of the WHERE loop and the second
126200** half does the tail of the WHERE loop.  An instance of
126201** this structure is returned by the first half and passed
126202** into the second half to give some continuity.
126203**
126204** An instance of this object holds the complete state of the query
126205** planner.
126206*/
126207struct WhereInfo {
126208  Parse *pParse;            /* Parsing and code generating context */
126209  SrcList *pTabList;        /* List of tables in the join */
126210  ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
126211  ExprList *pResultSet;     /* Result set of the query */
126212  LogEst iLimit;            /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
126213  int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
126214  int iContinue;            /* Jump here to continue with next record */
126215  int iBreak;               /* Jump here to break out of the loop */
126216  int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
126217  u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
126218  u8 nLevel;                /* Number of nested loop */
126219  i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
126220  u8 sorted;                /* True if really sorted (not just grouped) */
126221  u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
126222  u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
126223  u8 eDistinct;             /* One of the WHERE_DISTINCT_* values */
126224  u8 bOrderedInnerLoop;     /* True if only the inner-most loop is ordered */
126225  int iTop;                 /* The very beginning of the WHERE loop */
126226  WhereLoop *pLoops;        /* List of all WhereLoop objects */
126227  Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
126228  LogEst nRowOut;           /* Estimated number of output rows */
126229  WhereClause sWC;          /* Decomposition of the WHERE clause */
126230  WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
126231  WhereLevel a[1];          /* Information about each nest loop in WHERE */
126232};
126233
126234/*
126235** Private interfaces - callable only by other where.c routines.
126236**
126237** where.c:
126238*/
126239SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
126240#ifdef WHERETRACE_ENABLED
126241SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
126242#endif
126243SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
126244  WhereClause *pWC,     /* The WHERE clause to be searched */
126245  int iCur,             /* Cursor number of LHS */
126246  int iColumn,          /* Column number of LHS */
126247  Bitmask notReady,     /* RHS must not overlap with this mask */
126248  u32 op,               /* Mask of WO_xx values describing operator */
126249  Index *pIdx           /* Must be compatible with this index, if not NULL */
126250);
126251
126252/* wherecode.c: */
126253#ifndef SQLITE_OMIT_EXPLAIN
126254SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
126255  Parse *pParse,                  /* Parse context */
126256  SrcList *pTabList,              /* Table list this loop refers to */
126257  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
126258  int iLevel,                     /* Value for "level" column of output */
126259  int iFrom,                      /* Value for "from" column of output */
126260  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
126261);
126262#else
126263# define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
126264#endif /* SQLITE_OMIT_EXPLAIN */
126265#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
126266SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
126267  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
126268  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
126269  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
126270  int addrExplain                 /* Address of OP_Explain (or 0) */
126271);
126272#else
126273# define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
126274#endif
126275SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
126276  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
126277  int iLevel,          /* Which level of pWInfo->a[] should be coded */
126278  Bitmask notReady     /* Which tables are currently available */
126279);
126280
126281/* whereexpr.c: */
126282SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
126283SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
126284SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
126285SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
126286SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
126287SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
126288SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
126289
126290
126291
126292
126293
126294/*
126295** Bitmasks for the operators on WhereTerm objects.  These are all
126296** operators that are of interest to the query planner.  An
126297** OR-ed combination of these values can be used when searching for
126298** particular WhereTerms within a WhereClause.
126299**
126300** Value constraints:
126301**     WO_EQ    == SQLITE_INDEX_CONSTRAINT_EQ
126302**     WO_LT    == SQLITE_INDEX_CONSTRAINT_LT
126303**     WO_LE    == SQLITE_INDEX_CONSTRAINT_LE
126304**     WO_GT    == SQLITE_INDEX_CONSTRAINT_GT
126305**     WO_GE    == SQLITE_INDEX_CONSTRAINT_GE
126306**     WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH
126307*/
126308#define WO_IN     0x0001
126309#define WO_EQ     0x0002
126310#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
126311#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
126312#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
126313#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
126314#define WO_MATCH  0x0040
126315#define WO_IS     0x0080
126316#define WO_ISNULL 0x0100
126317#define WO_OR     0x0200       /* Two or more OR-connected terms */
126318#define WO_AND    0x0400       /* Two or more AND-connected terms */
126319#define WO_EQUIV  0x0800       /* Of the form A==B, both columns */
126320#define WO_NOOP   0x1000       /* This term does not restrict search space */
126321
126322#define WO_ALL    0x1fff       /* Mask of all possible WO_* values */
126323#define WO_SINGLE 0x01ff       /* Mask of all non-compound WO_* values */
126324
126325/*
126326** These are definitions of bits in the WhereLoop.wsFlags field.
126327** The particular combination of bits in each WhereLoop help to
126328** determine the algorithm that WhereLoop represents.
126329*/
126330#define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
126331#define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
126332#define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
126333#define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
126334#define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
126335#define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
126336#define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
126337#define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
126338#define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
126339#define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
126340#define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
126341#define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
126342#define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
126343#define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
126344#define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
126345#define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
126346#define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
126347#define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
126348#define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */
126349
126350/************** End of whereInt.h ********************************************/
126351/************** Continuing where we left off in wherecode.c ******************/
126352
126353#ifndef SQLITE_OMIT_EXPLAIN
126354
126355/*
126356** Return the name of the i-th column of the pIdx index.
126357*/
126358static const char *explainIndexColumnName(Index *pIdx, int i){
126359  i = pIdx->aiColumn[i];
126360  if( i==XN_EXPR ) return "<expr>";
126361  if( i==XN_ROWID ) return "rowid";
126362  return pIdx->pTable->aCol[i].zName;
126363}
126364
126365/*
126366** This routine is a helper for explainIndexRange() below
126367**
126368** pStr holds the text of an expression that we are building up one term
126369** at a time.  This routine adds a new term to the end of the expression.
126370** Terms are separated by AND so add the "AND" text for second and subsequent
126371** terms only.
126372*/
126373static void explainAppendTerm(
126374  StrAccum *pStr,             /* The text expression being built */
126375  Index *pIdx,                /* Index to read column names from */
126376  int nTerm,                  /* Number of terms */
126377  int iTerm,                  /* Zero-based index of first term. */
126378  int bAnd,                   /* Non-zero to append " AND " */
126379  const char *zOp             /* Name of the operator */
126380){
126381  int i;
126382
126383  assert( nTerm>=1 );
126384  if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5);
126385
126386  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
126387  for(i=0; i<nTerm; i++){
126388    if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
126389    sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i));
126390  }
126391  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
126392
126393  sqlite3StrAccumAppend(pStr, zOp, 1);
126394
126395  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
126396  for(i=0; i<nTerm; i++){
126397    if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
126398    sqlite3StrAccumAppend(pStr, "?", 1);
126399  }
126400  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
126401}
126402
126403/*
126404** Argument pLevel describes a strategy for scanning table pTab. This
126405** function appends text to pStr that describes the subset of table
126406** rows scanned by the strategy in the form of an SQL expression.
126407**
126408** For example, if the query:
126409**
126410**   SELECT * FROM t1 WHERE a=1 AND b>2;
126411**
126412** is run and there is an index on (a, b), then this function returns a
126413** string similar to:
126414**
126415**   "a=? AND b>?"
126416*/
126417static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
126418  Index *pIndex = pLoop->u.btree.pIndex;
126419  u16 nEq = pLoop->u.btree.nEq;
126420  u16 nSkip = pLoop->nSkip;
126421  int i, j;
126422
126423  if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
126424  sqlite3StrAccumAppend(pStr, " (", 2);
126425  for(i=0; i<nEq; i++){
126426    const char *z = explainIndexColumnName(pIndex, i);
126427    if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
126428    sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
126429  }
126430
126431  j = i;
126432  if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
126433    explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
126434    i = 1;
126435  }
126436  if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
126437    explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
126438  }
126439  sqlite3StrAccumAppend(pStr, ")", 1);
126440}
126441
126442/*
126443** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
126444** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
126445** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
126446** is added to the output to describe the table scan strategy in pLevel.
126447**
126448** If an OP_Explain opcode is added to the VM, its address is returned.
126449** Otherwise, if no OP_Explain is coded, zero is returned.
126450*/
126451SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
126452  Parse *pParse,                  /* Parse context */
126453  SrcList *pTabList,              /* Table list this loop refers to */
126454  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
126455  int iLevel,                     /* Value for "level" column of output */
126456  int iFrom,                      /* Value for "from" column of output */
126457  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
126458){
126459  int ret = 0;
126460#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
126461  if( pParse->explain==2 )
126462#endif
126463  {
126464    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
126465    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
126466    sqlite3 *db = pParse->db;     /* Database handle */
126467    int iId = pParse->iSelectId;  /* Select id (left-most output column) */
126468    int isSearch;                 /* True for a SEARCH. False for SCAN. */
126469    WhereLoop *pLoop;             /* The controlling WhereLoop object */
126470    u32 flags;                    /* Flags that describe this loop */
126471    char *zMsg;                   /* Text to add to EQP output */
126472    StrAccum str;                 /* EQP output string */
126473    char zBuf[100];               /* Initial space for EQP output string */
126474
126475    pLoop = pLevel->pWLoop;
126476    flags = pLoop->wsFlags;
126477    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
126478
126479    isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
126480            || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
126481            || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
126482
126483    sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
126484    sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
126485    if( pItem->pSelect ){
126486      sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
126487    }else{
126488      sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
126489    }
126490
126491    if( pItem->zAlias ){
126492      sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
126493    }
126494    if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
126495      const char *zFmt = 0;
126496      Index *pIdx;
126497
126498      assert( pLoop->u.btree.pIndex!=0 );
126499      pIdx = pLoop->u.btree.pIndex;
126500      assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
126501      if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
126502        if( isSearch ){
126503          zFmt = "PRIMARY KEY";
126504        }
126505      }else if( flags & WHERE_PARTIALIDX ){
126506        zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
126507      }else if( flags & WHERE_AUTO_INDEX ){
126508        zFmt = "AUTOMATIC COVERING INDEX";
126509      }else if( flags & WHERE_IDX_ONLY ){
126510        zFmt = "COVERING INDEX %s";
126511      }else{
126512        zFmt = "INDEX %s";
126513      }
126514      if( zFmt ){
126515        sqlite3StrAccumAppend(&str, " USING ", 7);
126516        sqlite3XPrintf(&str, zFmt, pIdx->zName);
126517        explainIndexRange(&str, pLoop);
126518      }
126519    }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
126520      const char *zRangeOp;
126521      if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
126522        zRangeOp = "=";
126523      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
126524        zRangeOp = ">? AND rowid<";
126525      }else if( flags&WHERE_BTM_LIMIT ){
126526        zRangeOp = ">";
126527      }else{
126528        assert( flags&WHERE_TOP_LIMIT);
126529        zRangeOp = "<";
126530      }
126531      sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
126532    }
126533#ifndef SQLITE_OMIT_VIRTUALTABLE
126534    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
126535      sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
126536                  pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
126537    }
126538#endif
126539#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
126540    if( pLoop->nOut>=10 ){
126541      sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
126542    }else{
126543      sqlite3StrAccumAppend(&str, " (~1 row)", 9);
126544    }
126545#endif
126546    zMsg = sqlite3StrAccumFinish(&str);
126547    ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
126548  }
126549  return ret;
126550}
126551#endif /* SQLITE_OMIT_EXPLAIN */
126552
126553#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
126554/*
126555** Configure the VM passed as the first argument with an
126556** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
126557** implement level pLvl. Argument pSrclist is a pointer to the FROM
126558** clause that the scan reads data from.
126559**
126560** If argument addrExplain is not 0, it must be the address of an
126561** OP_Explain instruction that describes the same loop.
126562*/
126563SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
126564  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
126565  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
126566  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
126567  int addrExplain                 /* Address of OP_Explain (or 0) */
126568){
126569  const char *zObj = 0;
126570  WhereLoop *pLoop = pLvl->pWLoop;
126571  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
126572    zObj = pLoop->u.btree.pIndex->zName;
126573  }else{
126574    zObj = pSrclist->a[pLvl->iFrom].zName;
126575  }
126576  sqlite3VdbeScanStatus(
126577      v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
126578  );
126579}
126580#endif
126581
126582
126583/*
126584** Disable a term in the WHERE clause.  Except, do not disable the term
126585** if it controls a LEFT OUTER JOIN and it did not originate in the ON
126586** or USING clause of that join.
126587**
126588** Consider the term t2.z='ok' in the following queries:
126589**
126590**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
126591**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
126592**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
126593**
126594** The t2.z='ok' is disabled in the in (2) because it originates
126595** in the ON clause.  The term is disabled in (3) because it is not part
126596** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
126597**
126598** Disabling a term causes that term to not be tested in the inner loop
126599** of the join.  Disabling is an optimization.  When terms are satisfied
126600** by indices, we disable them to prevent redundant tests in the inner
126601** loop.  We would get the correct results if nothing were ever disabled,
126602** but joins might run a little slower.  The trick is to disable as much
126603** as we can without disabling too much.  If we disabled in (1), we'd get
126604** the wrong answer.  See ticket #813.
126605**
126606** If all the children of a term are disabled, then that term is also
126607** automatically disabled.  In this way, terms get disabled if derived
126608** virtual terms are tested first.  For example:
126609**
126610**      x GLOB 'abc*' AND x>='abc' AND x<'acd'
126611**      \___________/     \______/     \_____/
126612**         parent          child1       child2
126613**
126614** Only the parent term was in the original WHERE clause.  The child1
126615** and child2 terms were added by the LIKE optimization.  If both of
126616** the virtual child terms are valid, then testing of the parent can be
126617** skipped.
126618**
126619** Usually the parent term is marked as TERM_CODED.  But if the parent
126620** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
126621** The TERM_LIKECOND marking indicates that the term should be coded inside
126622** a conditional such that is only evaluated on the second pass of a
126623** LIKE-optimization loop, when scanning BLOBs instead of strings.
126624*/
126625static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
126626  int nLoop = 0;
126627  while( ALWAYS(pTerm!=0)
126628      && (pTerm->wtFlags & TERM_CODED)==0
126629      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
126630      && (pLevel->notReady & pTerm->prereqAll)==0
126631  ){
126632    if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
126633      pTerm->wtFlags |= TERM_LIKECOND;
126634    }else{
126635      pTerm->wtFlags |= TERM_CODED;
126636    }
126637    if( pTerm->iParent<0 ) break;
126638    pTerm = &pTerm->pWC->a[pTerm->iParent];
126639    pTerm->nChild--;
126640    if( pTerm->nChild!=0 ) break;
126641    nLoop++;
126642  }
126643}
126644
126645/*
126646** Code an OP_Affinity opcode to apply the column affinity string zAff
126647** to the n registers starting at base.
126648**
126649** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
126650** beginning and end of zAff are ignored.  If all entries in zAff are
126651** SQLITE_AFF_BLOB, then no code gets generated.
126652**
126653** This routine makes its own copy of zAff so that the caller is free
126654** to modify zAff after this routine returns.
126655*/
126656static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
126657  Vdbe *v = pParse->pVdbe;
126658  if( zAff==0 ){
126659    assert( pParse->db->mallocFailed );
126660    return;
126661  }
126662  assert( v!=0 );
126663
126664  /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
126665  ** and end of the affinity string.
126666  */
126667  while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
126668    n--;
126669    base++;
126670    zAff++;
126671  }
126672  while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
126673    n--;
126674  }
126675
126676  /* Code the OP_Affinity opcode if there is anything left to do. */
126677  if( n>0 ){
126678    sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
126679    sqlite3ExprCacheAffinityChange(pParse, base, n);
126680  }
126681}
126682
126683/*
126684** Expression pRight, which is the RHS of a comparison operation, is
126685** either a vector of n elements or, if n==1, a scalar expression.
126686** Before the comparison operation, affinity zAff is to be applied
126687** to the pRight values. This function modifies characters within the
126688** affinity string to SQLITE_AFF_BLOB if either:
126689**
126690**   * the comparison will be performed with no affinity, or
126691**   * the affinity change in zAff is guaranteed not to change the value.
126692*/
126693static void updateRangeAffinityStr(
126694  Expr *pRight,                   /* RHS of comparison */
126695  int n,                          /* Number of vector elements in comparison */
126696  char *zAff                      /* Affinity string to modify */
126697){
126698  int i;
126699  for(i=0; i<n; i++){
126700    Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
126701    if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
126702     || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
126703    ){
126704      zAff[i] = SQLITE_AFF_BLOB;
126705    }
126706  }
126707}
126708
126709/*
126710** Generate code for a single equality term of the WHERE clause.  An equality
126711** term can be either X=expr or X IN (...).   pTerm is the term to be
126712** coded.
126713**
126714** The current value for the constraint is left in a register, the index
126715** of which is returned.  An attempt is made store the result in iTarget but
126716** this is only guaranteed for TK_ISNULL and TK_IN constraints.  If the
126717** constraint is a TK_EQ or TK_IS, then the current value might be left in
126718** some other register and it is the caller's responsibility to compensate.
126719**
126720** For a constraint of the form X=expr, the expression is evaluated in
126721** straight-line code.  For constraints of the form X IN (...)
126722** this routine sets up a loop that will iterate over all values of X.
126723*/
126724static int codeEqualityTerm(
126725  Parse *pParse,      /* The parsing context */
126726  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
126727  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
126728  int iEq,            /* Index of the equality term within this level */
126729  int bRev,           /* True for reverse-order IN operations */
126730  int iTarget         /* Attempt to leave results in this register */
126731){
126732  Expr *pX = pTerm->pExpr;
126733  Vdbe *v = pParse->pVdbe;
126734  int iReg;                  /* Register holding results */
126735
126736  assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
126737  assert( iTarget>0 );
126738  if( pX->op==TK_EQ || pX->op==TK_IS ){
126739    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
126740  }else if( pX->op==TK_ISNULL ){
126741    iReg = iTarget;
126742    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
126743#ifndef SQLITE_OMIT_SUBQUERY
126744  }else{
126745    int eType = IN_INDEX_NOOP;
126746    int iTab;
126747    struct InLoop *pIn;
126748    WhereLoop *pLoop = pLevel->pWLoop;
126749    int i;
126750    int nEq = 0;
126751    int *aiMap = 0;
126752
126753    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
126754      && pLoop->u.btree.pIndex!=0
126755      && pLoop->u.btree.pIndex->aSortOrder[iEq]
126756    ){
126757      testcase( iEq==0 );
126758      testcase( bRev );
126759      bRev = !bRev;
126760    }
126761    assert( pX->op==TK_IN );
126762    iReg = iTarget;
126763
126764    for(i=0; i<iEq; i++){
126765      if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
126766        disableTerm(pLevel, pTerm);
126767        return iTarget;
126768      }
126769    }
126770    for(i=iEq;i<pLoop->nLTerm; i++){
126771      if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++;
126772    }
126773
126774    if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
126775      eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0);
126776    }else{
126777      Select *pSelect = pX->x.pSelect;
126778      sqlite3 *db = pParse->db;
126779      u16 savedDbOptFlags = db->dbOptFlags;
126780      ExprList *pOrigRhs = pSelect->pEList;
126781      ExprList *pOrigLhs = pX->pLeft->x.pList;
126782      ExprList *pRhs = 0;         /* New Select.pEList for RHS */
126783      ExprList *pLhs = 0;         /* New pX->pLeft vector */
126784
126785      for(i=iEq;i<pLoop->nLTerm; i++){
126786        if( pLoop->aLTerm[i]->pExpr==pX ){
126787          int iField = pLoop->aLTerm[i]->iField - 1;
126788          Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0);
126789          Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0);
126790
126791          pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs);
126792          pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs);
126793        }
126794      }
126795      if( !db->mallocFailed ){
126796        Expr *pLeft = pX->pLeft;
126797
126798        if( pSelect->pOrderBy ){
126799          /* If the SELECT statement has an ORDER BY clause, zero the
126800          ** iOrderByCol variables. These are set to non-zero when an
126801          ** ORDER BY term exactly matches one of the terms of the
126802          ** result-set. Since the result-set of the SELECT statement may
126803          ** have been modified or reordered, these variables are no longer
126804          ** set correctly.  Since setting them is just an optimization,
126805          ** it's easiest just to zero them here.  */
126806          ExprList *pOrderBy = pSelect->pOrderBy;
126807          for(i=0; i<pOrderBy->nExpr; i++){
126808            pOrderBy->a[i].u.x.iOrderByCol = 0;
126809          }
126810        }
126811
126812        /* Take care here not to generate a TK_VECTOR containing only a
126813        ** single value. Since the parser never creates such a vector, some
126814        ** of the subroutines do not handle this case.  */
126815        if( pLhs->nExpr==1 ){
126816          pX->pLeft = pLhs->a[0].pExpr;
126817        }else{
126818          pLeft->x.pList = pLhs;
126819          aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq);
126820          testcase( aiMap==0 );
126821        }
126822        pSelect->pEList = pRhs;
126823        db->dbOptFlags |= SQLITE_QueryFlattener;
126824        eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap);
126825        db->dbOptFlags = savedDbOptFlags;
126826        testcase( aiMap!=0 && aiMap[0]!=0 );
126827        pSelect->pEList = pOrigRhs;
126828        pLeft->x.pList = pOrigLhs;
126829        pX->pLeft = pLeft;
126830      }
126831      sqlite3ExprListDelete(pParse->db, pLhs);
126832      sqlite3ExprListDelete(pParse->db, pRhs);
126833    }
126834
126835    if( eType==IN_INDEX_INDEX_DESC ){
126836      testcase( bRev );
126837      bRev = !bRev;
126838    }
126839    iTab = pX->iTable;
126840    sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
126841    VdbeCoverageIf(v, bRev);
126842    VdbeCoverageIf(v, !bRev);
126843    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
126844
126845    pLoop->wsFlags |= WHERE_IN_ABLE;
126846    if( pLevel->u.in.nIn==0 ){
126847      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
126848    }
126849
126850    i = pLevel->u.in.nIn;
126851    pLevel->u.in.nIn += nEq;
126852    pLevel->u.in.aInLoop =
126853       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
126854                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
126855    pIn = pLevel->u.in.aInLoop;
126856    if( pIn ){
126857      int iMap = 0;               /* Index in aiMap[] */
126858      pIn += i;
126859      for(i=iEq;i<pLoop->nLTerm; i++){
126860        if( pLoop->aLTerm[i]->pExpr==pX ){
126861          int iOut = iReg + i - iEq;
126862          if( eType==IN_INDEX_ROWID ){
126863            testcase( nEq>1 );  /* Happens with a UNIQUE index on ROWID */
126864            pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
126865          }else{
126866            int iCol = aiMap ? aiMap[iMap++] : 0;
126867            pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
126868          }
126869          sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
126870          if( i==iEq ){
126871            pIn->iCur = iTab;
126872            pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
126873          }else{
126874            pIn->eEndLoopOp = OP_Noop;
126875          }
126876          pIn++;
126877        }
126878      }
126879    }else{
126880      pLevel->u.in.nIn = 0;
126881    }
126882    sqlite3DbFree(pParse->db, aiMap);
126883#endif
126884  }
126885  disableTerm(pLevel, pTerm);
126886  return iReg;
126887}
126888
126889/*
126890** Generate code that will evaluate all == and IN constraints for an
126891** index scan.
126892**
126893** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
126894** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
126895** The index has as many as three equality constraints, but in this
126896** example, the third "c" value is an inequality.  So only two
126897** constraints are coded.  This routine will generate code to evaluate
126898** a==5 and b IN (1,2,3).  The current values for a and b will be stored
126899** in consecutive registers and the index of the first register is returned.
126900**
126901** In the example above nEq==2.  But this subroutine works for any value
126902** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
126903** The only thing it does is allocate the pLevel->iMem memory cell and
126904** compute the affinity string.
126905**
126906** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
126907** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
126908** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
126909** occurs after the nEq quality constraints.
126910**
126911** This routine allocates a range of nEq+nExtraReg memory cells and returns
126912** the index of the first memory cell in that range. The code that
126913** calls this routine will use that memory range to store keys for
126914** start and termination conditions of the loop.
126915** key value of the loop.  If one or more IN operators appear, then
126916** this routine allocates an additional nEq memory cells for internal
126917** use.
126918**
126919** Before returning, *pzAff is set to point to a buffer containing a
126920** copy of the column affinity string of the index allocated using
126921** sqlite3DbMalloc(). Except, entries in the copy of the string associated
126922** with equality constraints that use BLOB or NONE affinity are set to
126923** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
126924**
126925**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
126926**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
126927**
126928** In the example above, the index on t1(a) has TEXT affinity. But since
126929** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
126930** no conversion should be attempted before using a t2.b value as part of
126931** a key to search the index. Hence the first byte in the returned affinity
126932** string in this example would be set to SQLITE_AFF_BLOB.
126933*/
126934static int codeAllEqualityTerms(
126935  Parse *pParse,        /* Parsing context */
126936  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
126937  int bRev,             /* Reverse the order of IN operators */
126938  int nExtraReg,        /* Number of extra registers to allocate */
126939  char **pzAff          /* OUT: Set to point to affinity string */
126940){
126941  u16 nEq;                      /* The number of == or IN constraints to code */
126942  u16 nSkip;                    /* Number of left-most columns to skip */
126943  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
126944  Index *pIdx;                  /* The index being used for this loop */
126945  WhereTerm *pTerm;             /* A single constraint term */
126946  WhereLoop *pLoop;             /* The WhereLoop object */
126947  int j;                        /* Loop counter */
126948  int regBase;                  /* Base register */
126949  int nReg;                     /* Number of registers to allocate */
126950  char *zAff;                   /* Affinity string to return */
126951
126952  /* This module is only called on query plans that use an index. */
126953  pLoop = pLevel->pWLoop;
126954  assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
126955  nEq = pLoop->u.btree.nEq;
126956  nSkip = pLoop->nSkip;
126957  pIdx = pLoop->u.btree.pIndex;
126958  assert( pIdx!=0 );
126959
126960  /* Figure out how many memory cells we will need then allocate them.
126961  */
126962  regBase = pParse->nMem + 1;
126963  nReg = pLoop->u.btree.nEq + nExtraReg;
126964  pParse->nMem += nReg;
126965
126966  zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
126967  assert( zAff!=0 || pParse->db->mallocFailed );
126968
126969  if( nSkip ){
126970    int iIdxCur = pLevel->iIdxCur;
126971    sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
126972    VdbeCoverageIf(v, bRev==0);
126973    VdbeCoverageIf(v, bRev!=0);
126974    VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
126975    j = sqlite3VdbeAddOp0(v, OP_Goto);
126976    pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
126977                            iIdxCur, 0, regBase, nSkip);
126978    VdbeCoverageIf(v, bRev==0);
126979    VdbeCoverageIf(v, bRev!=0);
126980    sqlite3VdbeJumpHere(v, j);
126981    for(j=0; j<nSkip; j++){
126982      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
126983      testcase( pIdx->aiColumn[j]==XN_EXPR );
126984      VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
126985    }
126986  }
126987
126988  /* Evaluate the equality constraints
126989  */
126990  assert( zAff==0 || (int)strlen(zAff)>=nEq );
126991  for(j=nSkip; j<nEq; j++){
126992    int r1;
126993    pTerm = pLoop->aLTerm[j];
126994    assert( pTerm!=0 );
126995    /* The following testcase is true for indices with redundant columns.
126996    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
126997    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
126998    testcase( pTerm->wtFlags & TERM_VIRTUAL );
126999    r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
127000    if( r1!=regBase+j ){
127001      if( nReg==1 ){
127002        sqlite3ReleaseTempReg(pParse, regBase);
127003        regBase = r1;
127004      }else{
127005        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
127006      }
127007    }
127008    if( pTerm->eOperator & WO_IN ){
127009      if( pTerm->pExpr->flags & EP_xIsSelect ){
127010        /* No affinity ever needs to be (or should be) applied to a value
127011        ** from the RHS of an "? IN (SELECT ...)" expression. The
127012        ** sqlite3FindInIndex() routine has already ensured that the
127013        ** affinity of the comparison has been applied to the value.  */
127014        if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
127015      }
127016    }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
127017      Expr *pRight = pTerm->pExpr->pRight;
127018      if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
127019        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
127020        VdbeCoverage(v);
127021      }
127022      if( zAff ){
127023        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
127024          zAff[j] = SQLITE_AFF_BLOB;
127025        }
127026        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
127027          zAff[j] = SQLITE_AFF_BLOB;
127028        }
127029      }
127030    }
127031  }
127032  *pzAff = zAff;
127033  return regBase;
127034}
127035
127036#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
127037/*
127038** If the most recently coded instruction is a constant range constraint
127039** (a string literal) that originated from the LIKE optimization, then
127040** set P3 and P5 on the OP_String opcode so that the string will be cast
127041** to a BLOB at appropriate times.
127042**
127043** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
127044** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
127045** scan loop run twice, once for strings and a second time for BLOBs.
127046** The OP_String opcodes on the second pass convert the upper and lower
127047** bound string constants to blobs.  This routine makes the necessary changes
127048** to the OP_String opcodes for that to happen.
127049**
127050** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
127051** only the one pass through the string space is required, so this routine
127052** becomes a no-op.
127053*/
127054static void whereLikeOptimizationStringFixup(
127055  Vdbe *v,                /* prepared statement under construction */
127056  WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
127057  WhereTerm *pTerm        /* The upper or lower bound just coded */
127058){
127059  if( pTerm->wtFlags & TERM_LIKEOPT ){
127060    VdbeOp *pOp;
127061    assert( pLevel->iLikeRepCntr>0 );
127062    pOp = sqlite3VdbeGetOp(v, -1);
127063    assert( pOp!=0 );
127064    assert( pOp->opcode==OP_String8
127065            || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
127066    pOp->p3 = (int)(pLevel->iLikeRepCntr>>1);  /* Register holding counter */
127067    pOp->p5 = (u8)(pLevel->iLikeRepCntr&1);    /* ASC or DESC */
127068  }
127069}
127070#else
127071# define whereLikeOptimizationStringFixup(A,B,C)
127072#endif
127073
127074#ifdef SQLITE_ENABLE_CURSOR_HINTS
127075/*
127076** Information is passed from codeCursorHint() down to individual nodes of
127077** the expression tree (by sqlite3WalkExpr()) using an instance of this
127078** structure.
127079*/
127080struct CCurHint {
127081  int iTabCur;    /* Cursor for the main table */
127082  int iIdxCur;    /* Cursor for the index, if pIdx!=0.  Unused otherwise */
127083  Index *pIdx;    /* The index used to access the table */
127084};
127085
127086/*
127087** This function is called for every node of an expression that is a candidate
127088** for a cursor hint on an index cursor.  For TK_COLUMN nodes that reference
127089** the table CCurHint.iTabCur, verify that the same column can be
127090** accessed through the index.  If it cannot, then set pWalker->eCode to 1.
127091*/
127092static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
127093  struct CCurHint *pHint = pWalker->u.pCCurHint;
127094  assert( pHint->pIdx!=0 );
127095  if( pExpr->op==TK_COLUMN
127096   && pExpr->iTable==pHint->iTabCur
127097   && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
127098  ){
127099    pWalker->eCode = 1;
127100  }
127101  return WRC_Continue;
127102}
127103
127104/*
127105** Test whether or not expression pExpr, which was part of a WHERE clause,
127106** should be included in the cursor-hint for a table that is on the rhs
127107** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
127108** expression is not suitable.
127109**
127110** An expression is unsuitable if it might evaluate to non NULL even if
127111** a TK_COLUMN node that does affect the value of the expression is set
127112** to NULL. For example:
127113**
127114**   col IS NULL
127115**   col IS NOT NULL
127116**   coalesce(col, 1)
127117**   CASE WHEN col THEN 0 ELSE 1 END
127118*/
127119static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
127120  if( pExpr->op==TK_IS
127121   || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
127122   || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
127123  ){
127124    pWalker->eCode = 1;
127125  }else if( pExpr->op==TK_FUNCTION ){
127126    int d1;
127127    char d2[3];
127128    if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
127129      pWalker->eCode = 1;
127130    }
127131  }
127132
127133  return WRC_Continue;
127134}
127135
127136
127137/*
127138** This function is called on every node of an expression tree used as an
127139** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
127140** that accesses any table other than the one identified by
127141** CCurHint.iTabCur, then do the following:
127142**
127143**   1) allocate a register and code an OP_Column instruction to read
127144**      the specified column into the new register, and
127145**
127146**   2) transform the expression node to a TK_REGISTER node that reads
127147**      from the newly populated register.
127148**
127149** Also, if the node is a TK_COLUMN that does access the table idenified
127150** by pCCurHint.iTabCur, and an index is being used (which we will
127151** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
127152** an access of the index rather than the original table.
127153*/
127154static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
127155  int rc = WRC_Continue;
127156  struct CCurHint *pHint = pWalker->u.pCCurHint;
127157  if( pExpr->op==TK_COLUMN ){
127158    if( pExpr->iTable!=pHint->iTabCur ){
127159      Vdbe *v = pWalker->pParse->pVdbe;
127160      int reg = ++pWalker->pParse->nMem;   /* Register for column value */
127161      sqlite3ExprCodeGetColumnOfTable(
127162          v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
127163      );
127164      pExpr->op = TK_REGISTER;
127165      pExpr->iTable = reg;
127166    }else if( pHint->pIdx!=0 ){
127167      pExpr->iTable = pHint->iIdxCur;
127168      pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
127169      assert( pExpr->iColumn>=0 );
127170    }
127171  }else if( pExpr->op==TK_AGG_FUNCTION ){
127172    /* An aggregate function in the WHERE clause of a query means this must
127173    ** be a correlated sub-query, and expression pExpr is an aggregate from
127174    ** the parent context. Do not walk the function arguments in this case.
127175    **
127176    ** todo: It should be possible to replace this node with a TK_REGISTER
127177    ** expression, as the result of the expression must be stored in a
127178    ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
127179    rc = WRC_Prune;
127180  }
127181  return rc;
127182}
127183
127184/*
127185** Insert an OP_CursorHint instruction if it is appropriate to do so.
127186*/
127187static void codeCursorHint(
127188  struct SrcList_item *pTabItem,  /* FROM clause item */
127189  WhereInfo *pWInfo,    /* The where clause */
127190  WhereLevel *pLevel,   /* Which loop to provide hints for */
127191  WhereTerm *pEndRange  /* Hint this end-of-scan boundary term if not NULL */
127192){
127193  Parse *pParse = pWInfo->pParse;
127194  sqlite3 *db = pParse->db;
127195  Vdbe *v = pParse->pVdbe;
127196  Expr *pExpr = 0;
127197  WhereLoop *pLoop = pLevel->pWLoop;
127198  int iCur;
127199  WhereClause *pWC;
127200  WhereTerm *pTerm;
127201  int i, j;
127202  struct CCurHint sHint;
127203  Walker sWalker;
127204
127205  if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
127206  iCur = pLevel->iTabCur;
127207  assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
127208  sHint.iTabCur = iCur;
127209  sHint.iIdxCur = pLevel->iIdxCur;
127210  sHint.pIdx = pLoop->u.btree.pIndex;
127211  memset(&sWalker, 0, sizeof(sWalker));
127212  sWalker.pParse = pParse;
127213  sWalker.u.pCCurHint = &sHint;
127214  pWC = &pWInfo->sWC;
127215  for(i=0; i<pWC->nTerm; i++){
127216    pTerm = &pWC->a[i];
127217    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
127218    if( pTerm->prereqAll & pLevel->notReady ) continue;
127219
127220    /* Any terms specified as part of the ON(...) clause for any LEFT
127221    ** JOIN for which the current table is not the rhs are omitted
127222    ** from the cursor-hint.
127223    **
127224    ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
127225    ** that were specified as part of the WHERE clause must be excluded.
127226    ** This is to address the following:
127227    **
127228    **   SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
127229    **
127230    ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
127231    ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
127232    ** pushed down to the cursor, this row is filtered out, causing
127233    ** SQLite to synthesize a row of NULL values. Which does match the
127234    ** WHERE clause, and so the query returns a row. Which is incorrect.
127235    **
127236    ** For the same reason, WHERE terms such as:
127237    **
127238    **   WHERE 1 = (t2.c IS NULL)
127239    **
127240    ** are also excluded. See codeCursorHintIsOrFunction() for details.
127241    */
127242    if( pTabItem->fg.jointype & JT_LEFT ){
127243      Expr *pExpr = pTerm->pExpr;
127244      if( !ExprHasProperty(pExpr, EP_FromJoin)
127245       || pExpr->iRightJoinTable!=pTabItem->iCursor
127246      ){
127247        sWalker.eCode = 0;
127248        sWalker.xExprCallback = codeCursorHintIsOrFunction;
127249        sqlite3WalkExpr(&sWalker, pTerm->pExpr);
127250        if( sWalker.eCode ) continue;
127251      }
127252    }else{
127253      if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
127254    }
127255
127256    /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
127257    ** the cursor.  These terms are not needed as hints for a pure range
127258    ** scan (that has no == terms) so omit them. */
127259    if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
127260      for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
127261      if( j<pLoop->nLTerm ) continue;
127262    }
127263
127264    /* No subqueries or non-deterministic functions allowed */
127265    if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
127266
127267    /* For an index scan, make sure referenced columns are actually in
127268    ** the index. */
127269    if( sHint.pIdx!=0 ){
127270      sWalker.eCode = 0;
127271      sWalker.xExprCallback = codeCursorHintCheckExpr;
127272      sqlite3WalkExpr(&sWalker, pTerm->pExpr);
127273      if( sWalker.eCode ) continue;
127274    }
127275
127276    /* If we survive all prior tests, that means this term is worth hinting */
127277    pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
127278  }
127279  if( pExpr!=0 ){
127280    sWalker.xExprCallback = codeCursorHintFixExpr;
127281    sqlite3WalkExpr(&sWalker, pExpr);
127282    sqlite3VdbeAddOp4(v, OP_CursorHint,
127283                      (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
127284                      (const char*)pExpr, P4_EXPR);
127285  }
127286}
127287#else
127288# define codeCursorHint(A,B,C,D)  /* No-op */
127289#endif /* SQLITE_ENABLE_CURSOR_HINTS */
127290
127291/*
127292** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
127293** a rowid value just read from cursor iIdxCur, open on index pIdx. This
127294** function generates code to do a deferred seek of cursor iCur to the
127295** rowid stored in register iRowid.
127296**
127297** Normally, this is just:
127298**
127299**   OP_Seek $iCur $iRowid
127300**
127301** However, if the scan currently being coded is a branch of an OR-loop and
127302** the statement currently being coded is a SELECT, then P3 of the OP_Seek
127303** is set to iIdxCur and P4 is set to point to an array of integers
127304** containing one entry for each column of the table cursor iCur is open
127305** on. For each table column, if the column is the i'th column of the
127306** index, then the corresponding array entry is set to (i+1). If the column
127307** does not appear in the index at all, the array entry is set to 0.
127308*/
127309static void codeDeferredSeek(
127310  WhereInfo *pWInfo,              /* Where clause context */
127311  Index *pIdx,                    /* Index scan is using */
127312  int iCur,                       /* Cursor for IPK b-tree */
127313  int iIdxCur                     /* Index cursor */
127314){
127315  Parse *pParse = pWInfo->pParse; /* Parse context */
127316  Vdbe *v = pParse->pVdbe;        /* Vdbe to generate code within */
127317
127318  assert( iIdxCur>0 );
127319  assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
127320
127321  sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur);
127322  if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
127323   && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
127324  ){
127325    int i;
127326    Table *pTab = pIdx->pTable;
127327    int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
127328    if( ai ){
127329      ai[0] = pTab->nCol;
127330      for(i=0; i<pIdx->nColumn-1; i++){
127331        assert( pIdx->aiColumn[i]<pTab->nCol );
127332        if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
127333      }
127334      sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
127335    }
127336  }
127337}
127338
127339/*
127340** If the expression passed as the second argument is a vector, generate
127341** code to write the first nReg elements of the vector into an array
127342** of registers starting with iReg.
127343**
127344** If the expression is not a vector, then nReg must be passed 1. In
127345** this case, generate code to evaluate the expression and leave the
127346** result in register iReg.
127347*/
127348static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
127349  assert( nReg>0 );
127350  if( sqlite3ExprIsVector(p) ){
127351#ifndef SQLITE_OMIT_SUBQUERY
127352    if( (p->flags & EP_xIsSelect) ){
127353      Vdbe *v = pParse->pVdbe;
127354      int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0);
127355      sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
127356    }else
127357#endif
127358    {
127359      int i;
127360      ExprList *pList = p->x.pList;
127361      assert( nReg<=pList->nExpr );
127362      for(i=0; i<nReg; i++){
127363        sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
127364      }
127365    }
127366  }else{
127367    assert( nReg==1 );
127368    sqlite3ExprCode(pParse, p, iReg);
127369  }
127370}
127371
127372/*
127373** Generate code for the start of the iLevel-th loop in the WHERE clause
127374** implementation described by pWInfo.
127375*/
127376SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
127377  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
127378  int iLevel,          /* Which level of pWInfo->a[] should be coded */
127379  Bitmask notReady     /* Which tables are currently available */
127380){
127381  int j, k;            /* Loop counters */
127382  int iCur;            /* The VDBE cursor for the table */
127383  int addrNxt;         /* Where to jump to continue with the next IN case */
127384  int omitTable;       /* True if we use the index only */
127385  int bRev;            /* True if we need to scan in reverse order */
127386  WhereLevel *pLevel;  /* The where level to be coded */
127387  WhereLoop *pLoop;    /* The WhereLoop object being coded */
127388  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
127389  WhereTerm *pTerm;               /* A WHERE clause term */
127390  Parse *pParse;                  /* Parsing context */
127391  sqlite3 *db;                    /* Database connection */
127392  Vdbe *v;                        /* The prepared stmt under constructions */
127393  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
127394  int addrBrk;                    /* Jump here to break out of the loop */
127395  int addrHalt;                   /* addrBrk for the outermost loop */
127396  int addrCont;                   /* Jump here to continue with next cycle */
127397  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
127398  int iReleaseReg = 0;      /* Temp register to free before returning */
127399
127400  pParse = pWInfo->pParse;
127401  v = pParse->pVdbe;
127402  pWC = &pWInfo->sWC;
127403  db = pParse->db;
127404  pLevel = &pWInfo->a[iLevel];
127405  pLoop = pLevel->pWLoop;
127406  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
127407  iCur = pTabItem->iCursor;
127408  pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
127409  bRev = (pWInfo->revMask>>iLevel)&1;
127410  omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
127411           && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
127412  VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
127413
127414  /* Create labels for the "break" and "continue" instructions
127415  ** for the current loop.  Jump to addrBrk to break out of a loop.
127416  ** Jump to cont to go immediately to the next iteration of the
127417  ** loop.
127418  **
127419  ** When there is an IN operator, we also have a "addrNxt" label that
127420  ** means to continue with the next IN value combination.  When
127421  ** there are no IN operators in the constraints, the "addrNxt" label
127422  ** is the same as "addrBrk".
127423  */
127424  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
127425  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
127426
127427  /* If this is the right table of a LEFT OUTER JOIN, allocate and
127428  ** initialize a memory cell that records if this table matches any
127429  ** row of the left table of the join.
127430  */
127431  if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
127432    pLevel->iLeftJoin = ++pParse->nMem;
127433    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
127434    VdbeComment((v, "init LEFT JOIN no-match flag"));
127435  }
127436
127437  /* Compute a safe address to jump to if we discover that the table for
127438  ** this loop is empty and can never contribute content. */
127439  for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
127440  addrHalt = pWInfo->a[j].addrBrk;
127441
127442  /* Special case of a FROM clause subquery implemented as a co-routine */
127443  if( pTabItem->fg.viaCoroutine ){
127444    int regYield = pTabItem->regReturn;
127445    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
127446    pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
127447    VdbeCoverage(v);
127448    VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
127449    pLevel->op = OP_Goto;
127450  }else
127451
127452#ifndef SQLITE_OMIT_VIRTUALTABLE
127453  if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
127454    /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
127455    **          to access the data.
127456    */
127457    int iReg;   /* P3 Value for OP_VFilter */
127458    int addrNotFound;
127459    int nConstraint = pLoop->nLTerm;
127460    int iIn;    /* Counter for IN constraints */
127461
127462    sqlite3ExprCachePush(pParse);
127463    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
127464    addrNotFound = pLevel->addrBrk;
127465    for(j=0; j<nConstraint; j++){
127466      int iTarget = iReg+j+2;
127467      pTerm = pLoop->aLTerm[j];
127468      if( NEVER(pTerm==0) ) continue;
127469      if( pTerm->eOperator & WO_IN ){
127470        codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
127471        addrNotFound = pLevel->addrNxt;
127472      }else{
127473        Expr *pRight = pTerm->pExpr->pRight;
127474        codeExprOrVector(pParse, pRight, iTarget, 1);
127475      }
127476    }
127477    sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
127478    sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
127479    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
127480                      pLoop->u.vtab.idxStr,
127481                      pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
127482    VdbeCoverage(v);
127483    pLoop->u.vtab.needFree = 0;
127484    pLevel->p1 = iCur;
127485    pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
127486    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
127487    iIn = pLevel->u.in.nIn;
127488    for(j=nConstraint-1; j>=0; j--){
127489      pTerm = pLoop->aLTerm[j];
127490      if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
127491        disableTerm(pLevel, pTerm);
127492      }else if( (pTerm->eOperator & WO_IN)!=0 ){
127493        Expr *pCompare;  /* The comparison operator */
127494        Expr *pRight;    /* RHS of the comparison */
127495        VdbeOp *pOp;     /* Opcode to access the value of the IN constraint */
127496
127497        /* Reload the constraint value into reg[iReg+j+2].  The same value
127498        ** was loaded into the same register prior to the OP_VFilter, but
127499        ** the xFilter implementation might have changed the datatype or
127500        ** encoding of the value in the register, so it *must* be reloaded. */
127501        assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
127502        if( !db->mallocFailed ){
127503          assert( iIn>0 );
127504          pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
127505          assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
127506          assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
127507          assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
127508          testcase( pOp->opcode==OP_Rowid );
127509          sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
127510        }
127511
127512        /* Generate code that will continue to the next row if
127513        ** the IN constraint is not satisfied */
127514        pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
127515        assert( pCompare!=0 || db->mallocFailed );
127516        if( pCompare ){
127517          pCompare->pLeft = pTerm->pExpr->pLeft;
127518          pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
127519          if( pRight ){
127520            pRight->iTable = iReg+j+2;
127521            sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
127522          }
127523          pCompare->pLeft = 0;
127524          sqlite3ExprDelete(db, pCompare);
127525        }
127526      }
127527    }
127528    /* These registers need to be preserved in case there is an IN operator
127529    ** loop.  So we could deallocate the registers here (and potentially
127530    ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0.  But it seems
127531    ** simpler and safer to simply not reuse the registers.
127532    **
127533    **    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
127534    */
127535    sqlite3ExprCachePop(pParse);
127536  }else
127537#endif /* SQLITE_OMIT_VIRTUALTABLE */
127538
127539  if( (pLoop->wsFlags & WHERE_IPK)!=0
127540   && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
127541  ){
127542    /* Case 2:  We can directly reference a single row using an
127543    **          equality comparison against the ROWID field.  Or
127544    **          we reference multiple rows using a "rowid IN (...)"
127545    **          construct.
127546    */
127547    assert( pLoop->u.btree.nEq==1 );
127548    pTerm = pLoop->aLTerm[0];
127549    assert( pTerm!=0 );
127550    assert( pTerm->pExpr!=0 );
127551    assert( omitTable==0 );
127552    testcase( pTerm->wtFlags & TERM_VIRTUAL );
127553    iReleaseReg = ++pParse->nMem;
127554    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
127555    if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
127556    addrNxt = pLevel->addrNxt;
127557    sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
127558    VdbeCoverage(v);
127559    sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
127560    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
127561    VdbeComment((v, "pk"));
127562    pLevel->op = OP_Noop;
127563  }else if( (pLoop->wsFlags & WHERE_IPK)!=0
127564         && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
127565  ){
127566    /* Case 3:  We have an inequality comparison against the ROWID field.
127567    */
127568    int testOp = OP_Noop;
127569    int start;
127570    int memEndValue = 0;
127571    WhereTerm *pStart, *pEnd;
127572
127573    assert( omitTable==0 );
127574    j = 0;
127575    pStart = pEnd = 0;
127576    if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
127577    if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
127578    assert( pStart!=0 || pEnd!=0 );
127579    if( bRev ){
127580      pTerm = pStart;
127581      pStart = pEnd;
127582      pEnd = pTerm;
127583    }
127584    codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
127585    if( pStart ){
127586      Expr *pX;             /* The expression that defines the start bound */
127587      int r1, rTemp;        /* Registers for holding the start boundary */
127588      int op;               /* Cursor seek operation */
127589
127590      /* The following constant maps TK_xx codes into corresponding
127591      ** seek opcodes.  It depends on a particular ordering of TK_xx
127592      */
127593      const u8 aMoveOp[] = {
127594           /* TK_GT */  OP_SeekGT,
127595           /* TK_LE */  OP_SeekLE,
127596           /* TK_LT */  OP_SeekLT,
127597           /* TK_GE */  OP_SeekGE
127598      };
127599      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
127600      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
127601      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
127602
127603      assert( (pStart->wtFlags & TERM_VNULL)==0 );
127604      testcase( pStart->wtFlags & TERM_VIRTUAL );
127605      pX = pStart->pExpr;
127606      assert( pX!=0 );
127607      testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
127608      if( sqlite3ExprIsVector(pX->pRight) ){
127609        r1 = rTemp = sqlite3GetTempReg(pParse);
127610        codeExprOrVector(pParse, pX->pRight, r1, 1);
127611        op = aMoveOp[(pX->op - TK_GT) | 0x0001];
127612      }else{
127613        r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
127614        disableTerm(pLevel, pStart);
127615        op = aMoveOp[(pX->op - TK_GT)];
127616      }
127617      sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
127618      VdbeComment((v, "pk"));
127619      VdbeCoverageIf(v, pX->op==TK_GT);
127620      VdbeCoverageIf(v, pX->op==TK_LE);
127621      VdbeCoverageIf(v, pX->op==TK_LT);
127622      VdbeCoverageIf(v, pX->op==TK_GE);
127623      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
127624      sqlite3ReleaseTempReg(pParse, rTemp);
127625    }else{
127626      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
127627      VdbeCoverageIf(v, bRev==0);
127628      VdbeCoverageIf(v, bRev!=0);
127629    }
127630    if( pEnd ){
127631      Expr *pX;
127632      pX = pEnd->pExpr;
127633      assert( pX!=0 );
127634      assert( (pEnd->wtFlags & TERM_VNULL)==0 );
127635      testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
127636      testcase( pEnd->wtFlags & TERM_VIRTUAL );
127637      memEndValue = ++pParse->nMem;
127638      codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
127639      if( 0==sqlite3ExprIsVector(pX->pRight)
127640       && (pX->op==TK_LT || pX->op==TK_GT)
127641      ){
127642        testOp = bRev ? OP_Le : OP_Ge;
127643      }else{
127644        testOp = bRev ? OP_Lt : OP_Gt;
127645      }
127646      if( 0==sqlite3ExprIsVector(pX->pRight) ){
127647        disableTerm(pLevel, pEnd);
127648      }
127649    }
127650    start = sqlite3VdbeCurrentAddr(v);
127651    pLevel->op = bRev ? OP_Prev : OP_Next;
127652    pLevel->p1 = iCur;
127653    pLevel->p2 = start;
127654    assert( pLevel->p5==0 );
127655    if( testOp!=OP_Noop ){
127656      iRowidReg = ++pParse->nMem;
127657      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
127658      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
127659      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
127660      VdbeCoverageIf(v, testOp==OP_Le);
127661      VdbeCoverageIf(v, testOp==OP_Lt);
127662      VdbeCoverageIf(v, testOp==OP_Ge);
127663      VdbeCoverageIf(v, testOp==OP_Gt);
127664      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
127665    }
127666  }else if( pLoop->wsFlags & WHERE_INDEXED ){
127667    /* Case 4: A scan using an index.
127668    **
127669    **         The WHERE clause may contain zero or more equality
127670    **         terms ("==" or "IN" operators) that refer to the N
127671    **         left-most columns of the index. It may also contain
127672    **         inequality constraints (>, <, >= or <=) on the indexed
127673    **         column that immediately follows the N equalities. Only
127674    **         the right-most column can be an inequality - the rest must
127675    **         use the "==" and "IN" operators. For example, if the
127676    **         index is on (x,y,z), then the following clauses are all
127677    **         optimized:
127678    **
127679    **            x=5
127680    **            x=5 AND y=10
127681    **            x=5 AND y<10
127682    **            x=5 AND y>5 AND y<10
127683    **            x=5 AND y=5 AND z<=10
127684    **
127685    **         The z<10 term of the following cannot be used, only
127686    **         the x=5 term:
127687    **
127688    **            x=5 AND z<10
127689    **
127690    **         N may be zero if there are inequality constraints.
127691    **         If there are no inequality constraints, then N is at
127692    **         least one.
127693    **
127694    **         This case is also used when there are no WHERE clause
127695    **         constraints but an index is selected anyway, in order
127696    **         to force the output order to conform to an ORDER BY.
127697    */
127698    static const u8 aStartOp[] = {
127699      0,
127700      0,
127701      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
127702      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
127703      OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
127704      OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
127705      OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
127706      OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
127707    };
127708    static const u8 aEndOp[] = {
127709      OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
127710      OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
127711      OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
127712      OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
127713    };
127714    u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
127715    u16 nBtm = pLoop->u.btree.nBtm;   /* Length of BTM vector */
127716    u16 nTop = pLoop->u.btree.nTop;   /* Length of TOP vector */
127717    int regBase;                 /* Base register holding constraint values */
127718    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
127719    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
127720    int startEq;                 /* True if range start uses ==, >= or <= */
127721    int endEq;                   /* True if range end uses ==, >= or <= */
127722    int start_constraints;       /* Start of range is constrained */
127723    int nConstraint;             /* Number of constraint terms */
127724    Index *pIdx;                 /* The index we will be using */
127725    int iIdxCur;                 /* The VDBE cursor for the index */
127726    int nExtraReg = 0;           /* Number of extra registers needed */
127727    int op;                      /* Instruction opcode */
127728    char *zStartAff;             /* Affinity for start of range constraint */
127729    char *zEndAff = 0;           /* Affinity for end of range constraint */
127730    u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
127731    u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
127732
127733    pIdx = pLoop->u.btree.pIndex;
127734    iIdxCur = pLevel->iIdxCur;
127735    assert( nEq>=pLoop->nSkip );
127736
127737    /* If this loop satisfies a sort order (pOrderBy) request that
127738    ** was passed to this function to implement a "SELECT min(x) ..."
127739    ** query, then the caller will only allow the loop to run for
127740    ** a single iteration. This means that the first row returned
127741    ** should not have a NULL value stored in 'x'. If column 'x' is
127742    ** the first one after the nEq equality constraints in the index,
127743    ** this requires some special handling.
127744    */
127745    assert( pWInfo->pOrderBy==0
127746         || pWInfo->pOrderBy->nExpr==1
127747         || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
127748    if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
127749     && pWInfo->nOBSat>0
127750     && (pIdx->nKeyCol>nEq)
127751    ){
127752      assert( pLoop->nSkip==0 );
127753      bSeekPastNull = 1;
127754      nExtraReg = 1;
127755    }
127756
127757    /* Find any inequality constraint terms for the start and end
127758    ** of the range.
127759    */
127760    j = nEq;
127761    if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
127762      pRangeStart = pLoop->aLTerm[j++];
127763      nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
127764      /* Like optimization range constraints always occur in pairs */
127765      assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
127766              (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
127767    }
127768    if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
127769      pRangeEnd = pLoop->aLTerm[j++];
127770      nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
127771#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
127772      if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
127773        assert( pRangeStart!=0 );                     /* LIKE opt constraints */
127774        assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
127775        pLevel->iLikeRepCntr = (u32)++pParse->nMem;
127776        sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
127777        VdbeComment((v, "LIKE loop counter"));
127778        pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
127779        /* iLikeRepCntr actually stores 2x the counter register number.  The
127780        ** bottom bit indicates whether the search order is ASC or DESC. */
127781        testcase( bRev );
127782        testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
127783        assert( (bRev & ~1)==0 );
127784        pLevel->iLikeRepCntr <<=1;
127785        pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
127786      }
127787#endif
127788      if( pRangeStart==0 ){
127789        j = pIdx->aiColumn[nEq];
127790        if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
127791          bSeekPastNull = 1;
127792        }
127793      }
127794    }
127795    assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
127796
127797    /* If we are doing a reverse order scan on an ascending index, or
127798    ** a forward order scan on a descending index, interchange the
127799    ** start and end terms (pRangeStart and pRangeEnd).
127800    */
127801    if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
127802     || (bRev && pIdx->nKeyCol==nEq)
127803    ){
127804      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
127805      SWAP(u8, bSeekPastNull, bStopAtNull);
127806      SWAP(u8, nBtm, nTop);
127807    }
127808
127809    /* Generate code to evaluate all constraint terms using == or IN
127810    ** and store the values of those terms in an array of registers
127811    ** starting at regBase.
127812    */
127813    codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
127814    regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
127815    assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
127816    if( zStartAff && nTop ){
127817      zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
127818    }
127819    addrNxt = pLevel->addrNxt;
127820
127821    testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
127822    testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
127823    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
127824    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
127825    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
127826    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
127827    start_constraints = pRangeStart || nEq>0;
127828
127829    /* Seek the index cursor to the start of the range. */
127830    nConstraint = nEq;
127831    if( pRangeStart ){
127832      Expr *pRight = pRangeStart->pExpr->pRight;
127833      codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
127834      whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
127835      if( (pRangeStart->wtFlags & TERM_VNULL)==0
127836       && sqlite3ExprCanBeNull(pRight)
127837      ){
127838        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
127839        VdbeCoverage(v);
127840      }
127841      if( zStartAff ){
127842        updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
127843      }
127844      nConstraint += nBtm;
127845      testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
127846      if( sqlite3ExprIsVector(pRight)==0 ){
127847        disableTerm(pLevel, pRangeStart);
127848      }else{
127849        startEq = 1;
127850      }
127851      bSeekPastNull = 0;
127852    }else if( bSeekPastNull ){
127853      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
127854      nConstraint++;
127855      startEq = 0;
127856      start_constraints = 1;
127857    }
127858    codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
127859    if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
127860      /* The skip-scan logic inside the call to codeAllEqualityConstraints()
127861      ** above has already left the cursor sitting on the correct row,
127862      ** so no further seeking is needed */
127863    }else{
127864      op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
127865      assert( op!=0 );
127866      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
127867      VdbeCoverage(v);
127868      VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
127869      VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
127870      VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
127871      VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
127872      VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
127873      VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
127874    }
127875
127876    /* Load the value for the inequality constraint at the end of the
127877    ** range (if any).
127878    */
127879    nConstraint = nEq;
127880    if( pRangeEnd ){
127881      Expr *pRight = pRangeEnd->pExpr->pRight;
127882      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
127883      codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
127884      whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
127885      if( (pRangeEnd->wtFlags & TERM_VNULL)==0
127886       && sqlite3ExprCanBeNull(pRight)
127887      ){
127888        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
127889        VdbeCoverage(v);
127890      }
127891      if( zEndAff ){
127892        updateRangeAffinityStr(pRight, nTop, zEndAff);
127893        codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
127894      }else{
127895        assert( pParse->db->mallocFailed );
127896      }
127897      nConstraint += nTop;
127898      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
127899
127900      if( sqlite3ExprIsVector(pRight)==0 ){
127901        disableTerm(pLevel, pRangeEnd);
127902      }else{
127903        endEq = 1;
127904      }
127905    }else if( bStopAtNull ){
127906      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
127907      endEq = 0;
127908      nConstraint++;
127909    }
127910    sqlite3DbFree(db, zStartAff);
127911    sqlite3DbFree(db, zEndAff);
127912
127913    /* Top of the loop body */
127914    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
127915
127916    /* Check if the index cursor is past the end of the range. */
127917    if( nConstraint ){
127918      op = aEndOp[bRev*2 + endEq];
127919      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
127920      testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
127921      testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
127922      testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
127923      testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
127924    }
127925
127926    /* Seek the table cursor, if required */
127927    if( omitTable ){
127928      /* pIdx is a covering index.  No need to access the main table. */
127929    }else if( HasRowid(pIdx->pTable) ){
127930      if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
127931          (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)
127932       && (pWInfo->eOnePass==ONEPASS_SINGLE)
127933      )){
127934        iRowidReg = ++pParse->nMem;
127935        sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
127936        sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
127937        sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
127938        VdbeCoverage(v);
127939      }else{
127940        codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
127941      }
127942    }else if( iCur!=iIdxCur ){
127943      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
127944      iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
127945      for(j=0; j<pPk->nKeyCol; j++){
127946        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
127947        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
127948      }
127949      sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
127950                           iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
127951    }
127952
127953    /* Record the instruction used to terminate the loop. */
127954    if( pLoop->wsFlags & WHERE_ONEROW ){
127955      pLevel->op = OP_Noop;
127956    }else if( bRev ){
127957      pLevel->op = OP_Prev;
127958    }else{
127959      pLevel->op = OP_Next;
127960    }
127961    pLevel->p1 = iIdxCur;
127962    pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
127963    if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
127964      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
127965    }else{
127966      assert( pLevel->p5==0 );
127967    }
127968  }else
127969
127970#ifndef SQLITE_OMIT_OR_OPTIMIZATION
127971  if( pLoop->wsFlags & WHERE_MULTI_OR ){
127972    /* Case 5:  Two or more separately indexed terms connected by OR
127973    **
127974    ** Example:
127975    **
127976    **   CREATE TABLE t1(a,b,c,d);
127977    **   CREATE INDEX i1 ON t1(a);
127978    **   CREATE INDEX i2 ON t1(b);
127979    **   CREATE INDEX i3 ON t1(c);
127980    **
127981    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
127982    **
127983    ** In the example, there are three indexed terms connected by OR.
127984    ** The top of the loop looks like this:
127985    **
127986    **          Null       1                # Zero the rowset in reg 1
127987    **
127988    ** Then, for each indexed term, the following. The arguments to
127989    ** RowSetTest are such that the rowid of the current row is inserted
127990    ** into the RowSet. If it is already present, control skips the
127991    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
127992    **
127993    **        sqlite3WhereBegin(<term>)
127994    **          RowSetTest                  # Insert rowid into rowset
127995    **          Gosub      2 A
127996    **        sqlite3WhereEnd()
127997    **
127998    ** Following the above, code to terminate the loop. Label A, the target
127999    ** of the Gosub above, jumps to the instruction right after the Goto.
128000    **
128001    **          Null       1                # Zero the rowset in reg 1
128002    **          Goto       B                # The loop is finished.
128003    **
128004    **       A: <loop body>                 # Return data, whatever.
128005    **
128006    **          Return     2                # Jump back to the Gosub
128007    **
128008    **       B: <after the loop>
128009    **
128010    ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
128011    ** use an ephemeral index instead of a RowSet to record the primary
128012    ** keys of the rows we have already seen.
128013    **
128014    */
128015    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
128016    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
128017    Index *pCov = 0;             /* Potential covering index (or NULL) */
128018    int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
128019
128020    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
128021    int regRowset = 0;                        /* Register for RowSet object */
128022    int regRowid = 0;                         /* Register holding rowid */
128023    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
128024    int iRetInit;                             /* Address of regReturn init */
128025    int untestedTerms = 0;             /* Some terms not completely tested */
128026    int ii;                            /* Loop counter */
128027    u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
128028    Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
128029    Table *pTab = pTabItem->pTab;
128030
128031    pTerm = pLoop->aLTerm[0];
128032    assert( pTerm!=0 );
128033    assert( pTerm->eOperator & WO_OR );
128034    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
128035    pOrWc = &pTerm->u.pOrInfo->wc;
128036    pLevel->op = OP_Return;
128037    pLevel->p1 = regReturn;
128038
128039    /* Set up a new SrcList in pOrTab containing the table being scanned
128040    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
128041    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
128042    */
128043    if( pWInfo->nLevel>1 ){
128044      int nNotReady;                 /* The number of notReady tables */
128045      struct SrcList_item *origSrc;     /* Original list of tables */
128046      nNotReady = pWInfo->nLevel - iLevel - 1;
128047      pOrTab = sqlite3StackAllocRaw(db,
128048                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
128049      if( pOrTab==0 ) return notReady;
128050      pOrTab->nAlloc = (u8)(nNotReady + 1);
128051      pOrTab->nSrc = pOrTab->nAlloc;
128052      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
128053      origSrc = pWInfo->pTabList->a;
128054      for(k=1; k<=nNotReady; k++){
128055        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
128056      }
128057    }else{
128058      pOrTab = pWInfo->pTabList;
128059    }
128060
128061    /* Initialize the rowset register to contain NULL. An SQL NULL is
128062    ** equivalent to an empty rowset.  Or, create an ephemeral index
128063    ** capable of holding primary keys in the case of a WITHOUT ROWID.
128064    **
128065    ** Also initialize regReturn to contain the address of the instruction
128066    ** immediately following the OP_Return at the bottom of the loop. This
128067    ** is required in a few obscure LEFT JOIN cases where control jumps
128068    ** over the top of the loop into the body of it. In this case the
128069    ** correct response for the end-of-loop code (the OP_Return) is to
128070    ** fall through to the next instruction, just as an OP_Next does if
128071    ** called on an uninitialized cursor.
128072    */
128073    if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
128074      if( HasRowid(pTab) ){
128075        regRowset = ++pParse->nMem;
128076        sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
128077      }else{
128078        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
128079        regRowset = pParse->nTab++;
128080        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
128081        sqlite3VdbeSetP4KeyInfo(pParse, pPk);
128082      }
128083      regRowid = ++pParse->nMem;
128084    }
128085    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
128086
128087    /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
128088    ** Then for every term xN, evaluate as the subexpression: xN AND z
128089    ** That way, terms in y that are factored into the disjunction will
128090    ** be picked up by the recursive calls to sqlite3WhereBegin() below.
128091    **
128092    ** Actually, each subexpression is converted to "xN AND w" where w is
128093    ** the "interesting" terms of z - terms that did not originate in the
128094    ** ON or USING clause of a LEFT JOIN, and terms that are usable as
128095    ** indices.
128096    **
128097    ** This optimization also only applies if the (x1 OR x2 OR ...) term
128098    ** is not contained in the ON clause of a LEFT JOIN.
128099    ** See ticket http://www.sqlite.org/src/info/f2369304e4
128100    */
128101    if( pWC->nTerm>1 ){
128102      int iTerm;
128103      for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
128104        Expr *pExpr = pWC->a[iTerm].pExpr;
128105        if( &pWC->a[iTerm] == pTerm ) continue;
128106        if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
128107        testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
128108        testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
128109        if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
128110        if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
128111        testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
128112        pExpr = sqlite3ExprDup(db, pExpr, 0);
128113        pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
128114      }
128115      if( pAndExpr ){
128116        pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr);
128117      }
128118    }
128119
128120    /* Run a separate WHERE clause for each term of the OR clause.  After
128121    ** eliminating duplicates from other WHERE clauses, the action for each
128122    ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
128123    */
128124    wctrlFlags =  WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
128125    for(ii=0; ii<pOrWc->nTerm; ii++){
128126      WhereTerm *pOrTerm = &pOrWc->a[ii];
128127      if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
128128        WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
128129        Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
128130        int jmp1 = 0;                   /* Address of jump operation */
128131        if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
128132          pAndExpr->pLeft = pOrExpr;
128133          pOrExpr = pAndExpr;
128134        }
128135        /* Loop through table entries that match term pOrTerm. */
128136        WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
128137        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
128138                                      wctrlFlags, iCovCur);
128139        assert( pSubWInfo || pParse->nErr || db->mallocFailed );
128140        if( pSubWInfo ){
128141          WhereLoop *pSubLoop;
128142          int addrExplain = sqlite3WhereExplainOneScan(
128143              pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
128144          );
128145          sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
128146
128147          /* This is the sub-WHERE clause body.  First skip over
128148          ** duplicate rows from prior sub-WHERE clauses, and record the
128149          ** rowid (or PRIMARY KEY) for the current row so that the same
128150          ** row will be skipped in subsequent sub-WHERE clauses.
128151          */
128152          if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
128153            int r;
128154            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
128155            if( HasRowid(pTab) ){
128156              r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
128157              jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
128158                                           r,iSet);
128159              VdbeCoverage(v);
128160            }else{
128161              Index *pPk = sqlite3PrimaryKeyIndex(pTab);
128162              int nPk = pPk->nKeyCol;
128163              int iPk;
128164
128165              /* Read the PK into an array of temp registers. */
128166              r = sqlite3GetTempRange(pParse, nPk);
128167              for(iPk=0; iPk<nPk; iPk++){
128168                int iCol = pPk->aiColumn[iPk];
128169                sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
128170              }
128171
128172              /* Check if the temp table already contains this key. If so,
128173              ** the row has already been included in the result set and
128174              ** can be ignored (by jumping past the Gosub below). Otherwise,
128175              ** insert the key into the temp table and proceed with processing
128176              ** the row.
128177              **
128178              ** Use some of the same optimizations as OP_RowSetTest: If iSet
128179              ** is zero, assume that the key cannot already be present in
128180              ** the temp table. And if iSet is -1, assume that there is no
128181              ** need to insert the key into the temp table, as it will never
128182              ** be tested for.  */
128183              if( iSet ){
128184                jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
128185                VdbeCoverage(v);
128186              }
128187              if( iSet>=0 ){
128188                sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
128189                sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
128190                                     r, nPk);
128191                if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
128192              }
128193
128194              /* Release the array of temp registers */
128195              sqlite3ReleaseTempRange(pParse, r, nPk);
128196            }
128197          }
128198
128199          /* Invoke the main loop body as a subroutine */
128200          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
128201
128202          /* Jump here (skipping the main loop body subroutine) if the
128203          ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
128204          if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
128205
128206          /* The pSubWInfo->untestedTerms flag means that this OR term
128207          ** contained one or more AND term from a notReady table.  The
128208          ** terms from the notReady table could not be tested and will
128209          ** need to be tested later.
128210          */
128211          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
128212
128213          /* If all of the OR-connected terms are optimized using the same
128214          ** index, and the index is opened using the same cursor number
128215          ** by each call to sqlite3WhereBegin() made by this loop, it may
128216          ** be possible to use that index as a covering index.
128217          **
128218          ** If the call to sqlite3WhereBegin() above resulted in a scan that
128219          ** uses an index, and this is either the first OR-connected term
128220          ** processed or the index is the same as that used by all previous
128221          ** terms, set pCov to the candidate covering index. Otherwise, set
128222          ** pCov to NULL to indicate that no candidate covering index will
128223          ** be available.
128224          */
128225          pSubLoop = pSubWInfo->a[0].pWLoop;
128226          assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
128227          if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
128228           && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
128229           && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
128230          ){
128231            assert( pSubWInfo->a[0].iIdxCur==iCovCur );
128232            pCov = pSubLoop->u.btree.pIndex;
128233          }else{
128234            pCov = 0;
128235          }
128236
128237          /* Finish the loop through table entries that match term pOrTerm. */
128238          sqlite3WhereEnd(pSubWInfo);
128239        }
128240      }
128241    }
128242    pLevel->u.pCovidx = pCov;
128243    if( pCov ) pLevel->iIdxCur = iCovCur;
128244    if( pAndExpr ){
128245      pAndExpr->pLeft = 0;
128246      sqlite3ExprDelete(db, pAndExpr);
128247    }
128248    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
128249    sqlite3VdbeGoto(v, pLevel->addrBrk);
128250    sqlite3VdbeResolveLabel(v, iLoopBody);
128251
128252    if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
128253    if( !untestedTerms ) disableTerm(pLevel, pTerm);
128254  }else
128255#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
128256
128257  {
128258    /* Case 6:  There is no usable index.  We must do a complete
128259    **          scan of the entire table.
128260    */
128261    static const u8 aStep[] = { OP_Next, OP_Prev };
128262    static const u8 aStart[] = { OP_Rewind, OP_Last };
128263    assert( bRev==0 || bRev==1 );
128264    if( pTabItem->fg.isRecursive ){
128265      /* Tables marked isRecursive have only a single row that is stored in
128266      ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
128267      pLevel->op = OP_Noop;
128268    }else{
128269      codeCursorHint(pTabItem, pWInfo, pLevel, 0);
128270      pLevel->op = aStep[bRev];
128271      pLevel->p1 = iCur;
128272      pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
128273      VdbeCoverageIf(v, bRev==0);
128274      VdbeCoverageIf(v, bRev!=0);
128275      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
128276    }
128277  }
128278
128279#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
128280  pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
128281#endif
128282
128283  /* Insert code to test every subexpression that can be completely
128284  ** computed using the current set of tables.
128285  */
128286  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
128287    Expr *pE;
128288    int skipLikeAddr = 0;
128289    testcase( pTerm->wtFlags & TERM_VIRTUAL );
128290    testcase( pTerm->wtFlags & TERM_CODED );
128291    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
128292    if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
128293      testcase( pWInfo->untestedTerms==0
128294               && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
128295      pWInfo->untestedTerms = 1;
128296      continue;
128297    }
128298    pE = pTerm->pExpr;
128299    assert( pE!=0 );
128300    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
128301      continue;
128302    }
128303    if( pTerm->wtFlags & TERM_LIKECOND ){
128304      /* If the TERM_LIKECOND flag is set, that means that the range search
128305      ** is sufficient to guarantee that the LIKE operator is true, so we
128306      ** can skip the call to the like(A,B) function.  But this only works
128307      ** for strings.  So do not skip the call to the function on the pass
128308      ** that compares BLOBs. */
128309#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
128310      continue;
128311#else
128312      u32 x = pLevel->iLikeRepCntr;
128313      assert( x>0 );
128314      skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1));
128315      VdbeCoverage(v);
128316#endif
128317    }
128318    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
128319    if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
128320    pTerm->wtFlags |= TERM_CODED;
128321  }
128322
128323  /* Insert code to test for implied constraints based on transitivity
128324  ** of the "==" operator.
128325  **
128326  ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
128327  ** and we are coding the t1 loop and the t2 loop has not yet coded,
128328  ** then we cannot use the "t1.a=t2.b" constraint, but we can code
128329  ** the implied "t1.a=123" constraint.
128330  */
128331  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
128332    Expr *pE, sEAlt;
128333    WhereTerm *pAlt;
128334    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
128335    if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
128336    if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
128337    if( pTerm->leftCursor!=iCur ) continue;
128338    if( pLevel->iLeftJoin ) continue;
128339    pE = pTerm->pExpr;
128340    assert( !ExprHasProperty(pE, EP_FromJoin) );
128341    assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
128342    pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
128343                    WO_EQ|WO_IN|WO_IS, 0);
128344    if( pAlt==0 ) continue;
128345    if( pAlt->wtFlags & (TERM_CODED) ) continue;
128346    testcase( pAlt->eOperator & WO_EQ );
128347    testcase( pAlt->eOperator & WO_IS );
128348    testcase( pAlt->eOperator & WO_IN );
128349    VdbeModuleComment((v, "begin transitive constraint"));
128350    sEAlt = *pAlt->pExpr;
128351    sEAlt.pLeft = pE->pLeft;
128352    sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
128353  }
128354
128355  /* For a LEFT OUTER JOIN, generate code that will record the fact that
128356  ** at least one row of the right table has matched the left table.
128357  */
128358  if( pLevel->iLeftJoin ){
128359    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
128360    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
128361    VdbeComment((v, "record LEFT JOIN hit"));
128362    sqlite3ExprCacheClear(pParse);
128363    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
128364      testcase( pTerm->wtFlags & TERM_VIRTUAL );
128365      testcase( pTerm->wtFlags & TERM_CODED );
128366      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
128367      if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
128368        assert( pWInfo->untestedTerms );
128369        continue;
128370      }
128371      assert( pTerm->pExpr );
128372      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
128373      pTerm->wtFlags |= TERM_CODED;
128374    }
128375  }
128376
128377  return pLevel->notReady;
128378}
128379
128380/************** End of wherecode.c *******************************************/
128381/************** Begin file whereexpr.c ***************************************/
128382/*
128383** 2015-06-08
128384**
128385** The author disclaims copyright to this source code.  In place of
128386** a legal notice, here is a blessing:
128387**
128388**    May you do good and not evil.
128389**    May you find forgiveness for yourself and forgive others.
128390**    May you share freely, never taking more than you give.
128391**
128392*************************************************************************
128393** This module contains C code that generates VDBE code used to process
128394** the WHERE clause of SQL statements.
128395**
128396** This file was originally part of where.c but was split out to improve
128397** readability and editabiliity.  This file contains utility routines for
128398** analyzing Expr objects in the WHERE clause.
128399*/
128400/* #include "sqliteInt.h" */
128401/* #include "whereInt.h" */
128402
128403/* Forward declarations */
128404static void exprAnalyze(SrcList*, WhereClause*, int);
128405
128406/*
128407** Deallocate all memory associated with a WhereOrInfo object.
128408*/
128409static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
128410  sqlite3WhereClauseClear(&p->wc);
128411  sqlite3DbFree(db, p);
128412}
128413
128414/*
128415** Deallocate all memory associated with a WhereAndInfo object.
128416*/
128417static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
128418  sqlite3WhereClauseClear(&p->wc);
128419  sqlite3DbFree(db, p);
128420}
128421
128422/*
128423** Add a single new WhereTerm entry to the WhereClause object pWC.
128424** The new WhereTerm object is constructed from Expr p and with wtFlags.
128425** The index in pWC->a[] of the new WhereTerm is returned on success.
128426** 0 is returned if the new WhereTerm could not be added due to a memory
128427** allocation error.  The memory allocation failure will be recorded in
128428** the db->mallocFailed flag so that higher-level functions can detect it.
128429**
128430** This routine will increase the size of the pWC->a[] array as necessary.
128431**
128432** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
128433** for freeing the expression p is assumed by the WhereClause object pWC.
128434** This is true even if this routine fails to allocate a new WhereTerm.
128435**
128436** WARNING:  This routine might reallocate the space used to store
128437** WhereTerms.  All pointers to WhereTerms should be invalidated after
128438** calling this routine.  Such pointers may be reinitialized by referencing
128439** the pWC->a[] array.
128440*/
128441static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
128442  WhereTerm *pTerm;
128443  int idx;
128444  testcase( wtFlags & TERM_VIRTUAL );
128445  if( pWC->nTerm>=pWC->nSlot ){
128446    WhereTerm *pOld = pWC->a;
128447    sqlite3 *db = pWC->pWInfo->pParse->db;
128448    pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
128449    if( pWC->a==0 ){
128450      if( wtFlags & TERM_DYNAMIC ){
128451        sqlite3ExprDelete(db, p);
128452      }
128453      pWC->a = pOld;
128454      return 0;
128455    }
128456    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
128457    if( pOld!=pWC->aStatic ){
128458      sqlite3DbFree(db, pOld);
128459    }
128460    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
128461  }
128462  pTerm = &pWC->a[idx = pWC->nTerm++];
128463  if( p && ExprHasProperty(p, EP_Unlikely) ){
128464    pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
128465  }else{
128466    pTerm->truthProb = 1;
128467  }
128468  pTerm->pExpr = sqlite3ExprSkipCollate(p);
128469  pTerm->wtFlags = wtFlags;
128470  pTerm->pWC = pWC;
128471  pTerm->iParent = -1;
128472  memset(&pTerm->eOperator, 0,
128473         sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
128474  return idx;
128475}
128476
128477/*
128478** Return TRUE if the given operator is one of the operators that is
128479** allowed for an indexable WHERE clause term.  The allowed operators are
128480** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
128481*/
128482static int allowedOp(int op){
128483  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
128484  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
128485  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
128486  assert( TK_GE==TK_EQ+4 );
128487  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
128488}
128489
128490/*
128491** Commute a comparison operator.  Expressions of the form "X op Y"
128492** are converted into "Y op X".
128493**
128494** If left/right precedence rules come into play when determining the
128495** collating sequence, then COLLATE operators are adjusted to ensure
128496** that the collating sequence does not change.  For example:
128497** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
128498** the left hand side of a comparison overrides any collation sequence
128499** attached to the right. For the same reason the EP_Collate flag
128500** is not commuted.
128501*/
128502static void exprCommute(Parse *pParse, Expr *pExpr){
128503  u16 expRight = (pExpr->pRight->flags & EP_Collate);
128504  u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
128505  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
128506  if( expRight==expLeft ){
128507    /* Either X and Y both have COLLATE operator or neither do */
128508    if( expRight ){
128509      /* Both X and Y have COLLATE operators.  Make sure X is always
128510      ** used by clearing the EP_Collate flag from Y. */
128511      pExpr->pRight->flags &= ~EP_Collate;
128512    }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
128513      /* Neither X nor Y have COLLATE operators, but X has a non-default
128514      ** collating sequence.  So add the EP_Collate marker on X to cause
128515      ** it to be searched first. */
128516      pExpr->pLeft->flags |= EP_Collate;
128517    }
128518  }
128519  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
128520  if( pExpr->op>=TK_GT ){
128521    assert( TK_LT==TK_GT+2 );
128522    assert( TK_GE==TK_LE+2 );
128523    assert( TK_GT>TK_EQ );
128524    assert( TK_GT<TK_LE );
128525    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
128526    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
128527  }
128528}
128529
128530/*
128531** Translate from TK_xx operator to WO_xx bitmask.
128532*/
128533static u16 operatorMask(int op){
128534  u16 c;
128535  assert( allowedOp(op) );
128536  if( op==TK_IN ){
128537    c = WO_IN;
128538  }else if( op==TK_ISNULL ){
128539    c = WO_ISNULL;
128540  }else if( op==TK_IS ){
128541    c = WO_IS;
128542  }else{
128543    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
128544    c = (u16)(WO_EQ<<(op-TK_EQ));
128545  }
128546  assert( op!=TK_ISNULL || c==WO_ISNULL );
128547  assert( op!=TK_IN || c==WO_IN );
128548  assert( op!=TK_EQ || c==WO_EQ );
128549  assert( op!=TK_LT || c==WO_LT );
128550  assert( op!=TK_LE || c==WO_LE );
128551  assert( op!=TK_GT || c==WO_GT );
128552  assert( op!=TK_GE || c==WO_GE );
128553  assert( op!=TK_IS || c==WO_IS );
128554  return c;
128555}
128556
128557
128558#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
128559/*
128560** Check to see if the given expression is a LIKE or GLOB operator that
128561** can be optimized using inequality constraints.  Return TRUE if it is
128562** so and false if not.
128563**
128564** In order for the operator to be optimizible, the RHS must be a string
128565** literal that does not begin with a wildcard.  The LHS must be a column
128566** that may only be NULL, a string, or a BLOB, never a number. (This means
128567** that virtual tables cannot participate in the LIKE optimization.)  The
128568** collating sequence for the column on the LHS must be appropriate for
128569** the operator.
128570*/
128571static int isLikeOrGlob(
128572  Parse *pParse,    /* Parsing and code generating context */
128573  Expr *pExpr,      /* Test this expression */
128574  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
128575  int *pisComplete, /* True if the only wildcard is % in the last character */
128576  int *pnoCase      /* True if uppercase is equivalent to lowercase */
128577){
128578  const char *z = 0;         /* String on RHS of LIKE operator */
128579  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
128580  ExprList *pList;           /* List of operands to the LIKE operator */
128581  int c;                     /* One character in z[] */
128582  int cnt;                   /* Number of non-wildcard prefix characters */
128583  char wc[3];                /* Wildcard characters */
128584  sqlite3 *db = pParse->db;  /* Database connection */
128585  sqlite3_value *pVal = 0;
128586  int op;                    /* Opcode of pRight */
128587  int rc;                    /* Result code to return */
128588
128589  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
128590    return 0;
128591  }
128592#ifdef SQLITE_EBCDIC
128593  if( *pnoCase ) return 0;
128594#endif
128595  pList = pExpr->x.pList;
128596  pLeft = pList->a[1].pExpr;
128597
128598  pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
128599  op = pRight->op;
128600  if( op==TK_VARIABLE ){
128601    Vdbe *pReprepare = pParse->pReprepare;
128602    int iCol = pRight->iColumn;
128603    pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
128604    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
128605      z = (char *)sqlite3_value_text(pVal);
128606    }
128607    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
128608    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
128609  }else if( op==TK_STRING ){
128610    z = pRight->u.zToken;
128611  }
128612  if( z ){
128613
128614    /* If the RHS begins with a digit or a minus sign, then the LHS must
128615    ** be an ordinary column (not a virtual table column) with TEXT affinity.
128616    ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
128617    ** even though "lhs LIKE rhs" is true.  But if the RHS does not start
128618    ** with a digit or '-', then "lhs LIKE rhs" will always be false if
128619    ** the LHS is numeric and so the optimization still works.
128620    */
128621    if( sqlite3Isdigit(z[0]) || z[0]=='-' ){
128622      if( pLeft->op!=TK_COLUMN
128623       || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
128624       || IsVirtual(pLeft->pTab)  /* Value might be numeric */
128625      ){
128626        sqlite3ValueFree(pVal);
128627        return 0;
128628      }
128629    }
128630    cnt = 0;
128631    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
128632      cnt++;
128633    }
128634    if( cnt!=0 && 255!=(u8)z[cnt-1] ){
128635      Expr *pPrefix;
128636      *pisComplete = c==wc[0] && z[cnt+1]==0;
128637      pPrefix = sqlite3Expr(db, TK_STRING, z);
128638      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
128639      *ppPrefix = pPrefix;
128640      if( op==TK_VARIABLE ){
128641        Vdbe *v = pParse->pVdbe;
128642        sqlite3VdbeSetVarmask(v, pRight->iColumn);
128643        if( *pisComplete && pRight->u.zToken[1] ){
128644          /* If the rhs of the LIKE expression is a variable, and the current
128645          ** value of the variable means there is no need to invoke the LIKE
128646          ** function, then no OP_Variable will be added to the program.
128647          ** This causes problems for the sqlite3_bind_parameter_name()
128648          ** API. To work around them, add a dummy OP_Variable here.
128649          */
128650          int r1 = sqlite3GetTempReg(pParse);
128651          sqlite3ExprCodeTarget(pParse, pRight, r1);
128652          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
128653          sqlite3ReleaseTempReg(pParse, r1);
128654        }
128655      }
128656    }else{
128657      z = 0;
128658    }
128659  }
128660
128661  rc = (z!=0);
128662  sqlite3ValueFree(pVal);
128663  return rc;
128664}
128665#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
128666
128667
128668#ifndef SQLITE_OMIT_VIRTUALTABLE
128669/*
128670** Check to see if the given expression is of the form
128671**
128672**         column OP expr
128673**
128674** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a
128675** column of a virtual table.
128676**
128677** If it is then return TRUE.  If not, return FALSE.
128678*/
128679static int isMatchOfColumn(
128680  Expr *pExpr,                    /* Test this expression */
128681  unsigned char *peOp2            /* OUT: 0 for MATCH, or else an op2 value */
128682){
128683  static const struct Op2 {
128684    const char *zOp;
128685    unsigned char eOp2;
128686  } aOp[] = {
128687    { "match",  SQLITE_INDEX_CONSTRAINT_MATCH },
128688    { "glob",   SQLITE_INDEX_CONSTRAINT_GLOB },
128689    { "like",   SQLITE_INDEX_CONSTRAINT_LIKE },
128690    { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
128691  };
128692  ExprList *pList;
128693  Expr *pCol;                     /* Column reference */
128694  int i;
128695
128696  if( pExpr->op!=TK_FUNCTION ){
128697    return 0;
128698  }
128699  pList = pExpr->x.pList;
128700  if( pList==0 || pList->nExpr!=2 ){
128701    return 0;
128702  }
128703  pCol = pList->a[1].pExpr;
128704  if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
128705    return 0;
128706  }
128707  for(i=0; i<ArraySize(aOp); i++){
128708    if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
128709      *peOp2 = aOp[i].eOp2;
128710      return 1;
128711    }
128712  }
128713  return 0;
128714}
128715#endif /* SQLITE_OMIT_VIRTUALTABLE */
128716
128717/*
128718** If the pBase expression originated in the ON or USING clause of
128719** a join, then transfer the appropriate markings over to derived.
128720*/
128721static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
128722  if( pDerived ){
128723    pDerived->flags |= pBase->flags & EP_FromJoin;
128724    pDerived->iRightJoinTable = pBase->iRightJoinTable;
128725  }
128726}
128727
128728/*
128729** Mark term iChild as being a child of term iParent
128730*/
128731static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
128732  pWC->a[iChild].iParent = iParent;
128733  pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
128734  pWC->a[iParent].nChild++;
128735}
128736
128737/*
128738** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
128739** a conjunction, then return just pTerm when N==0.  If N is exceeds
128740** the number of available subterms, return NULL.
128741*/
128742static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
128743  if( pTerm->eOperator!=WO_AND ){
128744    return N==0 ? pTerm : 0;
128745  }
128746  if( N<pTerm->u.pAndInfo->wc.nTerm ){
128747    return &pTerm->u.pAndInfo->wc.a[N];
128748  }
128749  return 0;
128750}
128751
128752/*
128753** Subterms pOne and pTwo are contained within WHERE clause pWC.  The
128754** two subterms are in disjunction - they are OR-ed together.
128755**
128756** If these two terms are both of the form:  "A op B" with the same
128757** A and B values but different operators and if the operators are
128758** compatible (if one is = and the other is <, for example) then
128759** add a new virtual AND term to pWC that is the combination of the
128760** two.
128761**
128762** Some examples:
128763**
128764**    x<y OR x=y    -->     x<=y
128765**    x=y OR x=y    -->     x=y
128766**    x<=y OR x<y   -->     x<=y
128767**
128768** The following is NOT generated:
128769**
128770**    x<y OR x>y    -->     x!=y
128771*/
128772static void whereCombineDisjuncts(
128773  SrcList *pSrc,         /* the FROM clause */
128774  WhereClause *pWC,      /* The complete WHERE clause */
128775  WhereTerm *pOne,       /* First disjunct */
128776  WhereTerm *pTwo        /* Second disjunct */
128777){
128778  u16 eOp = pOne->eOperator | pTwo->eOperator;
128779  sqlite3 *db;           /* Database connection (for malloc) */
128780  Expr *pNew;            /* New virtual expression */
128781  int op;                /* Operator for the combined expression */
128782  int idxNew;            /* Index in pWC of the next virtual term */
128783
128784  if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
128785  if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
128786  if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
128787   && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
128788  assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
128789  assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
128790  if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
128791  if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
128792  /* If we reach this point, it means the two subterms can be combined */
128793  if( (eOp & (eOp-1))!=0 ){
128794    if( eOp & (WO_LT|WO_LE) ){
128795      eOp = WO_LE;
128796    }else{
128797      assert( eOp & (WO_GT|WO_GE) );
128798      eOp = WO_GE;
128799    }
128800  }
128801  db = pWC->pWInfo->pParse->db;
128802  pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
128803  if( pNew==0 ) return;
128804  for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
128805  pNew->op = op;
128806  idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
128807  exprAnalyze(pSrc, pWC, idxNew);
128808}
128809
128810#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
128811/*
128812** Analyze a term that consists of two or more OR-connected
128813** subterms.  So in:
128814**
128815**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
128816**                          ^^^^^^^^^^^^^^^^^^^^
128817**
128818** This routine analyzes terms such as the middle term in the above example.
128819** A WhereOrTerm object is computed and attached to the term under
128820** analysis, regardless of the outcome of the analysis.  Hence:
128821**
128822**     WhereTerm.wtFlags   |=  TERM_ORINFO
128823**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
128824**
128825** The term being analyzed must have two or more of OR-connected subterms.
128826** A single subterm might be a set of AND-connected sub-subterms.
128827** Examples of terms under analysis:
128828**
128829**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
128830**     (B)     x=expr1 OR expr2=x OR x=expr3
128831**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
128832**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
128833**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
128834**     (F)     x>A OR (x=A AND y>=B)
128835**
128836** CASE 1:
128837**
128838** If all subterms are of the form T.C=expr for some single column of C and
128839** a single table T (as shown in example B above) then create a new virtual
128840** term that is an equivalent IN expression.  In other words, if the term
128841** being analyzed is:
128842**
128843**      x = expr1  OR  expr2 = x  OR  x = expr3
128844**
128845** then create a new virtual term like this:
128846**
128847**      x IN (expr1,expr2,expr3)
128848**
128849** CASE 2:
128850**
128851** If there are exactly two disjuncts and one side has x>A and the other side
128852** has x=A (for the same x and A) then add a new virtual conjunct term to the
128853** WHERE clause of the form "x>=A".  Example:
128854**
128855**      x>A OR (x=A AND y>B)    adds:    x>=A
128856**
128857** The added conjunct can sometimes be helpful in query planning.
128858**
128859** CASE 3:
128860**
128861** If all subterms are indexable by a single table T, then set
128862**
128863**     WhereTerm.eOperator              =  WO_OR
128864**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
128865**
128866** A subterm is "indexable" if it is of the form
128867** "T.C <op> <expr>" where C is any column of table T and
128868** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
128869** A subterm is also indexable if it is an AND of two or more
128870** subsubterms at least one of which is indexable.  Indexable AND
128871** subterms have their eOperator set to WO_AND and they have
128872** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
128873**
128874** From another point of view, "indexable" means that the subterm could
128875** potentially be used with an index if an appropriate index exists.
128876** This analysis does not consider whether or not the index exists; that
128877** is decided elsewhere.  This analysis only looks at whether subterms
128878** appropriate for indexing exist.
128879**
128880** All examples A through E above satisfy case 3.  But if a term
128881** also satisfies case 1 (such as B) we know that the optimizer will
128882** always prefer case 1, so in that case we pretend that case 3 is not
128883** satisfied.
128884**
128885** It might be the case that multiple tables are indexable.  For example,
128886** (E) above is indexable on tables P, Q, and R.
128887**
128888** Terms that satisfy case 3 are candidates for lookup by using
128889** separate indices to find rowids for each subterm and composing
128890** the union of all rowids using a RowSet object.  This is similar
128891** to "bitmap indices" in other database engines.
128892**
128893** OTHERWISE:
128894**
128895** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
128896** zero.  This term is not useful for search.
128897*/
128898static void exprAnalyzeOrTerm(
128899  SrcList *pSrc,            /* the FROM clause */
128900  WhereClause *pWC,         /* the complete WHERE clause */
128901  int idxTerm               /* Index of the OR-term to be analyzed */
128902){
128903  WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
128904  Parse *pParse = pWInfo->pParse;         /* Parser context */
128905  sqlite3 *db = pParse->db;               /* Database connection */
128906  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
128907  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
128908  int i;                                  /* Loop counters */
128909  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
128910  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
128911  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
128912  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
128913  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
128914
128915  /*
128916  ** Break the OR clause into its separate subterms.  The subterms are
128917  ** stored in a WhereClause structure containing within the WhereOrInfo
128918  ** object that is attached to the original OR clause term.
128919  */
128920  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
128921  assert( pExpr->op==TK_OR );
128922  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
128923  if( pOrInfo==0 ) return;
128924  pTerm->wtFlags |= TERM_ORINFO;
128925  pOrWc = &pOrInfo->wc;
128926  memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
128927  sqlite3WhereClauseInit(pOrWc, pWInfo);
128928  sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
128929  sqlite3WhereExprAnalyze(pSrc, pOrWc);
128930  if( db->mallocFailed ) return;
128931  assert( pOrWc->nTerm>=2 );
128932
128933  /*
128934  ** Compute the set of tables that might satisfy cases 1 or 3.
128935  */
128936  indexable = ~(Bitmask)0;
128937  chngToIN = ~(Bitmask)0;
128938  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
128939    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
128940      WhereAndInfo *pAndInfo;
128941      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
128942      chngToIN = 0;
128943      pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
128944      if( pAndInfo ){
128945        WhereClause *pAndWC;
128946        WhereTerm *pAndTerm;
128947        int j;
128948        Bitmask b = 0;
128949        pOrTerm->u.pAndInfo = pAndInfo;
128950        pOrTerm->wtFlags |= TERM_ANDINFO;
128951        pOrTerm->eOperator = WO_AND;
128952        pAndWC = &pAndInfo->wc;
128953        memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
128954        sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
128955        sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
128956        sqlite3WhereExprAnalyze(pSrc, pAndWC);
128957        pAndWC->pOuter = pWC;
128958        if( !db->mallocFailed ){
128959          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
128960            assert( pAndTerm->pExpr );
128961            if( allowedOp(pAndTerm->pExpr->op)
128962             || pAndTerm->eOperator==WO_MATCH
128963            ){
128964              b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
128965            }
128966          }
128967        }
128968        indexable &= b;
128969      }
128970    }else if( pOrTerm->wtFlags & TERM_COPIED ){
128971      /* Skip this term for now.  We revisit it when we process the
128972      ** corresponding TERM_VIRTUAL term */
128973    }else{
128974      Bitmask b;
128975      b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
128976      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
128977        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
128978        b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
128979      }
128980      indexable &= b;
128981      if( (pOrTerm->eOperator & WO_EQ)==0 ){
128982        chngToIN = 0;
128983      }else{
128984        chngToIN &= b;
128985      }
128986    }
128987  }
128988
128989  /*
128990  ** Record the set of tables that satisfy case 3.  The set might be
128991  ** empty.
128992  */
128993  pOrInfo->indexable = indexable;
128994  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
128995
128996  /* For a two-way OR, attempt to implementation case 2.
128997  */
128998  if( indexable && pOrWc->nTerm==2 ){
128999    int iOne = 0;
129000    WhereTerm *pOne;
129001    while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
129002      int iTwo = 0;
129003      WhereTerm *pTwo;
129004      while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
129005        whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
129006      }
129007    }
129008  }
129009
129010  /*
129011  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
129012  ** we have to do some additional checking to see if case 1 really
129013  ** is satisfied.
129014  **
129015  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
129016  ** that there is no possibility of transforming the OR clause into an
129017  ** IN operator because one or more terms in the OR clause contain
129018  ** something other than == on a column in the single table.  The 1-bit
129019  ** case means that every term of the OR clause is of the form
129020  ** "table.column=expr" for some single table.  The one bit that is set
129021  ** will correspond to the common table.  We still need to check to make
129022  ** sure the same column is used on all terms.  The 2-bit case is when
129023  ** the all terms are of the form "table1.column=table2.column".  It
129024  ** might be possible to form an IN operator with either table1.column
129025  ** or table2.column as the LHS if either is common to every term of
129026  ** the OR clause.
129027  **
129028  ** Note that terms of the form "table.column1=table.column2" (the
129029  ** same table on both sizes of the ==) cannot be optimized.
129030  */
129031  if( chngToIN ){
129032    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
129033    int iColumn = -1;         /* Column index on lhs of IN operator */
129034    int iCursor = -1;         /* Table cursor common to all terms */
129035    int j = 0;                /* Loop counter */
129036
129037    /* Search for a table and column that appears on one side or the
129038    ** other of the == operator in every subterm.  That table and column
129039    ** will be recorded in iCursor and iColumn.  There might not be any
129040    ** such table and column.  Set okToChngToIN if an appropriate table
129041    ** and column is found but leave okToChngToIN false if not found.
129042    */
129043    for(j=0; j<2 && !okToChngToIN; j++){
129044      pOrTerm = pOrWc->a;
129045      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
129046        assert( pOrTerm->eOperator & WO_EQ );
129047        pOrTerm->wtFlags &= ~TERM_OR_OK;
129048        if( pOrTerm->leftCursor==iCursor ){
129049          /* This is the 2-bit case and we are on the second iteration and
129050          ** current term is from the first iteration.  So skip this term. */
129051          assert( j==1 );
129052          continue;
129053        }
129054        if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
129055                                            pOrTerm->leftCursor))==0 ){
129056          /* This term must be of the form t1.a==t2.b where t2 is in the
129057          ** chngToIN set but t1 is not.  This term will be either preceded
129058          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
129059          ** and use its inversion. */
129060          testcase( pOrTerm->wtFlags & TERM_COPIED );
129061          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
129062          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
129063          continue;
129064        }
129065        iColumn = pOrTerm->u.leftColumn;
129066        iCursor = pOrTerm->leftCursor;
129067        break;
129068      }
129069      if( i<0 ){
129070        /* No candidate table+column was found.  This can only occur
129071        ** on the second iteration */
129072        assert( j==1 );
129073        assert( IsPowerOfTwo(chngToIN) );
129074        assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
129075        break;
129076      }
129077      testcase( j==1 );
129078
129079      /* We have found a candidate table and column.  Check to see if that
129080      ** table and column is common to every term in the OR clause */
129081      okToChngToIN = 1;
129082      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
129083        assert( pOrTerm->eOperator & WO_EQ );
129084        if( pOrTerm->leftCursor!=iCursor ){
129085          pOrTerm->wtFlags &= ~TERM_OR_OK;
129086        }else if( pOrTerm->u.leftColumn!=iColumn ){
129087          okToChngToIN = 0;
129088        }else{
129089          int affLeft, affRight;
129090          /* If the right-hand side is also a column, then the affinities
129091          ** of both right and left sides must be such that no type
129092          ** conversions are required on the right.  (Ticket #2249)
129093          */
129094          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
129095          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
129096          if( affRight!=0 && affRight!=affLeft ){
129097            okToChngToIN = 0;
129098          }else{
129099            pOrTerm->wtFlags |= TERM_OR_OK;
129100          }
129101        }
129102      }
129103    }
129104
129105    /* At this point, okToChngToIN is true if original pTerm satisfies
129106    ** case 1.  In that case, construct a new virtual term that is
129107    ** pTerm converted into an IN operator.
129108    */
129109    if( okToChngToIN ){
129110      Expr *pDup;            /* A transient duplicate expression */
129111      ExprList *pList = 0;   /* The RHS of the IN operator */
129112      Expr *pLeft = 0;       /* The LHS of the IN operator */
129113      Expr *pNew;            /* The complete IN operator */
129114
129115      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
129116        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
129117        assert( pOrTerm->eOperator & WO_EQ );
129118        assert( pOrTerm->leftCursor==iCursor );
129119        assert( pOrTerm->u.leftColumn==iColumn );
129120        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
129121        pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
129122        pLeft = pOrTerm->pExpr->pLeft;
129123      }
129124      assert( pLeft!=0 );
129125      pDup = sqlite3ExprDup(db, pLeft, 0);
129126      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
129127      if( pNew ){
129128        int idxNew;
129129        transferJoinMarkings(pNew, pExpr);
129130        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
129131        pNew->x.pList = pList;
129132        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
129133        testcase( idxNew==0 );
129134        exprAnalyze(pSrc, pWC, idxNew);
129135        pTerm = &pWC->a[idxTerm];
129136        markTermAsChild(pWC, idxNew, idxTerm);
129137      }else{
129138        sqlite3ExprListDelete(db, pList);
129139      }
129140      pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 3 */
129141    }
129142  }
129143}
129144#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
129145
129146/*
129147** We already know that pExpr is a binary operator where both operands are
129148** column references.  This routine checks to see if pExpr is an equivalence
129149** relation:
129150**   1.  The SQLITE_Transitive optimization must be enabled
129151**   2.  Must be either an == or an IS operator
129152**   3.  Not originating in the ON clause of an OUTER JOIN
129153**   4.  The affinities of A and B must be compatible
129154**   5a. Both operands use the same collating sequence OR
129155**   5b. The overall collating sequence is BINARY
129156** If this routine returns TRUE, that means that the RHS can be substituted
129157** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
129158** This is an optimization.  No harm comes from returning 0.  But if 1 is
129159** returned when it should not be, then incorrect answers might result.
129160*/
129161static int termIsEquivalence(Parse *pParse, Expr *pExpr){
129162  char aff1, aff2;
129163  CollSeq *pColl;
129164  const char *zColl1, *zColl2;
129165  if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
129166  if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
129167  if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
129168  aff1 = sqlite3ExprAffinity(pExpr->pLeft);
129169  aff2 = sqlite3ExprAffinity(pExpr->pRight);
129170  if( aff1!=aff2
129171   && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
129172  ){
129173    return 0;
129174  }
129175  pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
129176  if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
129177  pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
129178  zColl1 = pColl ? pColl->zName : 0;
129179  pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
129180  zColl2 = pColl ? pColl->zName : 0;
129181  return sqlite3_stricmp(zColl1, zColl2)==0;
129182}
129183
129184/*
129185** Recursively walk the expressions of a SELECT statement and generate
129186** a bitmask indicating which tables are used in that expression
129187** tree.
129188*/
129189static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
129190  Bitmask mask = 0;
129191  while( pS ){
129192    SrcList *pSrc = pS->pSrc;
129193    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
129194    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
129195    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
129196    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
129197    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
129198    if( ALWAYS(pSrc!=0) ){
129199      int i;
129200      for(i=0; i<pSrc->nSrc; i++){
129201        mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
129202        mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
129203      }
129204    }
129205    pS = pS->pPrior;
129206  }
129207  return mask;
129208}
129209
129210/*
129211** Expression pExpr is one operand of a comparison operator that might
129212** be useful for indexing.  This routine checks to see if pExpr appears
129213** in any index.  Return TRUE (1) if pExpr is an indexed term and return
129214** FALSE (0) if not.  If TRUE is returned, also set *piCur to the cursor
129215** number of the table that is indexed and *piColumn to the column number
129216** of the column that is indexed, or XN_EXPR (-2) if an expression is being
129217** indexed.
129218**
129219** If pExpr is a TK_COLUMN column reference, then this routine always returns
129220** true even if that particular column is not indexed, because the column
129221** might be added to an automatic index later.
129222*/
129223static int exprMightBeIndexed(
129224  SrcList *pFrom,        /* The FROM clause */
129225  int op,                /* The specific comparison operator */
129226  Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
129227  Expr *pExpr,           /* An operand of a comparison operator */
129228  int *piCur,            /* Write the referenced table cursor number here */
129229  int *piColumn          /* Write the referenced table column number here */
129230){
129231  Index *pIdx;
129232  int i;
129233  int iCur;
129234
129235  /* If this expression is a vector to the left or right of a
129236  ** inequality constraint (>, <, >= or <=), perform the processing
129237  ** on the first element of the vector.  */
129238  assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
129239  assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
129240  assert( op<=TK_GE );
129241  if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
129242    pExpr = pExpr->x.pList->a[0].pExpr;
129243  }
129244
129245  if( pExpr->op==TK_COLUMN ){
129246    *piCur = pExpr->iTable;
129247    *piColumn = pExpr->iColumn;
129248    return 1;
129249  }
129250  if( mPrereq==0 ) return 0;                 /* No table references */
129251  if( (mPrereq&(mPrereq-1))!=0 ) return 0;   /* Refs more than one table */
129252  for(i=0; mPrereq>1; i++, mPrereq>>=1){}
129253  iCur = pFrom->a[i].iCursor;
129254  for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
129255    if( pIdx->aColExpr==0 ) continue;
129256    for(i=0; i<pIdx->nKeyCol; i++){
129257      if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
129258      if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
129259        *piCur = iCur;
129260        *piColumn = XN_EXPR;
129261        return 1;
129262      }
129263    }
129264  }
129265  return 0;
129266}
129267
129268/*
129269** The input to this routine is an WhereTerm structure with only the
129270** "pExpr" field filled in.  The job of this routine is to analyze the
129271** subexpression and populate all the other fields of the WhereTerm
129272** structure.
129273**
129274** If the expression is of the form "<expr> <op> X" it gets commuted
129275** to the standard form of "X <op> <expr>".
129276**
129277** If the expression is of the form "X <op> Y" where both X and Y are
129278** columns, then the original expression is unchanged and a new virtual
129279** term of the form "Y <op> X" is added to the WHERE clause and
129280** analyzed separately.  The original term is marked with TERM_COPIED
129281** and the new term is marked with TERM_DYNAMIC (because it's pExpr
129282** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
129283** is a commuted copy of a prior term.)  The original term has nChild=1
129284** and the copy has idxParent set to the index of the original term.
129285*/
129286static void exprAnalyze(
129287  SrcList *pSrc,            /* the FROM clause */
129288  WhereClause *pWC,         /* the WHERE clause */
129289  int idxTerm               /* Index of the term to be analyzed */
129290){
129291  WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
129292  WhereTerm *pTerm;                /* The term to be analyzed */
129293  WhereMaskSet *pMaskSet;          /* Set of table index masks */
129294  Expr *pExpr;                     /* The expression to be analyzed */
129295  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
129296  Bitmask prereqAll;               /* Prerequesites of pExpr */
129297  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
129298  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
129299  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
129300  int noCase = 0;                  /* uppercase equivalent to lowercase */
129301  int op;                          /* Top-level operator.  pExpr->op */
129302  Parse *pParse = pWInfo->pParse;  /* Parsing context */
129303  sqlite3 *db = pParse->db;        /* Database connection */
129304  unsigned char eOp2;              /* op2 value for LIKE/REGEXP/GLOB */
129305  int nLeft;                       /* Number of elements on left side vector */
129306
129307  if( db->mallocFailed ){
129308    return;
129309  }
129310  pTerm = &pWC->a[idxTerm];
129311  pMaskSet = &pWInfo->sMaskSet;
129312  pExpr = pTerm->pExpr;
129313  assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
129314  prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
129315  op = pExpr->op;
129316  if( op==TK_IN ){
129317    assert( pExpr->pRight==0 );
129318    if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
129319    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
129320      pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
129321    }else{
129322      pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
129323    }
129324  }else if( op==TK_ISNULL ){
129325    pTerm->prereqRight = 0;
129326  }else{
129327    pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
129328  }
129329  prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
129330  if( ExprHasProperty(pExpr, EP_FromJoin) ){
129331    Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
129332    prereqAll |= x;
129333    extraRight = x-1;  /* ON clause terms may not be used with an index
129334                       ** on left table of a LEFT JOIN.  Ticket #3015 */
129335    if( (prereqAll>>1)>=x ){
129336      sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
129337      return;
129338    }
129339  }
129340  pTerm->prereqAll = prereqAll;
129341  pTerm->leftCursor = -1;
129342  pTerm->iParent = -1;
129343  pTerm->eOperator = 0;
129344  if( allowedOp(op) ){
129345    int iCur, iColumn;
129346    Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
129347    Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
129348    u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
129349
129350    if( pTerm->iField>0 ){
129351      assert( op==TK_IN );
129352      assert( pLeft->op==TK_VECTOR );
129353      pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
129354    }
129355
129356    if( exprMightBeIndexed(pSrc, op, prereqLeft, pLeft, &iCur, &iColumn) ){
129357      pTerm->leftCursor = iCur;
129358      pTerm->u.leftColumn = iColumn;
129359      pTerm->eOperator = operatorMask(op) & opMask;
129360    }
129361    if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
129362    if( pRight
129363     && exprMightBeIndexed(pSrc, op, pTerm->prereqRight, pRight, &iCur,&iColumn)
129364    ){
129365      WhereTerm *pNew;
129366      Expr *pDup;
129367      u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
129368      assert( pTerm->iField==0 );
129369      if( pTerm->leftCursor>=0 ){
129370        int idxNew;
129371        pDup = sqlite3ExprDup(db, pExpr, 0);
129372        if( db->mallocFailed ){
129373          sqlite3ExprDelete(db, pDup);
129374          return;
129375        }
129376        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
129377        if( idxNew==0 ) return;
129378        pNew = &pWC->a[idxNew];
129379        markTermAsChild(pWC, idxNew, idxTerm);
129380        if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
129381        pTerm = &pWC->a[idxTerm];
129382        pTerm->wtFlags |= TERM_COPIED;
129383
129384        if( termIsEquivalence(pParse, pDup) ){
129385          pTerm->eOperator |= WO_EQUIV;
129386          eExtraOp = WO_EQUIV;
129387        }
129388      }else{
129389        pDup = pExpr;
129390        pNew = pTerm;
129391      }
129392      exprCommute(pParse, pDup);
129393      pNew->leftCursor = iCur;
129394      pNew->u.leftColumn = iColumn;
129395      testcase( (prereqLeft | extraRight) != prereqLeft );
129396      pNew->prereqRight = prereqLeft | extraRight;
129397      pNew->prereqAll = prereqAll;
129398      pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
129399    }
129400  }
129401
129402#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
129403  /* If a term is the BETWEEN operator, create two new virtual terms
129404  ** that define the range that the BETWEEN implements.  For example:
129405  **
129406  **      a BETWEEN b AND c
129407  **
129408  ** is converted into:
129409  **
129410  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
129411  **
129412  ** The two new terms are added onto the end of the WhereClause object.
129413  ** The new terms are "dynamic" and are children of the original BETWEEN
129414  ** term.  That means that if the BETWEEN term is coded, the children are
129415  ** skipped.  Or, if the children are satisfied by an index, the original
129416  ** BETWEEN term is skipped.
129417  */
129418  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
129419    ExprList *pList = pExpr->x.pList;
129420    int i;
129421    static const u8 ops[] = {TK_GE, TK_LE};
129422    assert( pList!=0 );
129423    assert( pList->nExpr==2 );
129424    for(i=0; i<2; i++){
129425      Expr *pNewExpr;
129426      int idxNew;
129427      pNewExpr = sqlite3PExpr(pParse, ops[i],
129428                             sqlite3ExprDup(db, pExpr->pLeft, 0),
129429                             sqlite3ExprDup(db, pList->a[i].pExpr, 0));
129430      transferJoinMarkings(pNewExpr, pExpr);
129431      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
129432      testcase( idxNew==0 );
129433      exprAnalyze(pSrc, pWC, idxNew);
129434      pTerm = &pWC->a[idxTerm];
129435      markTermAsChild(pWC, idxNew, idxTerm);
129436    }
129437  }
129438#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
129439
129440#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
129441  /* Analyze a term that is composed of two or more subterms connected by
129442  ** an OR operator.
129443  */
129444  else if( pExpr->op==TK_OR ){
129445    assert( pWC->op==TK_AND );
129446    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
129447    pTerm = &pWC->a[idxTerm];
129448  }
129449#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
129450
129451#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
129452  /* Add constraints to reduce the search space on a LIKE or GLOB
129453  ** operator.
129454  **
129455  ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
129456  **
129457  **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
129458  **
129459  ** The last character of the prefix "abc" is incremented to form the
129460  ** termination condition "abd".  If case is not significant (the default
129461  ** for LIKE) then the lower-bound is made all uppercase and the upper-
129462  ** bound is made all lowercase so that the bounds also work when comparing
129463  ** BLOBs.
129464  */
129465  if( pWC->op==TK_AND
129466   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
129467  ){
129468    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
129469    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
129470    Expr *pNewExpr1;
129471    Expr *pNewExpr2;
129472    int idxNew1;
129473    int idxNew2;
129474    const char *zCollSeqName;     /* Name of collating sequence */
129475    const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
129476
129477    pLeft = pExpr->x.pList->a[1].pExpr;
129478    pStr2 = sqlite3ExprDup(db, pStr1, 0);
129479
129480    /* Convert the lower bound to upper-case and the upper bound to
129481    ** lower-case (upper-case is less than lower-case in ASCII) so that
129482    ** the range constraints also work for BLOBs
129483    */
129484    if( noCase && !pParse->db->mallocFailed ){
129485      int i;
129486      char c;
129487      pTerm->wtFlags |= TERM_LIKE;
129488      for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
129489        pStr1->u.zToken[i] = sqlite3Toupper(c);
129490        pStr2->u.zToken[i] = sqlite3Tolower(c);
129491      }
129492    }
129493
129494    if( !db->mallocFailed ){
129495      u8 c, *pC;       /* Last character before the first wildcard */
129496      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
129497      c = *pC;
129498      if( noCase ){
129499        /* The point is to increment the last character before the first
129500        ** wildcard.  But if we increment '@', that will push it into the
129501        ** alphabetic range where case conversions will mess up the
129502        ** inequality.  To avoid this, make sure to also run the full
129503        ** LIKE on all candidate expressions by clearing the isComplete flag
129504        */
129505        if( c=='A'-1 ) isComplete = 0;
129506        c = sqlite3UpperToLower[c];
129507      }
129508      *pC = c + 1;
129509    }
129510    zCollSeqName = noCase ? "NOCASE" : "BINARY";
129511    pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
129512    pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
129513           sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
129514           pStr1);
129515    transferJoinMarkings(pNewExpr1, pExpr);
129516    idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
129517    testcase( idxNew1==0 );
129518    exprAnalyze(pSrc, pWC, idxNew1);
129519    pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
129520    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
129521           sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
129522           pStr2);
129523    transferJoinMarkings(pNewExpr2, pExpr);
129524    idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
129525    testcase( idxNew2==0 );
129526    exprAnalyze(pSrc, pWC, idxNew2);
129527    pTerm = &pWC->a[idxTerm];
129528    if( isComplete ){
129529      markTermAsChild(pWC, idxNew1, idxTerm);
129530      markTermAsChild(pWC, idxNew2, idxTerm);
129531    }
129532  }
129533#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
129534
129535#ifndef SQLITE_OMIT_VIRTUALTABLE
129536  /* Add a WO_MATCH auxiliary term to the constraint set if the
129537  ** current expression is of the form:  column MATCH expr.
129538  ** This information is used by the xBestIndex methods of
129539  ** virtual tables.  The native query optimizer does not attempt
129540  ** to do anything with MATCH functions.
129541  */
129542  if( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){
129543    int idxNew;
129544    Expr *pRight, *pLeft;
129545    WhereTerm *pNewTerm;
129546    Bitmask prereqColumn, prereqExpr;
129547
129548    pRight = pExpr->x.pList->a[0].pExpr;
129549    pLeft = pExpr->x.pList->a[1].pExpr;
129550    prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
129551    prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
129552    if( (prereqExpr & prereqColumn)==0 ){
129553      Expr *pNewExpr;
129554      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
129555                              0, sqlite3ExprDup(db, pRight, 0));
129556      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
129557      testcase( idxNew==0 );
129558      pNewTerm = &pWC->a[idxNew];
129559      pNewTerm->prereqRight = prereqExpr;
129560      pNewTerm->leftCursor = pLeft->iTable;
129561      pNewTerm->u.leftColumn = pLeft->iColumn;
129562      pNewTerm->eOperator = WO_MATCH;
129563      pNewTerm->eMatchOp = eOp2;
129564      markTermAsChild(pWC, idxNew, idxTerm);
129565      pTerm = &pWC->a[idxTerm];
129566      pTerm->wtFlags |= TERM_COPIED;
129567      pNewTerm->prereqAll = pTerm->prereqAll;
129568    }
129569  }
129570#endif /* SQLITE_OMIT_VIRTUALTABLE */
129571
129572  /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
129573  ** new terms for each component comparison - "a = ?" and "b = ?".  The
129574  ** new terms completely replace the original vector comparison, which is
129575  ** no longer used.
129576  **
129577  ** This is only required if at least one side of the comparison operation
129578  ** is not a sub-select.  */
129579  if( pWC->op==TK_AND
129580  && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
129581  && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
129582  && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
129583  && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
129584    || (pExpr->pRight->flags & EP_xIsSelect)==0)
129585  ){
129586    int i;
129587    for(i=0; i<nLeft; i++){
129588      int idxNew;
129589      Expr *pNew;
129590      Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
129591      Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
129592
129593      pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
129594      transferJoinMarkings(pNew, pExpr);
129595      idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
129596      exprAnalyze(pSrc, pWC, idxNew);
129597    }
129598    pTerm = &pWC->a[idxTerm];
129599    pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL;  /* Disable the original */
129600    pTerm->eOperator = 0;
129601  }
129602
129603  /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
129604  ** a virtual term for each vector component. The expression object
129605  ** used by each such virtual term is pExpr (the full vector IN(...)
129606  ** expression). The WhereTerm.iField variable identifies the index within
129607  ** the vector on the LHS that the virtual term represents.
129608  **
129609  ** This only works if the RHS is a simple SELECT, not a compound
129610  */
129611  if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
129612   && pExpr->pLeft->op==TK_VECTOR
129613   && pExpr->x.pSelect->pPrior==0
129614  ){
129615    int i;
129616    for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
129617      int idxNew;
129618      idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
129619      pWC->a[idxNew].iField = i+1;
129620      exprAnalyze(pSrc, pWC, idxNew);
129621      markTermAsChild(pWC, idxNew, idxTerm);
129622    }
129623  }
129624
129625#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129626  /* When sqlite_stat3 histogram data is available an operator of the
129627  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
129628  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
129629  ** virtual term of that form.
129630  **
129631  ** Note that the virtual term must be tagged with TERM_VNULL.
129632  */
129633  if( pExpr->op==TK_NOTNULL
129634   && pExpr->pLeft->op==TK_COLUMN
129635   && pExpr->pLeft->iColumn>=0
129636   && OptimizationEnabled(db, SQLITE_Stat34)
129637  ){
129638    Expr *pNewExpr;
129639    Expr *pLeft = pExpr->pLeft;
129640    int idxNew;
129641    WhereTerm *pNewTerm;
129642
129643    pNewExpr = sqlite3PExpr(pParse, TK_GT,
129644                            sqlite3ExprDup(db, pLeft, 0),
129645                            sqlite3ExprAlloc(db, TK_NULL, 0, 0));
129646
129647    idxNew = whereClauseInsert(pWC, pNewExpr,
129648                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
129649    if( idxNew ){
129650      pNewTerm = &pWC->a[idxNew];
129651      pNewTerm->prereqRight = 0;
129652      pNewTerm->leftCursor = pLeft->iTable;
129653      pNewTerm->u.leftColumn = pLeft->iColumn;
129654      pNewTerm->eOperator = WO_GT;
129655      markTermAsChild(pWC, idxNew, idxTerm);
129656      pTerm = &pWC->a[idxTerm];
129657      pTerm->wtFlags |= TERM_COPIED;
129658      pNewTerm->prereqAll = pTerm->prereqAll;
129659    }
129660  }
129661#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
129662
129663  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
129664  ** an index for tables to the left of the join.
129665  */
129666  testcase( pTerm!=&pWC->a[idxTerm] );
129667  pTerm = &pWC->a[idxTerm];
129668  pTerm->prereqRight |= extraRight;
129669}
129670
129671/***************************************************************************
129672** Routines with file scope above.  Interface to the rest of the where.c
129673** subsystem follows.
129674***************************************************************************/
129675
129676/*
129677** This routine identifies subexpressions in the WHERE clause where
129678** each subexpression is separated by the AND operator or some other
129679** operator specified in the op parameter.  The WhereClause structure
129680** is filled with pointers to subexpressions.  For example:
129681**
129682**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
129683**           \________/     \_______________/     \________________/
129684**            slot[0]            slot[1]               slot[2]
129685**
129686** The original WHERE clause in pExpr is unaltered.  All this routine
129687** does is make slot[] entries point to substructure within pExpr.
129688**
129689** In the previous sentence and in the diagram, "slot[]" refers to
129690** the WhereClause.a[] array.  The slot[] array grows as needed to contain
129691** all terms of the WHERE clause.
129692*/
129693SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
129694  Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
129695  pWC->op = op;
129696  if( pE2==0 ) return;
129697  if( pE2->op!=op ){
129698    whereClauseInsert(pWC, pExpr, 0);
129699  }else{
129700    sqlite3WhereSplit(pWC, pE2->pLeft, op);
129701    sqlite3WhereSplit(pWC, pE2->pRight, op);
129702  }
129703}
129704
129705/*
129706** Initialize a preallocated WhereClause structure.
129707*/
129708SQLITE_PRIVATE void sqlite3WhereClauseInit(
129709  WhereClause *pWC,        /* The WhereClause to be initialized */
129710  WhereInfo *pWInfo        /* The WHERE processing context */
129711){
129712  pWC->pWInfo = pWInfo;
129713  pWC->pOuter = 0;
129714  pWC->nTerm = 0;
129715  pWC->nSlot = ArraySize(pWC->aStatic);
129716  pWC->a = pWC->aStatic;
129717}
129718
129719/*
129720** Deallocate a WhereClause structure.  The WhereClause structure
129721** itself is not freed.  This routine is the inverse of
129722** sqlite3WhereClauseInit().
129723*/
129724SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
129725  int i;
129726  WhereTerm *a;
129727  sqlite3 *db = pWC->pWInfo->pParse->db;
129728  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
129729    if( a->wtFlags & TERM_DYNAMIC ){
129730      sqlite3ExprDelete(db, a->pExpr);
129731    }
129732    if( a->wtFlags & TERM_ORINFO ){
129733      whereOrInfoDelete(db, a->u.pOrInfo);
129734    }else if( a->wtFlags & TERM_ANDINFO ){
129735      whereAndInfoDelete(db, a->u.pAndInfo);
129736    }
129737  }
129738  if( pWC->a!=pWC->aStatic ){
129739    sqlite3DbFree(db, pWC->a);
129740  }
129741}
129742
129743
129744/*
129745** These routines walk (recursively) an expression tree and generate
129746** a bitmask indicating which tables are used in that expression
129747** tree.
129748*/
129749SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
129750  Bitmask mask;
129751  if( p==0 ) return 0;
129752  if( p->op==TK_COLUMN ){
129753    mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
129754    return mask;
129755  }
129756  assert( !ExprHasProperty(p, EP_TokenOnly) );
129757  mask = p->pRight ? sqlite3WhereExprUsage(pMaskSet, p->pRight) : 0;
129758  if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
129759  if( ExprHasProperty(p, EP_xIsSelect) ){
129760    mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
129761  }else if( p->x.pList ){
129762    mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
129763  }
129764  return mask;
129765}
129766SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
129767  int i;
129768  Bitmask mask = 0;
129769  if( pList ){
129770    for(i=0; i<pList->nExpr; i++){
129771      mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
129772    }
129773  }
129774  return mask;
129775}
129776
129777
129778/*
129779** Call exprAnalyze on all terms in a WHERE clause.
129780**
129781** Note that exprAnalyze() might add new virtual terms onto the
129782** end of the WHERE clause.  We do not want to analyze these new
129783** virtual terms, so start analyzing at the end and work forward
129784** so that the added virtual terms are never processed.
129785*/
129786SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
129787  SrcList *pTabList,       /* the FROM clause */
129788  WhereClause *pWC         /* the WHERE clause to be analyzed */
129789){
129790  int i;
129791  for(i=pWC->nTerm-1; i>=0; i--){
129792    exprAnalyze(pTabList, pWC, i);
129793  }
129794}
129795
129796/*
129797** For table-valued-functions, transform the function arguments into
129798** new WHERE clause terms.
129799**
129800** Each function argument translates into an equality constraint against
129801** a HIDDEN column in the table.
129802*/
129803SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
129804  Parse *pParse,                    /* Parsing context */
129805  struct SrcList_item *pItem,       /* The FROM clause term to process */
129806  WhereClause *pWC                  /* Xfer function arguments to here */
129807){
129808  Table *pTab;
129809  int j, k;
129810  ExprList *pArgs;
129811  Expr *pColRef;
129812  Expr *pTerm;
129813  if( pItem->fg.isTabFunc==0 ) return;
129814  pTab = pItem->pTab;
129815  assert( pTab!=0 );
129816  pArgs = pItem->u1.pFuncArg;
129817  if( pArgs==0 ) return;
129818  for(j=k=0; j<pArgs->nExpr; j++){
129819    while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
129820    if( k>=pTab->nCol ){
129821      sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
129822                      pTab->zName, j);
129823      return;
129824    }
129825    pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
129826    if( pColRef==0 ) return;
129827    pColRef->iTable = pItem->iCursor;
129828    pColRef->iColumn = k++;
129829    pColRef->pTab = pTab;
129830    pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
129831                         sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
129832    whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
129833  }
129834}
129835
129836/************** End of whereexpr.c *******************************************/
129837/************** Begin file where.c *******************************************/
129838/*
129839** 2001 September 15
129840**
129841** The author disclaims copyright to this source code.  In place of
129842** a legal notice, here is a blessing:
129843**
129844**    May you do good and not evil.
129845**    May you find forgiveness for yourself and forgive others.
129846**    May you share freely, never taking more than you give.
129847**
129848*************************************************************************
129849** This module contains C code that generates VDBE code used to process
129850** the WHERE clause of SQL statements.  This module is responsible for
129851** generating the code that loops through a table looking for applicable
129852** rows.  Indices are selected and used to speed the search when doing
129853** so is applicable.  Because this module is responsible for selecting
129854** indices, you might also think of this module as the "query optimizer".
129855*/
129856/* #include "sqliteInt.h" */
129857/* #include "whereInt.h" */
129858
129859/* Forward declaration of methods */
129860static int whereLoopResize(sqlite3*, WhereLoop*, int);
129861
129862/* Test variable that can be set to enable WHERE tracing */
129863#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
129864/***/ int sqlite3WhereTrace = 0;
129865#endif
129866
129867
129868/*
129869** Return the estimated number of output rows from a WHERE clause
129870*/
129871SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
129872  return pWInfo->nRowOut;
129873}
129874
129875/*
129876** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
129877** WHERE clause returns outputs for DISTINCT processing.
129878*/
129879SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
129880  return pWInfo->eDistinct;
129881}
129882
129883/*
129884** Return TRUE if the WHERE clause returns rows in ORDER BY order.
129885** Return FALSE if the output needs to be sorted.
129886*/
129887SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
129888  return pWInfo->nOBSat;
129889}
129890
129891/*
129892** Return TRUE if the innermost loop of the WHERE clause implementation
129893** returns rows in ORDER BY order for complete run of the inner loop.
129894**
129895** Across multiple iterations of outer loops, the output rows need not be
129896** sorted.  As long as rows are sorted for just the innermost loop, this
129897** routine can return TRUE.
129898*/
129899SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){
129900  return pWInfo->bOrderedInnerLoop;
129901}
129902
129903/*
129904** Return the VDBE address or label to jump to in order to continue
129905** immediately with the next row of a WHERE clause.
129906*/
129907SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
129908  assert( pWInfo->iContinue!=0 );
129909  return pWInfo->iContinue;
129910}
129911
129912/*
129913** Return the VDBE address or label to jump to in order to break
129914** out of a WHERE loop.
129915*/
129916SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
129917  return pWInfo->iBreak;
129918}
129919
129920/*
129921** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
129922** operate directly on the rowis returned by a WHERE clause.  Return
129923** ONEPASS_SINGLE (1) if the statement can operation directly because only
129924** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass
129925** optimization can be used on multiple
129926**
129927** If the ONEPASS optimization is used (if this routine returns true)
129928** then also write the indices of open cursors used by ONEPASS
129929** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
129930** table and iaCur[1] gets the cursor used by an auxiliary index.
129931** Either value may be -1, indicating that cursor is not used.
129932** Any cursors returned will have been opened for writing.
129933**
129934** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
129935** unable to use the ONEPASS optimization.
129936*/
129937SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
129938  memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
129939#ifdef WHERETRACE_ENABLED
129940  if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
129941    sqlite3DebugPrintf("%s cursors: %d %d\n",
129942         pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
129943         aiCur[0], aiCur[1]);
129944  }
129945#endif
129946  return pWInfo->eOnePass;
129947}
129948
129949/*
129950** Move the content of pSrc into pDest
129951*/
129952static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
129953  pDest->n = pSrc->n;
129954  memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
129955}
129956
129957/*
129958** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
129959**
129960** The new entry might overwrite an existing entry, or it might be
129961** appended, or it might be discarded.  Do whatever is the right thing
129962** so that pSet keeps the N_OR_COST best entries seen so far.
129963*/
129964static int whereOrInsert(
129965  WhereOrSet *pSet,      /* The WhereOrSet to be updated */
129966  Bitmask prereq,        /* Prerequisites of the new entry */
129967  LogEst rRun,           /* Run-cost of the new entry */
129968  LogEst nOut            /* Number of outputs for the new entry */
129969){
129970  u16 i;
129971  WhereOrCost *p;
129972  for(i=pSet->n, p=pSet->a; i>0; i--, p++){
129973    if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
129974      goto whereOrInsert_done;
129975    }
129976    if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
129977      return 0;
129978    }
129979  }
129980  if( pSet->n<N_OR_COST ){
129981    p = &pSet->a[pSet->n++];
129982    p->nOut = nOut;
129983  }else{
129984    p = pSet->a;
129985    for(i=1; i<pSet->n; i++){
129986      if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
129987    }
129988    if( p->rRun<=rRun ) return 0;
129989  }
129990whereOrInsert_done:
129991  p->prereq = prereq;
129992  p->rRun = rRun;
129993  if( p->nOut>nOut ) p->nOut = nOut;
129994  return 1;
129995}
129996
129997/*
129998** Return the bitmask for the given cursor number.  Return 0 if
129999** iCursor is not in the set.
130000*/
130001SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
130002  int i;
130003  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
130004  for(i=0; i<pMaskSet->n; i++){
130005    if( pMaskSet->ix[i]==iCursor ){
130006      return MASKBIT(i);
130007    }
130008  }
130009  return 0;
130010}
130011
130012/*
130013** Create a new mask for cursor iCursor.
130014**
130015** There is one cursor per table in the FROM clause.  The number of
130016** tables in the FROM clause is limited by a test early in the
130017** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
130018** array will never overflow.
130019*/
130020static void createMask(WhereMaskSet *pMaskSet, int iCursor){
130021  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
130022  pMaskSet->ix[pMaskSet->n++] = iCursor;
130023}
130024
130025/*
130026** Advance to the next WhereTerm that matches according to the criteria
130027** established when the pScan object was initialized by whereScanInit().
130028** Return NULL if there are no more matching WhereTerms.
130029*/
130030static WhereTerm *whereScanNext(WhereScan *pScan){
130031  int iCur;            /* The cursor on the LHS of the term */
130032  i16 iColumn;         /* The column on the LHS of the term.  -1 for IPK */
130033  Expr *pX;            /* An expression being tested */
130034  WhereClause *pWC;    /* Shorthand for pScan->pWC */
130035  WhereTerm *pTerm;    /* The term being tested */
130036  int k = pScan->k;    /* Where to start scanning */
130037
130038  assert( pScan->iEquiv<=pScan->nEquiv );
130039  pWC = pScan->pWC;
130040  while(1){
130041    iColumn = pScan->aiColumn[pScan->iEquiv-1];
130042    iCur = pScan->aiCur[pScan->iEquiv-1];
130043    assert( pWC!=0 );
130044    do{
130045      for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
130046        if( pTerm->leftCursor==iCur
130047         && pTerm->u.leftColumn==iColumn
130048         && (iColumn!=XN_EXPR
130049             || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
130050                                       pScan->pIdxExpr,iCur)==0)
130051         && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
130052        ){
130053          if( (pTerm->eOperator & WO_EQUIV)!=0
130054           && pScan->nEquiv<ArraySize(pScan->aiCur)
130055           && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
130056          ){
130057            int j;
130058            for(j=0; j<pScan->nEquiv; j++){
130059              if( pScan->aiCur[j]==pX->iTable
130060               && pScan->aiColumn[j]==pX->iColumn ){
130061                  break;
130062              }
130063            }
130064            if( j==pScan->nEquiv ){
130065              pScan->aiCur[j] = pX->iTable;
130066              pScan->aiColumn[j] = pX->iColumn;
130067              pScan->nEquiv++;
130068            }
130069          }
130070          if( (pTerm->eOperator & pScan->opMask)!=0 ){
130071            /* Verify the affinity and collating sequence match */
130072            if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
130073              CollSeq *pColl;
130074              Parse *pParse = pWC->pWInfo->pParse;
130075              pX = pTerm->pExpr;
130076              if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
130077                continue;
130078              }
130079              assert(pX->pLeft);
130080              pColl = sqlite3BinaryCompareCollSeq(pParse,
130081                                                  pX->pLeft, pX->pRight);
130082              if( pColl==0 ) pColl = pParse->db->pDfltColl;
130083              if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
130084                continue;
130085              }
130086            }
130087            if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
130088             && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
130089             && pX->iTable==pScan->aiCur[0]
130090             && pX->iColumn==pScan->aiColumn[0]
130091            ){
130092              testcase( pTerm->eOperator & WO_IS );
130093              continue;
130094            }
130095            pScan->pWC = pWC;
130096            pScan->k = k+1;
130097            return pTerm;
130098          }
130099        }
130100      }
130101      pWC = pWC->pOuter;
130102      k = 0;
130103    }while( pWC!=0 );
130104    if( pScan->iEquiv>=pScan->nEquiv ) break;
130105    pWC = pScan->pOrigWC;
130106    k = 0;
130107    pScan->iEquiv++;
130108  }
130109  return 0;
130110}
130111
130112/*
130113** Initialize a WHERE clause scanner object.  Return a pointer to the
130114** first match.  Return NULL if there are no matches.
130115**
130116** The scanner will be searching the WHERE clause pWC.  It will look
130117** for terms of the form "X <op> <expr>" where X is column iColumn of table
130118** iCur.   Or if pIdx!=0 then X is column iColumn of index pIdx.  pIdx
130119** must be one of the indexes of table iCur.
130120**
130121** The <op> must be one of the operators described by opMask.
130122**
130123** If the search is for X and the WHERE clause contains terms of the
130124** form X=Y then this routine might also return terms of the form
130125** "Y <op> <expr>".  The number of levels of transitivity is limited,
130126** but is enough to handle most commonly occurring SQL statements.
130127**
130128** If X is not the INTEGER PRIMARY KEY then X must be compatible with
130129** index pIdx.
130130*/
130131static WhereTerm *whereScanInit(
130132  WhereScan *pScan,       /* The WhereScan object being initialized */
130133  WhereClause *pWC,       /* The WHERE clause to be scanned */
130134  int iCur,               /* Cursor to scan for */
130135  int iColumn,            /* Column to scan for */
130136  u32 opMask,             /* Operator(s) to scan for */
130137  Index *pIdx             /* Must be compatible with this index */
130138){
130139  pScan->pOrigWC = pWC;
130140  pScan->pWC = pWC;
130141  pScan->pIdxExpr = 0;
130142  pScan->idxaff = 0;
130143  pScan->zCollName = 0;
130144  if( pIdx ){
130145    int j = iColumn;
130146    iColumn = pIdx->aiColumn[j];
130147    if( iColumn==XN_EXPR ){
130148      pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
130149      pScan->zCollName = pIdx->azColl[j];
130150    }else if( iColumn==pIdx->pTable->iPKey ){
130151      iColumn = XN_ROWID;
130152    }else if( iColumn>=0 ){
130153      pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
130154      pScan->zCollName = pIdx->azColl[j];
130155    }
130156  }else if( iColumn==XN_EXPR ){
130157    return 0;
130158  }
130159  pScan->opMask = opMask;
130160  pScan->k = 0;
130161  pScan->aiCur[0] = iCur;
130162  pScan->aiColumn[0] = iColumn;
130163  pScan->nEquiv = 1;
130164  pScan->iEquiv = 1;
130165  return whereScanNext(pScan);
130166}
130167
130168/*
130169** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
130170** where X is a reference to the iColumn of table iCur or of index pIdx
130171** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
130172** the op parameter.  Return a pointer to the term.  Return 0 if not found.
130173**
130174** If pIdx!=0 then it must be one of the indexes of table iCur.
130175** Search for terms matching the iColumn-th column of pIdx
130176** rather than the iColumn-th column of table iCur.
130177**
130178** The term returned might by Y=<expr> if there is another constraint in
130179** the WHERE clause that specifies that X=Y.  Any such constraints will be
130180** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
130181** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
130182** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
130183** other equivalent values.  Hence a search for X will return <expr> if X=A1
130184** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
130185**
130186** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
130187** then try for the one with no dependencies on <expr> - in other words where
130188** <expr> is a constant expression of some kind.  Only return entries of
130189** the form "X <op> Y" where Y is a column in another table if no terms of
130190** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
130191** exist, try to return a term that does not use WO_EQUIV.
130192*/
130193SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
130194  WhereClause *pWC,     /* The WHERE clause to be searched */
130195  int iCur,             /* Cursor number of LHS */
130196  int iColumn,          /* Column number of LHS */
130197  Bitmask notReady,     /* RHS must not overlap with this mask */
130198  u32 op,               /* Mask of WO_xx values describing operator */
130199  Index *pIdx           /* Must be compatible with this index, if not NULL */
130200){
130201  WhereTerm *pResult = 0;
130202  WhereTerm *p;
130203  WhereScan scan;
130204
130205  p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
130206  op &= WO_EQ|WO_IS;
130207  while( p ){
130208    if( (p->prereqRight & notReady)==0 ){
130209      if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
130210        testcase( p->eOperator & WO_IS );
130211        return p;
130212      }
130213      if( pResult==0 ) pResult = p;
130214    }
130215    p = whereScanNext(&scan);
130216  }
130217  return pResult;
130218}
130219
130220/*
130221** This function searches pList for an entry that matches the iCol-th column
130222** of index pIdx.
130223**
130224** If such an expression is found, its index in pList->a[] is returned. If
130225** no expression is found, -1 is returned.
130226*/
130227static int findIndexCol(
130228  Parse *pParse,                  /* Parse context */
130229  ExprList *pList,                /* Expression list to search */
130230  int iBase,                      /* Cursor for table associated with pIdx */
130231  Index *pIdx,                    /* Index to match column of */
130232  int iCol                        /* Column of index to match */
130233){
130234  int i;
130235  const char *zColl = pIdx->azColl[iCol];
130236
130237  for(i=0; i<pList->nExpr; i++){
130238    Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
130239    if( p->op==TK_COLUMN
130240     && p->iColumn==pIdx->aiColumn[iCol]
130241     && p->iTable==iBase
130242    ){
130243      CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
130244      if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
130245        return i;
130246      }
130247    }
130248  }
130249
130250  return -1;
130251}
130252
130253/*
130254** Return TRUE if the iCol-th column of index pIdx is NOT NULL
130255*/
130256static int indexColumnNotNull(Index *pIdx, int iCol){
130257  int j;
130258  assert( pIdx!=0 );
130259  assert( iCol>=0 && iCol<pIdx->nColumn );
130260  j = pIdx->aiColumn[iCol];
130261  if( j>=0 ){
130262    return pIdx->pTable->aCol[j].notNull;
130263  }else if( j==(-1) ){
130264    return 1;
130265  }else{
130266    assert( j==(-2) );
130267    return 0;  /* Assume an indexed expression can always yield a NULL */
130268
130269  }
130270}
130271
130272/*
130273** Return true if the DISTINCT expression-list passed as the third argument
130274** is redundant.
130275**
130276** A DISTINCT list is redundant if any subset of the columns in the
130277** DISTINCT list are collectively unique and individually non-null.
130278*/
130279static int isDistinctRedundant(
130280  Parse *pParse,            /* Parsing context */
130281  SrcList *pTabList,        /* The FROM clause */
130282  WhereClause *pWC,         /* The WHERE clause */
130283  ExprList *pDistinct       /* The result set that needs to be DISTINCT */
130284){
130285  Table *pTab;
130286  Index *pIdx;
130287  int i;
130288  int iBase;
130289
130290  /* If there is more than one table or sub-select in the FROM clause of
130291  ** this query, then it will not be possible to show that the DISTINCT
130292  ** clause is redundant. */
130293  if( pTabList->nSrc!=1 ) return 0;
130294  iBase = pTabList->a[0].iCursor;
130295  pTab = pTabList->a[0].pTab;
130296
130297  /* If any of the expressions is an IPK column on table iBase, then return
130298  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
130299  ** current SELECT is a correlated sub-query.
130300  */
130301  for(i=0; i<pDistinct->nExpr; i++){
130302    Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
130303    if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
130304  }
130305
130306  /* Loop through all indices on the table, checking each to see if it makes
130307  ** the DISTINCT qualifier redundant. It does so if:
130308  **
130309  **   1. The index is itself UNIQUE, and
130310  **
130311  **   2. All of the columns in the index are either part of the pDistinct
130312  **      list, or else the WHERE clause contains a term of the form "col=X",
130313  **      where X is a constant value. The collation sequences of the
130314  **      comparison and select-list expressions must match those of the index.
130315  **
130316  **   3. All of those index columns for which the WHERE clause does not
130317  **      contain a "col=X" term are subject to a NOT NULL constraint.
130318  */
130319  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
130320    if( !IsUniqueIndex(pIdx) ) continue;
130321    for(i=0; i<pIdx->nKeyCol; i++){
130322      if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
130323        if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
130324        if( indexColumnNotNull(pIdx, i)==0 ) break;
130325      }
130326    }
130327    if( i==pIdx->nKeyCol ){
130328      /* This index implies that the DISTINCT qualifier is redundant. */
130329      return 1;
130330    }
130331  }
130332
130333  return 0;
130334}
130335
130336
130337/*
130338** Estimate the logarithm of the input value to base 2.
130339*/
130340static LogEst estLog(LogEst N){
130341  return N<=10 ? 0 : sqlite3LogEst(N) - 33;
130342}
130343
130344/*
130345** Convert OP_Column opcodes to OP_Copy in previously generated code.
130346**
130347** This routine runs over generated VDBE code and translates OP_Column
130348** opcodes into OP_Copy when the table is being accessed via co-routine
130349** instead of via table lookup.
130350**
130351** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
130352** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
130353** then each OP_Rowid is transformed into an instruction to increment the
130354** value stored in its output register.
130355*/
130356static void translateColumnToCopy(
130357  Parse *pParse,      /* Parsing context */
130358  int iStart,         /* Translate from this opcode to the end */
130359  int iTabCur,        /* OP_Column/OP_Rowid references to this table */
130360  int iRegister,      /* The first column is in this register */
130361  int bIncrRowid      /* If non-zero, transform OP_rowid to OP_AddImm(1) */
130362){
130363  Vdbe *v = pParse->pVdbe;
130364  VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
130365  int iEnd = sqlite3VdbeCurrentAddr(v);
130366  if( pParse->db->mallocFailed ) return;
130367  for(; iStart<iEnd; iStart++, pOp++){
130368    if( pOp->p1!=iTabCur ) continue;
130369    if( pOp->opcode==OP_Column ){
130370      pOp->opcode = OP_Copy;
130371      pOp->p1 = pOp->p2 + iRegister;
130372      pOp->p2 = pOp->p3;
130373      pOp->p3 = 0;
130374    }else if( pOp->opcode==OP_Rowid ){
130375      if( bIncrRowid ){
130376        /* Increment the value stored in the P2 operand of the OP_Rowid. */
130377        pOp->opcode = OP_AddImm;
130378        pOp->p1 = pOp->p2;
130379        pOp->p2 = 1;
130380      }else{
130381        pOp->opcode = OP_Null;
130382        pOp->p1 = 0;
130383        pOp->p3 = 0;
130384      }
130385    }
130386  }
130387}
130388
130389/*
130390** Two routines for printing the content of an sqlite3_index_info
130391** structure.  Used for testing and debugging only.  If neither
130392** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
130393** are no-ops.
130394*/
130395#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
130396static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
130397  int i;
130398  if( !sqlite3WhereTrace ) return;
130399  for(i=0; i<p->nConstraint; i++){
130400    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
130401       i,
130402       p->aConstraint[i].iColumn,
130403       p->aConstraint[i].iTermOffset,
130404       p->aConstraint[i].op,
130405       p->aConstraint[i].usable);
130406  }
130407  for(i=0; i<p->nOrderBy; i++){
130408    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
130409       i,
130410       p->aOrderBy[i].iColumn,
130411       p->aOrderBy[i].desc);
130412  }
130413}
130414static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
130415  int i;
130416  if( !sqlite3WhereTrace ) return;
130417  for(i=0; i<p->nConstraint; i++){
130418    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
130419       i,
130420       p->aConstraintUsage[i].argvIndex,
130421       p->aConstraintUsage[i].omit);
130422  }
130423  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
130424  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
130425  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
130426  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
130427  sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
130428}
130429#else
130430#define TRACE_IDX_INPUTS(A)
130431#define TRACE_IDX_OUTPUTS(A)
130432#endif
130433
130434#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
130435/*
130436** Return TRUE if the WHERE clause term pTerm is of a form where it
130437** could be used with an index to access pSrc, assuming an appropriate
130438** index existed.
130439*/
130440static int termCanDriveIndex(
130441  WhereTerm *pTerm,              /* WHERE clause term to check */
130442  struct SrcList_item *pSrc,     /* Table we are trying to access */
130443  Bitmask notReady               /* Tables in outer loops of the join */
130444){
130445  char aff;
130446  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
130447  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
130448  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
130449  if( pTerm->u.leftColumn<0 ) return 0;
130450  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
130451  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
130452  testcase( pTerm->pExpr->op==TK_IS );
130453  return 1;
130454}
130455#endif
130456
130457
130458#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
130459/*
130460** Generate code to construct the Index object for an automatic index
130461** and to set up the WhereLevel object pLevel so that the code generator
130462** makes use of the automatic index.
130463*/
130464static void constructAutomaticIndex(
130465  Parse *pParse,              /* The parsing context */
130466  WhereClause *pWC,           /* The WHERE clause */
130467  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
130468  Bitmask notReady,           /* Mask of cursors that are not available */
130469  WhereLevel *pLevel          /* Write new index here */
130470){
130471  int nKeyCol;                /* Number of columns in the constructed index */
130472  WhereTerm *pTerm;           /* A single term of the WHERE clause */
130473  WhereTerm *pWCEnd;          /* End of pWC->a[] */
130474  Index *pIdx;                /* Object describing the transient index */
130475  Vdbe *v;                    /* Prepared statement under construction */
130476  int addrInit;               /* Address of the initialization bypass jump */
130477  Table *pTable;              /* The table being indexed */
130478  int addrTop;                /* Top of the index fill loop */
130479  int regRecord;              /* Register holding an index record */
130480  int n;                      /* Column counter */
130481  int i;                      /* Loop counter */
130482  int mxBitCol;               /* Maximum column in pSrc->colUsed */
130483  CollSeq *pColl;             /* Collating sequence to on a column */
130484  WhereLoop *pLoop;           /* The Loop object */
130485  char *zNotUsed;             /* Extra space on the end of pIdx */
130486  Bitmask idxCols;            /* Bitmap of columns used for indexing */
130487  Bitmask extraCols;          /* Bitmap of additional columns */
130488  u8 sentWarning = 0;         /* True if a warnning has been issued */
130489  Expr *pPartial = 0;         /* Partial Index Expression */
130490  int iContinue = 0;          /* Jump here to skip excluded rows */
130491  struct SrcList_item *pTabItem;  /* FROM clause term being indexed */
130492  int addrCounter = 0;        /* Address where integer counter is initialized */
130493  int regBase;                /* Array of registers where record is assembled */
130494
130495  /* Generate code to skip over the creation and initialization of the
130496  ** transient index on 2nd and subsequent iterations of the loop. */
130497  v = pParse->pVdbe;
130498  assert( v!=0 );
130499  addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
130500
130501  /* Count the number of columns that will be added to the index
130502  ** and used to match WHERE clause constraints */
130503  nKeyCol = 0;
130504  pTable = pSrc->pTab;
130505  pWCEnd = &pWC->a[pWC->nTerm];
130506  pLoop = pLevel->pWLoop;
130507  idxCols = 0;
130508  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
130509    Expr *pExpr = pTerm->pExpr;
130510    assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */
130511         || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */
130512         || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */
130513    if( pLoop->prereq==0
130514     && (pTerm->wtFlags & TERM_VIRTUAL)==0
130515     && !ExprHasProperty(pExpr, EP_FromJoin)
130516     && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
130517      pPartial = sqlite3ExprAnd(pParse->db, pPartial,
130518                                sqlite3ExprDup(pParse->db, pExpr, 0));
130519    }
130520    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
130521      int iCol = pTerm->u.leftColumn;
130522      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
130523      testcase( iCol==BMS );
130524      testcase( iCol==BMS-1 );
130525      if( !sentWarning ){
130526        sqlite3_log(SQLITE_WARNING_AUTOINDEX,
130527            "automatic index on %s(%s)", pTable->zName,
130528            pTable->aCol[iCol].zName);
130529        sentWarning = 1;
130530      }
130531      if( (idxCols & cMask)==0 ){
130532        if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
130533          goto end_auto_index_create;
130534        }
130535        pLoop->aLTerm[nKeyCol++] = pTerm;
130536        idxCols |= cMask;
130537      }
130538    }
130539  }
130540  assert( nKeyCol>0 );
130541  pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
130542  pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
130543                     | WHERE_AUTO_INDEX;
130544
130545  /* Count the number of additional columns needed to create a
130546  ** covering index.  A "covering index" is an index that contains all
130547  ** columns that are needed by the query.  With a covering index, the
130548  ** original table never needs to be accessed.  Automatic indices must
130549  ** be a covering index because the index will not be updated if the
130550  ** original table changes and the index and table cannot both be used
130551  ** if they go out of sync.
130552  */
130553  extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
130554  mxBitCol = MIN(BMS-1,pTable->nCol);
130555  testcase( pTable->nCol==BMS-1 );
130556  testcase( pTable->nCol==BMS-2 );
130557  for(i=0; i<mxBitCol; i++){
130558    if( extraCols & MASKBIT(i) ) nKeyCol++;
130559  }
130560  if( pSrc->colUsed & MASKBIT(BMS-1) ){
130561    nKeyCol += pTable->nCol - BMS + 1;
130562  }
130563
130564  /* Construct the Index object to describe this index */
130565  pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
130566  if( pIdx==0 ) goto end_auto_index_create;
130567  pLoop->u.btree.pIndex = pIdx;
130568  pIdx->zName = "auto-index";
130569  pIdx->pTable = pTable;
130570  n = 0;
130571  idxCols = 0;
130572  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
130573    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
130574      int iCol = pTerm->u.leftColumn;
130575      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
130576      testcase( iCol==BMS-1 );
130577      testcase( iCol==BMS );
130578      if( (idxCols & cMask)==0 ){
130579        Expr *pX = pTerm->pExpr;
130580        idxCols |= cMask;
130581        pIdx->aiColumn[n] = pTerm->u.leftColumn;
130582        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
130583        pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
130584        n++;
130585      }
130586    }
130587  }
130588  assert( (u32)n==pLoop->u.btree.nEq );
130589
130590  /* Add additional columns needed to make the automatic index into
130591  ** a covering index */
130592  for(i=0; i<mxBitCol; i++){
130593    if( extraCols & MASKBIT(i) ){
130594      pIdx->aiColumn[n] = i;
130595      pIdx->azColl[n] = sqlite3StrBINARY;
130596      n++;
130597    }
130598  }
130599  if( pSrc->colUsed & MASKBIT(BMS-1) ){
130600    for(i=BMS-1; i<pTable->nCol; i++){
130601      pIdx->aiColumn[n] = i;
130602      pIdx->azColl[n] = sqlite3StrBINARY;
130603      n++;
130604    }
130605  }
130606  assert( n==nKeyCol );
130607  pIdx->aiColumn[n] = XN_ROWID;
130608  pIdx->azColl[n] = sqlite3StrBINARY;
130609
130610  /* Create the automatic index */
130611  assert( pLevel->iIdxCur>=0 );
130612  pLevel->iIdxCur = pParse->nTab++;
130613  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
130614  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
130615  VdbeComment((v, "for %s", pTable->zName));
130616
130617  /* Fill the automatic index with content */
130618  sqlite3ExprCachePush(pParse);
130619  pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
130620  if( pTabItem->fg.viaCoroutine ){
130621    int regYield = pTabItem->regReturn;
130622    addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
130623    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
130624    addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
130625    VdbeCoverage(v);
130626    VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
130627  }else{
130628    addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
130629  }
130630  if( pPartial ){
130631    iContinue = sqlite3VdbeMakeLabel(v);
130632    sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
130633    pLoop->wsFlags |= WHERE_PARTIALIDX;
130634  }
130635  regRecord = sqlite3GetTempReg(pParse);
130636  regBase = sqlite3GenerateIndexKey(
130637      pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
130638  );
130639  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
130640  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
130641  if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
130642  if( pTabItem->fg.viaCoroutine ){
130643    sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
130644    testcase( pParse->db->mallocFailed );
130645    translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
130646                          pTabItem->regResult, 1);
130647    sqlite3VdbeGoto(v, addrTop);
130648    pTabItem->fg.viaCoroutine = 0;
130649  }else{
130650    sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
130651  }
130652  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
130653  sqlite3VdbeJumpHere(v, addrTop);
130654  sqlite3ReleaseTempReg(pParse, regRecord);
130655  sqlite3ExprCachePop(pParse);
130656
130657  /* Jump here when skipping the initialization */
130658  sqlite3VdbeJumpHere(v, addrInit);
130659
130660end_auto_index_create:
130661  sqlite3ExprDelete(pParse->db, pPartial);
130662}
130663#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
130664
130665#ifndef SQLITE_OMIT_VIRTUALTABLE
130666/*
130667** Allocate and populate an sqlite3_index_info structure. It is the
130668** responsibility of the caller to eventually release the structure
130669** by passing the pointer returned by this function to sqlite3_free().
130670*/
130671static sqlite3_index_info *allocateIndexInfo(
130672  Parse *pParse,
130673  WhereClause *pWC,
130674  Bitmask mUnusable,              /* Ignore terms with these prereqs */
130675  struct SrcList_item *pSrc,
130676  ExprList *pOrderBy,
130677  u16 *pmNoOmit                   /* Mask of terms not to omit */
130678){
130679  int i, j;
130680  int nTerm;
130681  struct sqlite3_index_constraint *pIdxCons;
130682  struct sqlite3_index_orderby *pIdxOrderBy;
130683  struct sqlite3_index_constraint_usage *pUsage;
130684  WhereTerm *pTerm;
130685  int nOrderBy;
130686  sqlite3_index_info *pIdxInfo;
130687  u16 mNoOmit = 0;
130688
130689  /* Count the number of possible WHERE clause constraints referring
130690  ** to this virtual table */
130691  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
130692    if( pTerm->leftCursor != pSrc->iCursor ) continue;
130693    if( pTerm->prereqRight & mUnusable ) continue;
130694    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
130695    testcase( pTerm->eOperator & WO_IN );
130696    testcase( pTerm->eOperator & WO_ISNULL );
130697    testcase( pTerm->eOperator & WO_IS );
130698    testcase( pTerm->eOperator & WO_ALL );
130699    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
130700    if( pTerm->wtFlags & TERM_VNULL ) continue;
130701    assert( pTerm->u.leftColumn>=(-1) );
130702    nTerm++;
130703  }
130704
130705  /* If the ORDER BY clause contains only columns in the current
130706  ** virtual table then allocate space for the aOrderBy part of
130707  ** the sqlite3_index_info structure.
130708  */
130709  nOrderBy = 0;
130710  if( pOrderBy ){
130711    int n = pOrderBy->nExpr;
130712    for(i=0; i<n; i++){
130713      Expr *pExpr = pOrderBy->a[i].pExpr;
130714      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
130715    }
130716    if( i==n){
130717      nOrderBy = n;
130718    }
130719  }
130720
130721  /* Allocate the sqlite3_index_info structure
130722  */
130723  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
130724                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
130725                           + sizeof(*pIdxOrderBy)*nOrderBy );
130726  if( pIdxInfo==0 ){
130727    sqlite3ErrorMsg(pParse, "out of memory");
130728    return 0;
130729  }
130730
130731  /* Initialize the structure.  The sqlite3_index_info structure contains
130732  ** many fields that are declared "const" to prevent xBestIndex from
130733  ** changing them.  We have to do some funky casting in order to
130734  ** initialize those fields.
130735  */
130736  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
130737  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
130738  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
130739  *(int*)&pIdxInfo->nConstraint = nTerm;
130740  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
130741  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
130742  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
130743  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
130744                                                                   pUsage;
130745
130746  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
130747    u8 op;
130748    if( pTerm->leftCursor != pSrc->iCursor ) continue;
130749    if( pTerm->prereqRight & mUnusable ) continue;
130750    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
130751    testcase( pTerm->eOperator & WO_IN );
130752    testcase( pTerm->eOperator & WO_IS );
130753    testcase( pTerm->eOperator & WO_ISNULL );
130754    testcase( pTerm->eOperator & WO_ALL );
130755    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
130756    if( pTerm->wtFlags & TERM_VNULL ) continue;
130757    assert( pTerm->u.leftColumn>=(-1) );
130758    pIdxCons[j].iColumn = pTerm->u.leftColumn;
130759    pIdxCons[j].iTermOffset = i;
130760    op = (u8)pTerm->eOperator & WO_ALL;
130761    if( op==WO_IN ) op = WO_EQ;
130762    if( op==WO_MATCH ){
130763      op = pTerm->eMatchOp;
130764    }
130765    pIdxCons[j].op = op;
130766    /* The direct assignment in the previous line is possible only because
130767    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
130768    ** following asserts verify this fact. */
130769    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
130770    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
130771    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
130772    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
130773    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
130774    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
130775    assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
130776
130777    if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
130778     && sqlite3ExprIsVector(pTerm->pExpr->pRight)
130779    ){
130780      if( i<16 ) mNoOmit |= (1 << i);
130781      if( op==WO_LT ) pIdxCons[j].op = WO_LE;
130782      if( op==WO_GT ) pIdxCons[j].op = WO_GE;
130783    }
130784
130785    j++;
130786  }
130787  for(i=0; i<nOrderBy; i++){
130788    Expr *pExpr = pOrderBy->a[i].pExpr;
130789    pIdxOrderBy[i].iColumn = pExpr->iColumn;
130790    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
130791  }
130792
130793  *pmNoOmit = mNoOmit;
130794  return pIdxInfo;
130795}
130796
130797/*
130798** The table object reference passed as the second argument to this function
130799** must represent a virtual table. This function invokes the xBestIndex()
130800** method of the virtual table with the sqlite3_index_info object that
130801** comes in as the 3rd argument to this function.
130802**
130803** If an error occurs, pParse is populated with an error message and a
130804** non-zero value is returned. Otherwise, 0 is returned and the output
130805** part of the sqlite3_index_info structure is left populated.
130806**
130807** Whether or not an error is returned, it is the responsibility of the
130808** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
130809** that this is required.
130810*/
130811static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
130812  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
130813  int rc;
130814
130815  TRACE_IDX_INPUTS(p);
130816  rc = pVtab->pModule->xBestIndex(pVtab, p);
130817  TRACE_IDX_OUTPUTS(p);
130818
130819  if( rc!=SQLITE_OK ){
130820    if( rc==SQLITE_NOMEM ){
130821      sqlite3OomFault(pParse->db);
130822    }else if( !pVtab->zErrMsg ){
130823      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
130824    }else{
130825      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
130826    }
130827  }
130828  sqlite3_free(pVtab->zErrMsg);
130829  pVtab->zErrMsg = 0;
130830
130831#if 0
130832  /* This error is now caught by the caller.
130833  ** Search for "xBestIndex malfunction" below */
130834  for(i=0; i<p->nConstraint; i++){
130835    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
130836      sqlite3ErrorMsg(pParse,
130837          "table %s: xBestIndex returned an invalid plan", pTab->zName);
130838    }
130839  }
130840#endif
130841
130842  return pParse->nErr;
130843}
130844#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
130845
130846#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
130847/*
130848** Estimate the location of a particular key among all keys in an
130849** index.  Store the results in aStat as follows:
130850**
130851**    aStat[0]      Est. number of rows less than pRec
130852**    aStat[1]      Est. number of rows equal to pRec
130853**
130854** Return the index of the sample that is the smallest sample that
130855** is greater than or equal to pRec. Note that this index is not an index
130856** into the aSample[] array - it is an index into a virtual set of samples
130857** based on the contents of aSample[] and the number of fields in record
130858** pRec.
130859*/
130860static int whereKeyStats(
130861  Parse *pParse,              /* Database connection */
130862  Index *pIdx,                /* Index to consider domain of */
130863  UnpackedRecord *pRec,       /* Vector of values to consider */
130864  int roundUp,                /* Round up if true.  Round down if false */
130865  tRowcnt *aStat              /* OUT: stats written here */
130866){
130867  IndexSample *aSample = pIdx->aSample;
130868  int iCol;                   /* Index of required stats in anEq[] etc. */
130869  int i;                      /* Index of first sample >= pRec */
130870  int iSample;                /* Smallest sample larger than or equal to pRec */
130871  int iMin = 0;               /* Smallest sample not yet tested */
130872  int iTest;                  /* Next sample to test */
130873  int res;                    /* Result of comparison operation */
130874  int nField;                 /* Number of fields in pRec */
130875  tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
130876
130877#ifndef SQLITE_DEBUG
130878  UNUSED_PARAMETER( pParse );
130879#endif
130880  assert( pRec!=0 );
130881  assert( pIdx->nSample>0 );
130882  assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
130883
130884  /* Do a binary search to find the first sample greater than or equal
130885  ** to pRec. If pRec contains a single field, the set of samples to search
130886  ** is simply the aSample[] array. If the samples in aSample[] contain more
130887  ** than one fields, all fields following the first are ignored.
130888  **
130889  ** If pRec contains N fields, where N is more than one, then as well as the
130890  ** samples in aSample[] (truncated to N fields), the search also has to
130891  ** consider prefixes of those samples. For example, if the set of samples
130892  ** in aSample is:
130893  **
130894  **     aSample[0] = (a, 5)
130895  **     aSample[1] = (a, 10)
130896  **     aSample[2] = (b, 5)
130897  **     aSample[3] = (c, 100)
130898  **     aSample[4] = (c, 105)
130899  **
130900  ** Then the search space should ideally be the samples above and the
130901  ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
130902  ** the code actually searches this set:
130903  **
130904  **     0: (a)
130905  **     1: (a, 5)
130906  **     2: (a, 10)
130907  **     3: (a, 10)
130908  **     4: (b)
130909  **     5: (b, 5)
130910  **     6: (c)
130911  **     7: (c, 100)
130912  **     8: (c, 105)
130913  **     9: (c, 105)
130914  **
130915  ** For each sample in the aSample[] array, N samples are present in the
130916  ** effective sample array. In the above, samples 0 and 1 are based on
130917  ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
130918  **
130919  ** Often, sample i of each block of N effective samples has (i+1) fields.
130920  ** Except, each sample may be extended to ensure that it is greater than or
130921  ** equal to the previous sample in the array. For example, in the above,
130922  ** sample 2 is the first sample of a block of N samples, so at first it
130923  ** appears that it should be 1 field in size. However, that would make it
130924  ** smaller than sample 1, so the binary search would not work. As a result,
130925  ** it is extended to two fields. The duplicates that this creates do not
130926  ** cause any problems.
130927  */
130928  nField = pRec->nField;
130929  iCol = 0;
130930  iSample = pIdx->nSample * nField;
130931  do{
130932    int iSamp;                    /* Index in aSample[] of test sample */
130933    int n;                        /* Number of fields in test sample */
130934
130935    iTest = (iMin+iSample)/2;
130936    iSamp = iTest / nField;
130937    if( iSamp>0 ){
130938      /* The proposed effective sample is a prefix of sample aSample[iSamp].
130939      ** Specifically, the shortest prefix of at least (1 + iTest%nField)
130940      ** fields that is greater than the previous effective sample.  */
130941      for(n=(iTest % nField) + 1; n<nField; n++){
130942        if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
130943      }
130944    }else{
130945      n = iTest + 1;
130946    }
130947
130948    pRec->nField = n;
130949    res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
130950    if( res<0 ){
130951      iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
130952      iMin = iTest+1;
130953    }else if( res==0 && n<nField ){
130954      iLower = aSample[iSamp].anLt[n-1];
130955      iMin = iTest+1;
130956      res = -1;
130957    }else{
130958      iSample = iTest;
130959      iCol = n-1;
130960    }
130961  }while( res && iMin<iSample );
130962  i = iSample / nField;
130963
130964#ifdef SQLITE_DEBUG
130965  /* The following assert statements check that the binary search code
130966  ** above found the right answer. This block serves no purpose other
130967  ** than to invoke the asserts.  */
130968  if( pParse->db->mallocFailed==0 ){
130969    if( res==0 ){
130970      /* If (res==0) is true, then pRec must be equal to sample i. */
130971      assert( i<pIdx->nSample );
130972      assert( iCol==nField-1 );
130973      pRec->nField = nField;
130974      assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
130975           || pParse->db->mallocFailed
130976      );
130977    }else{
130978      /* Unless i==pIdx->nSample, indicating that pRec is larger than
130979      ** all samples in the aSample[] array, pRec must be smaller than the
130980      ** (iCol+1) field prefix of sample i.  */
130981      assert( i<=pIdx->nSample && i>=0 );
130982      pRec->nField = iCol+1;
130983      assert( i==pIdx->nSample
130984           || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
130985           || pParse->db->mallocFailed );
130986
130987      /* if i==0 and iCol==0, then record pRec is smaller than all samples
130988      ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
130989      ** be greater than or equal to the (iCol) field prefix of sample i.
130990      ** If (i>0), then pRec must also be greater than sample (i-1).  */
130991      if( iCol>0 ){
130992        pRec->nField = iCol;
130993        assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
130994             || pParse->db->mallocFailed );
130995      }
130996      if( i>0 ){
130997        pRec->nField = nField;
130998        assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
130999             || pParse->db->mallocFailed );
131000      }
131001    }
131002  }
131003#endif /* ifdef SQLITE_DEBUG */
131004
131005  if( res==0 ){
131006    /* Record pRec is equal to sample i */
131007    assert( iCol==nField-1 );
131008    aStat[0] = aSample[i].anLt[iCol];
131009    aStat[1] = aSample[i].anEq[iCol];
131010  }else{
131011    /* At this point, the (iCol+1) field prefix of aSample[i] is the first
131012    ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
131013    ** is larger than all samples in the array. */
131014    tRowcnt iUpper, iGap;
131015    if( i>=pIdx->nSample ){
131016      iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
131017    }else{
131018      iUpper = aSample[i].anLt[iCol];
131019    }
131020
131021    if( iLower>=iUpper ){
131022      iGap = 0;
131023    }else{
131024      iGap = iUpper - iLower;
131025    }
131026    if( roundUp ){
131027      iGap = (iGap*2)/3;
131028    }else{
131029      iGap = iGap/3;
131030    }
131031    aStat[0] = iLower + iGap;
131032    aStat[1] = pIdx->aAvgEq[iCol];
131033  }
131034
131035  /* Restore the pRec->nField value before returning.  */
131036  pRec->nField = nField;
131037  return i;
131038}
131039#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
131040
131041/*
131042** If it is not NULL, pTerm is a term that provides an upper or lower
131043** bound on a range scan. Without considering pTerm, it is estimated
131044** that the scan will visit nNew rows. This function returns the number
131045** estimated to be visited after taking pTerm into account.
131046**
131047** If the user explicitly specified a likelihood() value for this term,
131048** then the return value is the likelihood multiplied by the number of
131049** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
131050** has a likelihood of 0.50, and any other term a likelihood of 0.25.
131051*/
131052static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
131053  LogEst nRet = nNew;
131054  if( pTerm ){
131055    if( pTerm->truthProb<=0 ){
131056      nRet += pTerm->truthProb;
131057    }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
131058      nRet -= 20;        assert( 20==sqlite3LogEst(4) );
131059    }
131060  }
131061  return nRet;
131062}
131063
131064
131065#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
131066/*
131067** Return the affinity for a single column of an index.
131068*/
131069SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
131070  assert( iCol>=0 && iCol<pIdx->nColumn );
131071  if( !pIdx->zColAff ){
131072    if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
131073  }
131074  return pIdx->zColAff[iCol];
131075}
131076#endif
131077
131078
131079#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
131080/*
131081** This function is called to estimate the number of rows visited by a
131082** range-scan on a skip-scan index. For example:
131083**
131084**   CREATE INDEX i1 ON t1(a, b, c);
131085**   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
131086**
131087** Value pLoop->nOut is currently set to the estimated number of rows
131088** visited for scanning (a=? AND b=?). This function reduces that estimate
131089** by some factor to account for the (c BETWEEN ? AND ?) expression based
131090** on the stat4 data for the index. this scan will be peformed multiple
131091** times (once for each (a,b) combination that matches a=?) is dealt with
131092** by the caller.
131093**
131094** It does this by scanning through all stat4 samples, comparing values
131095** extracted from pLower and pUpper with the corresponding column in each
131096** sample. If L and U are the number of samples found to be less than or
131097** equal to the values extracted from pLower and pUpper respectively, and
131098** N is the total number of samples, the pLoop->nOut value is adjusted
131099** as follows:
131100**
131101**   nOut = nOut * ( min(U - L, 1) / N )
131102**
131103** If pLower is NULL, or a value cannot be extracted from the term, L is
131104** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
131105** U is set to N.
131106**
131107** Normally, this function sets *pbDone to 1 before returning. However,
131108** if no value can be extracted from either pLower or pUpper (and so the
131109** estimate of the number of rows delivered remains unchanged), *pbDone
131110** is left as is.
131111**
131112** If an error occurs, an SQLite error code is returned. Otherwise,
131113** SQLITE_OK.
131114*/
131115static int whereRangeSkipScanEst(
131116  Parse *pParse,       /* Parsing & code generating context */
131117  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
131118  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
131119  WhereLoop *pLoop,    /* Update the .nOut value of this loop */
131120  int *pbDone          /* Set to true if at least one expr. value extracted */
131121){
131122  Index *p = pLoop->u.btree.pIndex;
131123  int nEq = pLoop->u.btree.nEq;
131124  sqlite3 *db = pParse->db;
131125  int nLower = -1;
131126  int nUpper = p->nSample+1;
131127  int rc = SQLITE_OK;
131128  u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
131129  CollSeq *pColl;
131130
131131  sqlite3_value *p1 = 0;          /* Value extracted from pLower */
131132  sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
131133  sqlite3_value *pVal = 0;        /* Value extracted from record */
131134
131135  pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
131136  if( pLower ){
131137    rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
131138    nLower = 0;
131139  }
131140  if( pUpper && rc==SQLITE_OK ){
131141    rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
131142    nUpper = p2 ? 0 : p->nSample;
131143  }
131144
131145  if( p1 || p2 ){
131146    int i;
131147    int nDiff;
131148    for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
131149      rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
131150      if( rc==SQLITE_OK && p1 ){
131151        int res = sqlite3MemCompare(p1, pVal, pColl);
131152        if( res>=0 ) nLower++;
131153      }
131154      if( rc==SQLITE_OK && p2 ){
131155        int res = sqlite3MemCompare(p2, pVal, pColl);
131156        if( res>=0 ) nUpper++;
131157      }
131158    }
131159    nDiff = (nUpper - nLower);
131160    if( nDiff<=0 ) nDiff = 1;
131161
131162    /* If there is both an upper and lower bound specified, and the
131163    ** comparisons indicate that they are close together, use the fallback
131164    ** method (assume that the scan visits 1/64 of the rows) for estimating
131165    ** the number of rows visited. Otherwise, estimate the number of rows
131166    ** using the method described in the header comment for this function. */
131167    if( nDiff!=1 || pUpper==0 || pLower==0 ){
131168      int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
131169      pLoop->nOut -= nAdjust;
131170      *pbDone = 1;
131171      WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
131172                           nLower, nUpper, nAdjust*-1, pLoop->nOut));
131173    }
131174
131175  }else{
131176    assert( *pbDone==0 );
131177  }
131178
131179  sqlite3ValueFree(p1);
131180  sqlite3ValueFree(p2);
131181  sqlite3ValueFree(pVal);
131182
131183  return rc;
131184}
131185#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
131186
131187/*
131188** This function is used to estimate the number of rows that will be visited
131189** by scanning an index for a range of values. The range may have an upper
131190** bound, a lower bound, or both. The WHERE clause terms that set the upper
131191** and lower bounds are represented by pLower and pUpper respectively. For
131192** example, assuming that index p is on t1(a):
131193**
131194**   ... FROM t1 WHERE a > ? AND a < ? ...
131195**                    |_____|   |_____|
131196**                       |         |
131197**                     pLower    pUpper
131198**
131199** If either of the upper or lower bound is not present, then NULL is passed in
131200** place of the corresponding WhereTerm.
131201**
131202** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
131203** column subject to the range constraint. Or, equivalently, the number of
131204** equality constraints optimized by the proposed index scan. For example,
131205** assuming index p is on t1(a, b), and the SQL query is:
131206**
131207**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
131208**
131209** then nEq is set to 1 (as the range restricted column, b, is the second
131210** left-most column of the index). Or, if the query is:
131211**
131212**   ... FROM t1 WHERE a > ? AND a < ? ...
131213**
131214** then nEq is set to 0.
131215**
131216** When this function is called, *pnOut is set to the sqlite3LogEst() of the
131217** number of rows that the index scan is expected to visit without
131218** considering the range constraints. If nEq is 0, then *pnOut is the number of
131219** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
131220** to account for the range constraints pLower and pUpper.
131221**
131222** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
131223** used, a single range inequality reduces the search space by a factor of 4.
131224** and a pair of constraints (x>? AND x<?) reduces the expected number of
131225** rows visited by a factor of 64.
131226*/
131227static int whereRangeScanEst(
131228  Parse *pParse,       /* Parsing & code generating context */
131229  WhereLoopBuilder *pBuilder,
131230  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
131231  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
131232  WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
131233){
131234  int rc = SQLITE_OK;
131235  int nOut = pLoop->nOut;
131236  LogEst nNew;
131237
131238#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
131239  Index *p = pLoop->u.btree.pIndex;
131240  int nEq = pLoop->u.btree.nEq;
131241
131242  if( p->nSample>0 && nEq<p->nSampleCol ){
131243    if( nEq==pBuilder->nRecValid ){
131244      UnpackedRecord *pRec = pBuilder->pRec;
131245      tRowcnt a[2];
131246      int nBtm = pLoop->u.btree.nBtm;
131247      int nTop = pLoop->u.btree.nTop;
131248
131249      /* Variable iLower will be set to the estimate of the number of rows in
131250      ** the index that are less than the lower bound of the range query. The
131251      ** lower bound being the concatenation of $P and $L, where $P is the
131252      ** key-prefix formed by the nEq values matched against the nEq left-most
131253      ** columns of the index, and $L is the value in pLower.
131254      **
131255      ** Or, if pLower is NULL or $L cannot be extracted from it (because it
131256      ** is not a simple variable or literal value), the lower bound of the
131257      ** range is $P. Due to a quirk in the way whereKeyStats() works, even
131258      ** if $L is available, whereKeyStats() is called for both ($P) and
131259      ** ($P:$L) and the larger of the two returned values is used.
131260      **
131261      ** Similarly, iUpper is to be set to the estimate of the number of rows
131262      ** less than the upper bound of the range query. Where the upper bound
131263      ** is either ($P) or ($P:$U). Again, even if $U is available, both values
131264      ** of iUpper are requested of whereKeyStats() and the smaller used.
131265      **
131266      ** The number of rows between the two bounds is then just iUpper-iLower.
131267      */
131268      tRowcnt iLower;     /* Rows less than the lower bound */
131269      tRowcnt iUpper;     /* Rows less than the upper bound */
131270      int iLwrIdx = -2;   /* aSample[] for the lower bound */
131271      int iUprIdx = -1;   /* aSample[] for the upper bound */
131272
131273      if( pRec ){
131274        testcase( pRec->nField!=pBuilder->nRecValid );
131275        pRec->nField = pBuilder->nRecValid;
131276      }
131277      /* Determine iLower and iUpper using ($P) only. */
131278      if( nEq==0 ){
131279        iLower = 0;
131280        iUpper = p->nRowEst0;
131281      }else{
131282        /* Note: this call could be optimized away - since the same values must
131283        ** have been requested when testing key $P in whereEqualScanEst().  */
131284        whereKeyStats(pParse, p, pRec, 0, a);
131285        iLower = a[0];
131286        iUpper = a[0] + a[1];
131287      }
131288
131289      assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
131290      assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
131291      assert( p->aSortOrder!=0 );
131292      if( p->aSortOrder[nEq] ){
131293        /* The roles of pLower and pUpper are swapped for a DESC index */
131294        SWAP(WhereTerm*, pLower, pUpper);
131295        SWAP(int, nBtm, nTop);
131296      }
131297
131298      /* If possible, improve on the iLower estimate using ($P:$L). */
131299      if( pLower ){
131300        int n;                    /* Values extracted from pExpr */
131301        Expr *pExpr = pLower->pExpr->pRight;
131302        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
131303        if( rc==SQLITE_OK && n ){
131304          tRowcnt iNew;
131305          u16 mask = WO_GT|WO_LE;
131306          if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
131307          iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
131308          iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
131309          if( iNew>iLower ) iLower = iNew;
131310          nOut--;
131311          pLower = 0;
131312        }
131313      }
131314
131315      /* If possible, improve on the iUpper estimate using ($P:$U). */
131316      if( pUpper ){
131317        int n;                    /* Values extracted from pExpr */
131318        Expr *pExpr = pUpper->pExpr->pRight;
131319        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
131320        if( rc==SQLITE_OK && n ){
131321          tRowcnt iNew;
131322          u16 mask = WO_GT|WO_LE;
131323          if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
131324          iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
131325          iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
131326          if( iNew<iUpper ) iUpper = iNew;
131327          nOut--;
131328          pUpper = 0;
131329        }
131330      }
131331
131332      pBuilder->pRec = pRec;
131333      if( rc==SQLITE_OK ){
131334        if( iUpper>iLower ){
131335          nNew = sqlite3LogEst(iUpper - iLower);
131336          /* TUNING:  If both iUpper and iLower are derived from the same
131337          ** sample, then assume they are 4x more selective.  This brings
131338          ** the estimated selectivity more in line with what it would be
131339          ** if estimated without the use of STAT3/4 tables. */
131340          if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );
131341        }else{
131342          nNew = 10;        assert( 10==sqlite3LogEst(2) );
131343        }
131344        if( nNew<nOut ){
131345          nOut = nNew;
131346        }
131347        WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
131348                           (u32)iLower, (u32)iUpper, nOut));
131349      }
131350    }else{
131351      int bDone = 0;
131352      rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
131353      if( bDone ) return rc;
131354    }
131355  }
131356#else
131357  UNUSED_PARAMETER(pParse);
131358  UNUSED_PARAMETER(pBuilder);
131359  assert( pLower || pUpper );
131360#endif
131361  assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
131362  nNew = whereRangeAdjust(pLower, nOut);
131363  nNew = whereRangeAdjust(pUpper, nNew);
131364
131365  /* TUNING: If there is both an upper and lower limit and neither limit
131366  ** has an application-defined likelihood(), assume the range is
131367  ** reduced by an additional 75%. This means that, by default, an open-ended
131368  ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
131369  ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
131370  ** match 1/64 of the index. */
131371  if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
131372    nNew -= 20;
131373  }
131374
131375  nOut -= (pLower!=0) + (pUpper!=0);
131376  if( nNew<10 ) nNew = 10;
131377  if( nNew<nOut ) nOut = nNew;
131378#if defined(WHERETRACE_ENABLED)
131379  if( pLoop->nOut>nOut ){
131380    WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
131381                    pLoop->nOut, nOut));
131382  }
131383#endif
131384  pLoop->nOut = (LogEst)nOut;
131385  return rc;
131386}
131387
131388#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
131389/*
131390** Estimate the number of rows that will be returned based on
131391** an equality constraint x=VALUE and where that VALUE occurs in
131392** the histogram data.  This only works when x is the left-most
131393** column of an index and sqlite_stat3 histogram data is available
131394** for that index.  When pExpr==NULL that means the constraint is
131395** "x IS NULL" instead of "x=VALUE".
131396**
131397** Write the estimated row count into *pnRow and return SQLITE_OK.
131398** If unable to make an estimate, leave *pnRow unchanged and return
131399** non-zero.
131400**
131401** This routine can fail if it is unable to load a collating sequence
131402** required for string comparison, or if unable to allocate memory
131403** for a UTF conversion required for comparison.  The error is stored
131404** in the pParse structure.
131405*/
131406static int whereEqualScanEst(
131407  Parse *pParse,       /* Parsing & code generating context */
131408  WhereLoopBuilder *pBuilder,
131409  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
131410  tRowcnt *pnRow       /* Write the revised row estimate here */
131411){
131412  Index *p = pBuilder->pNew->u.btree.pIndex;
131413  int nEq = pBuilder->pNew->u.btree.nEq;
131414  UnpackedRecord *pRec = pBuilder->pRec;
131415  int rc;                   /* Subfunction return code */
131416  tRowcnt a[2];             /* Statistics */
131417  int bOk;
131418
131419  assert( nEq>=1 );
131420  assert( nEq<=p->nColumn );
131421  assert( p->aSample!=0 );
131422  assert( p->nSample>0 );
131423  assert( pBuilder->nRecValid<nEq );
131424
131425  /* If values are not available for all fields of the index to the left
131426  ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
131427  if( pBuilder->nRecValid<(nEq-1) ){
131428    return SQLITE_NOTFOUND;
131429  }
131430
131431  /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
131432  ** below would return the same value.  */
131433  if( nEq>=p->nColumn ){
131434    *pnRow = 1;
131435    return SQLITE_OK;
131436  }
131437
131438  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
131439  pBuilder->pRec = pRec;
131440  if( rc!=SQLITE_OK ) return rc;
131441  if( bOk==0 ) return SQLITE_NOTFOUND;
131442  pBuilder->nRecValid = nEq;
131443
131444  whereKeyStats(pParse, p, pRec, 0, a);
131445  WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
131446                   p->zName, nEq-1, (int)a[1]));
131447  *pnRow = a[1];
131448
131449  return rc;
131450}
131451#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
131452
131453#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
131454/*
131455** Estimate the number of rows that will be returned based on
131456** an IN constraint where the right-hand side of the IN operator
131457** is a list of values.  Example:
131458**
131459**        WHERE x IN (1,2,3,4)
131460**
131461** Write the estimated row count into *pnRow and return SQLITE_OK.
131462** If unable to make an estimate, leave *pnRow unchanged and return
131463** non-zero.
131464**
131465** This routine can fail if it is unable to load a collating sequence
131466** required for string comparison, or if unable to allocate memory
131467** for a UTF conversion required for comparison.  The error is stored
131468** in the pParse structure.
131469*/
131470static int whereInScanEst(
131471  Parse *pParse,       /* Parsing & code generating context */
131472  WhereLoopBuilder *pBuilder,
131473  ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
131474  tRowcnt *pnRow       /* Write the revised row estimate here */
131475){
131476  Index *p = pBuilder->pNew->u.btree.pIndex;
131477  i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
131478  int nRecValid = pBuilder->nRecValid;
131479  int rc = SQLITE_OK;     /* Subfunction return code */
131480  tRowcnt nEst;           /* Number of rows for a single term */
131481  tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
131482  int i;                  /* Loop counter */
131483
131484  assert( p->aSample!=0 );
131485  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
131486    nEst = nRow0;
131487    rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
131488    nRowEst += nEst;
131489    pBuilder->nRecValid = nRecValid;
131490  }
131491
131492  if( rc==SQLITE_OK ){
131493    if( nRowEst > nRow0 ) nRowEst = nRow0;
131494    *pnRow = nRowEst;
131495    WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
131496  }
131497  assert( pBuilder->nRecValid==nRecValid );
131498  return rc;
131499}
131500#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
131501
131502
131503#ifdef WHERETRACE_ENABLED
131504/*
131505** Print the content of a WhereTerm object
131506*/
131507static void whereTermPrint(WhereTerm *pTerm, int iTerm){
131508  if( pTerm==0 ){
131509    sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
131510  }else{
131511    char zType[4];
131512    char zLeft[50];
131513    memcpy(zType, "...", 4);
131514    if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
131515    if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
131516    if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
131517    if( pTerm->eOperator & WO_SINGLE ){
131518      sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
131519                       pTerm->leftCursor, pTerm->u.leftColumn);
131520    }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
131521      sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
131522                       pTerm->u.pOrInfo->indexable);
131523    }else{
131524      sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
131525    }
131526    sqlite3DebugPrintf(
131527       "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
131528       iTerm, pTerm, zType, zLeft, pTerm->truthProb,
131529       pTerm->eOperator, pTerm->wtFlags);
131530    if( pTerm->iField ){
131531      sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
131532    }else{
131533      sqlite3DebugPrintf("\n");
131534    }
131535    sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
131536  }
131537}
131538#endif
131539
131540#ifdef WHERETRACE_ENABLED
131541/*
131542** Show the complete content of a WhereClause
131543*/
131544SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
131545  int i;
131546  for(i=0; i<pWC->nTerm; i++){
131547    whereTermPrint(&pWC->a[i], i);
131548  }
131549}
131550#endif
131551
131552#ifdef WHERETRACE_ENABLED
131553/*
131554** Print a WhereLoop object for debugging purposes
131555*/
131556static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
131557  WhereInfo *pWInfo = pWC->pWInfo;
131558  int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
131559  struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
131560  Table *pTab = pItem->pTab;
131561  Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
131562  sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
131563                     p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
131564  sqlite3DebugPrintf(" %12s",
131565                     pItem->zAlias ? pItem->zAlias : pTab->zName);
131566  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
131567    const char *zName;
131568    if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
131569      if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
131570        int i = sqlite3Strlen30(zName) - 1;
131571        while( zName[i]!='_' ) i--;
131572        zName += i;
131573      }
131574      sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
131575    }else{
131576      sqlite3DebugPrintf("%20s","");
131577    }
131578  }else{
131579    char *z;
131580    if( p->u.vtab.idxStr ){
131581      z = sqlite3_mprintf("(%d,\"%s\",%x)",
131582                p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
131583    }else{
131584      z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
131585    }
131586    sqlite3DebugPrintf(" %-19s", z);
131587    sqlite3_free(z);
131588  }
131589  if( p->wsFlags & WHERE_SKIPSCAN ){
131590    sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
131591  }else{
131592    sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
131593  }
131594  sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
131595  if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
131596    int i;
131597    for(i=0; i<p->nLTerm; i++){
131598      whereTermPrint(p->aLTerm[i], i);
131599    }
131600  }
131601}
131602#endif
131603
131604/*
131605** Convert bulk memory into a valid WhereLoop that can be passed
131606** to whereLoopClear harmlessly.
131607*/
131608static void whereLoopInit(WhereLoop *p){
131609  p->aLTerm = p->aLTermSpace;
131610  p->nLTerm = 0;
131611  p->nLSlot = ArraySize(p->aLTermSpace);
131612  p->wsFlags = 0;
131613}
131614
131615/*
131616** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
131617*/
131618static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
131619  if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
131620    if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
131621      sqlite3_free(p->u.vtab.idxStr);
131622      p->u.vtab.needFree = 0;
131623      p->u.vtab.idxStr = 0;
131624    }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
131625      sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
131626      sqlite3DbFree(db, p->u.btree.pIndex);
131627      p->u.btree.pIndex = 0;
131628    }
131629  }
131630}
131631
131632/*
131633** Deallocate internal memory used by a WhereLoop object
131634*/
131635static void whereLoopClear(sqlite3 *db, WhereLoop *p){
131636  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
131637  whereLoopClearUnion(db, p);
131638  whereLoopInit(p);
131639}
131640
131641/*
131642** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
131643*/
131644static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
131645  WhereTerm **paNew;
131646  if( p->nLSlot>=n ) return SQLITE_OK;
131647  n = (n+7)&~7;
131648  paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
131649  if( paNew==0 ) return SQLITE_NOMEM_BKPT;
131650  memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
131651  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
131652  p->aLTerm = paNew;
131653  p->nLSlot = n;
131654  return SQLITE_OK;
131655}
131656
131657/*
131658** Transfer content from the second pLoop into the first.
131659*/
131660static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
131661  whereLoopClearUnion(db, pTo);
131662  if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
131663    memset(&pTo->u, 0, sizeof(pTo->u));
131664    return SQLITE_NOMEM_BKPT;
131665  }
131666  memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
131667  memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
131668  if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
131669    pFrom->u.vtab.needFree = 0;
131670  }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
131671    pFrom->u.btree.pIndex = 0;
131672  }
131673  return SQLITE_OK;
131674}
131675
131676/*
131677** Delete a WhereLoop object
131678*/
131679static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
131680  whereLoopClear(db, p);
131681  sqlite3DbFree(db, p);
131682}
131683
131684/*
131685** Free a WhereInfo structure
131686*/
131687static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
131688  if( ALWAYS(pWInfo) ){
131689    int i;
131690    for(i=0; i<pWInfo->nLevel; i++){
131691      WhereLevel *pLevel = &pWInfo->a[i];
131692      if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
131693        sqlite3DbFree(db, pLevel->u.in.aInLoop);
131694      }
131695    }
131696    sqlite3WhereClauseClear(&pWInfo->sWC);
131697    while( pWInfo->pLoops ){
131698      WhereLoop *p = pWInfo->pLoops;
131699      pWInfo->pLoops = p->pNextLoop;
131700      whereLoopDelete(db, p);
131701    }
131702    sqlite3DbFree(db, pWInfo);
131703  }
131704}
131705
131706/*
131707** Return TRUE if all of the following are true:
131708**
131709**   (1)  X has the same or lower cost that Y
131710**   (2)  X is a proper subset of Y
131711**   (3)  X skips at least as many columns as Y
131712**
131713** By "proper subset" we mean that X uses fewer WHERE clause terms
131714** than Y and that every WHERE clause term used by X is also used
131715** by Y.
131716**
131717** If X is a proper subset of Y then Y is a better choice and ought
131718** to have a lower cost.  This routine returns TRUE when that cost
131719** relationship is inverted and needs to be adjusted.  The third rule
131720** was added because if X uses skip-scan less than Y it still might
131721** deserve a lower cost even if it is a proper subset of Y.
131722*/
131723static int whereLoopCheaperProperSubset(
131724  const WhereLoop *pX,       /* First WhereLoop to compare */
131725  const WhereLoop *pY        /* Compare against this WhereLoop */
131726){
131727  int i, j;
131728  if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
131729    return 0; /* X is not a subset of Y */
131730  }
131731  if( pY->nSkip > pX->nSkip ) return 0;
131732  if( pX->rRun >= pY->rRun ){
131733    if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
131734    if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
131735  }
131736  for(i=pX->nLTerm-1; i>=0; i--){
131737    if( pX->aLTerm[i]==0 ) continue;
131738    for(j=pY->nLTerm-1; j>=0; j--){
131739      if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
131740    }
131741    if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
131742  }
131743  return 1;  /* All conditions meet */
131744}
131745
131746/*
131747** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
131748** that:
131749**
131750**   (1) pTemplate costs less than any other WhereLoops that are a proper
131751**       subset of pTemplate
131752**
131753**   (2) pTemplate costs more than any other WhereLoops for which pTemplate
131754**       is a proper subset.
131755**
131756** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
131757** WHERE clause terms than Y and that every WHERE clause term used by X is
131758** also used by Y.
131759*/
131760static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
131761  if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
131762  for(; p; p=p->pNextLoop){
131763    if( p->iTab!=pTemplate->iTab ) continue;
131764    if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
131765    if( whereLoopCheaperProperSubset(p, pTemplate) ){
131766      /* Adjust pTemplate cost downward so that it is cheaper than its
131767      ** subset p. */
131768      WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
131769                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
131770      pTemplate->rRun = p->rRun;
131771      pTemplate->nOut = p->nOut - 1;
131772    }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
131773      /* Adjust pTemplate cost upward so that it is costlier than p since
131774      ** pTemplate is a proper subset of p */
131775      WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
131776                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
131777      pTemplate->rRun = p->rRun;
131778      pTemplate->nOut = p->nOut + 1;
131779    }
131780  }
131781}
131782
131783/*
131784** Search the list of WhereLoops in *ppPrev looking for one that can be
131785** supplanted by pTemplate.
131786**
131787** Return NULL if the WhereLoop list contains an entry that can supplant
131788** pTemplate, in other words if pTemplate does not belong on the list.
131789**
131790** If pX is a WhereLoop that pTemplate can supplant, then return the
131791** link that points to pX.
131792**
131793** If pTemplate cannot supplant any existing element of the list but needs
131794** to be added to the list, then return a pointer to the tail of the list.
131795*/
131796static WhereLoop **whereLoopFindLesser(
131797  WhereLoop **ppPrev,
131798  const WhereLoop *pTemplate
131799){
131800  WhereLoop *p;
131801  for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
131802    if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
131803      /* If either the iTab or iSortIdx values for two WhereLoop are different
131804      ** then those WhereLoops need to be considered separately.  Neither is
131805      ** a candidate to replace the other. */
131806      continue;
131807    }
131808    /* In the current implementation, the rSetup value is either zero
131809    ** or the cost of building an automatic index (NlogN) and the NlogN
131810    ** is the same for compatible WhereLoops. */
131811    assert( p->rSetup==0 || pTemplate->rSetup==0
131812                 || p->rSetup==pTemplate->rSetup );
131813
131814    /* whereLoopAddBtree() always generates and inserts the automatic index
131815    ** case first.  Hence compatible candidate WhereLoops never have a larger
131816    ** rSetup. Call this SETUP-INVARIANT */
131817    assert( p->rSetup>=pTemplate->rSetup );
131818
131819    /* Any loop using an appliation-defined index (or PRIMARY KEY or
131820    ** UNIQUE constraint) with one or more == constraints is better
131821    ** than an automatic index. Unless it is a skip-scan. */
131822    if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
131823     && (pTemplate->nSkip)==0
131824     && (pTemplate->wsFlags & WHERE_INDEXED)!=0
131825     && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
131826     && (p->prereq & pTemplate->prereq)==pTemplate->prereq
131827    ){
131828      break;
131829    }
131830
131831    /* If existing WhereLoop p is better than pTemplate, pTemplate can be
131832    ** discarded.  WhereLoop p is better if:
131833    **   (1)  p has no more dependencies than pTemplate, and
131834    **   (2)  p has an equal or lower cost than pTemplate
131835    */
131836    if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
131837     && p->rSetup<=pTemplate->rSetup                  /* (2a) */
131838     && p->rRun<=pTemplate->rRun                      /* (2b) */
131839     && p->nOut<=pTemplate->nOut                      /* (2c) */
131840    ){
131841      return 0;  /* Discard pTemplate */
131842    }
131843
131844    /* If pTemplate is always better than p, then cause p to be overwritten
131845    ** with pTemplate.  pTemplate is better than p if:
131846    **   (1)  pTemplate has no more dependences than p, and
131847    **   (2)  pTemplate has an equal or lower cost than p.
131848    */
131849    if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
131850     && p->rRun>=pTemplate->rRun                             /* (2a) */
131851     && p->nOut>=pTemplate->nOut                             /* (2b) */
131852    ){
131853      assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
131854      break;   /* Cause p to be overwritten by pTemplate */
131855    }
131856  }
131857  return ppPrev;
131858}
131859
131860/*
131861** Insert or replace a WhereLoop entry using the template supplied.
131862**
131863** An existing WhereLoop entry might be overwritten if the new template
131864** is better and has fewer dependencies.  Or the template will be ignored
131865** and no insert will occur if an existing WhereLoop is faster and has
131866** fewer dependencies than the template.  Otherwise a new WhereLoop is
131867** added based on the template.
131868**
131869** If pBuilder->pOrSet is not NULL then we care about only the
131870** prerequisites and rRun and nOut costs of the N best loops.  That
131871** information is gathered in the pBuilder->pOrSet object.  This special
131872** processing mode is used only for OR clause processing.
131873**
131874** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
131875** still might overwrite similar loops with the new template if the
131876** new template is better.  Loops may be overwritten if the following
131877** conditions are met:
131878**
131879**    (1)  They have the same iTab.
131880**    (2)  They have the same iSortIdx.
131881**    (3)  The template has same or fewer dependencies than the current loop
131882**    (4)  The template has the same or lower cost than the current loop
131883*/
131884static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
131885  WhereLoop **ppPrev, *p;
131886  WhereInfo *pWInfo = pBuilder->pWInfo;
131887  sqlite3 *db = pWInfo->pParse->db;
131888  int rc;
131889
131890  /* If pBuilder->pOrSet is defined, then only keep track of the costs
131891  ** and prereqs.
131892  */
131893  if( pBuilder->pOrSet!=0 ){
131894    if( pTemplate->nLTerm ){
131895#if WHERETRACE_ENABLED
131896      u16 n = pBuilder->pOrSet->n;
131897      int x =
131898#endif
131899      whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
131900                                    pTemplate->nOut);
131901#if WHERETRACE_ENABLED /* 0x8 */
131902      if( sqlite3WhereTrace & 0x8 ){
131903        sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
131904        whereLoopPrint(pTemplate, pBuilder->pWC);
131905      }
131906#endif
131907    }
131908    return SQLITE_OK;
131909  }
131910
131911  /* Look for an existing WhereLoop to replace with pTemplate
131912  */
131913  whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
131914  ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
131915
131916  if( ppPrev==0 ){
131917    /* There already exists a WhereLoop on the list that is better
131918    ** than pTemplate, so just ignore pTemplate */
131919#if WHERETRACE_ENABLED /* 0x8 */
131920    if( sqlite3WhereTrace & 0x8 ){
131921      sqlite3DebugPrintf("   skip: ");
131922      whereLoopPrint(pTemplate, pBuilder->pWC);
131923    }
131924#endif
131925    return SQLITE_OK;
131926  }else{
131927    p = *ppPrev;
131928  }
131929
131930  /* If we reach this point it means that either p[] should be overwritten
131931  ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
131932  ** WhereLoop and insert it.
131933  */
131934#if WHERETRACE_ENABLED /* 0x8 */
131935  if( sqlite3WhereTrace & 0x8 ){
131936    if( p!=0 ){
131937      sqlite3DebugPrintf("replace: ");
131938      whereLoopPrint(p, pBuilder->pWC);
131939    }
131940    sqlite3DebugPrintf("    add: ");
131941    whereLoopPrint(pTemplate, pBuilder->pWC);
131942  }
131943#endif
131944  if( p==0 ){
131945    /* Allocate a new WhereLoop to add to the end of the list */
131946    *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
131947    if( p==0 ) return SQLITE_NOMEM_BKPT;
131948    whereLoopInit(p);
131949    p->pNextLoop = 0;
131950  }else{
131951    /* We will be overwriting WhereLoop p[].  But before we do, first
131952    ** go through the rest of the list and delete any other entries besides
131953    ** p[] that are also supplated by pTemplate */
131954    WhereLoop **ppTail = &p->pNextLoop;
131955    WhereLoop *pToDel;
131956    while( *ppTail ){
131957      ppTail = whereLoopFindLesser(ppTail, pTemplate);
131958      if( ppTail==0 ) break;
131959      pToDel = *ppTail;
131960      if( pToDel==0 ) break;
131961      *ppTail = pToDel->pNextLoop;
131962#if WHERETRACE_ENABLED /* 0x8 */
131963      if( sqlite3WhereTrace & 0x8 ){
131964        sqlite3DebugPrintf(" delete: ");
131965        whereLoopPrint(pToDel, pBuilder->pWC);
131966      }
131967#endif
131968      whereLoopDelete(db, pToDel);
131969    }
131970  }
131971  rc = whereLoopXfer(db, p, pTemplate);
131972  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
131973    Index *pIndex = p->u.btree.pIndex;
131974    if( pIndex && pIndex->tnum==0 ){
131975      p->u.btree.pIndex = 0;
131976    }
131977  }
131978  return rc;
131979}
131980
131981/*
131982** Adjust the WhereLoop.nOut value downward to account for terms of the
131983** WHERE clause that reference the loop but which are not used by an
131984** index.
131985*
131986** For every WHERE clause term that is not used by the index
131987** and which has a truth probability assigned by one of the likelihood(),
131988** likely(), or unlikely() SQL functions, reduce the estimated number
131989** of output rows by the probability specified.
131990**
131991** TUNING:  For every WHERE clause term that is not used by the index
131992** and which does not have an assigned truth probability, heuristics
131993** described below are used to try to estimate the truth probability.
131994** TODO --> Perhaps this is something that could be improved by better
131995** table statistics.
131996**
131997** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
131998** value corresponds to -1 in LogEst notation, so this means decrement
131999** the WhereLoop.nOut field for every such WHERE clause term.
132000**
132001** Heuristic 2:  If there exists one or more WHERE clause terms of the
132002** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
132003** final output row estimate is no greater than 1/4 of the total number
132004** of rows in the table.  In other words, assume that x==EXPR will filter
132005** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
132006** "x" column is boolean or else -1 or 0 or 1 is a common default value
132007** on the "x" column and so in that case only cap the output row estimate
132008** at 1/2 instead of 1/4.
132009*/
132010static void whereLoopOutputAdjust(
132011  WhereClause *pWC,      /* The WHERE clause */
132012  WhereLoop *pLoop,      /* The loop to adjust downward */
132013  LogEst nRow            /* Number of rows in the entire table */
132014){
132015  WhereTerm *pTerm, *pX;
132016  Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
132017  int i, j, k;
132018  LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
132019
132020  assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
132021  for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
132022    if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
132023    if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
132024    if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
132025    for(j=pLoop->nLTerm-1; j>=0; j--){
132026      pX = pLoop->aLTerm[j];
132027      if( pX==0 ) continue;
132028      if( pX==pTerm ) break;
132029      if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
132030    }
132031    if( j<0 ){
132032      if( pTerm->truthProb<=0 ){
132033        /* If a truth probability is specified using the likelihood() hints,
132034        ** then use the probability provided by the application. */
132035        pLoop->nOut += pTerm->truthProb;
132036      }else{
132037        /* In the absence of explicit truth probabilities, use heuristics to
132038        ** guess a reasonable truth probability. */
132039        pLoop->nOut--;
132040        if( pTerm->eOperator&(WO_EQ|WO_IS) ){
132041          Expr *pRight = pTerm->pExpr->pRight;
132042          testcase( pTerm->pExpr->op==TK_IS );
132043          if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
132044            k = 10;
132045          }else{
132046            k = 20;
132047          }
132048          if( iReduce<k ) iReduce = k;
132049        }
132050      }
132051    }
132052  }
132053  if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
132054}
132055
132056/*
132057** Term pTerm is a vector range comparison operation. The first comparison
132058** in the vector can be optimized using column nEq of the index. This
132059** function returns the total number of vector elements that can be used
132060** as part of the range comparison.
132061**
132062** For example, if the query is:
132063**
132064**   WHERE a = ? AND (b, c, d) > (?, ?, ?)
132065**
132066** and the index:
132067**
132068**   CREATE INDEX ... ON (a, b, c, d, e)
132069**
132070** then this function would be invoked with nEq=1. The value returned in
132071** this case is 3.
132072*/
132073static int whereRangeVectorLen(
132074  Parse *pParse,       /* Parsing context */
132075  int iCur,            /* Cursor open on pIdx */
132076  Index *pIdx,         /* The index to be used for a inequality constraint */
132077  int nEq,             /* Number of prior equality constraints on same index */
132078  WhereTerm *pTerm     /* The vector inequality constraint */
132079){
132080  int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
132081  int i;
132082
132083  nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
132084  for(i=1; i<nCmp; i++){
132085    /* Test if comparison i of pTerm is compatible with column (i+nEq)
132086    ** of the index. If not, exit the loop.  */
132087    char aff;                     /* Comparison affinity */
132088    char idxaff = 0;              /* Indexed columns affinity */
132089    CollSeq *pColl;               /* Comparison collation sequence */
132090    Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
132091    Expr *pRhs = pTerm->pExpr->pRight;
132092    if( pRhs->flags & EP_xIsSelect ){
132093      pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
132094    }else{
132095      pRhs = pRhs->x.pList->a[i].pExpr;
132096    }
132097
132098    /* Check that the LHS of the comparison is a column reference to
132099    ** the right column of the right source table. And that the sort
132100    ** order of the index column is the same as the sort order of the
132101    ** leftmost index column.  */
132102    if( pLhs->op!=TK_COLUMN
132103     || pLhs->iTable!=iCur
132104     || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
132105     || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
132106    ){
132107      break;
132108    }
132109
132110    testcase( pLhs->iColumn==XN_ROWID );
132111    aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
132112    idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
132113    if( aff!=idxaff ) break;
132114
132115    pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
132116    if( pColl==0 ) break;
132117    if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
132118  }
132119  return i;
132120}
132121
132122/*
132123** Adjust the cost C by the costMult facter T.  This only occurs if
132124** compiled with -DSQLITE_ENABLE_COSTMULT
132125*/
132126#ifdef SQLITE_ENABLE_COSTMULT
132127# define ApplyCostMultiplier(C,T)  C += T
132128#else
132129# define ApplyCostMultiplier(C,T)
132130#endif
132131
132132/*
132133** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
132134** index pIndex. Try to match one more.
132135**
132136** When this function is called, pBuilder->pNew->nOut contains the
132137** number of rows expected to be visited by filtering using the nEq
132138** terms only. If it is modified, this value is restored before this
132139** function returns.
132140**
132141** If pProbe->tnum==0, that means pIndex is a fake index used for the
132142** INTEGER PRIMARY KEY.
132143*/
132144static int whereLoopAddBtreeIndex(
132145  WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
132146  struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
132147  Index *pProbe,                  /* An index on pSrc */
132148  LogEst nInMul                   /* log(Number of iterations due to IN) */
132149){
132150  WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
132151  Parse *pParse = pWInfo->pParse;        /* Parsing context */
132152  sqlite3 *db = pParse->db;       /* Database connection malloc context */
132153  WhereLoop *pNew;                /* Template WhereLoop under construction */
132154  WhereTerm *pTerm;               /* A WhereTerm under consideration */
132155  int opMask;                     /* Valid operators for constraints */
132156  WhereScan scan;                 /* Iterator for WHERE terms */
132157  Bitmask saved_prereq;           /* Original value of pNew->prereq */
132158  u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
132159  u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
132160  u16 saved_nBtm;                 /* Original value of pNew->u.btree.nBtm */
132161  u16 saved_nTop;                 /* Original value of pNew->u.btree.nTop */
132162  u16 saved_nSkip;                /* Original value of pNew->nSkip */
132163  u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
132164  LogEst saved_nOut;              /* Original value of pNew->nOut */
132165  int rc = SQLITE_OK;             /* Return code */
132166  LogEst rSize;                   /* Number of rows in the table */
132167  LogEst rLogSize;                /* Logarithm of table size */
132168  WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
132169
132170  pNew = pBuilder->pNew;
132171  if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
132172  WHERETRACE(0x800, ("BEGIN addBtreeIdx(%s), nEq=%d\n",
132173                     pProbe->zName, pNew->u.btree.nEq));
132174
132175  assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
132176  assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
132177  if( pNew->wsFlags & WHERE_BTM_LIMIT ){
132178    opMask = WO_LT|WO_LE;
132179  }else{
132180    assert( pNew->u.btree.nBtm==0 );
132181    opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
132182  }
132183  if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
132184
132185  assert( pNew->u.btree.nEq<pProbe->nColumn );
132186
132187  saved_nEq = pNew->u.btree.nEq;
132188  saved_nBtm = pNew->u.btree.nBtm;
132189  saved_nTop = pNew->u.btree.nTop;
132190  saved_nSkip = pNew->nSkip;
132191  saved_nLTerm = pNew->nLTerm;
132192  saved_wsFlags = pNew->wsFlags;
132193  saved_prereq = pNew->prereq;
132194  saved_nOut = pNew->nOut;
132195  pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
132196                        opMask, pProbe);
132197  pNew->rSetup = 0;
132198  rSize = pProbe->aiRowLogEst[0];
132199  rLogSize = estLog(rSize);
132200  for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
132201    u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
132202    LogEst rCostIdx;
132203    LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
132204    int nIn = 0;
132205#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
132206    int nRecValid = pBuilder->nRecValid;
132207#endif
132208    if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
132209     && indexColumnNotNull(pProbe, saved_nEq)
132210    ){
132211      continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
132212    }
132213    if( pTerm->prereqRight & pNew->maskSelf ) continue;
132214
132215    /* Do not allow the upper bound of a LIKE optimization range constraint
132216    ** to mix with a lower range bound from some other source */
132217    if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
132218
132219    /* Do not allow IS constraints from the WHERE clause to be used by the
132220    ** right table of a LEFT JOIN.  Only constraints in the ON clause are
132221    ** allowed */
132222    if( (pSrc->fg.jointype & JT_LEFT)!=0
132223     && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
132224     && (eOp & (WO_IS|WO_ISNULL))!=0
132225    ){
132226      testcase( eOp & WO_IS );
132227      testcase( eOp & WO_ISNULL );
132228      continue;
132229    }
132230
132231    if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
132232      pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
132233    }else{
132234      pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
132235    }
132236    pNew->wsFlags = saved_wsFlags;
132237    pNew->u.btree.nEq = saved_nEq;
132238    pNew->u.btree.nBtm = saved_nBtm;
132239    pNew->u.btree.nTop = saved_nTop;
132240    pNew->nLTerm = saved_nLTerm;
132241    if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
132242    pNew->aLTerm[pNew->nLTerm++] = pTerm;
132243    pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
132244
132245    assert( nInMul==0
132246        || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
132247        || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
132248        || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
132249    );
132250
132251    if( eOp & WO_IN ){
132252      Expr *pExpr = pTerm->pExpr;
132253      pNew->wsFlags |= WHERE_COLUMN_IN;
132254      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
132255        /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
132256        int i;
132257        nIn = 46;  assert( 46==sqlite3LogEst(25) );
132258
132259        /* The expression may actually be of the form (x, y) IN (SELECT...).
132260        ** In this case there is a separate term for each of (x) and (y).
132261        ** However, the nIn multiplier should only be applied once, not once
132262        ** for each such term. The following loop checks that pTerm is the
132263        ** first such term in use, and sets nIn back to 0 if it is not. */
132264        for(i=0; i<pNew->nLTerm-1; i++){
132265          if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
132266        }
132267      }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
132268        /* "x IN (value, value, ...)" */
132269        nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
132270        assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
132271                          ** changes "x IN (?)" into "x=?". */
132272      }
132273    }else if( eOp & (WO_EQ|WO_IS) ){
132274      int iCol = pProbe->aiColumn[saved_nEq];
132275      pNew->wsFlags |= WHERE_COLUMN_EQ;
132276      assert( saved_nEq==pNew->u.btree.nEq );
132277      if( iCol==XN_ROWID
132278       || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
132279      ){
132280        if( iCol>=0 && pProbe->uniqNotNull==0 ){
132281          pNew->wsFlags |= WHERE_UNQ_WANTED;
132282        }else{
132283          pNew->wsFlags |= WHERE_ONEROW;
132284        }
132285      }
132286    }else if( eOp & WO_ISNULL ){
132287      pNew->wsFlags |= WHERE_COLUMN_NULL;
132288    }else if( eOp & (WO_GT|WO_GE) ){
132289      testcase( eOp & WO_GT );
132290      testcase( eOp & WO_GE );
132291      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
132292      pNew->u.btree.nBtm = whereRangeVectorLen(
132293          pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
132294      );
132295      pBtm = pTerm;
132296      pTop = 0;
132297      if( pTerm->wtFlags & TERM_LIKEOPT ){
132298        /* Range contraints that come from the LIKE optimization are
132299        ** always used in pairs. */
132300        pTop = &pTerm[1];
132301        assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
132302        assert( pTop->wtFlags & TERM_LIKEOPT );
132303        assert( pTop->eOperator==WO_LT );
132304        if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
132305        pNew->aLTerm[pNew->nLTerm++] = pTop;
132306        pNew->wsFlags |= WHERE_TOP_LIMIT;
132307        pNew->u.btree.nTop = 1;
132308      }
132309    }else{
132310      assert( eOp & (WO_LT|WO_LE) );
132311      testcase( eOp & WO_LT );
132312      testcase( eOp & WO_LE );
132313      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
132314      pNew->u.btree.nTop = whereRangeVectorLen(
132315          pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
132316      );
132317      pTop = pTerm;
132318      pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
132319                     pNew->aLTerm[pNew->nLTerm-2] : 0;
132320    }
132321
132322    /* At this point pNew->nOut is set to the number of rows expected to
132323    ** be visited by the index scan before considering term pTerm, or the
132324    ** values of nIn and nInMul. In other words, assuming that all
132325    ** "x IN(...)" terms are replaced with "x = ?". This block updates
132326    ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
132327    assert( pNew->nOut==saved_nOut );
132328    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
132329      /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
132330      ** data, using some other estimate.  */
132331      whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
132332    }else{
132333      int nEq = ++pNew->u.btree.nEq;
132334      assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
132335
132336      assert( pNew->nOut==saved_nOut );
132337      if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
132338        assert( (eOp & WO_IN) || nIn==0 );
132339        testcase( eOp & WO_IN );
132340        pNew->nOut += pTerm->truthProb;
132341        pNew->nOut -= nIn;
132342      }else{
132343#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
132344        tRowcnt nOut = 0;
132345        if( nInMul==0
132346         && pProbe->nSample
132347         && pNew->u.btree.nEq<=pProbe->nSampleCol
132348         && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
132349        ){
132350          Expr *pExpr = pTerm->pExpr;
132351          if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
132352            testcase( eOp & WO_EQ );
132353            testcase( eOp & WO_IS );
132354            testcase( eOp & WO_ISNULL );
132355            rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
132356          }else{
132357            rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
132358          }
132359          if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
132360          if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
132361          if( nOut ){
132362            pNew->nOut = sqlite3LogEst(nOut);
132363            if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
132364            pNew->nOut -= nIn;
132365          }
132366        }
132367        if( nOut==0 )
132368#endif
132369        {
132370          pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
132371          if( eOp & WO_ISNULL ){
132372            /* TUNING: If there is no likelihood() value, assume that a
132373            ** "col IS NULL" expression matches twice as many rows
132374            ** as (col=?). */
132375            pNew->nOut += 10;
132376          }
132377        }
132378      }
132379    }
132380
132381    /* Set rCostIdx to the cost of visiting selected rows in index. Add
132382    ** it to pNew->rRun, which is currently set to the cost of the index
132383    ** seek only. Then, if this is a non-covering index, add the cost of
132384    ** visiting the rows in the main table.  */
132385    rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
132386    pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
132387    if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
132388      pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
132389    }
132390    ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
132391
132392    nOutUnadjusted = pNew->nOut;
132393    pNew->rRun += nInMul + nIn;
132394    pNew->nOut += nInMul + nIn;
132395    whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
132396    rc = whereLoopInsert(pBuilder, pNew);
132397
132398    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
132399      pNew->nOut = saved_nOut;
132400    }else{
132401      pNew->nOut = nOutUnadjusted;
132402    }
132403
132404    if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
132405     && pNew->u.btree.nEq<pProbe->nColumn
132406    ){
132407      whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
132408    }
132409    pNew->nOut = saved_nOut;
132410#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
132411    pBuilder->nRecValid = nRecValid;
132412#endif
132413  }
132414  pNew->prereq = saved_prereq;
132415  pNew->u.btree.nEq = saved_nEq;
132416  pNew->u.btree.nBtm = saved_nBtm;
132417  pNew->u.btree.nTop = saved_nTop;
132418  pNew->nSkip = saved_nSkip;
132419  pNew->wsFlags = saved_wsFlags;
132420  pNew->nOut = saved_nOut;
132421  pNew->nLTerm = saved_nLTerm;
132422
132423  /* Consider using a skip-scan if there are no WHERE clause constraints
132424  ** available for the left-most terms of the index, and if the average
132425  ** number of repeats in the left-most terms is at least 18.
132426  **
132427  ** The magic number 18 is selected on the basis that scanning 17 rows
132428  ** is almost always quicker than an index seek (even though if the index
132429  ** contains fewer than 2^17 rows we assume otherwise in other parts of
132430  ** the code). And, even if it is not, it should not be too much slower.
132431  ** On the other hand, the extra seeks could end up being significantly
132432  ** more expensive.  */
132433  assert( 42==sqlite3LogEst(18) );
132434  if( saved_nEq==saved_nSkip
132435   && saved_nEq+1<pProbe->nKeyCol
132436   && pProbe->noSkipScan==0
132437   && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
132438   && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
132439  ){
132440    LogEst nIter;
132441    pNew->u.btree.nEq++;
132442    pNew->nSkip++;
132443    pNew->aLTerm[pNew->nLTerm++] = 0;
132444    pNew->wsFlags |= WHERE_SKIPSCAN;
132445    nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
132446    pNew->nOut -= nIter;
132447    /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
132448    ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
132449    nIter += 5;
132450    whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
132451    pNew->nOut = saved_nOut;
132452    pNew->u.btree.nEq = saved_nEq;
132453    pNew->nSkip = saved_nSkip;
132454    pNew->wsFlags = saved_wsFlags;
132455  }
132456
132457  WHERETRACE(0x800, ("END addBtreeIdx(%s), nEq=%d, rc=%d\n",
132458                      pProbe->zName, saved_nEq, rc));
132459  return rc;
132460}
132461
132462/*
132463** Return True if it is possible that pIndex might be useful in
132464** implementing the ORDER BY clause in pBuilder.
132465**
132466** Return False if pBuilder does not contain an ORDER BY clause or
132467** if there is no way for pIndex to be useful in implementing that
132468** ORDER BY clause.
132469*/
132470static int indexMightHelpWithOrderBy(
132471  WhereLoopBuilder *pBuilder,
132472  Index *pIndex,
132473  int iCursor
132474){
132475  ExprList *pOB;
132476  ExprList *aColExpr;
132477  int ii, jj;
132478
132479  if( pIndex->bUnordered ) return 0;
132480  if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
132481  for(ii=0; ii<pOB->nExpr; ii++){
132482    Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
132483    if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
132484      if( pExpr->iColumn<0 ) return 1;
132485      for(jj=0; jj<pIndex->nKeyCol; jj++){
132486        if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
132487      }
132488    }else if( (aColExpr = pIndex->aColExpr)!=0 ){
132489      for(jj=0; jj<pIndex->nKeyCol; jj++){
132490        if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
132491        if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
132492          return 1;
132493        }
132494      }
132495    }
132496  }
132497  return 0;
132498}
132499
132500/*
132501** Return a bitmask where 1s indicate that the corresponding column of
132502** the table is used by an index.  Only the first 63 columns are considered.
132503*/
132504static Bitmask columnsInIndex(Index *pIdx){
132505  Bitmask m = 0;
132506  int j;
132507  for(j=pIdx->nColumn-1; j>=0; j--){
132508    int x = pIdx->aiColumn[j];
132509    if( x>=0 ){
132510      testcase( x==BMS-1 );
132511      testcase( x==BMS-2 );
132512      if( x<BMS-1 ) m |= MASKBIT(x);
132513    }
132514  }
132515  return m;
132516}
132517
132518/* Check to see if a partial index with pPartIndexWhere can be used
132519** in the current query.  Return true if it can be and false if not.
132520*/
132521static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
132522  int i;
132523  WhereTerm *pTerm;
132524  while( pWhere->op==TK_AND ){
132525    if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
132526    pWhere = pWhere->pRight;
132527  }
132528  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
132529    Expr *pExpr = pTerm->pExpr;
132530    if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
132531     && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
132532    ){
132533      return 1;
132534    }
132535  }
132536  return 0;
132537}
132538
132539/*
132540** Add all WhereLoop objects for a single table of the join where the table
132541** is identified by pBuilder->pNew->iTab.  That table is guaranteed to be
132542** a b-tree table, not a virtual table.
132543**
132544** The costs (WhereLoop.rRun) of the b-tree loops added by this function
132545** are calculated as follows:
132546**
132547** For a full scan, assuming the table (or index) contains nRow rows:
132548**
132549**     cost = nRow * 3.0                    // full-table scan
132550**     cost = nRow * K                      // scan of covering index
132551**     cost = nRow * (K+3.0)                // scan of non-covering index
132552**
132553** where K is a value between 1.1 and 3.0 set based on the relative
132554** estimated average size of the index and table records.
132555**
132556** For an index scan, where nVisit is the number of index rows visited
132557** by the scan, and nSeek is the number of seek operations required on
132558** the index b-tree:
132559**
132560**     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
132561**     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
132562**
132563** Normally, nSeek is 1. nSeek values greater than 1 come about if the
132564** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
132565** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
132566**
132567** The estimated values (nRow, nVisit, nSeek) often contain a large amount
132568** of uncertainty.  For this reason, scoring is designed to pick plans that
132569** "do the least harm" if the estimates are inaccurate.  For example, a
132570** log(nRow) factor is omitted from a non-covering index scan in order to
132571** bias the scoring in favor of using an index, since the worst-case
132572** performance of using an index is far better than the worst-case performance
132573** of a full table scan.
132574*/
132575static int whereLoopAddBtree(
132576  WhereLoopBuilder *pBuilder, /* WHERE clause information */
132577  Bitmask mPrereq             /* Extra prerequesites for using this table */
132578){
132579  WhereInfo *pWInfo;          /* WHERE analysis context */
132580  Index *pProbe;              /* An index we are evaluating */
132581  Index sPk;                  /* A fake index object for the primary key */
132582  LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
132583  i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
132584  SrcList *pTabList;          /* The FROM clause */
132585  struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
132586  WhereLoop *pNew;            /* Template WhereLoop object */
132587  int rc = SQLITE_OK;         /* Return code */
132588  int iSortIdx = 1;           /* Index number */
132589  int b;                      /* A boolean value */
132590  LogEst rSize;               /* number of rows in the table */
132591  LogEst rLogSize;            /* Logarithm of the number of rows in the table */
132592  WhereClause *pWC;           /* The parsed WHERE clause */
132593  Table *pTab;                /* Table being queried */
132594
132595  pNew = pBuilder->pNew;
132596  pWInfo = pBuilder->pWInfo;
132597  pTabList = pWInfo->pTabList;
132598  pSrc = pTabList->a + pNew->iTab;
132599  pTab = pSrc->pTab;
132600  pWC = pBuilder->pWC;
132601  assert( !IsVirtual(pSrc->pTab) );
132602
132603  if( pSrc->pIBIndex ){
132604    /* An INDEXED BY clause specifies a particular index to use */
132605    pProbe = pSrc->pIBIndex;
132606  }else if( !HasRowid(pTab) ){
132607    pProbe = pTab->pIndex;
132608  }else{
132609    /* There is no INDEXED BY clause.  Create a fake Index object in local
132610    ** variable sPk to represent the rowid primary key index.  Make this
132611    ** fake index the first in a chain of Index objects with all of the real
132612    ** indices to follow */
132613    Index *pFirst;                  /* First of real indices on the table */
132614    memset(&sPk, 0, sizeof(Index));
132615    sPk.nKeyCol = 1;
132616    sPk.nColumn = 1;
132617    sPk.aiColumn = &aiColumnPk;
132618    sPk.aiRowLogEst = aiRowEstPk;
132619    sPk.onError = OE_Replace;
132620    sPk.pTable = pTab;
132621    sPk.szIdxRow = pTab->szTabRow;
132622    aiRowEstPk[0] = pTab->nRowLogEst;
132623    aiRowEstPk[1] = 0;
132624    pFirst = pSrc->pTab->pIndex;
132625    if( pSrc->fg.notIndexed==0 ){
132626      /* The real indices of the table are only considered if the
132627      ** NOT INDEXED qualifier is omitted from the FROM clause */
132628      sPk.pNext = pFirst;
132629    }
132630    pProbe = &sPk;
132631  }
132632  rSize = pTab->nRowLogEst;
132633  rLogSize = estLog(rSize);
132634
132635#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
132636  /* Automatic indexes */
132637  if( !pBuilder->pOrSet      /* Not part of an OR optimization */
132638   && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
132639   && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
132640   && pSrc->pIBIndex==0      /* Has no INDEXED BY clause */
132641   && !pSrc->fg.notIndexed   /* Has no NOT INDEXED clause */
132642   && HasRowid(pTab)         /* Not WITHOUT ROWID table. (FIXME: Why not?) */
132643   && !pSrc->fg.isCorrelated /* Not a correlated subquery */
132644   && !pSrc->fg.isRecursive  /* Not a recursive common table expression. */
132645  ){
132646    /* Generate auto-index WhereLoops */
132647    WhereTerm *pTerm;
132648    WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
132649    for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
132650      if( pTerm->prereqRight & pNew->maskSelf ) continue;
132651      if( termCanDriveIndex(pTerm, pSrc, 0) ){
132652        pNew->u.btree.nEq = 1;
132653        pNew->nSkip = 0;
132654        pNew->u.btree.pIndex = 0;
132655        pNew->nLTerm = 1;
132656        pNew->aLTerm[0] = pTerm;
132657        /* TUNING: One-time cost for computing the automatic index is
132658        ** estimated to be X*N*log2(N) where N is the number of rows in
132659        ** the table being indexed and where X is 7 (LogEst=28) for normal
132660        ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
132661        ** of X is smaller for views and subqueries so that the query planner
132662        ** will be more aggressive about generating automatic indexes for
132663        ** those objects, since there is no opportunity to add schema
132664        ** indexes on subqueries and views. */
132665        pNew->rSetup = rLogSize + rSize + 4;
132666        if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
132667          pNew->rSetup += 24;
132668        }
132669        ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
132670        if( pNew->rSetup<0 ) pNew->rSetup = 0;
132671        /* TUNING: Each index lookup yields 20 rows in the table.  This
132672        ** is more than the usual guess of 10 rows, since we have no way
132673        ** of knowing how selective the index will ultimately be.  It would
132674        ** not be unreasonable to make this value much larger. */
132675        pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
132676        pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
132677        pNew->wsFlags = WHERE_AUTO_INDEX;
132678        pNew->prereq = mPrereq | pTerm->prereqRight;
132679        rc = whereLoopInsert(pBuilder, pNew);
132680      }
132681    }
132682  }
132683#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
132684
132685  /* Loop over all indices
132686  */
132687  for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
132688    if( pProbe->pPartIdxWhere!=0
132689     && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
132690      testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
132691      continue;  /* Partial index inappropriate for this query */
132692    }
132693    rSize = pProbe->aiRowLogEst[0];
132694    pNew->u.btree.nEq = 0;
132695    pNew->u.btree.nBtm = 0;
132696    pNew->u.btree.nTop = 0;
132697    pNew->nSkip = 0;
132698    pNew->nLTerm = 0;
132699    pNew->iSortIdx = 0;
132700    pNew->rSetup = 0;
132701    pNew->prereq = mPrereq;
132702    pNew->nOut = rSize;
132703    pNew->u.btree.pIndex = pProbe;
132704    b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
132705    /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
132706    assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
132707    if( pProbe->tnum<=0 ){
132708      /* Integer primary key index */
132709      pNew->wsFlags = WHERE_IPK;
132710
132711      /* Full table scan */
132712      pNew->iSortIdx = b ? iSortIdx : 0;
132713      /* TUNING: Cost of full table scan is (N*3.0). */
132714      pNew->rRun = rSize + 16;
132715      ApplyCostMultiplier(pNew->rRun, pTab->costMult);
132716      whereLoopOutputAdjust(pWC, pNew, rSize);
132717      rc = whereLoopInsert(pBuilder, pNew);
132718      pNew->nOut = rSize;
132719      if( rc ) break;
132720    }else{
132721      Bitmask m;
132722      if( pProbe->isCovering ){
132723        pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
132724        m = 0;
132725      }else{
132726        m = pSrc->colUsed & ~columnsInIndex(pProbe);
132727        pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
132728      }
132729
132730      /* Full scan via index */
132731      if( b
132732       || !HasRowid(pTab)
132733       || pProbe->pPartIdxWhere!=0
132734       || ( m==0
132735         && pProbe->bUnordered==0
132736         && (pProbe->szIdxRow<pTab->szTabRow)
132737         && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
132738         && sqlite3GlobalConfig.bUseCis
132739         && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
132740          )
132741      ){
132742        pNew->iSortIdx = b ? iSortIdx : 0;
132743
132744        /* The cost of visiting the index rows is N*K, where K is
132745        ** between 1.1 and 3.0, depending on the relative sizes of the
132746        ** index and table rows. */
132747        pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
132748        if( m!=0 ){
132749          /* If this is a non-covering index scan, add in the cost of
132750          ** doing table lookups.  The cost will be 3x the number of
132751          ** lookups.  Take into account WHERE clause terms that can be
132752          ** satisfied using just the index, and that do not require a
132753          ** table lookup. */
132754          LogEst nLookup = rSize + 16;  /* Base cost:  N*3 */
132755          int ii;
132756          int iCur = pSrc->iCursor;
132757          WhereClause *pWC2 = &pWInfo->sWC;
132758          for(ii=0; ii<pWC2->nTerm; ii++){
132759            WhereTerm *pTerm = &pWC2->a[ii];
132760            if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
132761              break;
132762            }
132763            /* pTerm can be evaluated using just the index.  So reduce
132764            ** the expected number of table lookups accordingly */
132765            if( pTerm->truthProb<=0 ){
132766              nLookup += pTerm->truthProb;
132767            }else{
132768              nLookup--;
132769              if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
132770            }
132771          }
132772
132773          pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
132774        }
132775        ApplyCostMultiplier(pNew->rRun, pTab->costMult);
132776        whereLoopOutputAdjust(pWC, pNew, rSize);
132777        rc = whereLoopInsert(pBuilder, pNew);
132778        pNew->nOut = rSize;
132779        if( rc ) break;
132780      }
132781    }
132782
132783    pBuilder->bldFlags = 0;
132784    rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
132785    if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
132786      /* If a non-unique index is used, or if a prefix of the key for
132787      ** unique index is used (making the index functionally non-unique)
132788      ** then the sqlite_stat1 data becomes important for scoring the
132789      ** plan */
132790      pTab->tabFlags |= TF_StatsUsed;
132791    }
132792#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
132793    sqlite3Stat4ProbeFree(pBuilder->pRec);
132794    pBuilder->nRecValid = 0;
132795    pBuilder->pRec = 0;
132796#endif
132797
132798    /* If there was an INDEXED BY clause, then only that one index is
132799    ** considered. */
132800    if( pSrc->pIBIndex ) break;
132801  }
132802  return rc;
132803}
132804
132805#ifndef SQLITE_OMIT_VIRTUALTABLE
132806
132807/*
132808** Argument pIdxInfo is already populated with all constraints that may
132809** be used by the virtual table identified by pBuilder->pNew->iTab. This
132810** function marks a subset of those constraints usable, invokes the
132811** xBestIndex method and adds the returned plan to pBuilder.
132812**
132813** A constraint is marked usable if:
132814**
132815**   * Argument mUsable indicates that its prerequisites are available, and
132816**
132817**   * It is not one of the operators specified in the mExclude mask passed
132818**     as the fourth argument (which in practice is either WO_IN or 0).
132819**
132820** Argument mPrereq is a mask of tables that must be scanned before the
132821** virtual table in question. These are added to the plans prerequisites
132822** before it is added to pBuilder.
132823**
132824** Output parameter *pbIn is set to true if the plan added to pBuilder
132825** uses one or more WO_IN terms, or false otherwise.
132826*/
132827static int whereLoopAddVirtualOne(
132828  WhereLoopBuilder *pBuilder,
132829  Bitmask mPrereq,                /* Mask of tables that must be used. */
132830  Bitmask mUsable,                /* Mask of usable tables */
132831  u16 mExclude,                   /* Exclude terms using these operators */
132832  sqlite3_index_info *pIdxInfo,   /* Populated object for xBestIndex */
132833  u16 mNoOmit,                    /* Do not omit these constraints */
132834  int *pbIn                       /* OUT: True if plan uses an IN(...) op */
132835){
132836  WhereClause *pWC = pBuilder->pWC;
132837  struct sqlite3_index_constraint *pIdxCons;
132838  struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
132839  int i;
132840  int mxTerm;
132841  int rc = SQLITE_OK;
132842  WhereLoop *pNew = pBuilder->pNew;
132843  Parse *pParse = pBuilder->pWInfo->pParse;
132844  struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
132845  int nConstraint = pIdxInfo->nConstraint;
132846
132847  assert( (mUsable & mPrereq)==mPrereq );
132848  *pbIn = 0;
132849  pNew->prereq = mPrereq;
132850
132851  /* Set the usable flag on the subset of constraints identified by
132852  ** arguments mUsable and mExclude. */
132853  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
132854  for(i=0; i<nConstraint; i++, pIdxCons++){
132855    WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
132856    pIdxCons->usable = 0;
132857    if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
132858     && (pTerm->eOperator & mExclude)==0
132859    ){
132860      pIdxCons->usable = 1;
132861    }
132862  }
132863
132864  /* Initialize the output fields of the sqlite3_index_info structure */
132865  memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
132866  assert( pIdxInfo->needToFreeIdxStr==0 );
132867  pIdxInfo->idxStr = 0;
132868  pIdxInfo->idxNum = 0;
132869  pIdxInfo->orderByConsumed = 0;
132870  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
132871  pIdxInfo->estimatedRows = 25;
132872  pIdxInfo->idxFlags = 0;
132873  pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
132874
132875  /* Invoke the virtual table xBestIndex() method */
132876  rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
132877  if( rc ) return rc;
132878
132879  mxTerm = -1;
132880  assert( pNew->nLSlot>=nConstraint );
132881  for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
132882  pNew->u.vtab.omitMask = 0;
132883  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
132884  for(i=0; i<nConstraint; i++, pIdxCons++){
132885    int iTerm;
132886    if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
132887      WhereTerm *pTerm;
132888      int j = pIdxCons->iTermOffset;
132889      if( iTerm>=nConstraint
132890       || j<0
132891       || j>=pWC->nTerm
132892       || pNew->aLTerm[iTerm]!=0
132893       || pIdxCons->usable==0
132894      ){
132895        rc = SQLITE_ERROR;
132896        sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
132897        return rc;
132898      }
132899      testcase( iTerm==nConstraint-1 );
132900      testcase( j==0 );
132901      testcase( j==pWC->nTerm-1 );
132902      pTerm = &pWC->a[j];
132903      pNew->prereq |= pTerm->prereqRight;
132904      assert( iTerm<pNew->nLSlot );
132905      pNew->aLTerm[iTerm] = pTerm;
132906      if( iTerm>mxTerm ) mxTerm = iTerm;
132907      testcase( iTerm==15 );
132908      testcase( iTerm==16 );
132909      if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
132910      if( (pTerm->eOperator & WO_IN)!=0 ){
132911        /* A virtual table that is constrained by an IN clause may not
132912        ** consume the ORDER BY clause because (1) the order of IN terms
132913        ** is not necessarily related to the order of output terms and
132914        ** (2) Multiple outputs from a single IN value will not merge
132915        ** together.  */
132916        pIdxInfo->orderByConsumed = 0;
132917        pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
132918        *pbIn = 1; assert( (mExclude & WO_IN)==0 );
132919      }
132920    }
132921  }
132922  pNew->u.vtab.omitMask &= ~mNoOmit;
132923
132924  pNew->nLTerm = mxTerm+1;
132925  assert( pNew->nLTerm<=pNew->nLSlot );
132926  pNew->u.vtab.idxNum = pIdxInfo->idxNum;
132927  pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
132928  pIdxInfo->needToFreeIdxStr = 0;
132929  pNew->u.vtab.idxStr = pIdxInfo->idxStr;
132930  pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
132931      pIdxInfo->nOrderBy : 0);
132932  pNew->rSetup = 0;
132933  pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
132934  pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
132935
132936  /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
132937  ** that the scan will visit at most one row. Clear it otherwise. */
132938  if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
132939    pNew->wsFlags |= WHERE_ONEROW;
132940  }else{
132941    pNew->wsFlags &= ~WHERE_ONEROW;
132942  }
132943  rc = whereLoopInsert(pBuilder, pNew);
132944  if( pNew->u.vtab.needFree ){
132945    sqlite3_free(pNew->u.vtab.idxStr);
132946    pNew->u.vtab.needFree = 0;
132947  }
132948  WHERETRACE(0xffff, ("  bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
132949                      *pbIn, (sqlite3_uint64)mPrereq,
132950                      (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
132951
132952  return rc;
132953}
132954
132955
132956/*
132957** Add all WhereLoop objects for a table of the join identified by
132958** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
132959**
132960** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
132961** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
132962** entries that occur before the virtual table in the FROM clause and are
132963** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
132964** mUnusable mask contains all FROM clause entries that occur after the
132965** virtual table and are separated from it by at least one LEFT or
132966** CROSS JOIN.
132967**
132968** For example, if the query were:
132969**
132970**   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
132971**
132972** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
132973**
132974** All the tables in mPrereq must be scanned before the current virtual
132975** table. So any terms for which all prerequisites are satisfied by
132976** mPrereq may be specified as "usable" in all calls to xBestIndex.
132977** Conversely, all tables in mUnusable must be scanned after the current
132978** virtual table, so any terms for which the prerequisites overlap with
132979** mUnusable should always be configured as "not-usable" for xBestIndex.
132980*/
132981static int whereLoopAddVirtual(
132982  WhereLoopBuilder *pBuilder,  /* WHERE clause information */
132983  Bitmask mPrereq,             /* Tables that must be scanned before this one */
132984  Bitmask mUnusable            /* Tables that must be scanned after this one */
132985){
132986  int rc = SQLITE_OK;          /* Return code */
132987  WhereInfo *pWInfo;           /* WHERE analysis context */
132988  Parse *pParse;               /* The parsing context */
132989  WhereClause *pWC;            /* The WHERE clause */
132990  struct SrcList_item *pSrc;   /* The FROM clause term to search */
132991  sqlite3_index_info *p;       /* Object to pass to xBestIndex() */
132992  int nConstraint;             /* Number of constraints in p */
132993  int bIn;                     /* True if plan uses IN(...) operator */
132994  WhereLoop *pNew;
132995  Bitmask mBest;               /* Tables used by best possible plan */
132996  u16 mNoOmit;
132997
132998  assert( (mPrereq & mUnusable)==0 );
132999  pWInfo = pBuilder->pWInfo;
133000  pParse = pWInfo->pParse;
133001  pWC = pBuilder->pWC;
133002  pNew = pBuilder->pNew;
133003  pSrc = &pWInfo->pTabList->a[pNew->iTab];
133004  assert( IsVirtual(pSrc->pTab) );
133005  p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
133006      &mNoOmit);
133007  if( p==0 ) return SQLITE_NOMEM_BKPT;
133008  pNew->rSetup = 0;
133009  pNew->wsFlags = WHERE_VIRTUALTABLE;
133010  pNew->nLTerm = 0;
133011  pNew->u.vtab.needFree = 0;
133012  nConstraint = p->nConstraint;
133013  if( whereLoopResize(pParse->db, pNew, nConstraint) ){
133014    sqlite3DbFree(pParse->db, p);
133015    return SQLITE_NOMEM_BKPT;
133016  }
133017
133018  /* First call xBestIndex() with all constraints usable. */
133019  WHERETRACE(0x40, ("  VirtualOne: all usable\n"));
133020  rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
133021
133022  /* If the call to xBestIndex() with all terms enabled produced a plan
133023  ** that does not require any source tables (IOW: a plan with mBest==0),
133024  ** then there is no point in making any further calls to xBestIndex()
133025  ** since they will all return the same result (if the xBestIndex()
133026  ** implementation is sane). */
133027  if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
133028    int seenZero = 0;             /* True if a plan with no prereqs seen */
133029    int seenZeroNoIN = 0;         /* Plan with no prereqs and no IN(...) seen */
133030    Bitmask mPrev = 0;
133031    Bitmask mBestNoIn = 0;
133032
133033    /* If the plan produced by the earlier call uses an IN(...) term, call
133034    ** xBestIndex again, this time with IN(...) terms disabled. */
133035    if( bIn ){
133036      WHERETRACE(0x40, ("  VirtualOne: all usable w/o IN\n"));
133037      rc = whereLoopAddVirtualOne(
133038          pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
133039      assert( bIn==0 );
133040      mBestNoIn = pNew->prereq & ~mPrereq;
133041      if( mBestNoIn==0 ){
133042        seenZero = 1;
133043        seenZeroNoIN = 1;
133044      }
133045    }
133046
133047    /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
133048    ** in the set of terms that apply to the current virtual table.  */
133049    while( rc==SQLITE_OK ){
133050      int i;
133051      Bitmask mNext = ALLBITS;
133052      assert( mNext>0 );
133053      for(i=0; i<nConstraint; i++){
133054        Bitmask mThis = (
133055            pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
133056        );
133057        if( mThis>mPrev && mThis<mNext ) mNext = mThis;
133058      }
133059      mPrev = mNext;
133060      if( mNext==ALLBITS ) break;
133061      if( mNext==mBest || mNext==mBestNoIn ) continue;
133062      WHERETRACE(0x40, ("  VirtualOne: mPrev=%04llx mNext=%04llx\n",
133063                       (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
133064      rc = whereLoopAddVirtualOne(
133065          pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
133066      if( pNew->prereq==mPrereq ){
133067        seenZero = 1;
133068        if( bIn==0 ) seenZeroNoIN = 1;
133069      }
133070    }
133071
133072    /* If the calls to xBestIndex() in the above loop did not find a plan
133073    ** that requires no source tables at all (i.e. one guaranteed to be
133074    ** usable), make a call here with all source tables disabled */
133075    if( rc==SQLITE_OK && seenZero==0 ){
133076      WHERETRACE(0x40, ("  VirtualOne: all disabled\n"));
133077      rc = whereLoopAddVirtualOne(
133078          pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
133079      if( bIn==0 ) seenZeroNoIN = 1;
133080    }
133081
133082    /* If the calls to xBestIndex() have so far failed to find a plan
133083    ** that requires no source tables at all and does not use an IN(...)
133084    ** operator, make a final call to obtain one here.  */
133085    if( rc==SQLITE_OK && seenZeroNoIN==0 ){
133086      WHERETRACE(0x40, ("  VirtualOne: all disabled and w/o IN\n"));
133087      rc = whereLoopAddVirtualOne(
133088          pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
133089    }
133090  }
133091
133092  if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
133093  sqlite3DbFree(pParse->db, p);
133094  return rc;
133095}
133096#endif /* SQLITE_OMIT_VIRTUALTABLE */
133097
133098/*
133099** Add WhereLoop entries to handle OR terms.  This works for either
133100** btrees or virtual tables.
133101*/
133102static int whereLoopAddOr(
133103  WhereLoopBuilder *pBuilder,
133104  Bitmask mPrereq,
133105  Bitmask mUnusable
133106){
133107  WhereInfo *pWInfo = pBuilder->pWInfo;
133108  WhereClause *pWC;
133109  WhereLoop *pNew;
133110  WhereTerm *pTerm, *pWCEnd;
133111  int rc = SQLITE_OK;
133112  int iCur;
133113  WhereClause tempWC;
133114  WhereLoopBuilder sSubBuild;
133115  WhereOrSet sSum, sCur;
133116  struct SrcList_item *pItem;
133117
133118  pWC = pBuilder->pWC;
133119  pWCEnd = pWC->a + pWC->nTerm;
133120  pNew = pBuilder->pNew;
133121  memset(&sSum, 0, sizeof(sSum));
133122  pItem = pWInfo->pTabList->a + pNew->iTab;
133123  iCur = pItem->iCursor;
133124
133125  for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
133126    if( (pTerm->eOperator & WO_OR)!=0
133127     && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
133128    ){
133129      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
133130      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
133131      WhereTerm *pOrTerm;
133132      int once = 1;
133133      int i, j;
133134
133135      sSubBuild = *pBuilder;
133136      sSubBuild.pOrderBy = 0;
133137      sSubBuild.pOrSet = &sCur;
133138
133139      WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
133140      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
133141        if( (pOrTerm->eOperator & WO_AND)!=0 ){
133142          sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
133143        }else if( pOrTerm->leftCursor==iCur ){
133144          tempWC.pWInfo = pWC->pWInfo;
133145          tempWC.pOuter = pWC;
133146          tempWC.op = TK_AND;
133147          tempWC.nTerm = 1;
133148          tempWC.a = pOrTerm;
133149          sSubBuild.pWC = &tempWC;
133150        }else{
133151          continue;
133152        }
133153        sCur.n = 0;
133154#ifdef WHERETRACE_ENABLED
133155        WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
133156                   (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
133157        if( sqlite3WhereTrace & 0x400 ){
133158          sqlite3WhereClausePrint(sSubBuild.pWC);
133159        }
133160#endif
133161#ifndef SQLITE_OMIT_VIRTUALTABLE
133162        if( IsVirtual(pItem->pTab) ){
133163          rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
133164        }else
133165#endif
133166        {
133167          rc = whereLoopAddBtree(&sSubBuild, mPrereq);
133168        }
133169        if( rc==SQLITE_OK ){
133170          rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
133171        }
133172        assert( rc==SQLITE_OK || sCur.n==0 );
133173        if( sCur.n==0 ){
133174          sSum.n = 0;
133175          break;
133176        }else if( once ){
133177          whereOrMove(&sSum, &sCur);
133178          once = 0;
133179        }else{
133180          WhereOrSet sPrev;
133181          whereOrMove(&sPrev, &sSum);
133182          sSum.n = 0;
133183          for(i=0; i<sPrev.n; i++){
133184            for(j=0; j<sCur.n; j++){
133185              whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
133186                            sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
133187                            sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
133188            }
133189          }
133190        }
133191      }
133192      pNew->nLTerm = 1;
133193      pNew->aLTerm[0] = pTerm;
133194      pNew->wsFlags = WHERE_MULTI_OR;
133195      pNew->rSetup = 0;
133196      pNew->iSortIdx = 0;
133197      memset(&pNew->u, 0, sizeof(pNew->u));
133198      for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
133199        /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
133200        ** of all sub-scans required by the OR-scan. However, due to rounding
133201        ** errors, it may be that the cost of the OR-scan is equal to its
133202        ** most expensive sub-scan. Add the smallest possible penalty
133203        ** (equivalent to multiplying the cost by 1.07) to ensure that
133204        ** this does not happen. Otherwise, for WHERE clauses such as the
133205        ** following where there is an index on "y":
133206        **
133207        **     WHERE likelihood(x=?, 0.99) OR y=?
133208        **
133209        ** the planner may elect to "OR" together a full-table scan and an
133210        ** index lookup. And other similarly odd results.  */
133211        pNew->rRun = sSum.a[i].rRun + 1;
133212        pNew->nOut = sSum.a[i].nOut;
133213        pNew->prereq = sSum.a[i].prereq;
133214        rc = whereLoopInsert(pBuilder, pNew);
133215      }
133216      WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
133217    }
133218  }
133219  return rc;
133220}
133221
133222/*
133223** Add all WhereLoop objects for all tables
133224*/
133225static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
133226  WhereInfo *pWInfo = pBuilder->pWInfo;
133227  Bitmask mPrereq = 0;
133228  Bitmask mPrior = 0;
133229  int iTab;
133230  SrcList *pTabList = pWInfo->pTabList;
133231  struct SrcList_item *pItem;
133232  struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
133233  sqlite3 *db = pWInfo->pParse->db;
133234  int rc = SQLITE_OK;
133235  WhereLoop *pNew;
133236  u8 priorJointype = 0;
133237
133238  /* Loop over the tables in the join, from left to right */
133239  pNew = pBuilder->pNew;
133240  whereLoopInit(pNew);
133241  for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
133242    Bitmask mUnusable = 0;
133243    pNew->iTab = iTab;
133244    pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
133245    if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
133246      /* This condition is true when pItem is the FROM clause term on the
133247      ** right-hand-side of a LEFT or CROSS JOIN.  */
133248      mPrereq = mPrior;
133249    }
133250    priorJointype = pItem->fg.jointype;
133251#ifndef SQLITE_OMIT_VIRTUALTABLE
133252    if( IsVirtual(pItem->pTab) ){
133253      struct SrcList_item *p;
133254      for(p=&pItem[1]; p<pEnd; p++){
133255        if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
133256          mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
133257        }
133258      }
133259      rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
133260    }else
133261#endif /* SQLITE_OMIT_VIRTUALTABLE */
133262    {
133263      rc = whereLoopAddBtree(pBuilder, mPrereq);
133264    }
133265    if( rc==SQLITE_OK ){
133266      rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
133267    }
133268    mPrior |= pNew->maskSelf;
133269    if( rc || db->mallocFailed ) break;
133270  }
133271
133272  whereLoopClear(db, pNew);
133273  return rc;
133274}
133275
133276/*
133277** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
133278** parameters) to see if it outputs rows in the requested ORDER BY
133279** (or GROUP BY) without requiring a separate sort operation.  Return N:
133280**
133281**   N>0:   N terms of the ORDER BY clause are satisfied
133282**   N==0:  No terms of the ORDER BY clause are satisfied
133283**   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
133284**
133285** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
133286** strict.  With GROUP BY and DISTINCT the only requirement is that
133287** equivalent rows appear immediately adjacent to one another.  GROUP BY
133288** and DISTINCT do not require rows to appear in any particular order as long
133289** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
133290** the pOrderBy terms can be matched in any order.  With ORDER BY, the
133291** pOrderBy terms must be matched in strict left-to-right order.
133292*/
133293static i8 wherePathSatisfiesOrderBy(
133294  WhereInfo *pWInfo,    /* The WHERE clause */
133295  ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
133296  WherePath *pPath,     /* The WherePath to check */
133297  u16 wctrlFlags,       /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
133298  u16 nLoop,            /* Number of entries in pPath->aLoop[] */
133299  WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
133300  Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
133301){
133302  u8 revSet;            /* True if rev is known */
133303  u8 rev;               /* Composite sort order */
133304  u8 revIdx;            /* Index sort order */
133305  u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
133306  u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
133307  u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
133308  u16 eqOpMask;         /* Allowed equality operators */
133309  u16 nKeyCol;          /* Number of key columns in pIndex */
133310  u16 nColumn;          /* Total number of ordered columns in the index */
133311  u16 nOrderBy;         /* Number terms in the ORDER BY clause */
133312  int iLoop;            /* Index of WhereLoop in pPath being processed */
133313  int i, j;             /* Loop counters */
133314  int iCur;             /* Cursor number for current WhereLoop */
133315  int iColumn;          /* A column number within table iCur */
133316  WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
133317  WhereTerm *pTerm;     /* A single term of the WHERE clause */
133318  Expr *pOBExpr;        /* An expression from the ORDER BY clause */
133319  CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
133320  Index *pIndex;        /* The index associated with pLoop */
133321  sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
133322  Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
133323  Bitmask obDone;       /* Mask of all ORDER BY terms */
133324  Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
133325  Bitmask ready;              /* Mask of inner loops */
133326
133327  /*
133328  ** We say the WhereLoop is "one-row" if it generates no more than one
133329  ** row of output.  A WhereLoop is one-row if all of the following are true:
133330  **  (a) All index columns match with WHERE_COLUMN_EQ.
133331  **  (b) The index is unique
133332  ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
133333  ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
133334  **
133335  ** We say the WhereLoop is "order-distinct" if the set of columns from
133336  ** that WhereLoop that are in the ORDER BY clause are different for every
133337  ** row of the WhereLoop.  Every one-row WhereLoop is automatically
133338  ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
133339  ** is not order-distinct. To be order-distinct is not quite the same as being
133340  ** UNIQUE since a UNIQUE column or index can have multiple rows that
133341  ** are NULL and NULL values are equivalent for the purpose of order-distinct.
133342  ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
133343  **
133344  ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
133345  ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
133346  ** automatically order-distinct.
133347  */
133348
133349  assert( pOrderBy!=0 );
133350  if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
133351
133352  nOrderBy = pOrderBy->nExpr;
133353  testcase( nOrderBy==BMS-1 );
133354  if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
133355  isOrderDistinct = 1;
133356  obDone = MASKBIT(nOrderBy)-1;
133357  orderDistinctMask = 0;
133358  ready = 0;
133359  eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
133360  if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
133361  for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
133362    if( iLoop>0 ) ready |= pLoop->maskSelf;
133363    if( iLoop<nLoop ){
133364      pLoop = pPath->aLoop[iLoop];
133365      if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
133366    }else{
133367      pLoop = pLast;
133368    }
133369    if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
133370      if( pLoop->u.vtab.isOrdered ) obSat = obDone;
133371      break;
133372    }
133373    iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
133374
133375    /* Mark off any ORDER BY term X that is a column in the table of
133376    ** the current loop for which there is term in the WHERE
133377    ** clause of the form X IS NULL or X=? that reference only outer
133378    ** loops.
133379    */
133380    for(i=0; i<nOrderBy; i++){
133381      if( MASKBIT(i) & obSat ) continue;
133382      pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
133383      if( pOBExpr->op!=TK_COLUMN ) continue;
133384      if( pOBExpr->iTable!=iCur ) continue;
133385      pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
133386                       ~ready, eqOpMask, 0);
133387      if( pTerm==0 ) continue;
133388      if( pTerm->eOperator==WO_IN ){
133389        /* IN terms are only valid for sorting in the ORDER BY LIMIT
133390        ** optimization, and then only if they are actually used
133391        ** by the query plan */
133392        assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
133393        for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
133394        if( j>=pLoop->nLTerm ) continue;
133395      }
133396      if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
133397        const char *z1, *z2;
133398        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
133399        if( !pColl ) pColl = db->pDfltColl;
133400        z1 = pColl->zName;
133401        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
133402        if( !pColl ) pColl = db->pDfltColl;
133403        z2 = pColl->zName;
133404        if( sqlite3StrICmp(z1, z2)!=0 ) continue;
133405        testcase( pTerm->pExpr->op==TK_IS );
133406      }
133407      obSat |= MASKBIT(i);
133408    }
133409
133410    if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
133411      if( pLoop->wsFlags & WHERE_IPK ){
133412        pIndex = 0;
133413        nKeyCol = 0;
133414        nColumn = 1;
133415      }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
133416        return 0;
133417      }else{
133418        nKeyCol = pIndex->nKeyCol;
133419        nColumn = pIndex->nColumn;
133420        assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
133421        assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
133422                          || !HasRowid(pIndex->pTable));
133423        isOrderDistinct = IsUniqueIndex(pIndex);
133424      }
133425
133426      /* Loop through all columns of the index and deal with the ones
133427      ** that are not constrained by == or IN.
133428      */
133429      rev = revSet = 0;
133430      distinctColumns = 0;
133431      for(j=0; j<nColumn; j++){
133432        u8 bOnce = 1; /* True to run the ORDER BY search loop */
133433
133434        assert( j>=pLoop->u.btree.nEq
133435            || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
133436        );
133437        if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
133438          u16 eOp = pLoop->aLTerm[j]->eOperator;
133439
133440          /* Skip over == and IS and ISNULL terms.  (Also skip IN terms when
133441          ** doing WHERE_ORDERBY_LIMIT processing).
133442          **
133443          ** If the current term is a column of an ((?,?) IN (SELECT...))
133444          ** expression for which the SELECT returns more than one column,
133445          ** check that it is the only column used by this loop. Otherwise,
133446          ** if it is one of two or more, none of the columns can be
133447          ** considered to match an ORDER BY term.  */
133448          if( (eOp & eqOpMask)!=0 ){
133449            if( eOp & WO_ISNULL ){
133450              testcase( isOrderDistinct );
133451              isOrderDistinct = 0;
133452            }
133453            continue;
133454          }else if( ALWAYS(eOp & WO_IN) ){
133455            /* ALWAYS() justification: eOp is an equality operator due to the
133456            ** j<pLoop->u.btree.nEq constraint above.  Any equality other
133457            ** than WO_IN is captured by the previous "if".  So this one
133458            ** always has to be WO_IN. */
133459            Expr *pX = pLoop->aLTerm[j]->pExpr;
133460            for(i=j+1; i<pLoop->u.btree.nEq; i++){
133461              if( pLoop->aLTerm[i]->pExpr==pX ){
133462                assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
133463                bOnce = 0;
133464                break;
133465              }
133466            }
133467          }
133468        }
133469
133470        /* Get the column number in the table (iColumn) and sort order
133471        ** (revIdx) for the j-th column of the index.
133472        */
133473        if( pIndex ){
133474          iColumn = pIndex->aiColumn[j];
133475          revIdx = pIndex->aSortOrder[j];
133476          if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
133477        }else{
133478          iColumn = XN_ROWID;
133479          revIdx = 0;
133480        }
133481
133482        /* An unconstrained column that might be NULL means that this
133483        ** WhereLoop is not well-ordered
133484        */
133485        if( isOrderDistinct
133486         && iColumn>=0
133487         && j>=pLoop->u.btree.nEq
133488         && pIndex->pTable->aCol[iColumn].notNull==0
133489        ){
133490          isOrderDistinct = 0;
133491        }
133492
133493        /* Find the ORDER BY term that corresponds to the j-th column
133494        ** of the index and mark that ORDER BY term off
133495        */
133496        isMatch = 0;
133497        for(i=0; bOnce && i<nOrderBy; i++){
133498          if( MASKBIT(i) & obSat ) continue;
133499          pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
133500          testcase( wctrlFlags & WHERE_GROUPBY );
133501          testcase( wctrlFlags & WHERE_DISTINCTBY );
133502          if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
133503          if( iColumn>=(-1) ){
133504            if( pOBExpr->op!=TK_COLUMN ) continue;
133505            if( pOBExpr->iTable!=iCur ) continue;
133506            if( pOBExpr->iColumn!=iColumn ) continue;
133507          }else{
133508            if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
133509              continue;
133510            }
133511          }
133512          if( iColumn>=0 ){
133513            pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
133514            if( !pColl ) pColl = db->pDfltColl;
133515            if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
133516          }
133517          isMatch = 1;
133518          break;
133519        }
133520        if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
133521          /* Make sure the sort order is compatible in an ORDER BY clause.
133522          ** Sort order is irrelevant for a GROUP BY clause. */
133523          if( revSet ){
133524            if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
133525          }else{
133526            rev = revIdx ^ pOrderBy->a[i].sortOrder;
133527            if( rev ) *pRevMask |= MASKBIT(iLoop);
133528            revSet = 1;
133529          }
133530        }
133531        if( isMatch ){
133532          if( iColumn==XN_ROWID ){
133533            testcase( distinctColumns==0 );
133534            distinctColumns = 1;
133535          }
133536          obSat |= MASKBIT(i);
133537        }else{
133538          /* No match found */
133539          if( j==0 || j<nKeyCol ){
133540            testcase( isOrderDistinct!=0 );
133541            isOrderDistinct = 0;
133542          }
133543          break;
133544        }
133545      } /* end Loop over all index columns */
133546      if( distinctColumns ){
133547        testcase( isOrderDistinct==0 );
133548        isOrderDistinct = 1;
133549      }
133550    } /* end-if not one-row */
133551
133552    /* Mark off any other ORDER BY terms that reference pLoop */
133553    if( isOrderDistinct ){
133554      orderDistinctMask |= pLoop->maskSelf;
133555      for(i=0; i<nOrderBy; i++){
133556        Expr *p;
133557        Bitmask mTerm;
133558        if( MASKBIT(i) & obSat ) continue;
133559        p = pOrderBy->a[i].pExpr;
133560        mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
133561        if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
133562        if( (mTerm&~orderDistinctMask)==0 ){
133563          obSat |= MASKBIT(i);
133564        }
133565      }
133566    }
133567  } /* End the loop over all WhereLoops from outer-most down to inner-most */
133568  if( obSat==obDone ) return (i8)nOrderBy;
133569  if( !isOrderDistinct ){
133570    for(i=nOrderBy-1; i>0; i--){
133571      Bitmask m = MASKBIT(i) - 1;
133572      if( (obSat&m)==m ) return i;
133573    }
133574    return 0;
133575  }
133576  return -1;
133577}
133578
133579
133580/*
133581** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
133582** the planner assumes that the specified pOrderBy list is actually a GROUP
133583** BY clause - and so any order that groups rows as required satisfies the
133584** request.
133585**
133586** Normally, in this case it is not possible for the caller to determine
133587** whether or not the rows are really being delivered in sorted order, or
133588** just in some other order that provides the required grouping. However,
133589** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
133590** this function may be called on the returned WhereInfo object. It returns
133591** true if the rows really will be sorted in the specified order, or false
133592** otherwise.
133593**
133594** For example, assuming:
133595**
133596**   CREATE INDEX i1 ON t1(x, Y);
133597**
133598** then
133599**
133600**   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
133601**   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
133602*/
133603SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
133604  assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
133605  assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
133606  return pWInfo->sorted;
133607}
133608
133609#ifdef WHERETRACE_ENABLED
133610/* For debugging use only: */
133611static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
133612  static char zName[65];
133613  int i;
133614  for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
133615  if( pLast ) zName[i++] = pLast->cId;
133616  zName[i] = 0;
133617  return zName;
133618}
133619#endif
133620
133621/*
133622** Return the cost of sorting nRow rows, assuming that the keys have
133623** nOrderby columns and that the first nSorted columns are already in
133624** order.
133625*/
133626static LogEst whereSortingCost(
133627  WhereInfo *pWInfo,
133628  LogEst nRow,
133629  int nOrderBy,
133630  int nSorted
133631){
133632  /* TUNING: Estimated cost of a full external sort, where N is
133633  ** the number of rows to sort is:
133634  **
133635  **   cost = (3.0 * N * log(N)).
133636  **
133637  ** Or, if the order-by clause has X terms but only the last Y
133638  ** terms are out of order, then block-sorting will reduce the
133639  ** sorting cost to:
133640  **
133641  **   cost = (3.0 * N * log(N)) * (Y/X)
133642  **
133643  ** The (Y/X) term is implemented using stack variable rScale
133644  ** below.  */
133645  LogEst rScale, rSortCost;
133646  assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
133647  rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
133648  rSortCost = nRow + rScale + 16;
133649
133650  /* Multiple by log(M) where M is the number of output rows.
133651  ** Use the LIMIT for M if it is smaller */
133652  if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
133653    nRow = pWInfo->iLimit;
133654  }
133655  rSortCost += estLog(nRow);
133656  return rSortCost;
133657}
133658
133659/*
133660** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
133661** attempts to find the lowest cost path that visits each WhereLoop
133662** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
133663**
133664** Assume that the total number of output rows that will need to be sorted
133665** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
133666** costs if nRowEst==0.
133667**
133668** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
133669** error occurs.
133670*/
133671static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
133672  int mxChoice;             /* Maximum number of simultaneous paths tracked */
133673  int nLoop;                /* Number of terms in the join */
133674  Parse *pParse;            /* Parsing context */
133675  sqlite3 *db;              /* The database connection */
133676  int iLoop;                /* Loop counter over the terms of the join */
133677  int ii, jj;               /* Loop counters */
133678  int mxI = 0;              /* Index of next entry to replace */
133679  int nOrderBy;             /* Number of ORDER BY clause terms */
133680  LogEst mxCost = 0;        /* Maximum cost of a set of paths */
133681  LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
133682  int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
133683  WherePath *aFrom;         /* All nFrom paths at the previous level */
133684  WherePath *aTo;           /* The nTo best paths at the current level */
133685  WherePath *pFrom;         /* An element of aFrom[] that we are working on */
133686  WherePath *pTo;           /* An element of aTo[] that we are working on */
133687  WhereLoop *pWLoop;        /* One of the WhereLoop objects */
133688  WhereLoop **pX;           /* Used to divy up the pSpace memory */
133689  LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
133690  char *pSpace;             /* Temporary memory used by this routine */
133691  int nSpace;               /* Bytes of space allocated at pSpace */
133692
133693  pParse = pWInfo->pParse;
133694  db = pParse->db;
133695  nLoop = pWInfo->nLevel;
133696  /* TUNING: For simple queries, only the best path is tracked.
133697  ** For 2-way joins, the 5 best paths are followed.
133698  ** For joins of 3 or more tables, track the 10 best paths */
133699  mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
133700  assert( nLoop<=pWInfo->pTabList->nSrc );
133701  WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
133702
133703  /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
133704  ** case the purpose of this call is to estimate the number of rows returned
133705  ** by the overall query. Once this estimate has been obtained, the caller
133706  ** will invoke this function a second time, passing the estimate as the
133707  ** nRowEst parameter.  */
133708  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
133709    nOrderBy = 0;
133710  }else{
133711    nOrderBy = pWInfo->pOrderBy->nExpr;
133712  }
133713
133714  /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
133715  nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
133716  nSpace += sizeof(LogEst) * nOrderBy;
133717  pSpace = sqlite3DbMallocRawNN(db, nSpace);
133718  if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
133719  aTo = (WherePath*)pSpace;
133720  aFrom = aTo+mxChoice;
133721  memset(aFrom, 0, sizeof(aFrom[0]));
133722  pX = (WhereLoop**)(aFrom+mxChoice);
133723  for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
133724    pFrom->aLoop = pX;
133725  }
133726  if( nOrderBy ){
133727    /* If there is an ORDER BY clause and it is not being ignored, set up
133728    ** space for the aSortCost[] array. Each element of the aSortCost array
133729    ** is either zero - meaning it has not yet been initialized - or the
133730    ** cost of sorting nRowEst rows of data where the first X terms of
133731    ** the ORDER BY clause are already in order, where X is the array
133732    ** index.  */
133733    aSortCost = (LogEst*)pX;
133734    memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
133735  }
133736  assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
133737  assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
133738
133739  /* Seed the search with a single WherePath containing zero WhereLoops.
133740  **
133741  ** TUNING: Do not let the number of iterations go above 28.  If the cost
133742  ** of computing an automatic index is not paid back within the first 28
133743  ** rows, then do not use the automatic index. */
133744  aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
133745  nFrom = 1;
133746  assert( aFrom[0].isOrdered==0 );
133747  if( nOrderBy ){
133748    /* If nLoop is zero, then there are no FROM terms in the query. Since
133749    ** in this case the query may return a maximum of one row, the results
133750    ** are already in the requested order. Set isOrdered to nOrderBy to
133751    ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
133752    ** -1, indicating that the result set may or may not be ordered,
133753    ** depending on the loops added to the current plan.  */
133754    aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
133755  }
133756
133757  /* Compute successively longer WherePaths using the previous generation
133758  ** of WherePaths as the basis for the next.  Keep track of the mxChoice
133759  ** best paths at each generation */
133760  for(iLoop=0; iLoop<nLoop; iLoop++){
133761    nTo = 0;
133762    for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
133763      for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
133764        LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
133765        LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
133766        LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
133767        i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
133768        Bitmask maskNew;                  /* Mask of src visited by (..) */
133769        Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
133770
133771        if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
133772        if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
133773        if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
133774          /* Do not use an automatic index if the this loop is expected
133775          ** to run less than 2 times. */
133776          assert( 10==sqlite3LogEst(2) );
133777          continue;
133778        }
133779        /* At this point, pWLoop is a candidate to be the next loop.
133780        ** Compute its cost */
133781        rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
133782        rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
133783        nOut = pFrom->nRow + pWLoop->nOut;
133784        maskNew = pFrom->maskLoop | pWLoop->maskSelf;
133785        if( isOrdered<0 ){
133786          isOrdered = wherePathSatisfiesOrderBy(pWInfo,
133787                       pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
133788                       iLoop, pWLoop, &revMask);
133789        }else{
133790          revMask = pFrom->revLoop;
133791        }
133792        if( isOrdered>=0 && isOrdered<nOrderBy ){
133793          if( aSortCost[isOrdered]==0 ){
133794            aSortCost[isOrdered] = whereSortingCost(
133795                pWInfo, nRowEst, nOrderBy, isOrdered
133796            );
133797          }
133798          rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
133799
133800          WHERETRACE(0x002,
133801              ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
133802               aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
133803               rUnsorted, rCost));
133804        }else{
133805          rCost = rUnsorted;
133806        }
133807
133808        /* Check to see if pWLoop should be added to the set of
133809        ** mxChoice best-so-far paths.
133810        **
133811        ** First look for an existing path among best-so-far paths
133812        ** that covers the same set of loops and has the same isOrdered
133813        ** setting as the current path candidate.
133814        **
133815        ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
133816        ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
133817        ** of legal values for isOrdered, -1..64.
133818        */
133819        for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
133820          if( pTo->maskLoop==maskNew
133821           && ((pTo->isOrdered^isOrdered)&0x80)==0
133822          ){
133823            testcase( jj==nTo-1 );
133824            break;
133825          }
133826        }
133827        if( jj>=nTo ){
133828          /* None of the existing best-so-far paths match the candidate. */
133829          if( nTo>=mxChoice
133830           && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
133831          ){
133832            /* The current candidate is no better than any of the mxChoice
133833            ** paths currently in the best-so-far buffer.  So discard
133834            ** this candidate as not viable. */
133835#ifdef WHERETRACE_ENABLED /* 0x4 */
133836            if( sqlite3WhereTrace&0x4 ){
133837              sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
133838                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
133839                  isOrdered>=0 ? isOrdered+'0' : '?');
133840            }
133841#endif
133842            continue;
133843          }
133844          /* If we reach this points it means that the new candidate path
133845          ** needs to be added to the set of best-so-far paths. */
133846          if( nTo<mxChoice ){
133847            /* Increase the size of the aTo set by one */
133848            jj = nTo++;
133849          }else{
133850            /* New path replaces the prior worst to keep count below mxChoice */
133851            jj = mxI;
133852          }
133853          pTo = &aTo[jj];
133854#ifdef WHERETRACE_ENABLED /* 0x4 */
133855          if( sqlite3WhereTrace&0x4 ){
133856            sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
133857                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
133858                isOrdered>=0 ? isOrdered+'0' : '?');
133859          }
133860#endif
133861        }else{
133862          /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
133863          ** same set of loops and has the sam isOrdered setting as the
133864          ** candidate path.  Check to see if the candidate should replace
133865          ** pTo or if the candidate should be skipped */
133866          if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
133867#ifdef WHERETRACE_ENABLED /* 0x4 */
133868            if( sqlite3WhereTrace&0x4 ){
133869              sqlite3DebugPrintf(
133870                  "Skip   %s cost=%-3d,%3d order=%c",
133871                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
133872                  isOrdered>=0 ? isOrdered+'0' : '?');
133873              sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
133874                  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
133875                  pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
133876            }
133877#endif
133878            /* Discard the candidate path from further consideration */
133879            testcase( pTo->rCost==rCost );
133880            continue;
133881          }
133882          testcase( pTo->rCost==rCost+1 );
133883          /* Control reaches here if the candidate path is better than the
133884          ** pTo path.  Replace pTo with the candidate. */
133885#ifdef WHERETRACE_ENABLED /* 0x4 */
133886          if( sqlite3WhereTrace&0x4 ){
133887            sqlite3DebugPrintf(
133888                "Update %s cost=%-3d,%3d order=%c",
133889                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
133890                isOrdered>=0 ? isOrdered+'0' : '?');
133891            sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
133892                wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
133893                pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
133894          }
133895#endif
133896        }
133897        /* pWLoop is a winner.  Add it to the set of best so far */
133898        pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
133899        pTo->revLoop = revMask;
133900        pTo->nRow = nOut;
133901        pTo->rCost = rCost;
133902        pTo->rUnsorted = rUnsorted;
133903        pTo->isOrdered = isOrdered;
133904        memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
133905        pTo->aLoop[iLoop] = pWLoop;
133906        if( nTo>=mxChoice ){
133907          mxI = 0;
133908          mxCost = aTo[0].rCost;
133909          mxUnsorted = aTo[0].nRow;
133910          for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
133911            if( pTo->rCost>mxCost
133912             || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
133913            ){
133914              mxCost = pTo->rCost;
133915              mxUnsorted = pTo->rUnsorted;
133916              mxI = jj;
133917            }
133918          }
133919        }
133920      }
133921    }
133922
133923#ifdef WHERETRACE_ENABLED  /* >=2 */
133924    if( sqlite3WhereTrace & 0x02 ){
133925      sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
133926      for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
133927        sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
133928           wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
133929           pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
133930        if( pTo->isOrdered>0 ){
133931          sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
133932        }else{
133933          sqlite3DebugPrintf("\n");
133934        }
133935      }
133936    }
133937#endif
133938
133939    /* Swap the roles of aFrom and aTo for the next generation */
133940    pFrom = aTo;
133941    aTo = aFrom;
133942    aFrom = pFrom;
133943    nFrom = nTo;
133944  }
133945
133946  if( nFrom==0 ){
133947    sqlite3ErrorMsg(pParse, "no query solution");
133948    sqlite3DbFree(db, pSpace);
133949    return SQLITE_ERROR;
133950  }
133951
133952  /* Find the lowest cost path.  pFrom will be left pointing to that path */
133953  pFrom = aFrom;
133954  for(ii=1; ii<nFrom; ii++){
133955    if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
133956  }
133957  assert( pWInfo->nLevel==nLoop );
133958  /* Load the lowest cost path into pWInfo */
133959  for(iLoop=0; iLoop<nLoop; iLoop++){
133960    WhereLevel *pLevel = pWInfo->a + iLoop;
133961    pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
133962    pLevel->iFrom = pWLoop->iTab;
133963    pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
133964  }
133965  if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
133966   && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
133967   && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
133968   && nRowEst
133969  ){
133970    Bitmask notUsed;
133971    int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
133972                 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
133973    if( rc==pWInfo->pResultSet->nExpr ){
133974      pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
133975    }
133976  }
133977  if( pWInfo->pOrderBy ){
133978    if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
133979      if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
133980        pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
133981      }
133982    }else{
133983      pWInfo->nOBSat = pFrom->isOrdered;
133984      pWInfo->revMask = pFrom->revLoop;
133985      if( pWInfo->nOBSat<=0 ){
133986        pWInfo->nOBSat = 0;
133987        if( nLoop>0 ){
133988          u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
133989          if( (wsFlags & WHERE_ONEROW)==0
133990           && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
133991          ){
133992            Bitmask m = 0;
133993            int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
133994                      WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
133995            testcase( wsFlags & WHERE_IPK );
133996            testcase( wsFlags & WHERE_COLUMN_IN );
133997            if( rc==pWInfo->pOrderBy->nExpr ){
133998              pWInfo->bOrderedInnerLoop = 1;
133999              pWInfo->revMask = m;
134000            }
134001          }
134002        }
134003      }
134004    }
134005    if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
134006        && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
134007    ){
134008      Bitmask revMask = 0;
134009      int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
134010          pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
134011      );
134012      assert( pWInfo->sorted==0 );
134013      if( nOrder==pWInfo->pOrderBy->nExpr ){
134014        pWInfo->sorted = 1;
134015        pWInfo->revMask = revMask;
134016      }
134017    }
134018  }
134019
134020
134021  pWInfo->nRowOut = pFrom->nRow;
134022
134023  /* Free temporary memory and return success */
134024  sqlite3DbFree(db, pSpace);
134025  return SQLITE_OK;
134026}
134027
134028/*
134029** Most queries use only a single table (they are not joins) and have
134030** simple == constraints against indexed fields.  This routine attempts
134031** to plan those simple cases using much less ceremony than the
134032** general-purpose query planner, and thereby yield faster sqlite3_prepare()
134033** times for the common case.
134034**
134035** Return non-zero on success, if this query can be handled by this
134036** no-frills query planner.  Return zero if this query needs the
134037** general-purpose query planner.
134038*/
134039static int whereShortCut(WhereLoopBuilder *pBuilder){
134040  WhereInfo *pWInfo;
134041  struct SrcList_item *pItem;
134042  WhereClause *pWC;
134043  WhereTerm *pTerm;
134044  WhereLoop *pLoop;
134045  int iCur;
134046  int j;
134047  Table *pTab;
134048  Index *pIdx;
134049
134050  pWInfo = pBuilder->pWInfo;
134051  if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
134052  assert( pWInfo->pTabList->nSrc>=1 );
134053  pItem = pWInfo->pTabList->a;
134054  pTab = pItem->pTab;
134055  if( IsVirtual(pTab) ) return 0;
134056  if( pItem->fg.isIndexedBy ) return 0;
134057  iCur = pItem->iCursor;
134058  pWC = &pWInfo->sWC;
134059  pLoop = pBuilder->pNew;
134060  pLoop->wsFlags = 0;
134061  pLoop->nSkip = 0;
134062  pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
134063  if( pTerm ){
134064    testcase( pTerm->eOperator & WO_IS );
134065    pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
134066    pLoop->aLTerm[0] = pTerm;
134067    pLoop->nLTerm = 1;
134068    pLoop->u.btree.nEq = 1;
134069    /* TUNING: Cost of a rowid lookup is 10 */
134070    pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
134071  }else{
134072    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
134073      int opMask;
134074      assert( pLoop->aLTermSpace==pLoop->aLTerm );
134075      if( !IsUniqueIndex(pIdx)
134076       || pIdx->pPartIdxWhere!=0
134077       || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
134078      ) continue;
134079      opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
134080      for(j=0; j<pIdx->nKeyCol; j++){
134081        pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
134082        if( pTerm==0 ) break;
134083        testcase( pTerm->eOperator & WO_IS );
134084        pLoop->aLTerm[j] = pTerm;
134085      }
134086      if( j!=pIdx->nKeyCol ) continue;
134087      pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
134088      if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
134089        pLoop->wsFlags |= WHERE_IDX_ONLY;
134090      }
134091      pLoop->nLTerm = j;
134092      pLoop->u.btree.nEq = j;
134093      pLoop->u.btree.pIndex = pIdx;
134094      /* TUNING: Cost of a unique index lookup is 15 */
134095      pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
134096      break;
134097    }
134098  }
134099  if( pLoop->wsFlags ){
134100    pLoop->nOut = (LogEst)1;
134101    pWInfo->a[0].pWLoop = pLoop;
134102    pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
134103    pWInfo->a[0].iTabCur = iCur;
134104    pWInfo->nRowOut = 1;
134105    if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
134106    if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
134107      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
134108    }
134109#ifdef SQLITE_DEBUG
134110    pLoop->cId = '0';
134111#endif
134112    return 1;
134113  }
134114  return 0;
134115}
134116
134117/*
134118** Generate the beginning of the loop used for WHERE clause processing.
134119** The return value is a pointer to an opaque structure that contains
134120** information needed to terminate the loop.  Later, the calling routine
134121** should invoke sqlite3WhereEnd() with the return value of this function
134122** in order to complete the WHERE clause processing.
134123**
134124** If an error occurs, this routine returns NULL.
134125**
134126** The basic idea is to do a nested loop, one loop for each table in
134127** the FROM clause of a select.  (INSERT and UPDATE statements are the
134128** same as a SELECT with only a single table in the FROM clause.)  For
134129** example, if the SQL is this:
134130**
134131**       SELECT * FROM t1, t2, t3 WHERE ...;
134132**
134133** Then the code generated is conceptually like the following:
134134**
134135**      foreach row1 in t1 do       \    Code generated
134136**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
134137**          foreach row3 in t3 do   /
134138**            ...
134139**          end                     \    Code generated
134140**        end                        |-- by sqlite3WhereEnd()
134141**      end                         /
134142**
134143** Note that the loops might not be nested in the order in which they
134144** appear in the FROM clause if a different order is better able to make
134145** use of indices.  Note also that when the IN operator appears in
134146** the WHERE clause, it might result in additional nested loops for
134147** scanning through all values on the right-hand side of the IN.
134148**
134149** There are Btree cursors associated with each table.  t1 uses cursor
134150** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
134151** And so forth.  This routine generates code to open those VDBE cursors
134152** and sqlite3WhereEnd() generates the code to close them.
134153**
134154** The code that sqlite3WhereBegin() generates leaves the cursors named
134155** in pTabList pointing at their appropriate entries.  The [...] code
134156** can use OP_Column and OP_Rowid opcodes on these cursors to extract
134157** data from the various tables of the loop.
134158**
134159** If the WHERE clause is empty, the foreach loops must each scan their
134160** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
134161** the tables have indices and there are terms in the WHERE clause that
134162** refer to those indices, a complete table scan can be avoided and the
134163** code will run much faster.  Most of the work of this routine is checking
134164** to see if there are indices that can be used to speed up the loop.
134165**
134166** Terms of the WHERE clause are also used to limit which rows actually
134167** make it to the "..." in the middle of the loop.  After each "foreach",
134168** terms of the WHERE clause that use only terms in that loop and outer
134169** loops are evaluated and if false a jump is made around all subsequent
134170** inner loops (or around the "..." if the test occurs within the inner-
134171** most loop)
134172**
134173** OUTER JOINS
134174**
134175** An outer join of tables t1 and t2 is conceptally coded as follows:
134176**
134177**    foreach row1 in t1 do
134178**      flag = 0
134179**      foreach row2 in t2 do
134180**        start:
134181**          ...
134182**          flag = 1
134183**      end
134184**      if flag==0 then
134185**        move the row2 cursor to a null row
134186**        goto start
134187**      fi
134188**    end
134189**
134190** ORDER BY CLAUSE PROCESSING
134191**
134192** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
134193** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
134194** if there is one.  If there is no ORDER BY clause or if this routine
134195** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
134196**
134197** The iIdxCur parameter is the cursor number of an index.  If
134198** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
134199** to use for OR clause processing.  The WHERE clause should use this
134200** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
134201** the first cursor in an array of cursors for all indices.  iIdxCur should
134202** be used to compute the appropriate cursor depending on which index is
134203** used.
134204*/
134205SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
134206  Parse *pParse,          /* The parser context */
134207  SrcList *pTabList,      /* FROM clause: A list of all tables to be scanned */
134208  Expr *pWhere,           /* The WHERE clause */
134209  ExprList *pOrderBy,     /* An ORDER BY (or GROUP BY) clause, or NULL */
134210  ExprList *pResultSet,   /* Query result set.  Req'd for DISTINCT */
134211  u16 wctrlFlags,         /* The WHERE_* flags defined in sqliteInt.h */
134212  int iAuxArg             /* If WHERE_OR_SUBCLAUSE is set, index cursor number
134213                          ** If WHERE_USE_LIMIT, then the limit amount */
134214){
134215  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
134216  int nTabList;              /* Number of elements in pTabList */
134217  WhereInfo *pWInfo;         /* Will become the return value of this function */
134218  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
134219  Bitmask notReady;          /* Cursors that are not yet positioned */
134220  WhereLoopBuilder sWLB;     /* The WhereLoop builder */
134221  WhereMaskSet *pMaskSet;    /* The expression mask set */
134222  WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
134223  WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
134224  int ii;                    /* Loop counter */
134225  sqlite3 *db;               /* Database connection */
134226  int rc;                    /* Return code */
134227  u8 bFordelete = 0;         /* OPFLAG_FORDELETE or zero, as appropriate */
134228
134229  assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
134230        (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
134231     && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
134232  ));
134233
134234  /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
134235  assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
134236            || (wctrlFlags & WHERE_USE_LIMIT)==0 );
134237
134238  /* Variable initialization */
134239  db = pParse->db;
134240  memset(&sWLB, 0, sizeof(sWLB));
134241
134242  /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
134243  testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
134244  if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
134245  sWLB.pOrderBy = pOrderBy;
134246
134247  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
134248  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
134249  if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
134250    wctrlFlags &= ~WHERE_WANT_DISTINCT;
134251  }
134252
134253  /* The number of tables in the FROM clause is limited by the number of
134254  ** bits in a Bitmask
134255  */
134256  testcase( pTabList->nSrc==BMS );
134257  if( pTabList->nSrc>BMS ){
134258    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
134259    return 0;
134260  }
134261
134262  /* This function normally generates a nested loop for all tables in
134263  ** pTabList.  But if the WHERE_OR_SUBCLAUSE flag is set, then we should
134264  ** only generate code for the first table in pTabList and assume that
134265  ** any cursors associated with subsequent tables are uninitialized.
134266  */
134267  nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
134268
134269  /* Allocate and initialize the WhereInfo structure that will become the
134270  ** return value. A single allocation is used to store the WhereInfo
134271  ** struct, the contents of WhereInfo.a[], the WhereClause structure
134272  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
134273  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
134274  ** some architectures. Hence the ROUND8() below.
134275  */
134276  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
134277  pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
134278  if( db->mallocFailed ){
134279    sqlite3DbFree(db, pWInfo);
134280    pWInfo = 0;
134281    goto whereBeginError;
134282  }
134283  pWInfo->pParse = pParse;
134284  pWInfo->pTabList = pTabList;
134285  pWInfo->pOrderBy = pOrderBy;
134286  pWInfo->pResultSet = pResultSet;
134287  pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
134288  pWInfo->nLevel = nTabList;
134289  pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
134290  pWInfo->wctrlFlags = wctrlFlags;
134291  pWInfo->iLimit = iAuxArg;
134292  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
134293  memset(&pWInfo->nOBSat, 0,
134294         offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
134295  memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
134296  assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */
134297  pMaskSet = &pWInfo->sMaskSet;
134298  sWLB.pWInfo = pWInfo;
134299  sWLB.pWC = &pWInfo->sWC;
134300  sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
134301  assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
134302  whereLoopInit(sWLB.pNew);
134303#ifdef SQLITE_DEBUG
134304  sWLB.pNew->cId = '*';
134305#endif
134306
134307  /* Split the WHERE clause into separate subexpressions where each
134308  ** subexpression is separated by an AND operator.
134309  */
134310  initMaskSet(pMaskSet);
134311  sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
134312  sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
134313
134314  /* Special case: a WHERE clause that is constant.  Evaluate the
134315  ** expression and either jump over all of the code or fall thru.
134316  */
134317  for(ii=0; ii<sWLB.pWC->nTerm; ii++){
134318    if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
134319      sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
134320                         SQLITE_JUMPIFNULL);
134321      sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
134322    }
134323  }
134324
134325  /* Special case: No FROM clause
134326  */
134327  if( nTabList==0 ){
134328    if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
134329    if( wctrlFlags & WHERE_WANT_DISTINCT ){
134330      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
134331    }
134332  }
134333
134334  /* Assign a bit from the bitmask to every term in the FROM clause.
134335  **
134336  ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
134337  **
134338  ** The rule of the previous sentence ensures thta if X is the bitmask for
134339  ** a table T, then X-1 is the bitmask for all other tables to the left of T.
134340  ** Knowing the bitmask for all tables to the left of a left join is
134341  ** important.  Ticket #3015.
134342  **
134343  ** Note that bitmasks are created for all pTabList->nSrc tables in
134344  ** pTabList, not just the first nTabList tables.  nTabList is normally
134345  ** equal to pTabList->nSrc but might be shortened to 1 if the
134346  ** WHERE_OR_SUBCLAUSE flag is set.
134347  */
134348  for(ii=0; ii<pTabList->nSrc; ii++){
134349    createMask(pMaskSet, pTabList->a[ii].iCursor);
134350    sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
134351  }
134352#ifdef SQLITE_DEBUG
134353  for(ii=0; ii<pTabList->nSrc; ii++){
134354    Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
134355    assert( m==MASKBIT(ii) );
134356  }
134357#endif
134358
134359  /* Analyze all of the subexpressions. */
134360  sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
134361  if( db->mallocFailed ) goto whereBeginError;
134362
134363  if( wctrlFlags & WHERE_WANT_DISTINCT ){
134364    if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
134365      /* The DISTINCT marking is pointless.  Ignore it. */
134366      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
134367    }else if( pOrderBy==0 ){
134368      /* Try to ORDER BY the result set to make distinct processing easier */
134369      pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
134370      pWInfo->pOrderBy = pResultSet;
134371    }
134372  }
134373
134374  /* Construct the WhereLoop objects */
134375#if defined(WHERETRACE_ENABLED)
134376  if( sqlite3WhereTrace & 0xffff ){
134377    sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
134378    if( wctrlFlags & WHERE_USE_LIMIT ){
134379      sqlite3DebugPrintf(", limit: %d", iAuxArg);
134380    }
134381    sqlite3DebugPrintf(")\n");
134382  }
134383  if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
134384    sqlite3WhereClausePrint(sWLB.pWC);
134385  }
134386#endif
134387
134388  if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
134389    rc = whereLoopAddAll(&sWLB);
134390    if( rc ) goto whereBeginError;
134391
134392#ifdef WHERETRACE_ENABLED
134393    if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
134394      WhereLoop *p;
134395      int i;
134396      static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
134397                                             "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
134398      for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
134399        p->cId = zLabel[i%sizeof(zLabel)];
134400        whereLoopPrint(p, sWLB.pWC);
134401      }
134402    }
134403#endif
134404
134405    wherePathSolver(pWInfo, 0);
134406    if( db->mallocFailed ) goto whereBeginError;
134407    if( pWInfo->pOrderBy ){
134408       wherePathSolver(pWInfo, pWInfo->nRowOut+1);
134409       if( db->mallocFailed ) goto whereBeginError;
134410    }
134411  }
134412  if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
134413     pWInfo->revMask = ALLBITS;
134414  }
134415  if( pParse->nErr || NEVER(db->mallocFailed) ){
134416    goto whereBeginError;
134417  }
134418#ifdef WHERETRACE_ENABLED
134419  if( sqlite3WhereTrace ){
134420    sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
134421    if( pWInfo->nOBSat>0 ){
134422      sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
134423    }
134424    switch( pWInfo->eDistinct ){
134425      case WHERE_DISTINCT_UNIQUE: {
134426        sqlite3DebugPrintf("  DISTINCT=unique");
134427        break;
134428      }
134429      case WHERE_DISTINCT_ORDERED: {
134430        sqlite3DebugPrintf("  DISTINCT=ordered");
134431        break;
134432      }
134433      case WHERE_DISTINCT_UNORDERED: {
134434        sqlite3DebugPrintf("  DISTINCT=unordered");
134435        break;
134436      }
134437    }
134438    sqlite3DebugPrintf("\n");
134439    for(ii=0; ii<pWInfo->nLevel; ii++){
134440      whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
134441    }
134442  }
134443#endif
134444  /* Attempt to omit tables from the join that do not effect the result */
134445  if( pWInfo->nLevel>=2
134446   && pResultSet!=0
134447   && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
134448  ){
134449    Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
134450    if( sWLB.pOrderBy ){
134451      tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
134452    }
134453    while( pWInfo->nLevel>=2 ){
134454      WhereTerm *pTerm, *pEnd;
134455      pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
134456      if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
134457      if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
134458       && (pLoop->wsFlags & WHERE_ONEROW)==0
134459      ){
134460        break;
134461      }
134462      if( (tabUsed & pLoop->maskSelf)!=0 ) break;
134463      pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
134464      for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
134465        if( (pTerm->prereqAll & pLoop->maskSelf)!=0
134466         && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
134467        ){
134468          break;
134469        }
134470      }
134471      if( pTerm<pEnd ) break;
134472      WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
134473      pWInfo->nLevel--;
134474      nTabList--;
134475    }
134476  }
134477  WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
134478  pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
134479
134480  /* If the caller is an UPDATE or DELETE statement that is requesting
134481  ** to use a one-pass algorithm, determine if this is appropriate.
134482  */
134483  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
134484  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
134485    int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
134486    int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
134487    if( bOnerow
134488     || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0
134489           && 0==(wsFlags & WHERE_VIRTUALTABLE))
134490    ){
134491      pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
134492      if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
134493        if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
134494          bFordelete = OPFLAG_FORDELETE;
134495        }
134496        pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
134497      }
134498    }
134499  }
134500
134501  /* Open all tables in the pTabList and any indices selected for
134502  ** searching those tables.
134503  */
134504  for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
134505    Table *pTab;     /* Table to open */
134506    int iDb;         /* Index of database containing table/index */
134507    struct SrcList_item *pTabItem;
134508
134509    pTabItem = &pTabList->a[pLevel->iFrom];
134510    pTab = pTabItem->pTab;
134511    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
134512    pLoop = pLevel->pWLoop;
134513    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
134514      /* Do nothing */
134515    }else
134516#ifndef SQLITE_OMIT_VIRTUALTABLE
134517    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
134518      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
134519      int iCur = pTabItem->iCursor;
134520      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
134521    }else if( IsVirtual(pTab) ){
134522      /* noop */
134523    }else
134524#endif
134525    if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
134526         && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
134527      int op = OP_OpenRead;
134528      if( pWInfo->eOnePass!=ONEPASS_OFF ){
134529        op = OP_OpenWrite;
134530        pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
134531      };
134532      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
134533      assert( pTabItem->iCursor==pLevel->iTabCur );
134534      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
134535      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
134536      if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
134537        Bitmask b = pTabItem->colUsed;
134538        int n = 0;
134539        for(; b; b=b>>1, n++){}
134540        sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
134541        assert( n<=pTab->nCol );
134542      }
134543#ifdef SQLITE_ENABLE_CURSOR_HINTS
134544      if( pLoop->u.btree.pIndex!=0 ){
134545        sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
134546      }else
134547#endif
134548      {
134549        sqlite3VdbeChangeP5(v, bFordelete);
134550      }
134551#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
134552      sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
134553                            (const u8*)&pTabItem->colUsed, P4_INT64);
134554#endif
134555    }else{
134556      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
134557    }
134558    if( pLoop->wsFlags & WHERE_INDEXED ){
134559      Index *pIx = pLoop->u.btree.pIndex;
134560      int iIndexCur;
134561      int op = OP_OpenRead;
134562      /* iAuxArg is always set if to a positive value if ONEPASS is possible */
134563      assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
134564      if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
134565       && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
134566      ){
134567        /* This is one term of an OR-optimization using the PRIMARY KEY of a
134568        ** WITHOUT ROWID table.  No need for a separate index */
134569        iIndexCur = pLevel->iTabCur;
134570        op = 0;
134571      }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
134572        Index *pJ = pTabItem->pTab->pIndex;
134573        iIndexCur = iAuxArg;
134574        assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
134575        while( ALWAYS(pJ) && pJ!=pIx ){
134576          iIndexCur++;
134577          pJ = pJ->pNext;
134578        }
134579        op = OP_OpenWrite;
134580        pWInfo->aiCurOnePass[1] = iIndexCur;
134581      }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
134582        iIndexCur = iAuxArg;
134583        op = OP_ReopenIdx;
134584      }else{
134585        iIndexCur = pParse->nTab++;
134586      }
134587      pLevel->iIdxCur = iIndexCur;
134588      assert( pIx->pSchema==pTab->pSchema );
134589      assert( iIndexCur>=0 );
134590      if( op ){
134591        sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
134592        sqlite3VdbeSetP4KeyInfo(pParse, pIx);
134593        if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
134594         && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
134595         && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
134596        ){
134597          sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
134598        }
134599        VdbeComment((v, "%s", pIx->zName));
134600#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
134601        {
134602          u64 colUsed = 0;
134603          int ii, jj;
134604          for(ii=0; ii<pIx->nColumn; ii++){
134605            jj = pIx->aiColumn[ii];
134606            if( jj<0 ) continue;
134607            if( jj>63 ) jj = 63;
134608            if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
134609            colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
134610          }
134611          sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
134612                                (u8*)&colUsed, P4_INT64);
134613        }
134614#endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
134615      }
134616    }
134617    if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
134618  }
134619  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
134620  if( db->mallocFailed ) goto whereBeginError;
134621
134622  /* Generate the code to do the search.  Each iteration of the for
134623  ** loop below generates code for a single nested loop of the VM
134624  ** program.
134625  */
134626  notReady = ~(Bitmask)0;
134627  for(ii=0; ii<nTabList; ii++){
134628    int addrExplain;
134629    int wsFlags;
134630    pLevel = &pWInfo->a[ii];
134631    wsFlags = pLevel->pWLoop->wsFlags;
134632#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
134633    if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
134634      constructAutomaticIndex(pParse, &pWInfo->sWC,
134635                &pTabList->a[pLevel->iFrom], notReady, pLevel);
134636      if( db->mallocFailed ) goto whereBeginError;
134637    }
134638#endif
134639    addrExplain = sqlite3WhereExplainOneScan(
134640        pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
134641    );
134642    pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
134643    notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
134644    pWInfo->iContinue = pLevel->addrCont;
134645    if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
134646      sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
134647    }
134648  }
134649
134650  /* Done. */
134651  VdbeModuleComment((v, "Begin WHERE-core"));
134652  return pWInfo;
134653
134654  /* Jump here if malloc fails */
134655whereBeginError:
134656  if( pWInfo ){
134657    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
134658    whereInfoFree(db, pWInfo);
134659  }
134660  return 0;
134661}
134662
134663/*
134664** Generate the end of the WHERE loop.  See comments on
134665** sqlite3WhereBegin() for additional information.
134666*/
134667SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
134668  Parse *pParse = pWInfo->pParse;
134669  Vdbe *v = pParse->pVdbe;
134670  int i;
134671  WhereLevel *pLevel;
134672  WhereLoop *pLoop;
134673  SrcList *pTabList = pWInfo->pTabList;
134674  sqlite3 *db = pParse->db;
134675
134676  /* Generate loop termination code.
134677  */
134678  VdbeModuleComment((v, "End WHERE-core"));
134679  sqlite3ExprCacheClear(pParse);
134680  for(i=pWInfo->nLevel-1; i>=0; i--){
134681    int addr;
134682    pLevel = &pWInfo->a[i];
134683    pLoop = pLevel->pWLoop;
134684    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
134685    if( pLevel->op!=OP_Noop ){
134686      sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
134687      sqlite3VdbeChangeP5(v, pLevel->p5);
134688      VdbeCoverage(v);
134689      VdbeCoverageIf(v, pLevel->op==OP_Next);
134690      VdbeCoverageIf(v, pLevel->op==OP_Prev);
134691      VdbeCoverageIf(v, pLevel->op==OP_VNext);
134692    }
134693    if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
134694      struct InLoop *pIn;
134695      int j;
134696      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
134697      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
134698        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
134699        if( pIn->eEndLoopOp!=OP_Noop ){
134700          sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
134701          VdbeCoverage(v);
134702          VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
134703          VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
134704        }
134705        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
134706      }
134707    }
134708    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
134709    if( pLevel->addrSkip ){
134710      sqlite3VdbeGoto(v, pLevel->addrSkip);
134711      VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
134712      sqlite3VdbeJumpHere(v, pLevel->addrSkip);
134713      sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
134714    }
134715#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
134716    if( pLevel->addrLikeRep ){
134717      sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
134718                        pLevel->addrLikeRep);
134719      VdbeCoverage(v);
134720    }
134721#endif
134722    if( pLevel->iLeftJoin ){
134723      int ws = pLoop->wsFlags;
134724      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
134725      assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
134726      if( (ws & WHERE_IDX_ONLY)==0 ){
134727        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
134728      }
134729      if( (ws & WHERE_INDEXED)
134730       || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
134731      ){
134732        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
134733      }
134734      if( pLevel->op==OP_Return ){
134735        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
134736      }else{
134737        sqlite3VdbeGoto(v, pLevel->addrFirst);
134738      }
134739      sqlite3VdbeJumpHere(v, addr);
134740    }
134741    VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
134742                     pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
134743  }
134744
134745  /* The "break" point is here, just past the end of the outer loop.
134746  ** Set it.
134747  */
134748  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
134749
134750  assert( pWInfo->nLevel<=pTabList->nSrc );
134751  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
134752    int k, last;
134753    VdbeOp *pOp;
134754    Index *pIdx = 0;
134755    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
134756    Table *pTab = pTabItem->pTab;
134757    assert( pTab!=0 );
134758    pLoop = pLevel->pWLoop;
134759
134760    /* For a co-routine, change all OP_Column references to the table of
134761    ** the co-routine into OP_Copy of result contained in a register.
134762    ** OP_Rowid becomes OP_Null.
134763    */
134764    if( pTabItem->fg.viaCoroutine ){
134765      testcase( pParse->db->mallocFailed );
134766      translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
134767                            pTabItem->regResult, 0);
134768      continue;
134769    }
134770
134771    /* If this scan uses an index, make VDBE code substitutions to read data
134772    ** from the index instead of from the table where possible.  In some cases
134773    ** this optimization prevents the table from ever being read, which can
134774    ** yield a significant performance boost.
134775    **
134776    ** Calls to the code generator in between sqlite3WhereBegin and
134777    ** sqlite3WhereEnd will have created code that references the table
134778    ** directly.  This loop scans all that code looking for opcodes
134779    ** that reference the table and converts them into opcodes that
134780    ** reference the index.
134781    */
134782    if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
134783      pIdx = pLoop->u.btree.pIndex;
134784    }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
134785      pIdx = pLevel->u.pCovidx;
134786    }
134787    if( pIdx
134788     && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
134789     && !db->mallocFailed
134790    ){
134791      last = sqlite3VdbeCurrentAddr(v);
134792      k = pLevel->addrBody;
134793      pOp = sqlite3VdbeGetOp(v, k);
134794      for(; k<last; k++, pOp++){
134795        if( pOp->p1!=pLevel->iTabCur ) continue;
134796        if( pOp->opcode==OP_Column ){
134797          int x = pOp->p2;
134798          assert( pIdx->pTable==pTab );
134799          if( !HasRowid(pTab) ){
134800            Index *pPk = sqlite3PrimaryKeyIndex(pTab);
134801            x = pPk->aiColumn[x];
134802            assert( x>=0 );
134803          }
134804          x = sqlite3ColumnOfIndex(pIdx, x);
134805          if( x>=0 ){
134806            pOp->p2 = x;
134807            pOp->p1 = pLevel->iIdxCur;
134808          }
134809          assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
134810              || pWInfo->eOnePass );
134811        }else if( pOp->opcode==OP_Rowid ){
134812          pOp->p1 = pLevel->iIdxCur;
134813          pOp->opcode = OP_IdxRowid;
134814        }
134815      }
134816    }
134817  }
134818
134819  /* Final cleanup
134820  */
134821  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
134822  whereInfoFree(db, pWInfo);
134823  return;
134824}
134825
134826/************** End of where.c ***********************************************/
134827/************** Begin file parse.c *******************************************/
134828/*
134829** 2000-05-29
134830**
134831** The author disclaims copyright to this source code.  In place of
134832** a legal notice, here is a blessing:
134833**
134834**    May you do good and not evil.
134835**    May you find forgiveness for yourself and forgive others.
134836**    May you share freely, never taking more than you give.
134837**
134838*************************************************************************
134839** Driver template for the LEMON parser generator.
134840**
134841** The "lemon" program processes an LALR(1) input grammar file, then uses
134842** this template to construct a parser.  The "lemon" program inserts text
134843** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
134844** interstitial "-" characters) contained in this template is changed into
134845** the value of the %name directive from the grammar.  Otherwise, the content
134846** of this template is copied straight through into the generate parser
134847** source file.
134848**
134849** The following is the concatenation of all %include directives from the
134850** input grammar file:
134851*/
134852/* #include <stdio.h> */
134853/************ Begin %include sections from the grammar ************************/
134854
134855/* #include "sqliteInt.h" */
134856
134857/*
134858** Disable all error recovery processing in the parser push-down
134859** automaton.
134860*/
134861#define YYNOERRORRECOVERY 1
134862
134863/*
134864** Make yytestcase() the same as testcase()
134865*/
134866#define yytestcase(X) testcase(X)
134867
134868/*
134869** Indicate that sqlite3ParserFree() will never be called with a null
134870** pointer.
134871*/
134872#define YYPARSEFREENEVERNULL 1
134873
134874/*
134875** In the amalgamation, the parse.c file generated by lemon and the
134876** tokenize.c file are concatenated.  In that case, sqlite3RunParser()
134877** has access to the the size of the yyParser object and so the parser
134878** engine can be allocated from stack.  In that case, only the
134879** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
134880** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
134881** omitted.
134882*/
134883#ifdef SQLITE_AMALGAMATION
134884# define sqlite3Parser_ENGINEALWAYSONSTACK 1
134885#endif
134886
134887/*
134888** Alternative datatype for the argument to the malloc() routine passed
134889** into sqlite3ParserAlloc().  The default is size_t.
134890*/
134891#define YYMALLOCARGTYPE  u64
134892
134893/*
134894** An instance of this structure holds information about the
134895** LIMIT clause of a SELECT statement.
134896*/
134897struct LimitVal {
134898  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
134899  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
134900};
134901
134902/*
134903** An instance of the following structure describes the event of a
134904** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
134905** TK_DELETE, or TK_INSTEAD.  If the event is of the form
134906**
134907**      UPDATE ON (a,b,c)
134908**
134909** Then the "b" IdList records the list "a,b,c".
134910*/
134911struct TrigEvent { int a; IdList * b; };
134912
134913/*
134914** Disable lookaside memory allocation for objects that might be
134915** shared across database connections.
134916*/
134917static void disableLookaside(Parse *pParse){
134918  pParse->disableLookaside++;
134919  pParse->db->lookaside.bDisable++;
134920}
134921
134922
134923  /*
134924  ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
134925  ** all elements in the list.  And make sure list length does not exceed
134926  ** SQLITE_LIMIT_COMPOUND_SELECT.
134927  */
134928  static void parserDoubleLinkSelect(Parse *pParse, Select *p){
134929    if( p->pPrior ){
134930      Select *pNext = 0, *pLoop;
134931      int mxSelect, cnt = 0;
134932      for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
134933        pLoop->pNext = pNext;
134934        pLoop->selFlags |= SF_Compound;
134935      }
134936      if( (p->selFlags & SF_MultiValue)==0 &&
134937        (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
134938        cnt>mxSelect
134939      ){
134940        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
134941      }
134942    }
134943  }
134944
134945  /* This is a utility routine used to set the ExprSpan.zStart and
134946  ** ExprSpan.zEnd values of pOut so that the span covers the complete
134947  ** range of text beginning with pStart and going to the end of pEnd.
134948  */
134949  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
134950    pOut->zStart = pStart->z;
134951    pOut->zEnd = &pEnd->z[pEnd->n];
134952  }
134953
134954  /* Construct a new Expr object from a single identifier.  Use the
134955  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
134956  ** that created the expression.
134957  */
134958  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){
134959    Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
134960    if( p ){
134961      memset(p, 0, sizeof(Expr));
134962      p->op = (u8)op;
134963      p->flags = EP_Leaf;
134964      p->iAgg = -1;
134965      p->u.zToken = (char*)&p[1];
134966      memcpy(p->u.zToken, t.z, t.n);
134967      p->u.zToken[t.n] = 0;
134968      if( sqlite3Isquote(p->u.zToken[0]) ){
134969        if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
134970        sqlite3Dequote(p->u.zToken);
134971      }
134972#if SQLITE_MAX_EXPR_DEPTH>0
134973      p->nHeight = 1;
134974#endif
134975    }
134976    pOut->pExpr = p;
134977    pOut->zStart = t.z;
134978    pOut->zEnd = &t.z[t.n];
134979  }
134980
134981  /* This routine constructs a binary expression node out of two ExprSpan
134982  ** objects and uses the result to populate a new ExprSpan object.
134983  */
134984  static void spanBinaryExpr(
134985    Parse *pParse,      /* The parsing context.  Errors accumulate here */
134986    int op,             /* The binary operation */
134987    ExprSpan *pLeft,    /* The left operand, and output */
134988    ExprSpan *pRight    /* The right operand */
134989  ){
134990    pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr);
134991    pLeft->zEnd = pRight->zEnd;
134992  }
134993
134994  /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
134995  ** outside of *ppExpr.
134996  */
134997  static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){
134998    if( doNot ){
134999      pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0);
135000    }
135001  }
135002
135003  /* Construct an expression node for a unary postfix operator
135004  */
135005  static void spanUnaryPostfix(
135006    Parse *pParse,         /* Parsing context to record errors */
135007    int op,                /* The operator */
135008    ExprSpan *pOperand,    /* The operand, and output */
135009    Token *pPostOp         /* The operand token for setting the span */
135010  ){
135011    pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0);
135012    pOperand->zEnd = &pPostOp->z[pPostOp->n];
135013  }
135014
135015  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
135016  ** unary TK_ISNULL or TK_NOTNULL expression. */
135017  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
135018    sqlite3 *db = pParse->db;
135019    if( pA && pY && pY->op==TK_NULL ){
135020      pA->op = (u8)op;
135021      sqlite3ExprDelete(db, pA->pRight);
135022      pA->pRight = 0;
135023    }
135024  }
135025
135026  /* Construct an expression node for a unary prefix operator
135027  */
135028  static void spanUnaryPrefix(
135029    ExprSpan *pOut,        /* Write the new expression node here */
135030    Parse *pParse,         /* Parsing context to record errors */
135031    int op,                /* The operator */
135032    ExprSpan *pOperand,    /* The operand */
135033    Token *pPreOp         /* The operand token for setting the span */
135034  ){
135035    pOut->zStart = pPreOp->z;
135036    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0);
135037    pOut->zEnd = pOperand->zEnd;
135038  }
135039
135040  /* Add a single new term to an ExprList that is used to store a
135041  ** list of identifiers.  Report an error if the ID list contains
135042  ** a COLLATE clause or an ASC or DESC keyword, except ignore the
135043  ** error while parsing a legacy schema.
135044  */
135045  static ExprList *parserAddExprIdListTerm(
135046    Parse *pParse,
135047    ExprList *pPrior,
135048    Token *pIdToken,
135049    int hasCollate,
135050    int sortOrder
135051  ){
135052    ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
135053    if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
135054        && pParse->db->init.busy==0
135055    ){
135056      sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
135057                         pIdToken->n, pIdToken->z);
135058    }
135059    sqlite3ExprListSetName(pParse, p, pIdToken, 1);
135060    return p;
135061  }
135062/**************** End of %include directives **********************************/
135063/* These constants specify the various numeric values for terminal symbols
135064** in a format understandable to "makeheaders".  This section is blank unless
135065** "lemon" is run with the "-m" command-line option.
135066***************** Begin makeheaders token definitions *************************/
135067/**************** End makeheaders token definitions ***************************/
135068
135069/* The next sections is a series of control #defines.
135070** various aspects of the generated parser.
135071**    YYCODETYPE         is the data type used to store the integer codes
135072**                       that represent terminal and non-terminal symbols.
135073**                       "unsigned char" is used if there are fewer than
135074**                       256 symbols.  Larger types otherwise.
135075**    YYNOCODE           is a number of type YYCODETYPE that is not used for
135076**                       any terminal or nonterminal symbol.
135077**    YYFALLBACK         If defined, this indicates that one or more tokens
135078**                       (also known as: "terminal symbols") have fall-back
135079**                       values which should be used if the original symbol
135080**                       would not parse.  This permits keywords to sometimes
135081**                       be used as identifiers, for example.
135082**    YYACTIONTYPE       is the data type used for "action codes" - numbers
135083**                       that indicate what to do in response to the next
135084**                       token.
135085**    sqlite3ParserTOKENTYPE     is the data type used for minor type for terminal
135086**                       symbols.  Background: A "minor type" is a semantic
135087**                       value associated with a terminal or non-terminal
135088**                       symbols.  For example, for an "ID" terminal symbol,
135089**                       the minor type might be the name of the identifier.
135090**                       Each non-terminal can have a different minor type.
135091**                       Terminal symbols all have the same minor type, though.
135092**                       This macros defines the minor type for terminal
135093**                       symbols.
135094**    YYMINORTYPE        is the data type used for all minor types.
135095**                       This is typically a union of many types, one of
135096**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
135097**                       for terminal symbols is called "yy0".
135098**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
135099**                       zero the stack is dynamically sized using realloc()
135100**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
135101**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
135102**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
135103**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
135104**    YYERRORSYMBOL      is the code number of the error symbol.  If not
135105**                       defined, then do no error processing.
135106**    YYNSTATE           the combined number of states.
135107**    YYNRULE            the number of rules in the grammar
135108**    YY_MAX_SHIFT       Maximum value for shift actions
135109**    YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
135110**    YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
135111**    YY_MIN_REDUCE      Maximum value for reduce actions
135112**    YY_ERROR_ACTION    The yy_action[] code for syntax error
135113**    YY_ACCEPT_ACTION   The yy_action[] code for accept
135114**    YY_NO_ACTION       The yy_action[] code for no-op
135115*/
135116#ifndef INTERFACE
135117# define INTERFACE 1
135118#endif
135119/************* Begin control #defines *****************************************/
135120#define YYCODETYPE unsigned char
135121#define YYNOCODE 252
135122#define YYACTIONTYPE unsigned short int
135123#define YYWILDCARD 96
135124#define sqlite3ParserTOKENTYPE Token
135125typedef union {
135126  int yyinit;
135127  sqlite3ParserTOKENTYPE yy0;
135128  Expr* yy72;
135129  TriggerStep* yy145;
135130  ExprList* yy148;
135131  SrcList* yy185;
135132  ExprSpan yy190;
135133  int yy194;
135134  Select* yy243;
135135  IdList* yy254;
135136  With* yy285;
135137  struct TrigEvent yy332;
135138  struct LimitVal yy354;
135139  struct {int value; int mask;} yy497;
135140} YYMINORTYPE;
135141#ifndef YYSTACKDEPTH
135142#define YYSTACKDEPTH 100
135143#endif
135144#define sqlite3ParserARG_SDECL Parse *pParse;
135145#define sqlite3ParserARG_PDECL ,Parse *pParse
135146#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
135147#define sqlite3ParserARG_STORE yypParser->pParse = pParse
135148#define YYFALLBACK 1
135149#define YYNSTATE             456
135150#define YYNRULE              332
135151#define YY_MAX_SHIFT         455
135152#define YY_MIN_SHIFTREDUCE   668
135153#define YY_MAX_SHIFTREDUCE   999
135154#define YY_MIN_REDUCE        1000
135155#define YY_MAX_REDUCE        1331
135156#define YY_ERROR_ACTION      1332
135157#define YY_ACCEPT_ACTION     1333
135158#define YY_NO_ACTION         1334
135159/************* End control #defines *******************************************/
135160
135161/* Define the yytestcase() macro to be a no-op if is not already defined
135162** otherwise.
135163**
135164** Applications can choose to define yytestcase() in the %include section
135165** to a macro that can assist in verifying code coverage.  For production
135166** code the yytestcase() macro should be turned off.  But it is useful
135167** for testing.
135168*/
135169#ifndef yytestcase
135170# define yytestcase(X)
135171#endif
135172
135173
135174/* Next are the tables used to determine what action to take based on the
135175** current state and lookahead token.  These tables are used to implement
135176** functions that take a state number and lookahead value and return an
135177** action integer.
135178**
135179** Suppose the action integer is N.  Then the action is determined as
135180** follows
135181**
135182**   0 <= N <= YY_MAX_SHIFT             Shift N.  That is, push the lookahead
135183**                                      token onto the stack and goto state N.
135184**
135185**   N between YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
135186**     and YY_MAX_SHIFTREDUCE           reduce by rule N-YY_MIN_SHIFTREDUCE.
135187**
135188**   N between YY_MIN_REDUCE            Reduce by rule N-YY_MIN_REDUCE
135189**     and YY_MAX_REDUCE
135190**
135191**   N == YY_ERROR_ACTION               A syntax error has occurred.
135192**
135193**   N == YY_ACCEPT_ACTION              The parser accepts its input.
135194**
135195**   N == YY_NO_ACTION                  No such action.  Denotes unused
135196**                                      slots in the yy_action[] table.
135197**
135198** The action table is constructed as a single large table named yy_action[].
135199** Given state S and lookahead X, the action is computed as either:
135200**
135201**    (A)   N = yy_action[ yy_shift_ofst[S] + X ]
135202**    (B)   N = yy_default[S]
135203**
135204** The (A) formula is preferred.  The B formula is used instead if:
135205**    (1)  The yy_shift_ofst[S]+X value is out of range, or
135206**    (2)  yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or
135207**    (3)  yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT.
135208** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that
135209** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
135210** Hence only tests (1) and (2) need to be evaluated.)
135211**
135212** The formulas above are for computing the action when the lookahead is
135213** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
135214** a reduce action) then the yy_reduce_ofst[] array is used in place of
135215** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
135216** YY_SHIFT_USE_DFLT.
135217**
135218** The following are the tables generated in this section:
135219**
135220**  yy_action[]        A single table containing all actions.
135221**  yy_lookahead[]     A table containing the lookahead for each entry in
135222**                     yy_action.  Used to detect hash collisions.
135223**  yy_shift_ofst[]    For each state, the offset into yy_action for
135224**                     shifting terminals.
135225**  yy_reduce_ofst[]   For each state, the offset into yy_action for
135226**                     shifting non-terminals after a reduce.
135227**  yy_default[]       Default action for each state.
135228**
135229*********** Begin parsing tables **********************************************/
135230#define YY_ACTTAB_COUNT (1567)
135231static const YYACTIONTYPE yy_action[] = {
135232 /*     0 */   325,  832,  351,  825,    5,  203,  203,  819,   99,  100,
135233 /*    10 */    90,  978,  978,  853,  856,  845,  845,   97,   97,   98,
135234 /*    20 */    98,   98,   98,  301,   96,   96,   96,   96,   95,   95,
135235 /*    30 */    94,   94,   94,   93,  351,  325,  976,  976,  824,  824,
135236 /*    40 */   826,  946,  354,   99,  100,   90,  978,  978,  853,  856,
135237 /*    50 */   845,  845,   97,   97,   98,   98,   98,   98,  338,   96,
135238 /*    60 */    96,   96,   96,   95,   95,   94,   94,   94,   93,  351,
135239 /*    70 */    95,   95,   94,   94,   94,   93,  351,  791,  976,  976,
135240 /*    80 */   325,   94,   94,   94,   93,  351,  792,   75,   99,  100,
135241 /*    90 */    90,  978,  978,  853,  856,  845,  845,   97,   97,   98,
135242 /*   100 */    98,   98,   98,  450,   96,   96,   96,   96,   95,   95,
135243 /*   110 */    94,   94,   94,   93,  351, 1333,  155,  155,    2,  325,
135244 /*   120 */   275,  146,  132,   52,   52,   93,  351,   99,  100,   90,
135245 /*   130 */   978,  978,  853,  856,  845,  845,   97,   97,   98,   98,
135246 /*   140 */    98,   98,  101,   96,   96,   96,   96,   95,   95,   94,
135247 /*   150 */    94,   94,   93,  351,  957,  957,  325,  268,  428,  413,
135248 /*   160 */   411,   61,  752,  752,   99,  100,   90,  978,  978,  853,
135249 /*   170 */   856,  845,  845,   97,   97,   98,   98,   98,   98,   60,
135250 /*   180 */    96,   96,   96,   96,   95,   95,   94,   94,   94,   93,
135251 /*   190 */   351,  325,  270,  329,  273,  277,  958,  959,  250,   99,
135252 /*   200 */   100,   90,  978,  978,  853,  856,  845,  845,   97,   97,
135253 /*   210 */    98,   98,   98,   98,  301,   96,   96,   96,   96,   95,
135254 /*   220 */    95,   94,   94,   94,   93,  351,  325,  937, 1326,  698,
135255 /*   230 */   706, 1326,  242,  412,   99,  100,   90,  978,  978,  853,
135256 /*   240 */   856,  845,  845,   97,   97,   98,   98,   98,   98,  347,
135257 /*   250 */    96,   96,   96,   96,   95,   95,   94,   94,   94,   93,
135258 /*   260 */   351,  325,  937, 1327,  384,  699, 1327,  381,  379,   99,
135259 /*   270 */   100,   90,  978,  978,  853,  856,  845,  845,   97,   97,
135260 /*   280 */    98,   98,   98,   98,  701,   96,   96,   96,   96,   95,
135261 /*   290 */    95,   94,   94,   94,   93,  351,  325,   92,   89,  178,
135262 /*   300 */   833,  935,  373,  700,   99,  100,   90,  978,  978,  853,
135263 /*   310 */   856,  845,  845,   97,   97,   98,   98,   98,   98,  375,
135264 /*   320 */    96,   96,   96,   96,   95,   95,   94,   94,   94,   93,
135265 /*   330 */   351,  325, 1275,  946,  354,  818,  935,  739,  739,   99,
135266 /*   340 */   100,   90,  978,  978,  853,  856,  845,  845,   97,   97,
135267 /*   350 */    98,   98,   98,   98,  230,   96,   96,   96,   96,   95,
135268 /*   360 */    95,   94,   94,   94,   93,  351,  325,  968,  227,   92,
135269 /*   370 */    89,  178,  373,  300,   99,  100,   90,  978,  978,  853,
135270 /*   380 */   856,  845,  845,   97,   97,   98,   98,   98,   98,  920,
135271 /*   390 */    96,   96,   96,   96,   95,   95,   94,   94,   94,   93,
135272 /*   400 */   351,  325,  449,  447,  447,  447,  147,  737,  737,   99,
135273 /*   410 */   100,   90,  978,  978,  853,  856,  845,  845,   97,   97,
135274 /*   420 */    98,   98,   98,   98,  296,   96,   96,   96,   96,   95,
135275 /*   430 */    95,   94,   94,   94,   93,  351,  325,  419,  231,  957,
135276 /*   440 */   957,  158,   25,  422,   99,  100,   90,  978,  978,  853,
135277 /*   450 */   856,  845,  845,   97,   97,   98,   98,   98,   98,  450,
135278 /*   460 */    96,   96,   96,   96,   95,   95,   94,   94,   94,   93,
135279 /*   470 */   351,  443,  224,  224,  420,  957,  957,  961,  325,   52,
135280 /*   480 */    52,  958,  959,  176,  415,   78,   99,  100,   90,  978,
135281 /*   490 */   978,  853,  856,  845,  845,   97,   97,   98,   98,   98,
135282 /*   500 */    98,  379,   96,   96,   96,   96,   95,   95,   94,   94,
135283 /*   510 */    94,   93,  351,  325,  428,  418,  298,  958,  959,  961,
135284 /*   520 */    81,   99,   88,   90,  978,  978,  853,  856,  845,  845,
135285 /*   530 */    97,   97,   98,   98,   98,   98,  717,   96,   96,   96,
135286 /*   540 */    96,   95,   95,   94,   94,   94,   93,  351,  325,  842,
135287 /*   550 */   842,  854,  857,  996,  318,  343,  379,  100,   90,  978,
135288 /*   560 */   978,  853,  856,  845,  845,   97,   97,   98,   98,   98,
135289 /*   570 */    98,  450,   96,   96,   96,   96,   95,   95,   94,   94,
135290 /*   580 */    94,   93,  351,  325,  350,  350,  350,  260,  377,  340,
135291 /*   590 */   928,   52,   52,   90,  978,  978,  853,  856,  845,  845,
135292 /*   600 */    97,   97,   98,   98,   98,   98,  361,   96,   96,   96,
135293 /*   610 */    96,   95,   95,   94,   94,   94,   93,  351,   86,  445,
135294 /*   620 */   846,    3, 1202,  361,  360,  378,  344,  813,  957,  957,
135295 /*   630 */  1299,   86,  445,  729,    3,  212,  169,  287,  405,  282,
135296 /*   640 */   404,  199,  232,  450,  300,  760,   83,   84,  280,  245,
135297 /*   650 */   262,  365,  251,   85,  352,  352,   92,   89,  178,   83,
135298 /*   660 */    84,  242,  412,   52,   52,  448,   85,  352,  352,  246,
135299 /*   670 */   958,  959,  194,  455,  670,  402,  399,  398,  448,  243,
135300 /*   680 */   221,  114,  434,  776,  361,  450,  397,  268,  747,  224,
135301 /*   690 */   224,  132,  132,  198,  832,  434,  452,  451,  428,  427,
135302 /*   700 */   819,  415,  734,  713,  132,   52,   52,  832,  268,  452,
135303 /*   710 */   451,  734,  194,  819,  363,  402,  399,  398,  450, 1270,
135304 /*   720 */  1270,   23,  957,  957,   86,  445,  397,    3,  228,  429,
135305 /*   730 */   894,  824,  824,  826,  827,   19,  203,  720,   52,   52,
135306 /*   740 */   428,  408,  439,  249,  824,  824,  826,  827,   19,  229,
135307 /*   750 */   403,  153,   83,   84,  761,  177,  241,  450,  721,   85,
135308 /*   760 */   352,  352,  120,  157,  958,  959,   58,  976,  409,  355,
135309 /*   770 */   330,  448,  268,  428,  430,  320,  790,   32,   32,   86,
135310 /*   780 */   445,  776,    3,  341,   98,   98,   98,   98,  434,   96,
135311 /*   790 */    96,   96,   96,   95,   95,   94,   94,   94,   93,  351,
135312 /*   800 */   832,  120,  452,  451,  813,  886,  819,   83,   84,  976,
135313 /*   810 */   813,  132,  410,  919,   85,  352,  352,  132,  407,  789,
135314 /*   820 */   957,  957,   92,   89,  178,  916,  448,  262,  370,  261,
135315 /*   830 */    82,  913,   80,  262,  370,  261,  776,  824,  824,  826,
135316 /*   840 */   827,   19,  933,  434,   96,   96,   96,   96,   95,   95,
135317 /*   850 */    94,   94,   94,   93,  351,  832,   74,  452,  451,  957,
135318 /*   860 */   957,  819,  958,  959,  120,   92,   89,  178,  944,    2,
135319 /*   870 */   917,  964,  268,    1,  975,   76,  445,  762,    3,  708,
135320 /*   880 */   900,  900,  387,  957,  957,  757,  918,  371,  740,  778,
135321 /*   890 */   756,  257,  824,  824,  826,  827,   19,  417,  741,  450,
135322 /*   900 */    24,  958,  959,   83,   84,  369,  957,  957,  177,  226,
135323 /*   910 */    85,  352,  352,  884,  315,  314,  313,  215,  311,   10,
135324 /*   920 */    10,  683,  448,  349,  348,  958,  959,  908,  777,  157,
135325 /*   930 */   120,  957,  957,  337,  776,  416,  711,  310,  450,  434,
135326 /*   940 */   450,  321,  450,  791,  103,  200,  175,  450,  958,  959,
135327 /*   950 */   907,  832,  792,  452,  451,    9,    9,  819,   10,   10,
135328 /*   960 */    52,   52,   51,   51,  180,  716,  248,   10,   10,  171,
135329 /*   970 */   170,  167,  339,  958,  959,  247,  984,  702,  702,  450,
135330 /*   980 */   715,  233,  686,  982,  888,  983,  182,  913,  824,  824,
135331 /*   990 */   826,  827,   19,  183,  256,  423,  132,  181,  394,   10,
135332 /*  1000 */    10,  888,  890,  749,  957,  957,  916,  268,  985,  198,
135333 /*  1010 */   985,  349,  348,  425,  415,  299,  817,  832,  326,  825,
135334 /*  1020 */   120,  332,  133,  819,  268,   98,   98,   98,   98,   91,
135335 /*  1030 */    96,   96,   96,   96,   95,   95,   94,   94,   94,   93,
135336 /*  1040 */   351,  157,  810,  371,  382,  359,  958,  959,  358,  268,
135337 /*  1050 */   450,  917,  368,  324,  824,  824,  826,  450,  709,  450,
135338 /*  1060 */   264,  380,  888,  450,  876,  746,  253,  918,  255,  433,
135339 /*  1070 */    36,   36,  234,  450,  234,  120,  269,   37,   37,   12,
135340 /*  1080 */    12,  334,  272,   27,   27,  450,  330,  118,  450,  162,
135341 /*  1090 */   742,  280,  450,   38,   38,  450,  985,  356,  985,  450,
135342 /*  1100 */   709, 1209,  450,  132,  450,   39,   39,  450,   40,   40,
135343 /*  1110 */   450,  362,   41,   41,  450,   42,   42,  450,  254,   28,
135344 /*  1120 */    28,  450,   29,   29,   31,   31,  450,   43,   43,  450,
135345 /*  1130 */    44,   44,  450,  714,   45,   45,  450,   11,   11,  767,
135346 /*  1140 */   450,   46,   46,  450,  268,  450,  105,  105,  450,   47,
135347 /*  1150 */    47,  450,   48,   48,  450,  237,   33,   33,  450,  172,
135348 /*  1160 */    49,   49,  450,   50,   50,   34,   34,  274,  122,  122,
135349 /*  1170 */   450,  123,  123,  450,  124,  124,  450,  897,   56,   56,
135350 /*  1180 */   450,  896,   35,   35,  450,  267,  450,  817,  450,  817,
135351 /*  1190 */   106,  106,  450,   53,   53,  385,  107,  107,  450,  817,
135352 /*  1200 */   108,  108,  817,  450,  104,  104,  121,  121,  119,  119,
135353 /*  1210 */   450,  117,  112,  112,  450,  276,  450,  225,  111,  111,
135354 /*  1220 */   450,  730,  450,  109,  109,  450,  673,  674,  675,  911,
135355 /*  1230 */   110,  110,  317,  998,   55,   55,   57,   57,  692,  331,
135356 /*  1240 */    54,   54,   26,   26,  696,   30,   30,  317,  936,  197,
135357 /*  1250 */   196,  195,  335,  281,  336,  446,  331,  745,  689,  436,
135358 /*  1260 */   440,  444,  120,   72,  386,  223,  175,  345,  757,  932,
135359 /*  1270 */    20,  286,  319,  756,  815,  372,  374,  202,  202,  202,
135360 /*  1280 */   263,  395,  285,   74,  208,   21,  696,  719,  718,  883,
135361 /*  1290 */   120,  120,  120,  120,  120,  754,  278,  828,   77,   74,
135362 /*  1300 */   726,  727,  785,  783,  879,  202,  999,  208,  893,  892,
135363 /*  1310 */   893,  892,  694,  816,  763,  116,  774, 1289,  431,  432,
135364 /*  1320 */   302,  999,  390,  303,  823,  697,  691,  680,  159,  289,
135365 /*  1330 */   679,  883,  681,  951,  291,  218,  293,    7,  316,  828,
135366 /*  1340 */   173,  805,  259,  364,  252,  910,  376,  713,  295,  435,
135367 /*  1350 */   308,  168,  954,  993,  135,  400,  990,  284,  881,  880,
135368 /*  1360 */   205,  927,  925,   59,  333,   62,  144,  156,  130,   72,
135369 /*  1370 */   802,  366,  367,  393,  137,  185,  189,  160,  139,  383,
135370 /*  1380 */    67,  895,  140,  141,  142,  148,  389,  812,  775,  266,
135371 /*  1390 */   219,  190,  154,  391,  912,  875,  271,  406,  191,  322,
135372 /*  1400 */   682,  733,  192,  342,  732,  724,  731,  711,  723,  421,
135373 /*  1410 */   705,   71,  323,    6,  204,  771,  288,   79,  297,  346,
135374 /*  1420 */   772,  704,  290,  283,  703,  770,  292,  294,  966,  239,
135375 /*  1430 */   769,  102,  861,  438,  426,  240,  424,  442,   73,  213,
135376 /*  1440 */   688,  238,   22,  453,  952,  214,  217,  216,  454,  677,
135377 /*  1450 */   676,  671,  753,  125,  115,  235,  126,  669,  353,  166,
135378 /*  1460 */   127,  244,  179,  357,  306,  304,  305,  307,  113,  891,
135379 /*  1470 */   327,  889,  811,  328,  134,  128,  136,  138,  743,  258,
135380 /*  1480 */   906,  184,  143,  129,  909,  186,   63,   64,  145,  187,
135381 /*  1490 */   905,   65,    8,   66,   13,  188,  202,  898,  265,  149,
135382 /*  1500 */   987,  388,  150,  685,  161,  392,  285,  193,  279,  396,
135383 /*  1510 */   151,  401,   68,   14,   15,  722,   69,  236,  831,  131,
135384 /*  1520 */   830,  859,   70,  751,   16,  414,  755,    4,  174,  220,
135385 /*  1530 */   222,  784,  201,  152,  779,   77,   74,   17,   18,  874,
135386 /*  1540 */   860,  858,  915,  863,  914,  207,  206,  941,  163,  437,
135387 /*  1550 */   947,  942,  164,  209, 1002,  441,  862,  165,  210,  829,
135388 /*  1560 */   695,   87,  312,  211, 1291, 1290,  309,
135389};
135390static const YYCODETYPE yy_lookahead[] = {
135391 /*     0 */    19,   95,   53,   97,   22,   24,   24,  101,   27,   28,
135392 /*    10 */    29,   30,   31,   32,   33,   34,   35,   36,   37,   38,
135393 /*    20 */    39,   40,   41,  152,   43,   44,   45,   46,   47,   48,
135394 /*    30 */    49,   50,   51,   52,   53,   19,   55,   55,  132,  133,
135395 /*    40 */   134,    1,    2,   27,   28,   29,   30,   31,   32,   33,
135396 /*    50 */    34,   35,   36,   37,   38,   39,   40,   41,  187,   43,
135397 /*    60 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
135398 /*    70 */    47,   48,   49,   50,   51,   52,   53,   61,   97,   97,
135399 /*    80 */    19,   49,   50,   51,   52,   53,   70,   26,   27,   28,
135400 /*    90 */    29,   30,   31,   32,   33,   34,   35,   36,   37,   38,
135401 /*   100 */    39,   40,   41,  152,   43,   44,   45,   46,   47,   48,
135402 /*   110 */    49,   50,   51,   52,   53,  144,  145,  146,  147,   19,
135403 /*   120 */    16,   22,   92,  172,  173,   52,   53,   27,   28,   29,
135404 /*   130 */    30,   31,   32,   33,   34,   35,   36,   37,   38,   39,
135405 /*   140 */    40,   41,   81,   43,   44,   45,   46,   47,   48,   49,
135406 /*   150 */    50,   51,   52,   53,   55,   56,   19,  152,  207,  208,
135407 /*   160 */   115,   24,  117,  118,   27,   28,   29,   30,   31,   32,
135408 /*   170 */    33,   34,   35,   36,   37,   38,   39,   40,   41,   79,
135409 /*   180 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
135410 /*   190 */    53,   19,   88,  157,   90,   23,   97,   98,  193,   27,
135411 /*   200 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
135412 /*   210 */    38,   39,   40,   41,  152,   43,   44,   45,   46,   47,
135413 /*   220 */    48,   49,   50,   51,   52,   53,   19,   22,   23,  172,
135414 /*   230 */    23,   26,  119,  120,   27,   28,   29,   30,   31,   32,
135415 /*   240 */    33,   34,   35,   36,   37,   38,   39,   40,   41,  187,
135416 /*   250 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
135417 /*   260 */    53,   19,   22,   23,  228,   23,   26,  231,  152,   27,
135418 /*   270 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
135419 /*   280 */    38,   39,   40,   41,  172,   43,   44,   45,   46,   47,
135420 /*   290 */    48,   49,   50,   51,   52,   53,   19,  221,  222,  223,
135421 /*   300 */    23,   96,  152,  172,   27,   28,   29,   30,   31,   32,
135422 /*   310 */    33,   34,   35,   36,   37,   38,   39,   40,   41,  152,
135423 /*   320 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
135424 /*   330 */    53,   19,    0,    1,    2,   23,   96,  190,  191,   27,
135425 /*   340 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
135426 /*   350 */    38,   39,   40,   41,  238,   43,   44,   45,   46,   47,
135427 /*   360 */    48,   49,   50,   51,   52,   53,   19,  185,  218,  221,
135428 /*   370 */   222,  223,  152,  152,   27,   28,   29,   30,   31,   32,
135429 /*   380 */    33,   34,   35,   36,   37,   38,   39,   40,   41,  241,
135430 /*   390 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
135431 /*   400 */    53,   19,  152,  168,  169,  170,   22,  190,  191,   27,
135432 /*   410 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
135433 /*   420 */    38,   39,   40,   41,  152,   43,   44,   45,   46,   47,
135434 /*   430 */    48,   49,   50,   51,   52,   53,   19,   19,  218,   55,
135435 /*   440 */    56,   24,   22,  152,   27,   28,   29,   30,   31,   32,
135436 /*   450 */    33,   34,   35,   36,   37,   38,   39,   40,   41,  152,
135437 /*   460 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
135438 /*   470 */    53,  250,  194,  195,   56,   55,   56,   55,   19,  172,
135439 /*   480 */   173,   97,   98,  152,  206,  138,   27,   28,   29,   30,
135440 /*   490 */    31,   32,   33,   34,   35,   36,   37,   38,   39,   40,
135441 /*   500 */    41,  152,   43,   44,   45,   46,   47,   48,   49,   50,
135442 /*   510 */    51,   52,   53,   19,  207,  208,  152,   97,   98,   97,
135443 /*   520 */   138,   27,   28,   29,   30,   31,   32,   33,   34,   35,
135444 /*   530 */    36,   37,   38,   39,   40,   41,  181,   43,   44,   45,
135445 /*   540 */    46,   47,   48,   49,   50,   51,   52,   53,   19,   30,
135446 /*   550 */    31,   32,   33,  247,  248,   19,  152,   28,   29,   30,
135447 /*   560 */    31,   32,   33,   34,   35,   36,   37,   38,   39,   40,
135448 /*   570 */    41,  152,   43,   44,   45,   46,   47,   48,   49,   50,
135449 /*   580 */    51,   52,   53,   19,  168,  169,  170,  238,   19,   53,
135450 /*   590 */   152,  172,  173,   29,   30,   31,   32,   33,   34,   35,
135451 /*   600 */    36,   37,   38,   39,   40,   41,  152,   43,   44,   45,
135452 /*   610 */    46,   47,   48,   49,   50,   51,   52,   53,   19,   20,
135453 /*   620 */   101,   22,   23,  169,  170,   56,  207,   85,   55,   56,
135454 /*   630 */    23,   19,   20,   26,   22,   99,  100,  101,  102,  103,
135455 /*   640 */   104,  105,  238,  152,  152,  210,   47,   48,  112,  152,
135456 /*   650 */   108,  109,  110,   54,   55,   56,  221,  222,  223,   47,
135457 /*   660 */    48,  119,  120,  172,  173,   66,   54,   55,   56,  152,
135458 /*   670 */    97,   98,   99,  148,  149,  102,  103,  104,   66,  154,
135459 /*   680 */    23,  156,   83,   26,  230,  152,  113,  152,  163,  194,
135460 /*   690 */   195,   92,   92,   30,   95,   83,   97,   98,  207,  208,
135461 /*   700 */   101,  206,  179,  180,   92,  172,  173,   95,  152,   97,
135462 /*   710 */    98,  188,   99,  101,  219,  102,  103,  104,  152,  119,
135463 /*   720 */   120,  196,   55,   56,   19,   20,  113,   22,  193,  163,
135464 /*   730 */    11,  132,  133,  134,  135,  136,   24,   65,  172,  173,
135465 /*   740 */   207,  208,  250,  152,  132,  133,  134,  135,  136,  193,
135466 /*   750 */    78,   84,   47,   48,   49,   98,  199,  152,   86,   54,
135467 /*   760 */    55,   56,  196,  152,   97,   98,  209,   55,  163,  244,
135468 /*   770 */   107,   66,  152,  207,  208,  164,  175,  172,  173,   19,
135469 /*   780 */    20,  124,   22,  111,   38,   39,   40,   41,   83,   43,
135470 /*   790 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
135471 /*   800 */    95,  196,   97,   98,   85,  152,  101,   47,   48,   97,
135472 /*   810 */    85,   92,  207,  193,   54,   55,   56,   92,   49,  175,
135473 /*   820 */    55,   56,  221,  222,  223,   12,   66,  108,  109,  110,
135474 /*   830 */   137,  163,  139,  108,  109,  110,   26,  132,  133,  134,
135475 /*   840 */   135,  136,  152,   83,   43,   44,   45,   46,   47,   48,
135476 /*   850 */    49,   50,   51,   52,   53,   95,   26,   97,   98,   55,
135477 /*   860 */    56,  101,   97,   98,  196,  221,  222,  223,  146,  147,
135478 /*   870 */    57,  171,  152,   22,   26,   19,   20,   49,   22,  179,
135479 /*   880 */   108,  109,  110,   55,   56,  116,   73,  219,   75,  124,
135480 /*   890 */   121,  152,  132,  133,  134,  135,  136,  163,   85,  152,
135481 /*   900 */   232,   97,   98,   47,   48,  237,   55,   56,   98,    5,
135482 /*   910 */    54,   55,   56,  193,   10,   11,   12,   13,   14,  172,
135483 /*   920 */   173,   17,   66,   47,   48,   97,   98,  152,  124,  152,
135484 /*   930 */   196,   55,   56,  186,  124,  152,  106,  160,  152,   83,
135485 /*   940 */   152,  164,  152,   61,   22,  211,  212,  152,   97,   98,
135486 /*   950 */   152,   95,   70,   97,   98,  172,  173,  101,  172,  173,
135487 /*   960 */   172,  173,  172,  173,   60,  181,   62,  172,  173,   47,
135488 /*   970 */    48,  123,  186,   97,   98,   71,  100,   55,   56,  152,
135489 /*   980 */   181,  186,   21,  107,  152,  109,   82,  163,  132,  133,
135490 /*   990 */   134,  135,  136,   89,   16,  207,   92,   93,   19,  172,
135491 /*  1000 */   173,  169,  170,  195,   55,   56,   12,  152,  132,   30,
135492 /*  1010 */   134,   47,   48,  186,  206,  225,  152,   95,  114,   97,
135493 /*  1020 */   196,  245,  246,  101,  152,   38,   39,   40,   41,   42,
135494 /*  1030 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
135495 /*  1040 */    53,  152,  163,  219,  152,  141,   97,   98,  193,  152,
135496 /*  1050 */   152,   57,   91,  164,  132,  133,  134,  152,   55,  152,
135497 /*  1060 */   152,  237,  230,  152,  103,  193,   88,   73,   90,   75,
135498 /*  1070 */   172,  173,  183,  152,  185,  196,  152,  172,  173,  172,
135499 /*  1080 */   173,  217,  152,  172,  173,  152,  107,   22,  152,   24,
135500 /*  1090 */   193,  112,  152,  172,  173,  152,  132,  242,  134,  152,
135501 /*  1100 */    97,  140,  152,   92,  152,  172,  173,  152,  172,  173,
135502 /*  1110 */   152,  100,  172,  173,  152,  172,  173,  152,  140,  172,
135503 /*  1120 */   173,  152,  172,  173,  172,  173,  152,  172,  173,  152,
135504 /*  1130 */   172,  173,  152,  152,  172,  173,  152,  172,  173,  213,
135505 /*  1140 */   152,  172,  173,  152,  152,  152,  172,  173,  152,  172,
135506 /*  1150 */   173,  152,  172,  173,  152,  210,  172,  173,  152,   26,
135507 /*  1160 */   172,  173,  152,  172,  173,  172,  173,  152,  172,  173,
135508 /*  1170 */   152,  172,  173,  152,  172,  173,  152,   59,  172,  173,
135509 /*  1180 */   152,   63,  172,  173,  152,  193,  152,  152,  152,  152,
135510 /*  1190 */   172,  173,  152,  172,  173,   77,  172,  173,  152,  152,
135511 /*  1200 */   172,  173,  152,  152,  172,  173,  172,  173,  172,  173,
135512 /*  1210 */   152,   22,  172,  173,  152,  152,  152,   22,  172,  173,
135513 /*  1220 */   152,  152,  152,  172,  173,  152,    7,    8,    9,  163,
135514 /*  1230 */   172,  173,   22,   23,  172,  173,  172,  173,  166,  167,
135515 /*  1240 */   172,  173,  172,  173,   55,  172,  173,   22,   23,  108,
135516 /*  1250 */   109,  110,  217,  152,  217,  166,  167,  163,  163,  163,
135517 /*  1260 */   163,  163,  196,  130,  217,  211,  212,  217,  116,   23,
135518 /*  1270 */    22,  101,   26,  121,   23,   23,   23,   26,   26,   26,
135519 /*  1280 */    23,   23,  112,   26,   26,   37,   97,  100,  101,   55,
135520 /*  1290 */   196,  196,  196,  196,  196,   23,   23,   55,   26,   26,
135521 /*  1300 */     7,    8,   23,  152,   23,   26,   96,   26,  132,  132,
135522 /*  1310 */   134,  134,   23,  152,  152,   26,  152,  122,  152,  191,
135523 /*  1320 */   152,   96,  234,  152,  152,  152,  152,  152,  197,  210,
135524 /*  1330 */   152,   97,  152,  152,  210,  233,  210,  198,  150,   97,
135525 /*  1340 */   184,  201,  239,  214,  214,  201,  239,  180,  214,  227,
135526 /*  1350 */   200,  198,  155,   67,  243,  176,   69,  175,  175,  175,
135527 /*  1360 */   122,  159,  159,  240,  159,  240,   22,  220,   27,  130,
135528 /*  1370 */   201,   18,  159,   18,  189,  158,  158,  220,  192,  159,
135529 /*  1380 */   137,  236,  192,  192,  192,  189,   74,  189,  159,  235,
135530 /*  1390 */   159,  158,   22,  177,  201,  201,  159,  107,  158,  177,
135531 /*  1400 */   159,  174,  158,   76,  174,  182,  174,  106,  182,  125,
135532 /*  1410 */   174,  107,  177,   22,  159,  216,  215,  137,  159,   53,
135533 /*  1420 */   216,  176,  215,  174,  174,  216,  215,  215,  174,  229,
135534 /*  1430 */   216,  129,  224,  177,  126,  229,  127,  177,  128,   25,
135535 /*  1440 */   162,  226,   26,  161,   13,  153,    6,  153,  151,  151,
135536 /*  1450 */   151,  151,  205,  165,  178,  178,  165,    4,    3,   22,
135537 /*  1460 */   165,  142,   15,   94,  202,  204,  203,  201,   16,   23,
135538 /*  1470 */   249,   23,  120,  249,  246,  111,  131,  123,   20,   16,
135539 /*  1480 */     1,  125,  123,  111,   56,   64,   37,   37,  131,  122,
135540 /*  1490 */     1,   37,    5,   37,   22,  107,   26,   80,  140,   80,
135541 /*  1500 */    87,   72,  107,   20,   24,   19,  112,  105,   23,   79,
135542 /*  1510 */    22,   79,   22,   22,   22,   58,   22,   79,   23,   68,
135543 /*  1520 */    23,   23,   26,  116,   22,   26,   23,   22,  122,   23,
135544 /*  1530 */    23,   56,   64,   22,  124,   26,   26,   64,   64,   23,
135545 /*  1540 */    23,   23,   23,   11,   23,   22,   26,   23,   22,   24,
135546 /*  1550 */     1,   23,   22,   26,  251,   24,   23,   22,  122,   23,
135547 /*  1560 */    23,   22,   15,  122,  122,  122,   23,
135548};
135549#define YY_SHIFT_USE_DFLT (1567)
135550#define YY_SHIFT_COUNT    (455)
135551#define YY_SHIFT_MIN      (-94)
135552#define YY_SHIFT_MAX      (1549)
135553static const short yy_shift_ofst[] = {
135554 /*     0 */    40,  599,  904,  612,  760,  760,  760,  760,  725,  -19,
135555 /*    10 */    16,   16,  100,  760,  760,  760,  760,  760,  760,  760,
135556 /*    20 */   876,  876,  573,  542,  719,  600,   61,  137,  172,  207,
135557 /*    30 */   242,  277,  312,  347,  382,  417,  459,  459,  459,  459,
135558 /*    40 */   459,  459,  459,  459,  459,  459,  459,  459,  459,  459,
135559 /*    50 */   459,  459,  459,  494,  459,  529,  564,  564,  705,  760,
135560 /*    60 */   760,  760,  760,  760,  760,  760,  760,  760,  760,  760,
135561 /*    70 */   760,  760,  760,  760,  760,  760,  760,  760,  760,  760,
135562 /*    80 */   760,  760,  760,  760,  760,  760,  760,  760,  760,  760,
135563 /*    90 */   856,  760,  760,  760,  760,  760,  760,  760,  760,  760,
135564 /*   100 */   760,  760,  760,  760,  987,  746,  746,  746,  746,  746,
135565 /*   110 */   801,   23,   32,  949,  961,  979,  964,  964,  949,   73,
135566 /*   120 */   113,  -51, 1567, 1567, 1567,  536,  536,  536,   99,   99,
135567 /*   130 */   813,  813,  667,  205,  240,  949,  949,  949,  949,  949,
135568 /*   140 */   949,  949,  949,  949,  949,  949,  949,  949,  949,  949,
135569 /*   150 */   949,  949,  949,  949,  949,  332, 1011,  422,  422,  113,
135570 /*   160 */    30,   30,   30,   30,   30,   30, 1567, 1567, 1567,  922,
135571 /*   170 */   -94,  -94,  384,  613,  828,  420,  765,  804,  851,  949,
135572 /*   180 */   949,  949,  949,  949,  949,  949,  949,  949,  949,  949,
135573 /*   190 */   949,  949,  949,  949,  949,  672,  672,  672,  949,  949,
135574 /*   200 */   657,  949,  949,  949,  -18,  949,  949,  994,  949,  949,
135575 /*   210 */   949,  949,  949,  949,  949,  949,  949,  949,  772, 1118,
135576 /*   220 */   712,  712,  712,  810,   45,  769, 1219, 1133,  418,  418,
135577 /*   230 */   569, 1133,  569,  830,  607,  663,  882,  418,  693,  882,
135578 /*   240 */   882,  848, 1152, 1065, 1286, 1238, 1238, 1287, 1287, 1238,
135579 /*   250 */  1344, 1341, 1239, 1353, 1353, 1353, 1353, 1238, 1355, 1239,
135580 /*   260 */  1344, 1341, 1341, 1239, 1238, 1355, 1243, 1312, 1238, 1238,
135581 /*   270 */  1355, 1370, 1238, 1355, 1238, 1355, 1370, 1290, 1290, 1290,
135582 /*   280 */  1327, 1370, 1290, 1301, 1290, 1327, 1290, 1290, 1284, 1304,
135583 /*   290 */  1284, 1304, 1284, 1304, 1284, 1304, 1238, 1391, 1238, 1280,
135584 /*   300 */  1370, 1366, 1366, 1370, 1302, 1308, 1310, 1309, 1239, 1414,
135585 /*   310 */  1416, 1431, 1431, 1440, 1440, 1440, 1440, 1567, 1567, 1567,
135586 /*   320 */  1567, 1567, 1567, 1567, 1567,  519,  978, 1210, 1225,  104,
135587 /*   330 */  1141, 1189, 1246, 1248, 1251, 1252, 1253, 1257, 1258, 1273,
135588 /*   340 */  1003, 1187, 1293, 1170, 1272, 1279, 1234, 1281, 1176, 1177,
135589 /*   350 */  1289, 1242, 1195, 1453, 1455, 1437, 1319, 1447, 1369, 1452,
135590 /*   360 */  1446, 1448, 1352, 1345, 1364, 1354, 1458, 1356, 1463, 1479,
135591 /*   370 */  1359, 1357, 1449, 1450, 1454, 1456, 1372, 1428, 1421, 1367,
135592 /*   380 */  1489, 1487, 1472, 1388, 1358, 1417, 1470, 1419, 1413, 1429,
135593 /*   390 */  1395, 1480, 1483, 1486, 1394, 1402, 1488, 1430, 1490, 1491,
135594 /*   400 */  1485, 1492, 1432, 1457, 1494, 1438, 1451, 1495, 1497, 1498,
135595 /*   410 */  1496, 1407, 1502, 1503, 1505, 1499, 1406, 1506, 1507, 1475,
135596 /*   420 */  1468, 1511, 1410, 1509, 1473, 1510, 1474, 1516, 1509, 1517,
135597 /*   430 */  1518, 1519, 1520, 1521, 1523, 1532, 1524, 1526, 1525, 1527,
135598 /*   440 */  1528, 1530, 1531, 1527, 1533, 1535, 1536, 1537, 1539, 1436,
135599 /*   450 */  1441, 1442, 1443, 1543, 1547, 1549,
135600};
135601#define YY_REDUCE_USE_DFLT (-130)
135602#define YY_REDUCE_COUNT (324)
135603#define YY_REDUCE_MIN   (-129)
135604#define YY_REDUCE_MAX   (1300)
135605static const short yy_reduce_ofst[] = {
135606 /*     0 */   -29,  566,  525,  605,  -49,  307,  491,  533,  668,  435,
135607 /*    10 */   601,  644,  148,  747,  786,  795,  419,  788,  827,  790,
135608 /*    20 */   454,  832,  889,  495,  824,  734,   76,   76,   76,   76,
135609 /*    30 */    76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
135610 /*    40 */    76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
135611 /*    50 */    76,   76,   76,   76,   76,   76,   76,   76,  783,  898,
135612 /*    60 */   905,  907,  911,  921,  933,  936,  940,  943,  947,  950,
135613 /*    70 */   952,  955,  958,  962,  965,  969,  974,  977,  980,  984,
135614 /*    80 */   988,  991,  993,  996,  999, 1002, 1006, 1010, 1018, 1021,
135615 /*    90 */  1024, 1028, 1032, 1034, 1036, 1040, 1046, 1051, 1058, 1062,
135616 /*   100 */  1064, 1068, 1070, 1073,   76,   76,   76,   76,   76,   76,
135617 /*   110 */    76,   76,   76,  855,   36,  523,  235,  416,  777,   76,
135618 /*   120 */   278,   76,   76,   76,   76,  700,  700,  700,  150,  220,
135619 /*   130 */   147,  217,  221,  306,  306,  611,    5,  535,  556,  620,
135620 /*   140 */   720,  872,  897,  116,  864,  349, 1035, 1037,  404, 1047,
135621 /*   150 */   992, -129, 1050,  492,   62,  722,  879, 1072, 1089,  808,
135622 /*   160 */  1066, 1094, 1095, 1096, 1097, 1098,  776, 1054,  557,   57,
135623 /*   170 */   112,  131,  167,  182,  250,  272,  291,  331,  364,  438,
135624 /*   180 */   497,  517,  591,  653,  690,  739,  775,  798,  892,  908,
135625 /*   190 */   924,  930, 1015, 1063, 1069,  355,  784,  799,  981, 1101,
135626 /*   200 */   926, 1151, 1161, 1162,  945, 1164, 1166, 1128, 1168, 1171,
135627 /*   210 */  1172,  250, 1173, 1174, 1175, 1178, 1180, 1181, 1088, 1102,
135628 /*   220 */  1119, 1124, 1126,  926, 1131, 1139, 1188, 1140, 1129, 1130,
135629 /*   230 */  1103, 1144, 1107, 1179, 1156, 1167, 1182, 1134, 1122, 1183,
135630 /*   240 */  1184, 1150, 1153, 1197, 1111, 1202, 1203, 1123, 1125, 1205,
135631 /*   250 */  1147, 1185, 1169, 1186, 1190, 1191, 1192, 1213, 1217, 1193,
135632 /*   260 */  1157, 1196, 1198, 1194, 1220, 1218, 1145, 1154, 1229, 1231,
135633 /*   270 */  1233, 1216, 1237, 1240, 1241, 1244, 1222, 1227, 1230, 1232,
135634 /*   280 */  1223, 1235, 1236, 1245, 1249, 1226, 1250, 1254, 1199, 1201,
135635 /*   290 */  1204, 1207, 1209, 1211, 1214, 1212, 1255, 1208, 1259, 1215,
135636 /*   300 */  1256, 1200, 1206, 1260, 1247, 1261, 1263, 1262, 1266, 1278,
135637 /*   310 */  1282, 1292, 1294, 1297, 1298, 1299, 1300, 1221, 1224, 1228,
135638 /*   320 */  1288, 1291, 1276, 1277, 1295,
135639};
135640static const YYACTIONTYPE yy_default[] = {
135641 /*     0 */  1280, 1270, 1270, 1270, 1202, 1202, 1202, 1202, 1270, 1096,
135642 /*    10 */  1125, 1125, 1254, 1332, 1332, 1332, 1332, 1332, 1332, 1201,
135643 /*    20 */  1332, 1332, 1332, 1332, 1270, 1100, 1131, 1332, 1332, 1332,
135644 /*    30 */  1332, 1203, 1204, 1332, 1332, 1332, 1253, 1255, 1141, 1140,
135645 /*    40 */  1139, 1138, 1236, 1112, 1136, 1129, 1133, 1203, 1197, 1198,
135646 /*    50 */  1196, 1200, 1204, 1332, 1132, 1167, 1181, 1166, 1332, 1332,
135647 /*    60 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
135648 /*    70 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
135649 /*    80 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
135650 /*    90 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
135651 /*   100 */  1332, 1332, 1332, 1332, 1175, 1180, 1187, 1179, 1176, 1169,
135652 /*   110 */  1168, 1170, 1171, 1332, 1019, 1067, 1332, 1332, 1332, 1172,
135653 /*   120 */  1332, 1173, 1184, 1183, 1182, 1261, 1288, 1287, 1332, 1332,
135654 /*   130 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
135655 /*   140 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
135656 /*   150 */  1332, 1332, 1332, 1332, 1332, 1280, 1270, 1025, 1025, 1332,
135657 /*   160 */  1270, 1270, 1270, 1270, 1270, 1270, 1266, 1100, 1091, 1332,
135658 /*   170 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
135659 /*   180 */  1258, 1256, 1332, 1217, 1332, 1332, 1332, 1332, 1332, 1332,
135660 /*   190 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
135661 /*   200 */  1332, 1332, 1332, 1332, 1096, 1332, 1332, 1332, 1332, 1332,
135662 /*   210 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1282, 1332, 1231,
135663 /*   220 */  1096, 1096, 1096, 1098, 1080, 1090, 1004, 1135, 1114, 1114,
135664 /*   230 */  1321, 1135, 1321, 1042, 1302, 1039, 1125, 1114, 1199, 1125,
135665 /*   240 */  1125, 1097, 1090, 1332, 1324, 1105, 1105, 1323, 1323, 1105,
135666 /*   250 */  1146, 1070, 1135, 1076, 1076, 1076, 1076, 1105, 1016, 1135,
135667 /*   260 */  1146, 1070, 1070, 1135, 1105, 1016, 1235, 1318, 1105, 1105,
135668 /*   270 */  1016, 1210, 1105, 1016, 1105, 1016, 1210, 1068, 1068, 1068,
135669 /*   280 */  1057, 1210, 1068, 1042, 1068, 1057, 1068, 1068, 1118, 1113,
135670 /*   290 */  1118, 1113, 1118, 1113, 1118, 1113, 1105, 1205, 1105, 1332,
135671 /*   300 */  1210, 1214, 1214, 1210, 1130, 1119, 1128, 1126, 1135, 1022,
135672 /*   310 */  1060, 1285, 1285, 1281, 1281, 1281, 1281, 1329, 1329, 1266,
135673 /*   320 */  1297, 1297, 1044, 1044, 1297, 1332, 1332, 1332, 1332, 1332,
135674 /*   330 */  1332, 1292, 1332, 1219, 1332, 1332, 1332, 1332, 1332, 1332,
135675 /*   340 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
135676 /*   350 */  1332, 1332, 1152, 1332, 1000, 1263, 1332, 1332, 1262, 1332,
135677 /*   360 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
135678 /*   370 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1320,
135679 /*   380 */  1332, 1332, 1332, 1332, 1332, 1332, 1234, 1233, 1332, 1332,
135680 /*   390 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
135681 /*   400 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
135682 /*   410 */  1332, 1082, 1332, 1332, 1332, 1306, 1332, 1332, 1332, 1332,
135683 /*   420 */  1332, 1332, 1332, 1127, 1332, 1120, 1332, 1332, 1311, 1332,
135684 /*   430 */  1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1272,
135685 /*   440 */  1332, 1332, 1332, 1271, 1332, 1332, 1332, 1332, 1332, 1154,
135686 /*   450 */  1332, 1153, 1157, 1332, 1010, 1332,
135687};
135688/********** End of lemon-generated parsing tables *****************************/
135689
135690/* The next table maps tokens (terminal symbols) into fallback tokens.
135691** If a construct like the following:
135692**
135693**      %fallback ID X Y Z.
135694**
135695** appears in the grammar, then ID becomes a fallback token for X, Y,
135696** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
135697** but it does not parse, the type of the token is changed to ID and
135698** the parse is retried before an error is thrown.
135699**
135700** This feature can be used, for example, to cause some keywords in a language
135701** to revert to identifiers if they keyword does not apply in the context where
135702** it appears.
135703*/
135704#ifdef YYFALLBACK
135705static const YYCODETYPE yyFallback[] = {
135706    0,  /*          $ => nothing */
135707    0,  /*       SEMI => nothing */
135708   55,  /*    EXPLAIN => ID */
135709   55,  /*      QUERY => ID */
135710   55,  /*       PLAN => ID */
135711   55,  /*      BEGIN => ID */
135712    0,  /* TRANSACTION => nothing */
135713   55,  /*   DEFERRED => ID */
135714   55,  /*  IMMEDIATE => ID */
135715   55,  /*  EXCLUSIVE => ID */
135716    0,  /*     COMMIT => nothing */
135717   55,  /*        END => ID */
135718   55,  /*   ROLLBACK => ID */
135719   55,  /*  SAVEPOINT => ID */
135720   55,  /*    RELEASE => ID */
135721    0,  /*         TO => nothing */
135722    0,  /*      TABLE => nothing */
135723    0,  /*     CREATE => nothing */
135724   55,  /*         IF => ID */
135725    0,  /*        NOT => nothing */
135726    0,  /*     EXISTS => nothing */
135727   55,  /*       TEMP => ID */
135728    0,  /*         LP => nothing */
135729    0,  /*         RP => nothing */
135730    0,  /*         AS => nothing */
135731   55,  /*    WITHOUT => ID */
135732    0,  /*      COMMA => nothing */
135733    0,  /*         OR => nothing */
135734    0,  /*        AND => nothing */
135735    0,  /*         IS => nothing */
135736   55,  /*      MATCH => ID */
135737   55,  /*    LIKE_KW => ID */
135738    0,  /*    BETWEEN => nothing */
135739    0,  /*         IN => nothing */
135740    0,  /*     ISNULL => nothing */
135741    0,  /*    NOTNULL => nothing */
135742    0,  /*         NE => nothing */
135743    0,  /*         EQ => nothing */
135744    0,  /*         GT => nothing */
135745    0,  /*         LE => nothing */
135746    0,  /*         LT => nothing */
135747    0,  /*         GE => nothing */
135748    0,  /*     ESCAPE => nothing */
135749    0,  /*     BITAND => nothing */
135750    0,  /*      BITOR => nothing */
135751    0,  /*     LSHIFT => nothing */
135752    0,  /*     RSHIFT => nothing */
135753    0,  /*       PLUS => nothing */
135754    0,  /*      MINUS => nothing */
135755    0,  /*       STAR => nothing */
135756    0,  /*      SLASH => nothing */
135757    0,  /*        REM => nothing */
135758    0,  /*     CONCAT => nothing */
135759    0,  /*    COLLATE => nothing */
135760    0,  /*     BITNOT => nothing */
135761    0,  /*         ID => nothing */
135762    0,  /*    INDEXED => nothing */
135763   55,  /*      ABORT => ID */
135764   55,  /*     ACTION => ID */
135765   55,  /*      AFTER => ID */
135766   55,  /*    ANALYZE => ID */
135767   55,  /*        ASC => ID */
135768   55,  /*     ATTACH => ID */
135769   55,  /*     BEFORE => ID */
135770   55,  /*         BY => ID */
135771   55,  /*    CASCADE => ID */
135772   55,  /*       CAST => ID */
135773   55,  /*   COLUMNKW => ID */
135774   55,  /*   CONFLICT => ID */
135775   55,  /*   DATABASE => ID */
135776   55,  /*       DESC => ID */
135777   55,  /*     DETACH => ID */
135778   55,  /*       EACH => ID */
135779   55,  /*       FAIL => ID */
135780   55,  /*        FOR => ID */
135781   55,  /*     IGNORE => ID */
135782   55,  /*  INITIALLY => ID */
135783   55,  /*    INSTEAD => ID */
135784   55,  /*         NO => ID */
135785   55,  /*        KEY => ID */
135786   55,  /*         OF => ID */
135787   55,  /*     OFFSET => ID */
135788   55,  /*     PRAGMA => ID */
135789   55,  /*      RAISE => ID */
135790   55,  /*  RECURSIVE => ID */
135791   55,  /*    REPLACE => ID */
135792   55,  /*   RESTRICT => ID */
135793   55,  /*        ROW => ID */
135794   55,  /*    TRIGGER => ID */
135795   55,  /*     VACUUM => ID */
135796   55,  /*       VIEW => ID */
135797   55,  /*    VIRTUAL => ID */
135798   55,  /*       WITH => ID */
135799   55,  /*    REINDEX => ID */
135800   55,  /*     RENAME => ID */
135801   55,  /*   CTIME_KW => ID */
135802};
135803#endif /* YYFALLBACK */
135804
135805/* The following structure represents a single element of the
135806** parser's stack.  Information stored includes:
135807**
135808**   +  The state number for the parser at this level of the stack.
135809**
135810**   +  The value of the token stored at this level of the stack.
135811**      (In other words, the "major" token.)
135812**
135813**   +  The semantic value stored at this level of the stack.  This is
135814**      the information used by the action routines in the grammar.
135815**      It is sometimes called the "minor" token.
135816**
135817** After the "shift" half of a SHIFTREDUCE action, the stateno field
135818** actually contains the reduce action for the second half of the
135819** SHIFTREDUCE.
135820*/
135821struct yyStackEntry {
135822  YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
135823  YYCODETYPE major;      /* The major token value.  This is the code
135824                         ** number for the token at this stack level */
135825  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
135826                         ** is the value of the token  */
135827};
135828typedef struct yyStackEntry yyStackEntry;
135829
135830/* The state of the parser is completely contained in an instance of
135831** the following structure */
135832struct yyParser {
135833  yyStackEntry *yytos;          /* Pointer to top element of the stack */
135834#ifdef YYTRACKMAXSTACKDEPTH
135835  int yyhwm;                    /* High-water mark of the stack */
135836#endif
135837#ifndef YYNOERRORRECOVERY
135838  int yyerrcnt;                 /* Shifts left before out of the error */
135839#endif
135840  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
135841#if YYSTACKDEPTH<=0
135842  int yystksz;                  /* Current side of the stack */
135843  yyStackEntry *yystack;        /* The parser's stack */
135844  yyStackEntry yystk0;          /* First stack entry */
135845#else
135846  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
135847#endif
135848};
135849typedef struct yyParser yyParser;
135850
135851#ifndef NDEBUG
135852/* #include <stdio.h> */
135853static FILE *yyTraceFILE = 0;
135854static char *yyTracePrompt = 0;
135855#endif /* NDEBUG */
135856
135857#ifndef NDEBUG
135858/*
135859** Turn parser tracing on by giving a stream to which to write the trace
135860** and a prompt to preface each trace message.  Tracing is turned off
135861** by making either argument NULL
135862**
135863** Inputs:
135864** <ul>
135865** <li> A FILE* to which trace output should be written.
135866**      If NULL, then tracing is turned off.
135867** <li> A prefix string written at the beginning of every
135868**      line of trace output.  If NULL, then tracing is
135869**      turned off.
135870** </ul>
135871**
135872** Outputs:
135873** None.
135874*/
135875SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
135876  yyTraceFILE = TraceFILE;
135877  yyTracePrompt = zTracePrompt;
135878  if( yyTraceFILE==0 ) yyTracePrompt = 0;
135879  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
135880}
135881#endif /* NDEBUG */
135882
135883#ifndef NDEBUG
135884/* For tracing shifts, the names of all terminals and nonterminals
135885** are required.  The following table supplies these names */
135886static const char *const yyTokenName[] = {
135887  "$",             "SEMI",          "EXPLAIN",       "QUERY",
135888  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
135889  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
135890  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
135891  "TABLE",         "CREATE",        "IF",            "NOT",
135892  "EXISTS",        "TEMP",          "LP",            "RP",
135893  "AS",            "WITHOUT",       "COMMA",         "OR",
135894  "AND",           "IS",            "MATCH",         "LIKE_KW",
135895  "BETWEEN",       "IN",            "ISNULL",        "NOTNULL",
135896  "NE",            "EQ",            "GT",            "LE",
135897  "LT",            "GE",            "ESCAPE",        "BITAND",
135898  "BITOR",         "LSHIFT",        "RSHIFT",        "PLUS",
135899  "MINUS",         "STAR",          "SLASH",         "REM",
135900  "CONCAT",        "COLLATE",       "BITNOT",        "ID",
135901  "INDEXED",       "ABORT",         "ACTION",        "AFTER",
135902  "ANALYZE",       "ASC",           "ATTACH",        "BEFORE",
135903  "BY",            "CASCADE",       "CAST",          "COLUMNKW",
135904  "CONFLICT",      "DATABASE",      "DESC",          "DETACH",
135905  "EACH",          "FAIL",          "FOR",           "IGNORE",
135906  "INITIALLY",     "INSTEAD",       "NO",            "KEY",
135907  "OF",            "OFFSET",        "PRAGMA",        "RAISE",
135908  "RECURSIVE",     "REPLACE",       "RESTRICT",      "ROW",
135909  "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
135910  "WITH",          "REINDEX",       "RENAME",        "CTIME_KW",
135911  "ANY",           "STRING",        "JOIN_KW",       "CONSTRAINT",
135912  "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",
135913  "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",
135914  "INSERT",        "DELETE",        "UPDATE",        "SET",
135915  "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",
135916  "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",
135917  "VALUES",        "DISTINCT",      "DOT",           "FROM",
135918  "JOIN",          "USING",         "ORDER",         "GROUP",
135919  "HAVING",        "LIMIT",         "WHERE",         "INTO",
135920  "FLOAT",         "BLOB",          "INTEGER",       "VARIABLE",
135921  "CASE",          "WHEN",          "THEN",          "ELSE",
135922  "INDEX",         "ALTER",         "ADD",           "error",
135923  "input",         "cmdlist",       "ecmd",          "explain",
135924  "cmdx",          "cmd",           "transtype",     "trans_opt",
135925  "nm",            "savepoint_opt",  "create_table",  "create_table_args",
135926  "createkw",      "temp",          "ifnotexists",   "dbnm",
135927  "columnlist",    "conslist_opt",  "table_options",  "select",
135928  "columnname",    "carglist",      "typetoken",     "typename",
135929  "signed",        "plus_num",      "minus_num",     "ccons",
135930  "term",          "expr",          "onconf",        "sortorder",
135931  "autoinc",       "eidlist_opt",   "refargs",       "defer_subclause",
135932  "refarg",        "refact",        "init_deferred_pred_opt",  "conslist",
135933  "tconscomma",    "tcons",         "sortlist",      "eidlist",
135934  "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
135935  "ifexists",      "fullname",      "selectnowith",  "oneselect",
135936  "with",          "multiselect_op",  "distinct",      "selcollist",
135937  "from",          "where_opt",     "groupby_opt",   "having_opt",
135938  "orderby_opt",   "limit_opt",     "values",        "nexprlist",
135939  "exprlist",      "sclp",          "as",            "seltablist",
135940  "stl_prefix",    "joinop",        "indexed_opt",   "on_opt",
135941  "using_opt",     "idlist",        "setlist",       "insert_cmd",
135942  "idlist_opt",    "likeop",        "between_op",    "in_op",
135943  "paren_exprlist",  "case_operand",  "case_exprlist",  "case_else",
135944  "uniqueflag",    "collate",       "nmnum",         "trigger_decl",
135945  "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
135946  "when_clause",   "trigger_cmd",   "trnm",          "tridxby",
135947  "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
135948  "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
135949  "lp",            "anylist",       "wqlist",
135950};
135951#endif /* NDEBUG */
135952
135953#ifndef NDEBUG
135954/* For tracing reduce actions, the names of all rules are required.
135955*/
135956static const char *const yyRuleName[] = {
135957 /*   0 */ "explain ::= EXPLAIN",
135958 /*   1 */ "explain ::= EXPLAIN QUERY PLAN",
135959 /*   2 */ "cmdx ::= cmd",
135960 /*   3 */ "cmd ::= BEGIN transtype trans_opt",
135961 /*   4 */ "transtype ::=",
135962 /*   5 */ "transtype ::= DEFERRED",
135963 /*   6 */ "transtype ::= IMMEDIATE",
135964 /*   7 */ "transtype ::= EXCLUSIVE",
135965 /*   8 */ "cmd ::= COMMIT trans_opt",
135966 /*   9 */ "cmd ::= END trans_opt",
135967 /*  10 */ "cmd ::= ROLLBACK trans_opt",
135968 /*  11 */ "cmd ::= SAVEPOINT nm",
135969 /*  12 */ "cmd ::= RELEASE savepoint_opt nm",
135970 /*  13 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
135971 /*  14 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
135972 /*  15 */ "createkw ::= CREATE",
135973 /*  16 */ "ifnotexists ::=",
135974 /*  17 */ "ifnotexists ::= IF NOT EXISTS",
135975 /*  18 */ "temp ::= TEMP",
135976 /*  19 */ "temp ::=",
135977 /*  20 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
135978 /*  21 */ "create_table_args ::= AS select",
135979 /*  22 */ "table_options ::=",
135980 /*  23 */ "table_options ::= WITHOUT nm",
135981 /*  24 */ "columnname ::= nm typetoken",
135982 /*  25 */ "typetoken ::=",
135983 /*  26 */ "typetoken ::= typename LP signed RP",
135984 /*  27 */ "typetoken ::= typename LP signed COMMA signed RP",
135985 /*  28 */ "typename ::= typename ID|STRING",
135986 /*  29 */ "ccons ::= CONSTRAINT nm",
135987 /*  30 */ "ccons ::= DEFAULT term",
135988 /*  31 */ "ccons ::= DEFAULT LP expr RP",
135989 /*  32 */ "ccons ::= DEFAULT PLUS term",
135990 /*  33 */ "ccons ::= DEFAULT MINUS term",
135991 /*  34 */ "ccons ::= DEFAULT ID|INDEXED",
135992 /*  35 */ "ccons ::= NOT NULL onconf",
135993 /*  36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
135994 /*  37 */ "ccons ::= UNIQUE onconf",
135995 /*  38 */ "ccons ::= CHECK LP expr RP",
135996 /*  39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
135997 /*  40 */ "ccons ::= defer_subclause",
135998 /*  41 */ "ccons ::= COLLATE ID|STRING",
135999 /*  42 */ "autoinc ::=",
136000 /*  43 */ "autoinc ::= AUTOINCR",
136001 /*  44 */ "refargs ::=",
136002 /*  45 */ "refargs ::= refargs refarg",
136003 /*  46 */ "refarg ::= MATCH nm",
136004 /*  47 */ "refarg ::= ON INSERT refact",
136005 /*  48 */ "refarg ::= ON DELETE refact",
136006 /*  49 */ "refarg ::= ON UPDATE refact",
136007 /*  50 */ "refact ::= SET NULL",
136008 /*  51 */ "refact ::= SET DEFAULT",
136009 /*  52 */ "refact ::= CASCADE",
136010 /*  53 */ "refact ::= RESTRICT",
136011 /*  54 */ "refact ::= NO ACTION",
136012 /*  55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
136013 /*  56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
136014 /*  57 */ "init_deferred_pred_opt ::=",
136015 /*  58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
136016 /*  59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
136017 /*  60 */ "conslist_opt ::=",
136018 /*  61 */ "tconscomma ::= COMMA",
136019 /*  62 */ "tcons ::= CONSTRAINT nm",
136020 /*  63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
136021 /*  64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
136022 /*  65 */ "tcons ::= CHECK LP expr RP onconf",
136023 /*  66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
136024 /*  67 */ "defer_subclause_opt ::=",
136025 /*  68 */ "onconf ::=",
136026 /*  69 */ "onconf ::= ON CONFLICT resolvetype",
136027 /*  70 */ "orconf ::=",
136028 /*  71 */ "orconf ::= OR resolvetype",
136029 /*  72 */ "resolvetype ::= IGNORE",
136030 /*  73 */ "resolvetype ::= REPLACE",
136031 /*  74 */ "cmd ::= DROP TABLE ifexists fullname",
136032 /*  75 */ "ifexists ::= IF EXISTS",
136033 /*  76 */ "ifexists ::=",
136034 /*  77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
136035 /*  78 */ "cmd ::= DROP VIEW ifexists fullname",
136036 /*  79 */ "cmd ::= select",
136037 /*  80 */ "select ::= with selectnowith",
136038 /*  81 */ "selectnowith ::= selectnowith multiselect_op oneselect",
136039 /*  82 */ "multiselect_op ::= UNION",
136040 /*  83 */ "multiselect_op ::= UNION ALL",
136041 /*  84 */ "multiselect_op ::= EXCEPT|INTERSECT",
136042 /*  85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
136043 /*  86 */ "values ::= VALUES LP nexprlist RP",
136044 /*  87 */ "values ::= values COMMA LP exprlist RP",
136045 /*  88 */ "distinct ::= DISTINCT",
136046 /*  89 */ "distinct ::= ALL",
136047 /*  90 */ "distinct ::=",
136048 /*  91 */ "sclp ::=",
136049 /*  92 */ "selcollist ::= sclp expr as",
136050 /*  93 */ "selcollist ::= sclp STAR",
136051 /*  94 */ "selcollist ::= sclp nm DOT STAR",
136052 /*  95 */ "as ::= AS nm",
136053 /*  96 */ "as ::=",
136054 /*  97 */ "from ::=",
136055 /*  98 */ "from ::= FROM seltablist",
136056 /*  99 */ "stl_prefix ::= seltablist joinop",
136057 /* 100 */ "stl_prefix ::=",
136058 /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
136059 /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
136060 /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
136061 /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
136062 /* 105 */ "dbnm ::=",
136063 /* 106 */ "dbnm ::= DOT nm",
136064 /* 107 */ "fullname ::= nm dbnm",
136065 /* 108 */ "joinop ::= COMMA|JOIN",
136066 /* 109 */ "joinop ::= JOIN_KW JOIN",
136067 /* 110 */ "joinop ::= JOIN_KW nm JOIN",
136068 /* 111 */ "joinop ::= JOIN_KW nm nm JOIN",
136069 /* 112 */ "on_opt ::= ON expr",
136070 /* 113 */ "on_opt ::=",
136071 /* 114 */ "indexed_opt ::=",
136072 /* 115 */ "indexed_opt ::= INDEXED BY nm",
136073 /* 116 */ "indexed_opt ::= NOT INDEXED",
136074 /* 117 */ "using_opt ::= USING LP idlist RP",
136075 /* 118 */ "using_opt ::=",
136076 /* 119 */ "orderby_opt ::=",
136077 /* 120 */ "orderby_opt ::= ORDER BY sortlist",
136078 /* 121 */ "sortlist ::= sortlist COMMA expr sortorder",
136079 /* 122 */ "sortlist ::= expr sortorder",
136080 /* 123 */ "sortorder ::= ASC",
136081 /* 124 */ "sortorder ::= DESC",
136082 /* 125 */ "sortorder ::=",
136083 /* 126 */ "groupby_opt ::=",
136084 /* 127 */ "groupby_opt ::= GROUP BY nexprlist",
136085 /* 128 */ "having_opt ::=",
136086 /* 129 */ "having_opt ::= HAVING expr",
136087 /* 130 */ "limit_opt ::=",
136088 /* 131 */ "limit_opt ::= LIMIT expr",
136089 /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr",
136090 /* 133 */ "limit_opt ::= LIMIT expr COMMA expr",
136091 /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
136092 /* 135 */ "where_opt ::=",
136093 /* 136 */ "where_opt ::= WHERE expr",
136094 /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
136095 /* 138 */ "setlist ::= setlist COMMA nm EQ expr",
136096 /* 139 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
136097 /* 140 */ "setlist ::= nm EQ expr",
136098 /* 141 */ "setlist ::= LP idlist RP EQ expr",
136099 /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
136100 /* 143 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
136101 /* 144 */ "insert_cmd ::= INSERT orconf",
136102 /* 145 */ "insert_cmd ::= REPLACE",
136103 /* 146 */ "idlist_opt ::=",
136104 /* 147 */ "idlist_opt ::= LP idlist RP",
136105 /* 148 */ "idlist ::= idlist COMMA nm",
136106 /* 149 */ "idlist ::= nm",
136107 /* 150 */ "expr ::= LP expr RP",
136108 /* 151 */ "term ::= NULL",
136109 /* 152 */ "expr ::= ID|INDEXED",
136110 /* 153 */ "expr ::= JOIN_KW",
136111 /* 154 */ "expr ::= nm DOT nm",
136112 /* 155 */ "expr ::= nm DOT nm DOT nm",
136113 /* 156 */ "term ::= FLOAT|BLOB",
136114 /* 157 */ "term ::= STRING",
136115 /* 158 */ "term ::= INTEGER",
136116 /* 159 */ "expr ::= VARIABLE",
136117 /* 160 */ "expr ::= expr COLLATE ID|STRING",
136118 /* 161 */ "expr ::= CAST LP expr AS typetoken RP",
136119 /* 162 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
136120 /* 163 */ "expr ::= ID|INDEXED LP STAR RP",
136121 /* 164 */ "term ::= CTIME_KW",
136122 /* 165 */ "expr ::= LP nexprlist COMMA expr RP",
136123 /* 166 */ "expr ::= expr AND expr",
136124 /* 167 */ "expr ::= expr OR expr",
136125 /* 168 */ "expr ::= expr LT|GT|GE|LE expr",
136126 /* 169 */ "expr ::= expr EQ|NE expr",
136127 /* 170 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
136128 /* 171 */ "expr ::= expr PLUS|MINUS expr",
136129 /* 172 */ "expr ::= expr STAR|SLASH|REM expr",
136130 /* 173 */ "expr ::= expr CONCAT expr",
136131 /* 174 */ "likeop ::= NOT LIKE_KW|MATCH",
136132 /* 175 */ "expr ::= expr likeop expr",
136133 /* 176 */ "expr ::= expr likeop expr ESCAPE expr",
136134 /* 177 */ "expr ::= expr ISNULL|NOTNULL",
136135 /* 178 */ "expr ::= expr NOT NULL",
136136 /* 179 */ "expr ::= expr IS expr",
136137 /* 180 */ "expr ::= expr IS NOT expr",
136138 /* 181 */ "expr ::= NOT expr",
136139 /* 182 */ "expr ::= BITNOT expr",
136140 /* 183 */ "expr ::= MINUS expr",
136141 /* 184 */ "expr ::= PLUS expr",
136142 /* 185 */ "between_op ::= BETWEEN",
136143 /* 186 */ "between_op ::= NOT BETWEEN",
136144 /* 187 */ "expr ::= expr between_op expr AND expr",
136145 /* 188 */ "in_op ::= IN",
136146 /* 189 */ "in_op ::= NOT IN",
136147 /* 190 */ "expr ::= expr in_op LP exprlist RP",
136148 /* 191 */ "expr ::= LP select RP",
136149 /* 192 */ "expr ::= expr in_op LP select RP",
136150 /* 193 */ "expr ::= expr in_op nm dbnm paren_exprlist",
136151 /* 194 */ "expr ::= EXISTS LP select RP",
136152 /* 195 */ "expr ::= CASE case_operand case_exprlist case_else END",
136153 /* 196 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
136154 /* 197 */ "case_exprlist ::= WHEN expr THEN expr",
136155 /* 198 */ "case_else ::= ELSE expr",
136156 /* 199 */ "case_else ::=",
136157 /* 200 */ "case_operand ::= expr",
136158 /* 201 */ "case_operand ::=",
136159 /* 202 */ "exprlist ::=",
136160 /* 203 */ "nexprlist ::= nexprlist COMMA expr",
136161 /* 204 */ "nexprlist ::= expr",
136162 /* 205 */ "paren_exprlist ::=",
136163 /* 206 */ "paren_exprlist ::= LP exprlist RP",
136164 /* 207 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
136165 /* 208 */ "uniqueflag ::= UNIQUE",
136166 /* 209 */ "uniqueflag ::=",
136167 /* 210 */ "eidlist_opt ::=",
136168 /* 211 */ "eidlist_opt ::= LP eidlist RP",
136169 /* 212 */ "eidlist ::= eidlist COMMA nm collate sortorder",
136170 /* 213 */ "eidlist ::= nm collate sortorder",
136171 /* 214 */ "collate ::=",
136172 /* 215 */ "collate ::= COLLATE ID|STRING",
136173 /* 216 */ "cmd ::= DROP INDEX ifexists fullname",
136174 /* 217 */ "cmd ::= VACUUM",
136175 /* 218 */ "cmd ::= VACUUM nm",
136176 /* 219 */ "cmd ::= PRAGMA nm dbnm",
136177 /* 220 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
136178 /* 221 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
136179 /* 222 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
136180 /* 223 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
136181 /* 224 */ "plus_num ::= PLUS INTEGER|FLOAT",
136182 /* 225 */ "minus_num ::= MINUS INTEGER|FLOAT",
136183 /* 226 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
136184 /* 227 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
136185 /* 228 */ "trigger_time ::= BEFORE",
136186 /* 229 */ "trigger_time ::= AFTER",
136187 /* 230 */ "trigger_time ::= INSTEAD OF",
136188 /* 231 */ "trigger_time ::=",
136189 /* 232 */ "trigger_event ::= DELETE|INSERT",
136190 /* 233 */ "trigger_event ::= UPDATE",
136191 /* 234 */ "trigger_event ::= UPDATE OF idlist",
136192 /* 235 */ "when_clause ::=",
136193 /* 236 */ "when_clause ::= WHEN expr",
136194 /* 237 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
136195 /* 238 */ "trigger_cmd_list ::= trigger_cmd SEMI",
136196 /* 239 */ "trnm ::= nm DOT nm",
136197 /* 240 */ "tridxby ::= INDEXED BY nm",
136198 /* 241 */ "tridxby ::= NOT INDEXED",
136199 /* 242 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
136200 /* 243 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
136201 /* 244 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
136202 /* 245 */ "trigger_cmd ::= select",
136203 /* 246 */ "expr ::= RAISE LP IGNORE RP",
136204 /* 247 */ "expr ::= RAISE LP raisetype COMMA nm RP",
136205 /* 248 */ "raisetype ::= ROLLBACK",
136206 /* 249 */ "raisetype ::= ABORT",
136207 /* 250 */ "raisetype ::= FAIL",
136208 /* 251 */ "cmd ::= DROP TRIGGER ifexists fullname",
136209 /* 252 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
136210 /* 253 */ "cmd ::= DETACH database_kw_opt expr",
136211 /* 254 */ "key_opt ::=",
136212 /* 255 */ "key_opt ::= KEY expr",
136213 /* 256 */ "cmd ::= REINDEX",
136214 /* 257 */ "cmd ::= REINDEX nm dbnm",
136215 /* 258 */ "cmd ::= ANALYZE",
136216 /* 259 */ "cmd ::= ANALYZE nm dbnm",
136217 /* 260 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
136218 /* 261 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
136219 /* 262 */ "add_column_fullname ::= fullname",
136220 /* 263 */ "cmd ::= create_vtab",
136221 /* 264 */ "cmd ::= create_vtab LP vtabarglist RP",
136222 /* 265 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
136223 /* 266 */ "vtabarg ::=",
136224 /* 267 */ "vtabargtoken ::= ANY",
136225 /* 268 */ "vtabargtoken ::= lp anylist RP",
136226 /* 269 */ "lp ::= LP",
136227 /* 270 */ "with ::=",
136228 /* 271 */ "with ::= WITH wqlist",
136229 /* 272 */ "with ::= WITH RECURSIVE wqlist",
136230 /* 273 */ "wqlist ::= nm eidlist_opt AS LP select RP",
136231 /* 274 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
136232 /* 275 */ "input ::= cmdlist",
136233 /* 276 */ "cmdlist ::= cmdlist ecmd",
136234 /* 277 */ "cmdlist ::= ecmd",
136235 /* 278 */ "ecmd ::= SEMI",
136236 /* 279 */ "ecmd ::= explain cmdx SEMI",
136237 /* 280 */ "explain ::=",
136238 /* 281 */ "trans_opt ::=",
136239 /* 282 */ "trans_opt ::= TRANSACTION",
136240 /* 283 */ "trans_opt ::= TRANSACTION nm",
136241 /* 284 */ "savepoint_opt ::= SAVEPOINT",
136242 /* 285 */ "savepoint_opt ::=",
136243 /* 286 */ "cmd ::= create_table create_table_args",
136244 /* 287 */ "columnlist ::= columnlist COMMA columnname carglist",
136245 /* 288 */ "columnlist ::= columnname carglist",
136246 /* 289 */ "nm ::= ID|INDEXED",
136247 /* 290 */ "nm ::= STRING",
136248 /* 291 */ "nm ::= JOIN_KW",
136249 /* 292 */ "typetoken ::= typename",
136250 /* 293 */ "typename ::= ID|STRING",
136251 /* 294 */ "signed ::= plus_num",
136252 /* 295 */ "signed ::= minus_num",
136253 /* 296 */ "carglist ::= carglist ccons",
136254 /* 297 */ "carglist ::=",
136255 /* 298 */ "ccons ::= NULL onconf",
136256 /* 299 */ "conslist_opt ::= COMMA conslist",
136257 /* 300 */ "conslist ::= conslist tconscomma tcons",
136258 /* 301 */ "conslist ::= tcons",
136259 /* 302 */ "tconscomma ::=",
136260 /* 303 */ "defer_subclause_opt ::= defer_subclause",
136261 /* 304 */ "resolvetype ::= raisetype",
136262 /* 305 */ "selectnowith ::= oneselect",
136263 /* 306 */ "oneselect ::= values",
136264 /* 307 */ "sclp ::= selcollist COMMA",
136265 /* 308 */ "as ::= ID|STRING",
136266 /* 309 */ "expr ::= term",
136267 /* 310 */ "likeop ::= LIKE_KW|MATCH",
136268 /* 311 */ "exprlist ::= nexprlist",
136269 /* 312 */ "nmnum ::= plus_num",
136270 /* 313 */ "nmnum ::= nm",
136271 /* 314 */ "nmnum ::= ON",
136272 /* 315 */ "nmnum ::= DELETE",
136273 /* 316 */ "nmnum ::= DEFAULT",
136274 /* 317 */ "plus_num ::= INTEGER|FLOAT",
136275 /* 318 */ "foreach_clause ::=",
136276 /* 319 */ "foreach_clause ::= FOR EACH ROW",
136277 /* 320 */ "trnm ::= nm",
136278 /* 321 */ "tridxby ::=",
136279 /* 322 */ "database_kw_opt ::= DATABASE",
136280 /* 323 */ "database_kw_opt ::=",
136281 /* 324 */ "kwcolumn_opt ::=",
136282 /* 325 */ "kwcolumn_opt ::= COLUMNKW",
136283 /* 326 */ "vtabarglist ::= vtabarg",
136284 /* 327 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
136285 /* 328 */ "vtabarg ::= vtabarg vtabargtoken",
136286 /* 329 */ "anylist ::=",
136287 /* 330 */ "anylist ::= anylist LP anylist RP",
136288 /* 331 */ "anylist ::= anylist ANY",
136289};
136290#endif /* NDEBUG */
136291
136292
136293#if YYSTACKDEPTH<=0
136294/*
136295** Try to increase the size of the parser stack.  Return the number
136296** of errors.  Return 0 on success.
136297*/
136298static int yyGrowStack(yyParser *p){
136299  int newSize;
136300  int idx;
136301  yyStackEntry *pNew;
136302
136303  newSize = p->yystksz*2 + 100;
136304  idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
136305  if( p->yystack==&p->yystk0 ){
136306    pNew = malloc(newSize*sizeof(pNew[0]));
136307    if( pNew ) pNew[0] = p->yystk0;
136308  }else{
136309    pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
136310  }
136311  if( pNew ){
136312    p->yystack = pNew;
136313    p->yytos = &p->yystack[idx];
136314#ifndef NDEBUG
136315    if( yyTraceFILE ){
136316      fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
136317              yyTracePrompt, p->yystksz, newSize);
136318    }
136319#endif
136320    p->yystksz = newSize;
136321  }
136322  return pNew==0;
136323}
136324#endif
136325
136326/* Datatype of the argument to the memory allocated passed as the
136327** second argument to sqlite3ParserAlloc() below.  This can be changed by
136328** putting an appropriate #define in the %include section of the input
136329** grammar.
136330*/
136331#ifndef YYMALLOCARGTYPE
136332# define YYMALLOCARGTYPE size_t
136333#endif
136334
136335/* Initialize a new parser that has already been allocated.
136336*/
136337SQLITE_PRIVATE void sqlite3ParserInit(void *yypParser){
136338  yyParser *pParser = (yyParser*)yypParser;
136339#ifdef YYTRACKMAXSTACKDEPTH
136340  pParser->yyhwm = 0;
136341#endif
136342#if YYSTACKDEPTH<=0
136343  pParser->yytos = NULL;
136344  pParser->yystack = NULL;
136345  pParser->yystksz = 0;
136346  if( yyGrowStack(pParser) ){
136347    pParser->yystack = &pParser->yystk0;
136348    pParser->yystksz = 1;
136349  }
136350#endif
136351#ifndef YYNOERRORRECOVERY
136352  pParser->yyerrcnt = -1;
136353#endif
136354  pParser->yytos = pParser->yystack;
136355  pParser->yystack[0].stateno = 0;
136356  pParser->yystack[0].major = 0;
136357}
136358
136359#ifndef sqlite3Parser_ENGINEALWAYSONSTACK
136360/*
136361** This function allocates a new parser.
136362** The only argument is a pointer to a function which works like
136363** malloc.
136364**
136365** Inputs:
136366** A pointer to the function used to allocate memory.
136367**
136368** Outputs:
136369** A pointer to a parser.  This pointer is used in subsequent calls
136370** to sqlite3Parser and sqlite3ParserFree.
136371*/
136372SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
136373  yyParser *pParser;
136374  pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
136375  if( pParser ) sqlite3ParserInit(pParser);
136376  return pParser;
136377}
136378#endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
136379
136380
136381/* The following function deletes the "minor type" or semantic value
136382** associated with a symbol.  The symbol can be either a terminal
136383** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
136384** a pointer to the value to be deleted.  The code used to do the
136385** deletions is derived from the %destructor and/or %token_destructor
136386** directives of the input grammar.
136387*/
136388static void yy_destructor(
136389  yyParser *yypParser,    /* The parser */
136390  YYCODETYPE yymajor,     /* Type code for object to destroy */
136391  YYMINORTYPE *yypminor   /* The object to be destroyed */
136392){
136393  sqlite3ParserARG_FETCH;
136394  switch( yymajor ){
136395    /* Here is inserted the actions which take place when a
136396    ** terminal or non-terminal is destroyed.  This can happen
136397    ** when the symbol is popped from the stack during a
136398    ** reduce or during error processing or when a parser is
136399    ** being destroyed before it is finished parsing.
136400    **
136401    ** Note: during a reduce, the only symbols destroyed are those
136402    ** which appear on the RHS of the rule, but which are *not* used
136403    ** inside the C code.
136404    */
136405/********* Begin destructor definitions ***************************************/
136406    case 163: /* select */
136407    case 194: /* selectnowith */
136408    case 195: /* oneselect */
136409    case 206: /* values */
136410{
136411sqlite3SelectDelete(pParse->db, (yypminor->yy243));
136412}
136413      break;
136414    case 172: /* term */
136415    case 173: /* expr */
136416{
136417sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr);
136418}
136419      break;
136420    case 177: /* eidlist_opt */
136421    case 186: /* sortlist */
136422    case 187: /* eidlist */
136423    case 199: /* selcollist */
136424    case 202: /* groupby_opt */
136425    case 204: /* orderby_opt */
136426    case 207: /* nexprlist */
136427    case 208: /* exprlist */
136428    case 209: /* sclp */
136429    case 218: /* setlist */
136430    case 224: /* paren_exprlist */
136431    case 226: /* case_exprlist */
136432{
136433sqlite3ExprListDelete(pParse->db, (yypminor->yy148));
136434}
136435      break;
136436    case 193: /* fullname */
136437    case 200: /* from */
136438    case 211: /* seltablist */
136439    case 212: /* stl_prefix */
136440{
136441sqlite3SrcListDelete(pParse->db, (yypminor->yy185));
136442}
136443      break;
136444    case 196: /* with */
136445    case 250: /* wqlist */
136446{
136447sqlite3WithDelete(pParse->db, (yypminor->yy285));
136448}
136449      break;
136450    case 201: /* where_opt */
136451    case 203: /* having_opt */
136452    case 215: /* on_opt */
136453    case 225: /* case_operand */
136454    case 227: /* case_else */
136455    case 236: /* when_clause */
136456    case 241: /* key_opt */
136457{
136458sqlite3ExprDelete(pParse->db, (yypminor->yy72));
136459}
136460      break;
136461    case 216: /* using_opt */
136462    case 217: /* idlist */
136463    case 220: /* idlist_opt */
136464{
136465sqlite3IdListDelete(pParse->db, (yypminor->yy254));
136466}
136467      break;
136468    case 232: /* trigger_cmd_list */
136469    case 237: /* trigger_cmd */
136470{
136471sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145));
136472}
136473      break;
136474    case 234: /* trigger_event */
136475{
136476sqlite3IdListDelete(pParse->db, (yypminor->yy332).b);
136477}
136478      break;
136479/********* End destructor definitions *****************************************/
136480    default:  break;   /* If no destructor action specified: do nothing */
136481  }
136482}
136483
136484/*
136485** Pop the parser's stack once.
136486**
136487** If there is a destructor routine associated with the token which
136488** is popped from the stack, then call it.
136489*/
136490static void yy_pop_parser_stack(yyParser *pParser){
136491  yyStackEntry *yytos;
136492  assert( pParser->yytos!=0 );
136493  assert( pParser->yytos > pParser->yystack );
136494  yytos = pParser->yytos--;
136495#ifndef NDEBUG
136496  if( yyTraceFILE ){
136497    fprintf(yyTraceFILE,"%sPopping %s\n",
136498      yyTracePrompt,
136499      yyTokenName[yytos->major]);
136500  }
136501#endif
136502  yy_destructor(pParser, yytos->major, &yytos->minor);
136503}
136504
136505/*
136506** Clear all secondary memory allocations from the parser
136507*/
136508SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
136509  yyParser *pParser = (yyParser*)p;
136510  while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
136511#if YYSTACKDEPTH<=0
136512  if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
136513#endif
136514}
136515
136516#ifndef sqlite3Parser_ENGINEALWAYSONSTACK
136517/*
136518** Deallocate and destroy a parser.  Destructors are called for
136519** all stack elements before shutting the parser down.
136520**
136521** If the YYPARSEFREENEVERNULL macro exists (for example because it
136522** is defined in a %include section of the input grammar) then it is
136523** assumed that the input pointer is never NULL.
136524*/
136525SQLITE_PRIVATE void sqlite3ParserFree(
136526  void *p,                    /* The parser to be deleted */
136527  void (*freeProc)(void*)     /* Function used to reclaim memory */
136528){
136529#ifndef YYPARSEFREENEVERNULL
136530  if( p==0 ) return;
136531#endif
136532  sqlite3ParserFinalize(p);
136533  (*freeProc)(p);
136534}
136535#endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
136536
136537/*
136538** Return the peak depth of the stack for a parser.
136539*/
136540#ifdef YYTRACKMAXSTACKDEPTH
136541SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
136542  yyParser *pParser = (yyParser*)p;
136543  return pParser->yyhwm;
136544}
136545#endif
136546
136547/*
136548** Find the appropriate action for a parser given the terminal
136549** look-ahead token iLookAhead.
136550*/
136551static unsigned int yy_find_shift_action(
136552  yyParser *pParser,        /* The parser */
136553  YYCODETYPE iLookAhead     /* The look-ahead token */
136554){
136555  int i;
136556  int stateno = pParser->yytos->stateno;
136557
136558  if( stateno>=YY_MIN_REDUCE ) return stateno;
136559  assert( stateno <= YY_SHIFT_COUNT );
136560  do{
136561    i = yy_shift_ofst[stateno];
136562    assert( iLookAhead!=YYNOCODE );
136563    i += iLookAhead;
136564    if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
136565#ifdef YYFALLBACK
136566      YYCODETYPE iFallback;            /* Fallback token */
136567      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
136568             && (iFallback = yyFallback[iLookAhead])!=0 ){
136569#ifndef NDEBUG
136570        if( yyTraceFILE ){
136571          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
136572             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
136573        }
136574#endif
136575        assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
136576        iLookAhead = iFallback;
136577        continue;
136578      }
136579#endif
136580#ifdef YYWILDCARD
136581      {
136582        int j = i - iLookAhead + YYWILDCARD;
136583        if(
136584#if YY_SHIFT_MIN+YYWILDCARD<0
136585          j>=0 &&
136586#endif
136587#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
136588          j<YY_ACTTAB_COUNT &&
136589#endif
136590          yy_lookahead[j]==YYWILDCARD && iLookAhead>0
136591        ){
136592#ifndef NDEBUG
136593          if( yyTraceFILE ){
136594            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
136595               yyTracePrompt, yyTokenName[iLookAhead],
136596               yyTokenName[YYWILDCARD]);
136597          }
136598#endif /* NDEBUG */
136599          return yy_action[j];
136600        }
136601      }
136602#endif /* YYWILDCARD */
136603      return yy_default[stateno];
136604    }else{
136605      return yy_action[i];
136606    }
136607  }while(1);
136608}
136609
136610/*
136611** Find the appropriate action for a parser given the non-terminal
136612** look-ahead token iLookAhead.
136613*/
136614static int yy_find_reduce_action(
136615  int stateno,              /* Current state number */
136616  YYCODETYPE iLookAhead     /* The look-ahead token */
136617){
136618  int i;
136619#ifdef YYERRORSYMBOL
136620  if( stateno>YY_REDUCE_COUNT ){
136621    return yy_default[stateno];
136622  }
136623#else
136624  assert( stateno<=YY_REDUCE_COUNT );
136625#endif
136626  i = yy_reduce_ofst[stateno];
136627  assert( i!=YY_REDUCE_USE_DFLT );
136628  assert( iLookAhead!=YYNOCODE );
136629  i += iLookAhead;
136630#ifdef YYERRORSYMBOL
136631  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
136632    return yy_default[stateno];
136633  }
136634#else
136635  assert( i>=0 && i<YY_ACTTAB_COUNT );
136636  assert( yy_lookahead[i]==iLookAhead );
136637#endif
136638  return yy_action[i];
136639}
136640
136641/*
136642** The following routine is called if the stack overflows.
136643*/
136644static void yyStackOverflow(yyParser *yypParser){
136645   sqlite3ParserARG_FETCH;
136646#ifndef NDEBUG
136647   if( yyTraceFILE ){
136648     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
136649   }
136650#endif
136651   while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
136652   /* Here code is inserted which will execute if the parser
136653   ** stack every overflows */
136654/******** Begin %stack_overflow code ******************************************/
136655
136656  sqlite3ErrorMsg(pParse, "parser stack overflow");
136657/******** End %stack_overflow code ********************************************/
136658   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
136659}
136660
136661/*
136662** Print tracing information for a SHIFT action
136663*/
136664#ifndef NDEBUG
136665static void yyTraceShift(yyParser *yypParser, int yyNewState){
136666  if( yyTraceFILE ){
136667    if( yyNewState<YYNSTATE ){
136668      fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
136669         yyTracePrompt,yyTokenName[yypParser->yytos->major],
136670         yyNewState);
136671    }else{
136672      fprintf(yyTraceFILE,"%sShift '%s'\n",
136673         yyTracePrompt,yyTokenName[yypParser->yytos->major]);
136674    }
136675  }
136676}
136677#else
136678# define yyTraceShift(X,Y)
136679#endif
136680
136681/*
136682** Perform a shift action.
136683*/
136684static void yy_shift(
136685  yyParser *yypParser,          /* The parser to be shifted */
136686  int yyNewState,               /* The new state to shift in */
136687  int yyMajor,                  /* The major token to shift in */
136688  sqlite3ParserTOKENTYPE yyMinor        /* The minor token to shift in */
136689){
136690  yyStackEntry *yytos;
136691  yypParser->yytos++;
136692#ifdef YYTRACKMAXSTACKDEPTH
136693  if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
136694    yypParser->yyhwm++;
136695    assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
136696  }
136697#endif
136698#if YYSTACKDEPTH>0
136699  if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH] ){
136700    yypParser->yytos--;
136701    yyStackOverflow(yypParser);
136702    return;
136703  }
136704#else
136705  if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
136706    if( yyGrowStack(yypParser) ){
136707      yypParser->yytos--;
136708      yyStackOverflow(yypParser);
136709      return;
136710    }
136711  }
136712#endif
136713  if( yyNewState > YY_MAX_SHIFT ){
136714    yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
136715  }
136716  yytos = yypParser->yytos;
136717  yytos->stateno = (YYACTIONTYPE)yyNewState;
136718  yytos->major = (YYCODETYPE)yyMajor;
136719  yytos->minor.yy0 = yyMinor;
136720  yyTraceShift(yypParser, yyNewState);
136721}
136722
136723/* The following table contains information about every rule that
136724** is used during the reduce.
136725*/
136726static const struct {
136727  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
136728  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
136729} yyRuleInfo[] = {
136730  { 147, 1 },
136731  { 147, 3 },
136732  { 148, 1 },
136733  { 149, 3 },
136734  { 150, 0 },
136735  { 150, 1 },
136736  { 150, 1 },
136737  { 150, 1 },
136738  { 149, 2 },
136739  { 149, 2 },
136740  { 149, 2 },
136741  { 149, 2 },
136742  { 149, 3 },
136743  { 149, 5 },
136744  { 154, 6 },
136745  { 156, 1 },
136746  { 158, 0 },
136747  { 158, 3 },
136748  { 157, 1 },
136749  { 157, 0 },
136750  { 155, 5 },
136751  { 155, 2 },
136752  { 162, 0 },
136753  { 162, 2 },
136754  { 164, 2 },
136755  { 166, 0 },
136756  { 166, 4 },
136757  { 166, 6 },
136758  { 167, 2 },
136759  { 171, 2 },
136760  { 171, 2 },
136761  { 171, 4 },
136762  { 171, 3 },
136763  { 171, 3 },
136764  { 171, 2 },
136765  { 171, 3 },
136766  { 171, 5 },
136767  { 171, 2 },
136768  { 171, 4 },
136769  { 171, 4 },
136770  { 171, 1 },
136771  { 171, 2 },
136772  { 176, 0 },
136773  { 176, 1 },
136774  { 178, 0 },
136775  { 178, 2 },
136776  { 180, 2 },
136777  { 180, 3 },
136778  { 180, 3 },
136779  { 180, 3 },
136780  { 181, 2 },
136781  { 181, 2 },
136782  { 181, 1 },
136783  { 181, 1 },
136784  { 181, 2 },
136785  { 179, 3 },
136786  { 179, 2 },
136787  { 182, 0 },
136788  { 182, 2 },
136789  { 182, 2 },
136790  { 161, 0 },
136791  { 184, 1 },
136792  { 185, 2 },
136793  { 185, 7 },
136794  { 185, 5 },
136795  { 185, 5 },
136796  { 185, 10 },
136797  { 188, 0 },
136798  { 174, 0 },
136799  { 174, 3 },
136800  { 189, 0 },
136801  { 189, 2 },
136802  { 190, 1 },
136803  { 190, 1 },
136804  { 149, 4 },
136805  { 192, 2 },
136806  { 192, 0 },
136807  { 149, 9 },
136808  { 149, 4 },
136809  { 149, 1 },
136810  { 163, 2 },
136811  { 194, 3 },
136812  { 197, 1 },
136813  { 197, 2 },
136814  { 197, 1 },
136815  { 195, 9 },
136816  { 206, 4 },
136817  { 206, 5 },
136818  { 198, 1 },
136819  { 198, 1 },
136820  { 198, 0 },
136821  { 209, 0 },
136822  { 199, 3 },
136823  { 199, 2 },
136824  { 199, 4 },
136825  { 210, 2 },
136826  { 210, 0 },
136827  { 200, 0 },
136828  { 200, 2 },
136829  { 212, 2 },
136830  { 212, 0 },
136831  { 211, 7 },
136832  { 211, 9 },
136833  { 211, 7 },
136834  { 211, 7 },
136835  { 159, 0 },
136836  { 159, 2 },
136837  { 193, 2 },
136838  { 213, 1 },
136839  { 213, 2 },
136840  { 213, 3 },
136841  { 213, 4 },
136842  { 215, 2 },
136843  { 215, 0 },
136844  { 214, 0 },
136845  { 214, 3 },
136846  { 214, 2 },
136847  { 216, 4 },
136848  { 216, 0 },
136849  { 204, 0 },
136850  { 204, 3 },
136851  { 186, 4 },
136852  { 186, 2 },
136853  { 175, 1 },
136854  { 175, 1 },
136855  { 175, 0 },
136856  { 202, 0 },
136857  { 202, 3 },
136858  { 203, 0 },
136859  { 203, 2 },
136860  { 205, 0 },
136861  { 205, 2 },
136862  { 205, 4 },
136863  { 205, 4 },
136864  { 149, 6 },
136865  { 201, 0 },
136866  { 201, 2 },
136867  { 149, 8 },
136868  { 218, 5 },
136869  { 218, 7 },
136870  { 218, 3 },
136871  { 218, 5 },
136872  { 149, 6 },
136873  { 149, 7 },
136874  { 219, 2 },
136875  { 219, 1 },
136876  { 220, 0 },
136877  { 220, 3 },
136878  { 217, 3 },
136879  { 217, 1 },
136880  { 173, 3 },
136881  { 172, 1 },
136882  { 173, 1 },
136883  { 173, 1 },
136884  { 173, 3 },
136885  { 173, 5 },
136886  { 172, 1 },
136887  { 172, 1 },
136888  { 172, 1 },
136889  { 173, 1 },
136890  { 173, 3 },
136891  { 173, 6 },
136892  { 173, 5 },
136893  { 173, 4 },
136894  { 172, 1 },
136895  { 173, 5 },
136896  { 173, 3 },
136897  { 173, 3 },
136898  { 173, 3 },
136899  { 173, 3 },
136900  { 173, 3 },
136901  { 173, 3 },
136902  { 173, 3 },
136903  { 173, 3 },
136904  { 221, 2 },
136905  { 173, 3 },
136906  { 173, 5 },
136907  { 173, 2 },
136908  { 173, 3 },
136909  { 173, 3 },
136910  { 173, 4 },
136911  { 173, 2 },
136912  { 173, 2 },
136913  { 173, 2 },
136914  { 173, 2 },
136915  { 222, 1 },
136916  { 222, 2 },
136917  { 173, 5 },
136918  { 223, 1 },
136919  { 223, 2 },
136920  { 173, 5 },
136921  { 173, 3 },
136922  { 173, 5 },
136923  { 173, 5 },
136924  { 173, 4 },
136925  { 173, 5 },
136926  { 226, 5 },
136927  { 226, 4 },
136928  { 227, 2 },
136929  { 227, 0 },
136930  { 225, 1 },
136931  { 225, 0 },
136932  { 208, 0 },
136933  { 207, 3 },
136934  { 207, 1 },
136935  { 224, 0 },
136936  { 224, 3 },
136937  { 149, 12 },
136938  { 228, 1 },
136939  { 228, 0 },
136940  { 177, 0 },
136941  { 177, 3 },
136942  { 187, 5 },
136943  { 187, 3 },
136944  { 229, 0 },
136945  { 229, 2 },
136946  { 149, 4 },
136947  { 149, 1 },
136948  { 149, 2 },
136949  { 149, 3 },
136950  { 149, 5 },
136951  { 149, 6 },
136952  { 149, 5 },
136953  { 149, 6 },
136954  { 169, 2 },
136955  { 170, 2 },
136956  { 149, 5 },
136957  { 231, 11 },
136958  { 233, 1 },
136959  { 233, 1 },
136960  { 233, 2 },
136961  { 233, 0 },
136962  { 234, 1 },
136963  { 234, 1 },
136964  { 234, 3 },
136965  { 236, 0 },
136966  { 236, 2 },
136967  { 232, 3 },
136968  { 232, 2 },
136969  { 238, 3 },
136970  { 239, 3 },
136971  { 239, 2 },
136972  { 237, 7 },
136973  { 237, 5 },
136974  { 237, 5 },
136975  { 237, 1 },
136976  { 173, 4 },
136977  { 173, 6 },
136978  { 191, 1 },
136979  { 191, 1 },
136980  { 191, 1 },
136981  { 149, 4 },
136982  { 149, 6 },
136983  { 149, 3 },
136984  { 241, 0 },
136985  { 241, 2 },
136986  { 149, 1 },
136987  { 149, 3 },
136988  { 149, 1 },
136989  { 149, 3 },
136990  { 149, 6 },
136991  { 149, 7 },
136992  { 242, 1 },
136993  { 149, 1 },
136994  { 149, 4 },
136995  { 244, 8 },
136996  { 246, 0 },
136997  { 247, 1 },
136998  { 247, 3 },
136999  { 248, 1 },
137000  { 196, 0 },
137001  { 196, 2 },
137002  { 196, 3 },
137003  { 250, 6 },
137004  { 250, 8 },
137005  { 144, 1 },
137006  { 145, 2 },
137007  { 145, 1 },
137008  { 146, 1 },
137009  { 146, 3 },
137010  { 147, 0 },
137011  { 151, 0 },
137012  { 151, 1 },
137013  { 151, 2 },
137014  { 153, 1 },
137015  { 153, 0 },
137016  { 149, 2 },
137017  { 160, 4 },
137018  { 160, 2 },
137019  { 152, 1 },
137020  { 152, 1 },
137021  { 152, 1 },
137022  { 166, 1 },
137023  { 167, 1 },
137024  { 168, 1 },
137025  { 168, 1 },
137026  { 165, 2 },
137027  { 165, 0 },
137028  { 171, 2 },
137029  { 161, 2 },
137030  { 183, 3 },
137031  { 183, 1 },
137032  { 184, 0 },
137033  { 188, 1 },
137034  { 190, 1 },
137035  { 194, 1 },
137036  { 195, 1 },
137037  { 209, 2 },
137038  { 210, 1 },
137039  { 173, 1 },
137040  { 221, 1 },
137041  { 208, 1 },
137042  { 230, 1 },
137043  { 230, 1 },
137044  { 230, 1 },
137045  { 230, 1 },
137046  { 230, 1 },
137047  { 169, 1 },
137048  { 235, 0 },
137049  { 235, 3 },
137050  { 238, 1 },
137051  { 239, 0 },
137052  { 240, 1 },
137053  { 240, 0 },
137054  { 243, 0 },
137055  { 243, 1 },
137056  { 245, 1 },
137057  { 245, 3 },
137058  { 246, 2 },
137059  { 249, 0 },
137060  { 249, 4 },
137061  { 249, 2 },
137062};
137063
137064static void yy_accept(yyParser*);  /* Forward Declaration */
137065
137066/*
137067** Perform a reduce action and the shift that must immediately
137068** follow the reduce.
137069*/
137070static void yy_reduce(
137071  yyParser *yypParser,         /* The parser */
137072  unsigned int yyruleno        /* Number of the rule by which to reduce */
137073){
137074  int yygoto;                     /* The next state */
137075  int yyact;                      /* The next action */
137076  yyStackEntry *yymsp;            /* The top of the parser's stack */
137077  int yysize;                     /* Amount to pop the stack */
137078  sqlite3ParserARG_FETCH;
137079  yymsp = yypParser->yytos;
137080#ifndef NDEBUG
137081  if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
137082    yysize = yyRuleInfo[yyruleno].nrhs;
137083    fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
137084      yyRuleName[yyruleno], yymsp[-yysize].stateno);
137085  }
137086#endif /* NDEBUG */
137087
137088  /* Check that the stack is large enough to grow by a single entry
137089  ** if the RHS of the rule is empty.  This ensures that there is room
137090  ** enough on the stack to push the LHS value */
137091  if( yyRuleInfo[yyruleno].nrhs==0 ){
137092#ifdef YYTRACKMAXSTACKDEPTH
137093    if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
137094      yypParser->yyhwm++;
137095      assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
137096    }
137097#endif
137098#if YYSTACKDEPTH>0
137099    if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH-1] ){
137100      yyStackOverflow(yypParser);
137101      return;
137102    }
137103#else
137104    if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
137105      if( yyGrowStack(yypParser) ){
137106        yyStackOverflow(yypParser);
137107        return;
137108      }
137109      yymsp = yypParser->yytos;
137110    }
137111#endif
137112  }
137113
137114  switch( yyruleno ){
137115  /* Beginning here are the reduction cases.  A typical example
137116  ** follows:
137117  **   case 0:
137118  **  #line <lineno> <grammarfile>
137119  **     { ... }           // User supplied code
137120  **  #line <lineno> <thisfile>
137121  **     break;
137122  */
137123/********** Begin reduce actions **********************************************/
137124        YYMINORTYPE yylhsminor;
137125      case 0: /* explain ::= EXPLAIN */
137126{ pParse->explain = 1; }
137127        break;
137128      case 1: /* explain ::= EXPLAIN QUERY PLAN */
137129{ pParse->explain = 2; }
137130        break;
137131      case 2: /* cmdx ::= cmd */
137132{ sqlite3FinishCoding(pParse); }
137133        break;
137134      case 3: /* cmd ::= BEGIN transtype trans_opt */
137135{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);}
137136        break;
137137      case 4: /* transtype ::= */
137138{yymsp[1].minor.yy194 = TK_DEFERRED;}
137139        break;
137140      case 5: /* transtype ::= DEFERRED */
137141      case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
137142      case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
137143{yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/}
137144        break;
137145      case 8: /* cmd ::= COMMIT trans_opt */
137146      case 9: /* cmd ::= END trans_opt */ yytestcase(yyruleno==9);
137147{sqlite3CommitTransaction(pParse);}
137148        break;
137149      case 10: /* cmd ::= ROLLBACK trans_opt */
137150{sqlite3RollbackTransaction(pParse);}
137151        break;
137152      case 11: /* cmd ::= SAVEPOINT nm */
137153{
137154  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
137155}
137156        break;
137157      case 12: /* cmd ::= RELEASE savepoint_opt nm */
137158{
137159  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
137160}
137161        break;
137162      case 13: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
137163{
137164  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
137165}
137166        break;
137167      case 14: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
137168{
137169   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194);
137170}
137171        break;
137172      case 15: /* createkw ::= CREATE */
137173{disableLookaside(pParse);}
137174        break;
137175      case 16: /* ifnotexists ::= */
137176      case 19: /* temp ::= */ yytestcase(yyruleno==19);
137177      case 22: /* table_options ::= */ yytestcase(yyruleno==22);
137178      case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
137179      case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
137180      case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
137181      case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
137182      case 90: /* distinct ::= */ yytestcase(yyruleno==90);
137183      case 214: /* collate ::= */ yytestcase(yyruleno==214);
137184{yymsp[1].minor.yy194 = 0;}
137185        break;
137186      case 17: /* ifnotexists ::= IF NOT EXISTS */
137187{yymsp[-2].minor.yy194 = 1;}
137188        break;
137189      case 18: /* temp ::= TEMP */
137190      case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
137191{yymsp[0].minor.yy194 = 1;}
137192        break;
137193      case 20: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
137194{
137195  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0);
137196}
137197        break;
137198      case 21: /* create_table_args ::= AS select */
137199{
137200  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243);
137201  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
137202}
137203        break;
137204      case 23: /* table_options ::= WITHOUT nm */
137205{
137206  if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
137207    yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid;
137208  }else{
137209    yymsp[-1].minor.yy194 = 0;
137210    sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
137211  }
137212}
137213        break;
137214      case 24: /* columnname ::= nm typetoken */
137215{sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
137216        break;
137217      case 25: /* typetoken ::= */
137218      case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
137219      case 96: /* as ::= */ yytestcase(yyruleno==96);
137220{yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
137221        break;
137222      case 26: /* typetoken ::= typename LP signed RP */
137223{
137224  yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
137225}
137226        break;
137227      case 27: /* typetoken ::= typename LP signed COMMA signed RP */
137228{
137229  yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
137230}
137231        break;
137232      case 28: /* typename ::= typename ID|STRING */
137233{yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
137234        break;
137235      case 29: /* ccons ::= CONSTRAINT nm */
137236      case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
137237{pParse->constraintName = yymsp[0].minor.yy0;}
137238        break;
137239      case 30: /* ccons ::= DEFAULT term */
137240      case 32: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==32);
137241{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);}
137242        break;
137243      case 31: /* ccons ::= DEFAULT LP expr RP */
137244{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);}
137245        break;
137246      case 33: /* ccons ::= DEFAULT MINUS term */
137247{
137248  ExprSpan v;
137249  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0);
137250  v.zStart = yymsp[-1].minor.yy0.z;
137251  v.zEnd = yymsp[0].minor.yy190.zEnd;
137252  sqlite3AddDefaultValue(pParse,&v);
137253}
137254        break;
137255      case 34: /* ccons ::= DEFAULT ID|INDEXED */
137256{
137257  ExprSpan v;
137258  spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0);
137259  sqlite3AddDefaultValue(pParse,&v);
137260}
137261        break;
137262      case 35: /* ccons ::= NOT NULL onconf */
137263{sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);}
137264        break;
137265      case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
137266{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);}
137267        break;
137268      case 37: /* ccons ::= UNIQUE onconf */
137269{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0,
137270                                   SQLITE_IDXTYPE_UNIQUE);}
137271        break;
137272      case 38: /* ccons ::= CHECK LP expr RP */
137273{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);}
137274        break;
137275      case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
137276{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);}
137277        break;
137278      case 40: /* ccons ::= defer_subclause */
137279{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);}
137280        break;
137281      case 41: /* ccons ::= COLLATE ID|STRING */
137282{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
137283        break;
137284      case 44: /* refargs ::= */
137285{ yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */}
137286        break;
137287      case 45: /* refargs ::= refargs refarg */
137288{ yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; }
137289        break;
137290      case 46: /* refarg ::= MATCH nm */
137291{ yymsp[-1].minor.yy497.value = 0;     yymsp[-1].minor.yy497.mask = 0x000000; }
137292        break;
137293      case 47: /* refarg ::= ON INSERT refact */
137294{ yymsp[-2].minor.yy497.value = 0;     yymsp[-2].minor.yy497.mask = 0x000000; }
137295        break;
137296      case 48: /* refarg ::= ON DELETE refact */
137297{ yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194;     yymsp[-2].minor.yy497.mask = 0x0000ff; }
137298        break;
137299      case 49: /* refarg ::= ON UPDATE refact */
137300{ yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8;  yymsp[-2].minor.yy497.mask = 0x00ff00; }
137301        break;
137302      case 50: /* refact ::= SET NULL */
137303{ yymsp[-1].minor.yy194 = OE_SetNull;  /* EV: R-33326-45252 */}
137304        break;
137305      case 51: /* refact ::= SET DEFAULT */
137306{ yymsp[-1].minor.yy194 = OE_SetDflt;  /* EV: R-33326-45252 */}
137307        break;
137308      case 52: /* refact ::= CASCADE */
137309{ yymsp[0].minor.yy194 = OE_Cascade;  /* EV: R-33326-45252 */}
137310        break;
137311      case 53: /* refact ::= RESTRICT */
137312{ yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */}
137313        break;
137314      case 54: /* refact ::= NO ACTION */
137315{ yymsp[-1].minor.yy194 = OE_None;     /* EV: R-33326-45252 */}
137316        break;
137317      case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
137318{yymsp[-2].minor.yy194 = 0;}
137319        break;
137320      case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
137321      case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
137322      case 144: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==144);
137323{yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;}
137324        break;
137325      case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
137326      case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
137327      case 186: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==186);
137328      case 189: /* in_op ::= NOT IN */ yytestcase(yyruleno==189);
137329      case 215: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==215);
137330{yymsp[-1].minor.yy194 = 1;}
137331        break;
137332      case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
137333{yymsp[-1].minor.yy194 = 0;}
137334        break;
137335      case 61: /* tconscomma ::= COMMA */
137336{pParse->constraintName.n = 0;}
137337        break;
137338      case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
137339{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);}
137340        break;
137341      case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
137342{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0,
137343                                       SQLITE_IDXTYPE_UNIQUE);}
137344        break;
137345      case 65: /* tcons ::= CHECK LP expr RP onconf */
137346{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);}
137347        break;
137348      case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
137349{
137350    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194);
137351    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194);
137352}
137353        break;
137354      case 68: /* onconf ::= */
137355      case 70: /* orconf ::= */ yytestcase(yyruleno==70);
137356{yymsp[1].minor.yy194 = OE_Default;}
137357        break;
137358      case 69: /* onconf ::= ON CONFLICT resolvetype */
137359{yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;}
137360        break;
137361      case 72: /* resolvetype ::= IGNORE */
137362{yymsp[0].minor.yy194 = OE_Ignore;}
137363        break;
137364      case 73: /* resolvetype ::= REPLACE */
137365      case 145: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==145);
137366{yymsp[0].minor.yy194 = OE_Replace;}
137367        break;
137368      case 74: /* cmd ::= DROP TABLE ifexists fullname */
137369{
137370  sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194);
137371}
137372        break;
137373      case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
137374{
137375  sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[0].minor.yy243, yymsp[-7].minor.yy194, yymsp[-5].minor.yy194);
137376}
137377        break;
137378      case 78: /* cmd ::= DROP VIEW ifexists fullname */
137379{
137380  sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194);
137381}
137382        break;
137383      case 79: /* cmd ::= select */
137384{
137385  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
137386  sqlite3Select(pParse, yymsp[0].minor.yy243, &dest);
137387  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
137388}
137389        break;
137390      case 80: /* select ::= with selectnowith */
137391{
137392  Select *p = yymsp[0].minor.yy243;
137393  if( p ){
137394    p->pWith = yymsp[-1].minor.yy285;
137395    parserDoubleLinkSelect(pParse, p);
137396  }else{
137397    sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285);
137398  }
137399  yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/
137400}
137401        break;
137402      case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */
137403{
137404  Select *pRhs = yymsp[0].minor.yy243;
137405  Select *pLhs = yymsp[-2].minor.yy243;
137406  if( pRhs && pRhs->pPrior ){
137407    SrcList *pFrom;
137408    Token x;
137409    x.n = 0;
137410    parserDoubleLinkSelect(pParse, pRhs);
137411    pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
137412    pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
137413  }
137414  if( pRhs ){
137415    pRhs->op = (u8)yymsp[-1].minor.yy194;
137416    pRhs->pPrior = pLhs;
137417    if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
137418    pRhs->selFlags &= ~SF_MultiValue;
137419    if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1;
137420  }else{
137421    sqlite3SelectDelete(pParse->db, pLhs);
137422  }
137423  yymsp[-2].minor.yy243 = pRhs;
137424}
137425        break;
137426      case 82: /* multiselect_op ::= UNION */
137427      case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84);
137428{yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/}
137429        break;
137430      case 83: /* multiselect_op ::= UNION ALL */
137431{yymsp[-1].minor.yy194 = TK_ALL;}
137432        break;
137433      case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
137434{
137435#if SELECTTRACE_ENABLED
137436  Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
137437#endif
137438  yymsp[-8].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy148,yymsp[-5].minor.yy185,yymsp[-4].minor.yy72,yymsp[-3].minor.yy148,yymsp[-2].minor.yy72,yymsp[-1].minor.yy148,yymsp[-7].minor.yy194,yymsp[0].minor.yy354.pLimit,yymsp[0].minor.yy354.pOffset);
137439#if SELECTTRACE_ENABLED
137440  /* Populate the Select.zSelName[] string that is used to help with
137441  ** query planner debugging, to differentiate between multiple Select
137442  ** objects in a complex query.
137443  **
137444  ** If the SELECT keyword is immediately followed by a C-style comment
137445  ** then extract the first few alphanumeric characters from within that
137446  ** comment to be the zSelName value.  Otherwise, the label is #N where
137447  ** is an integer that is incremented with each SELECT statement seen.
137448  */
137449  if( yymsp[-8].minor.yy243!=0 ){
137450    const char *z = s.z+6;
137451    int i;
137452    sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d",
137453                     ++pParse->nSelect);
137454    while( z[0]==' ' ) z++;
137455    if( z[0]=='/' && z[1]=='*' ){
137456      z += 2;
137457      while( z[0]==' ' ) z++;
137458      for(i=0; sqlite3Isalnum(z[i]); i++){}
137459      sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z);
137460    }
137461  }
137462#endif /* SELECTRACE_ENABLED */
137463}
137464        break;
137465      case 86: /* values ::= VALUES LP nexprlist RP */
137466{
137467  yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0);
137468}
137469        break;
137470      case 87: /* values ::= values COMMA LP exprlist RP */
137471{
137472  Select *pRight, *pLeft = yymsp[-4].minor.yy243;
137473  pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
137474  if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
137475  if( pRight ){
137476    pRight->op = TK_ALL;
137477    pRight->pPrior = pLeft;
137478    yymsp[-4].minor.yy243 = pRight;
137479  }else{
137480    yymsp[-4].minor.yy243 = pLeft;
137481  }
137482}
137483        break;
137484      case 88: /* distinct ::= DISTINCT */
137485{yymsp[0].minor.yy194 = SF_Distinct;}
137486        break;
137487      case 89: /* distinct ::= ALL */
137488{yymsp[0].minor.yy194 = SF_All;}
137489        break;
137490      case 91: /* sclp ::= */
137491      case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119);
137492      case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126);
137493      case 202: /* exprlist ::= */ yytestcase(yyruleno==202);
137494      case 205: /* paren_exprlist ::= */ yytestcase(yyruleno==205);
137495      case 210: /* eidlist_opt ::= */ yytestcase(yyruleno==210);
137496{yymsp[1].minor.yy148 = 0;}
137497        break;
137498      case 92: /* selcollist ::= sclp expr as */
137499{
137500   yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr);
137501   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1);
137502   sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190);
137503}
137504        break;
137505      case 93: /* selcollist ::= sclp STAR */
137506{
137507  Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
137508  yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p);
137509}
137510        break;
137511      case 94: /* selcollist ::= sclp nm DOT STAR */
137512{
137513  Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
137514  Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
137515  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
137516  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot);
137517}
137518        break;
137519      case 95: /* as ::= AS nm */
137520      case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106);
137521      case 224: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==224);
137522      case 225: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==225);
137523{yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
137524        break;
137525      case 97: /* from ::= */
137526{yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));}
137527        break;
137528      case 98: /* from ::= FROM seltablist */
137529{
137530  yymsp[-1].minor.yy185 = yymsp[0].minor.yy185;
137531  sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185);
137532}
137533        break;
137534      case 99: /* stl_prefix ::= seltablist joinop */
137535{
137536   if( ALWAYS(yymsp[-1].minor.yy185 && yymsp[-1].minor.yy185->nSrc>0) ) yymsp[-1].minor.yy185->a[yymsp[-1].minor.yy185->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy194;
137537}
137538        break;
137539      case 100: /* stl_prefix ::= */
137540{yymsp[1].minor.yy185 = 0;}
137541        break;
137542      case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
137543{
137544  yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
137545  sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0);
137546}
137547        break;
137548      case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
137549{
137550  yymsp[-8].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy185,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
137551  sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148);
137552}
137553        break;
137554      case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
137555{
137556    yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy243,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
137557  }
137558        break;
137559      case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
137560{
137561    if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){
137562      yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185;
137563    }else if( yymsp[-4].minor.yy185->nSrc==1 ){
137564      yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
137565      if( yymsp[-6].minor.yy185 ){
137566        struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1];
137567        struct SrcList_item *pOld = yymsp[-4].minor.yy185->a;
137568        pNew->zName = pOld->zName;
137569        pNew->zDatabase = pOld->zDatabase;
137570        pNew->pSelect = pOld->pSelect;
137571        pOld->zName = pOld->zDatabase = 0;
137572        pOld->pSelect = 0;
137573      }
137574      sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185);
137575    }else{
137576      Select *pSubquery;
137577      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185);
137578      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0);
137579      yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
137580    }
137581  }
137582        break;
137583      case 105: /* dbnm ::= */
137584      case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114);
137585{yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
137586        break;
137587      case 107: /* fullname ::= nm dbnm */
137588{yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
137589        break;
137590      case 108: /* joinop ::= COMMA|JOIN */
137591{ yymsp[0].minor.yy194 = JT_INNER; }
137592        break;
137593      case 109: /* joinop ::= JOIN_KW JOIN */
137594{yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0);  /*X-overwrites-A*/}
137595        break;
137596      case 110: /* joinop ::= JOIN_KW nm JOIN */
137597{yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
137598        break;
137599      case 111: /* joinop ::= JOIN_KW nm nm JOIN */
137600{yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
137601        break;
137602      case 112: /* on_opt ::= ON expr */
137603      case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129);
137604      case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136);
137605      case 198: /* case_else ::= ELSE expr */ yytestcase(yyruleno==198);
137606{yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;}
137607        break;
137608      case 113: /* on_opt ::= */
137609      case 128: /* having_opt ::= */ yytestcase(yyruleno==128);
137610      case 135: /* where_opt ::= */ yytestcase(yyruleno==135);
137611      case 199: /* case_else ::= */ yytestcase(yyruleno==199);
137612      case 201: /* case_operand ::= */ yytestcase(yyruleno==201);
137613{yymsp[1].minor.yy72 = 0;}
137614        break;
137615      case 115: /* indexed_opt ::= INDEXED BY nm */
137616{yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
137617        break;
137618      case 116: /* indexed_opt ::= NOT INDEXED */
137619{yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
137620        break;
137621      case 117: /* using_opt ::= USING LP idlist RP */
137622{yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;}
137623        break;
137624      case 118: /* using_opt ::= */
137625      case 146: /* idlist_opt ::= */ yytestcase(yyruleno==146);
137626{yymsp[1].minor.yy254 = 0;}
137627        break;
137628      case 120: /* orderby_opt ::= ORDER BY sortlist */
137629      case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127);
137630{yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;}
137631        break;
137632      case 121: /* sortlist ::= sortlist COMMA expr sortorder */
137633{
137634  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr);
137635  sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194);
137636}
137637        break;
137638      case 122: /* sortlist ::= expr sortorder */
137639{
137640  yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/
137641  sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194);
137642}
137643        break;
137644      case 123: /* sortorder ::= ASC */
137645{yymsp[0].minor.yy194 = SQLITE_SO_ASC;}
137646        break;
137647      case 124: /* sortorder ::= DESC */
137648{yymsp[0].minor.yy194 = SQLITE_SO_DESC;}
137649        break;
137650      case 125: /* sortorder ::= */
137651{yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;}
137652        break;
137653      case 130: /* limit_opt ::= */
137654{yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;}
137655        break;
137656      case 131: /* limit_opt ::= LIMIT expr */
137657{yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;}
137658        break;
137659      case 132: /* limit_opt ::= LIMIT expr OFFSET expr */
137660{yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;}
137661        break;
137662      case 133: /* limit_opt ::= LIMIT expr COMMA expr */
137663{yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;}
137664        break;
137665      case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
137666{
137667  sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
137668  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0);
137669  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72);
137670}
137671        break;
137672      case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
137673{
137674  sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1);
137675  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0);
137676  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list");
137677  sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194);
137678}
137679        break;
137680      case 138: /* setlist ::= setlist COMMA nm EQ expr */
137681{
137682  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
137683  sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1);
137684}
137685        break;
137686      case 139: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
137687{
137688  yymsp[-6].minor.yy148 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy148, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
137689}
137690        break;
137691      case 140: /* setlist ::= nm EQ expr */
137692{
137693  yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr);
137694  sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1);
137695}
137696  yymsp[-2].minor.yy148 = yylhsminor.yy148;
137697        break;
137698      case 141: /* setlist ::= LP idlist RP EQ expr */
137699{
137700  yymsp[-4].minor.yy148 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
137701}
137702        break;
137703      case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
137704{
137705  sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
137706  sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194);
137707}
137708        break;
137709      case 143: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
137710{
137711  sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1);
137712  sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194);
137713}
137714        break;
137715      case 147: /* idlist_opt ::= LP idlist RP */
137716{yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;}
137717        break;
137718      case 148: /* idlist ::= idlist COMMA nm */
137719{yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
137720        break;
137721      case 149: /* idlist ::= nm */
137722{yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
137723        break;
137724      case 150: /* expr ::= LP expr RP */
137725{spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/  yymsp[-2].minor.yy190.pExpr = yymsp[-1].minor.yy190.pExpr;}
137726        break;
137727      case 151: /* term ::= NULL */
137728      case 156: /* term ::= FLOAT|BLOB */ yytestcase(yyruleno==156);
137729      case 157: /* term ::= STRING */ yytestcase(yyruleno==157);
137730{spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0);/*A-overwrites-X*/}
137731        break;
137732      case 152: /* expr ::= ID|INDEXED */
137733      case 153: /* expr ::= JOIN_KW */ yytestcase(yyruleno==153);
137734{spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
137735        break;
137736      case 154: /* expr ::= nm DOT nm */
137737{
137738  Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
137739  Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
137740  spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
137741  yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
137742}
137743        break;
137744      case 155: /* expr ::= nm DOT nm DOT nm */
137745{
137746  Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
137747  Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
137748  Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
137749  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
137750  spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
137751  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
137752}
137753        break;
137754      case 158: /* term ::= INTEGER */
137755{
137756  yylhsminor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
137757  yylhsminor.yy190.zStart = yymsp[0].minor.yy0.z;
137758  yylhsminor.yy190.zEnd = yymsp[0].minor.yy0.z + yymsp[0].minor.yy0.n;
137759  if( yylhsminor.yy190.pExpr ) yylhsminor.yy190.pExpr->flags |= EP_Leaf|EP_Resolved;
137760}
137761  yymsp[0].minor.yy190 = yylhsminor.yy190;
137762        break;
137763      case 159: /* expr ::= VARIABLE */
137764{
137765  if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
137766    u32 n = yymsp[0].minor.yy0.n;
137767    spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
137768    sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr, n);
137769  }else{
137770    /* When doing a nested parse, one can include terms in an expression
137771    ** that look like this:   #1 #2 ...  These terms refer to registers
137772    ** in the virtual machine.  #N is the N-th register. */
137773    Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
137774    assert( t.n>=2 );
137775    spanSet(&yymsp[0].minor.yy190, &t, &t);
137776    if( pParse->nested==0 ){
137777      sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
137778      yymsp[0].minor.yy190.pExpr = 0;
137779    }else{
137780      yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
137781      if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable);
137782    }
137783  }
137784}
137785        break;
137786      case 160: /* expr ::= expr COLLATE ID|STRING */
137787{
137788  yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1);
137789  yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
137790}
137791        break;
137792      case 161: /* expr ::= CAST LP expr AS typetoken RP */
137793{
137794  spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
137795  yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
137796  sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, 0);
137797}
137798        break;
137799      case 162: /* expr ::= ID|INDEXED LP distinct exprlist RP */
137800{
137801  if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
137802    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
137803  }
137804  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0);
137805  spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
137806  if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){
137807    yylhsminor.yy190.pExpr->flags |= EP_Distinct;
137808  }
137809}
137810  yymsp[-4].minor.yy190 = yylhsminor.yy190;
137811        break;
137812      case 163: /* expr ::= ID|INDEXED LP STAR RP */
137813{
137814  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
137815  spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
137816}
137817  yymsp[-3].minor.yy190 = yylhsminor.yy190;
137818        break;
137819      case 164: /* term ::= CTIME_KW */
137820{
137821  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
137822  spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
137823}
137824  yymsp[0].minor.yy190 = yylhsminor.yy190;
137825        break;
137826      case 165: /* expr ::= LP nexprlist COMMA expr RP */
137827{
137828  ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy148, yymsp[-1].minor.yy190.pExpr);
137829  yylhsminor.yy190.pExpr = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
137830  if( yylhsminor.yy190.pExpr ){
137831    yylhsminor.yy190.pExpr->x.pList = pList;
137832    spanSet(&yylhsminor.yy190, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
137833  }else{
137834    sqlite3ExprListDelete(pParse->db, pList);
137835  }
137836}
137837  yymsp[-4].minor.yy190 = yylhsminor.yy190;
137838        break;
137839      case 166: /* expr ::= expr AND expr */
137840      case 167: /* expr ::= expr OR expr */ yytestcase(yyruleno==167);
137841      case 168: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==168);
137842      case 169: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==169);
137843      case 170: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==170);
137844      case 171: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==171);
137845      case 172: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==172);
137846      case 173: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==173);
137847{spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);}
137848        break;
137849      case 174: /* likeop ::= NOT LIKE_KW|MATCH */
137850{yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
137851        break;
137852      case 175: /* expr ::= expr likeop expr */
137853{
137854  ExprList *pList;
137855  int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
137856  yymsp[-1].minor.yy0.n &= 0x7fffffff;
137857  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr);
137858  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr);
137859  yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0);
137860  exprNot(pParse, bNot, &yymsp[-2].minor.yy190);
137861  yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
137862  if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc;
137863}
137864        break;
137865      case 176: /* expr ::= expr likeop expr ESCAPE expr */
137866{
137867  ExprList *pList;
137868  int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
137869  yymsp[-3].minor.yy0.n &= 0x7fffffff;
137870  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
137871  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr);
137872  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
137873  yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0);
137874  exprNot(pParse, bNot, &yymsp[-4].minor.yy190);
137875  yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
137876  if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc;
137877}
137878        break;
137879      case 177: /* expr ::= expr ISNULL|NOTNULL */
137880{spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);}
137881        break;
137882      case 178: /* expr ::= expr NOT NULL */
137883{spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);}
137884        break;
137885      case 179: /* expr ::= expr IS expr */
137886{
137887  spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);
137888  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL);
137889}
137890        break;
137891      case 180: /* expr ::= expr IS NOT expr */
137892{
137893  spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190);
137894  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL);
137895}
137896        break;
137897      case 181: /* expr ::= NOT expr */
137898      case 182: /* expr ::= BITNOT expr */ yytestcase(yyruleno==182);
137899{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
137900        break;
137901      case 183: /* expr ::= MINUS expr */
137902{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
137903        break;
137904      case 184: /* expr ::= PLUS expr */
137905{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
137906        break;
137907      case 185: /* between_op ::= BETWEEN */
137908      case 188: /* in_op ::= IN */ yytestcase(yyruleno==188);
137909{yymsp[0].minor.yy194 = 0;}
137910        break;
137911      case 187: /* expr ::= expr between_op expr AND expr */
137912{
137913  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
137914  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
137915  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0);
137916  if( yymsp[-4].minor.yy190.pExpr ){
137917    yymsp[-4].minor.yy190.pExpr->x.pList = pList;
137918  }else{
137919    sqlite3ExprListDelete(pParse->db, pList);
137920  }
137921  exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
137922  yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
137923}
137924        break;
137925      case 190: /* expr ::= expr in_op LP exprlist RP */
137926{
137927    if( yymsp[-1].minor.yy148==0 ){
137928      /* Expressions of the form
137929      **
137930      **      expr1 IN ()
137931      **      expr1 NOT IN ()
137932      **
137933      ** simplify to constants 0 (false) and 1 (true), respectively,
137934      ** regardless of the value of expr1.
137935      */
137936      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr);
137937      yymsp[-4].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy194],1);
137938    }else if( yymsp[-1].minor.yy148->nExpr==1 ){
137939      /* Expressions of the form:
137940      **
137941      **      expr1 IN (?1)
137942      **      expr1 NOT IN (?2)
137943      **
137944      ** with exactly one value on the RHS can be simplified to something
137945      ** like this:
137946      **
137947      **      expr1 == ?1
137948      **      expr1 <> ?2
137949      **
137950      ** But, the RHS of the == or <> is marked with the EP_Generic flag
137951      ** so that it may not contribute to the computation of comparison
137952      ** affinity or the collating sequence to use for comparison.  Otherwise,
137953      ** the semantics would be subtly different from IN or NOT IN.
137954      */
137955      Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr;
137956      yymsp[-1].minor.yy148->a[0].pExpr = 0;
137957      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
137958      /* pRHS cannot be NULL because a malloc error would have been detected
137959      ** before now and control would have never reached this point */
137960      if( ALWAYS(pRHS) ){
137961        pRHS->flags &= ~EP_Collate;
137962        pRHS->flags |= EP_Generic;
137963      }
137964      yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS);
137965    }else{
137966      yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
137967      if( yymsp[-4].minor.yy190.pExpr ){
137968        yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148;
137969        sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
137970      }else{
137971        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
137972      }
137973      exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
137974    }
137975    yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
137976  }
137977        break;
137978      case 191: /* expr ::= LP select RP */
137979{
137980    spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
137981    yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
137982    sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243);
137983  }
137984        break;
137985      case 192: /* expr ::= expr in_op LP select RP */
137986{
137987    yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
137988    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243);
137989    exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
137990    yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
137991  }
137992        break;
137993      case 193: /* expr ::= expr in_op nm dbnm paren_exprlist */
137994{
137995    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
137996    Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
137997    if( yymsp[0].minor.yy148 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148);
137998    yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
137999    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect);
138000    exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
138001    yymsp[-4].minor.yy190.zEnd = yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n] : &yymsp[-2].minor.yy0.z[yymsp[-2].minor.yy0.n];
138002  }
138003        break;
138004      case 194: /* expr ::= EXISTS LP select RP */
138005{
138006    Expr *p;
138007    spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
138008    p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
138009    sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243);
138010  }
138011        break;
138012      case 195: /* expr ::= CASE case_operand case_exprlist case_else END */
138013{
138014  spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-C*/
138015  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0);
138016  if( yymsp[-4].minor.yy190.pExpr ){
138017    yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy72 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[-1].minor.yy72) : yymsp[-2].minor.yy148;
138018    sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
138019  }else{
138020    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148);
138021    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72);
138022  }
138023}
138024        break;
138025      case 196: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
138026{
138027  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr);
138028  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
138029}
138030        break;
138031      case 197: /* case_exprlist ::= WHEN expr THEN expr */
138032{
138033  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
138034  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr);
138035}
138036        break;
138037      case 200: /* case_operand ::= expr */
138038{yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/}
138039        break;
138040      case 203: /* nexprlist ::= nexprlist COMMA expr */
138041{yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);}
138042        break;
138043      case 204: /* nexprlist ::= expr */
138044{yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/}
138045        break;
138046      case 206: /* paren_exprlist ::= LP exprlist RP */
138047      case 211: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==211);
138048{yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;}
138049        break;
138050      case 207: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
138051{
138052  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
138053                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194,
138054                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF);
138055}
138056        break;
138057      case 208: /* uniqueflag ::= UNIQUE */
138058      case 249: /* raisetype ::= ABORT */ yytestcase(yyruleno==249);
138059{yymsp[0].minor.yy194 = OE_Abort;}
138060        break;
138061      case 209: /* uniqueflag ::= */
138062{yymsp[1].minor.yy194 = OE_None;}
138063        break;
138064      case 212: /* eidlist ::= eidlist COMMA nm collate sortorder */
138065{
138066  yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194);
138067}
138068        break;
138069      case 213: /* eidlist ::= nm collate sortorder */
138070{
138071  yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/
138072}
138073        break;
138074      case 216: /* cmd ::= DROP INDEX ifexists fullname */
138075{sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);}
138076        break;
138077      case 217: /* cmd ::= VACUUM */
138078{sqlite3Vacuum(pParse,0);}
138079        break;
138080      case 218: /* cmd ::= VACUUM nm */
138081{sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);}
138082        break;
138083      case 219: /* cmd ::= PRAGMA nm dbnm */
138084{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
138085        break;
138086      case 220: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
138087{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
138088        break;
138089      case 221: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
138090{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
138091        break;
138092      case 222: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
138093{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
138094        break;
138095      case 223: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
138096{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
138097        break;
138098      case 226: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
138099{
138100  Token all;
138101  all.z = yymsp[-3].minor.yy0.z;
138102  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
138103  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all);
138104}
138105        break;
138106      case 227: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
138107{
138108  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy194, yymsp[-4].minor.yy332.a, yymsp[-4].minor.yy332.b, yymsp[-2].minor.yy185, yymsp[0].minor.yy72, yymsp[-10].minor.yy194, yymsp[-8].minor.yy194);
138109  yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
138110}
138111        break;
138112      case 228: /* trigger_time ::= BEFORE */
138113{ yymsp[0].minor.yy194 = TK_BEFORE; }
138114        break;
138115      case 229: /* trigger_time ::= AFTER */
138116{ yymsp[0].minor.yy194 = TK_AFTER;  }
138117        break;
138118      case 230: /* trigger_time ::= INSTEAD OF */
138119{ yymsp[-1].minor.yy194 = TK_INSTEAD;}
138120        break;
138121      case 231: /* trigger_time ::= */
138122{ yymsp[1].minor.yy194 = TK_BEFORE; }
138123        break;
138124      case 232: /* trigger_event ::= DELETE|INSERT */
138125      case 233: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==233);
138126{yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;}
138127        break;
138128      case 234: /* trigger_event ::= UPDATE OF idlist */
138129{yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;}
138130        break;
138131      case 235: /* when_clause ::= */
138132      case 254: /* key_opt ::= */ yytestcase(yyruleno==254);
138133{ yymsp[1].minor.yy72 = 0; }
138134        break;
138135      case 236: /* when_clause ::= WHEN expr */
138136      case 255: /* key_opt ::= KEY expr */ yytestcase(yyruleno==255);
138137{ yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; }
138138        break;
138139      case 237: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
138140{
138141  assert( yymsp[-2].minor.yy145!=0 );
138142  yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145;
138143  yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145;
138144}
138145        break;
138146      case 238: /* trigger_cmd_list ::= trigger_cmd SEMI */
138147{
138148  assert( yymsp[-1].minor.yy145!=0 );
138149  yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145;
138150}
138151        break;
138152      case 239: /* trnm ::= nm DOT nm */
138153{
138154  yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
138155  sqlite3ErrorMsg(pParse,
138156        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
138157        "statements within triggers");
138158}
138159        break;
138160      case 240: /* tridxby ::= INDEXED BY nm */
138161{
138162  sqlite3ErrorMsg(pParse,
138163        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
138164        "within triggers");
138165}
138166        break;
138167      case 241: /* tridxby ::= NOT INDEXED */
138168{
138169  sqlite3ErrorMsg(pParse,
138170        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
138171        "within triggers");
138172}
138173        break;
138174      case 242: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
138175{yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);}
138176        break;
138177      case 243: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
138178{yymsp[-4].minor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy254, yymsp[0].minor.yy243, yymsp[-4].minor.yy194);/*A-overwrites-R*/}
138179        break;
138180      case 244: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
138181{yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);}
138182        break;
138183      case 245: /* trigger_cmd ::= select */
138184{yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/}
138185        break;
138186      case 246: /* expr ::= RAISE LP IGNORE RP */
138187{
138188  spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-X*/
138189  yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
138190  if( yymsp[-3].minor.yy190.pExpr ){
138191    yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore;
138192  }
138193}
138194        break;
138195      case 247: /* expr ::= RAISE LP raisetype COMMA nm RP */
138196{
138197  spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-X*/
138198  yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
138199  if( yymsp[-5].minor.yy190.pExpr ) {
138200    yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194;
138201  }
138202}
138203        break;
138204      case 248: /* raisetype ::= ROLLBACK */
138205{yymsp[0].minor.yy194 = OE_Rollback;}
138206        break;
138207      case 250: /* raisetype ::= FAIL */
138208{yymsp[0].minor.yy194 = OE_Fail;}
138209        break;
138210      case 251: /* cmd ::= DROP TRIGGER ifexists fullname */
138211{
138212  sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194);
138213}
138214        break;
138215      case 252: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
138216{
138217  sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72);
138218}
138219        break;
138220      case 253: /* cmd ::= DETACH database_kw_opt expr */
138221{
138222  sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr);
138223}
138224        break;
138225      case 256: /* cmd ::= REINDEX */
138226{sqlite3Reindex(pParse, 0, 0);}
138227        break;
138228      case 257: /* cmd ::= REINDEX nm dbnm */
138229{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
138230        break;
138231      case 258: /* cmd ::= ANALYZE */
138232{sqlite3Analyze(pParse, 0, 0);}
138233        break;
138234      case 259: /* cmd ::= ANALYZE nm dbnm */
138235{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
138236        break;
138237      case 260: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
138238{
138239  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0);
138240}
138241        break;
138242      case 261: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
138243{
138244  yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
138245  sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
138246}
138247        break;
138248      case 262: /* add_column_fullname ::= fullname */
138249{
138250  disableLookaside(pParse);
138251  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185);
138252}
138253        break;
138254      case 263: /* cmd ::= create_vtab */
138255{sqlite3VtabFinishParse(pParse,0);}
138256        break;
138257      case 264: /* cmd ::= create_vtab LP vtabarglist RP */
138258{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
138259        break;
138260      case 265: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
138261{
138262    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194);
138263}
138264        break;
138265      case 266: /* vtabarg ::= */
138266{sqlite3VtabArgInit(pParse);}
138267        break;
138268      case 267: /* vtabargtoken ::= ANY */
138269      case 268: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==268);
138270      case 269: /* lp ::= LP */ yytestcase(yyruleno==269);
138271{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
138272        break;
138273      case 270: /* with ::= */
138274{yymsp[1].minor.yy285 = 0;}
138275        break;
138276      case 271: /* with ::= WITH wqlist */
138277{ yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; }
138278        break;
138279      case 272: /* with ::= WITH RECURSIVE wqlist */
138280{ yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; }
138281        break;
138282      case 273: /* wqlist ::= nm eidlist_opt AS LP select RP */
138283{
138284  yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/
138285}
138286        break;
138287      case 274: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
138288{
138289  yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243);
138290}
138291        break;
138292      default:
138293      /* (275) input ::= cmdlist */ yytestcase(yyruleno==275);
138294      /* (276) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==276);
138295      /* (277) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=277);
138296      /* (278) ecmd ::= SEMI */ yytestcase(yyruleno==278);
138297      /* (279) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==279);
138298      /* (280) explain ::= */ yytestcase(yyruleno==280);
138299      /* (281) trans_opt ::= */ yytestcase(yyruleno==281);
138300      /* (282) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==282);
138301      /* (283) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==283);
138302      /* (284) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==284);
138303      /* (285) savepoint_opt ::= */ yytestcase(yyruleno==285);
138304      /* (286) cmd ::= create_table create_table_args */ yytestcase(yyruleno==286);
138305      /* (287) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==287);
138306      /* (288) columnlist ::= columnname carglist */ yytestcase(yyruleno==288);
138307      /* (289) nm ::= ID|INDEXED */ yytestcase(yyruleno==289);
138308      /* (290) nm ::= STRING */ yytestcase(yyruleno==290);
138309      /* (291) nm ::= JOIN_KW */ yytestcase(yyruleno==291);
138310      /* (292) typetoken ::= typename */ yytestcase(yyruleno==292);
138311      /* (293) typename ::= ID|STRING */ yytestcase(yyruleno==293);
138312      /* (294) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=294);
138313      /* (295) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=295);
138314      /* (296) carglist ::= carglist ccons */ yytestcase(yyruleno==296);
138315      /* (297) carglist ::= */ yytestcase(yyruleno==297);
138316      /* (298) ccons ::= NULL onconf */ yytestcase(yyruleno==298);
138317      /* (299) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==299);
138318      /* (300) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==300);
138319      /* (301) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=301);
138320      /* (302) tconscomma ::= */ yytestcase(yyruleno==302);
138321      /* (303) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=303);
138322      /* (304) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=304);
138323      /* (305) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=305);
138324      /* (306) oneselect ::= values */ yytestcase(yyruleno==306);
138325      /* (307) sclp ::= selcollist COMMA */ yytestcase(yyruleno==307);
138326      /* (308) as ::= ID|STRING */ yytestcase(yyruleno==308);
138327      /* (309) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=309);
138328      /* (310) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==310);
138329      /* (311) exprlist ::= nexprlist */ yytestcase(yyruleno==311);
138330      /* (312) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=312);
138331      /* (313) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=313);
138332      /* (314) nmnum ::= ON */ yytestcase(yyruleno==314);
138333      /* (315) nmnum ::= DELETE */ yytestcase(yyruleno==315);
138334      /* (316) nmnum ::= DEFAULT */ yytestcase(yyruleno==316);
138335      /* (317) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==317);
138336      /* (318) foreach_clause ::= */ yytestcase(yyruleno==318);
138337      /* (319) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==319);
138338      /* (320) trnm ::= nm */ yytestcase(yyruleno==320);
138339      /* (321) tridxby ::= */ yytestcase(yyruleno==321);
138340      /* (322) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==322);
138341      /* (323) database_kw_opt ::= */ yytestcase(yyruleno==323);
138342      /* (324) kwcolumn_opt ::= */ yytestcase(yyruleno==324);
138343      /* (325) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==325);
138344      /* (326) vtabarglist ::= vtabarg */ yytestcase(yyruleno==326);
138345      /* (327) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==327);
138346      /* (328) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==328);
138347      /* (329) anylist ::= */ yytestcase(yyruleno==329);
138348      /* (330) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==330);
138349      /* (331) anylist ::= anylist ANY */ yytestcase(yyruleno==331);
138350        break;
138351/********** End reduce actions ************************************************/
138352  };
138353  assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
138354  yygoto = yyRuleInfo[yyruleno].lhs;
138355  yysize = yyRuleInfo[yyruleno].nrhs;
138356  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
138357  if( yyact <= YY_MAX_SHIFTREDUCE ){
138358    if( yyact>YY_MAX_SHIFT ){
138359      yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
138360    }
138361    yymsp -= yysize-1;
138362    yypParser->yytos = yymsp;
138363    yymsp->stateno = (YYACTIONTYPE)yyact;
138364    yymsp->major = (YYCODETYPE)yygoto;
138365    yyTraceShift(yypParser, yyact);
138366  }else{
138367    assert( yyact == YY_ACCEPT_ACTION );
138368    yypParser->yytos -= yysize;
138369    yy_accept(yypParser);
138370  }
138371}
138372
138373/*
138374** The following code executes when the parse fails
138375*/
138376#ifndef YYNOERRORRECOVERY
138377static void yy_parse_failed(
138378  yyParser *yypParser           /* The parser */
138379){
138380  sqlite3ParserARG_FETCH;
138381#ifndef NDEBUG
138382  if( yyTraceFILE ){
138383    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
138384  }
138385#endif
138386  while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
138387  /* Here code is inserted which will be executed whenever the
138388  ** parser fails */
138389/************ Begin %parse_failure code ***************************************/
138390/************ End %parse_failure code *****************************************/
138391  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
138392}
138393#endif /* YYNOERRORRECOVERY */
138394
138395/*
138396** The following code executes when a syntax error first occurs.
138397*/
138398static void yy_syntax_error(
138399  yyParser *yypParser,           /* The parser */
138400  int yymajor,                   /* The major type of the error token */
138401  sqlite3ParserTOKENTYPE yyminor         /* The minor type of the error token */
138402){
138403  sqlite3ParserARG_FETCH;
138404#define TOKEN yyminor
138405/************ Begin %syntax_error code ****************************************/
138406
138407  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
138408  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
138409  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
138410/************ End %syntax_error code ******************************************/
138411  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
138412}
138413
138414/*
138415** The following is executed when the parser accepts
138416*/
138417static void yy_accept(
138418  yyParser *yypParser           /* The parser */
138419){
138420  sqlite3ParserARG_FETCH;
138421#ifndef NDEBUG
138422  if( yyTraceFILE ){
138423    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
138424  }
138425#endif
138426#ifndef YYNOERRORRECOVERY
138427  yypParser->yyerrcnt = -1;
138428#endif
138429  assert( yypParser->yytos==yypParser->yystack );
138430  /* Here code is inserted which will be executed whenever the
138431  ** parser accepts */
138432/*********** Begin %parse_accept code *****************************************/
138433/*********** End %parse_accept code *******************************************/
138434  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
138435}
138436
138437/* The main parser program.
138438** The first argument is a pointer to a structure obtained from
138439** "sqlite3ParserAlloc" which describes the current state of the parser.
138440** The second argument is the major token number.  The third is
138441** the minor token.  The fourth optional argument is whatever the
138442** user wants (and specified in the grammar) and is available for
138443** use by the action routines.
138444**
138445** Inputs:
138446** <ul>
138447** <li> A pointer to the parser (an opaque structure.)
138448** <li> The major token number.
138449** <li> The minor token number.
138450** <li> An option argument of a grammar-specified type.
138451** </ul>
138452**
138453** Outputs:
138454** None.
138455*/
138456SQLITE_PRIVATE void sqlite3Parser(
138457  void *yyp,                   /* The parser */
138458  int yymajor,                 /* The major token code number */
138459  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
138460  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
138461){
138462  YYMINORTYPE yyminorunion;
138463  unsigned int yyact;   /* The parser action. */
138464#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
138465  int yyendofinput;     /* True if we are at the end of input */
138466#endif
138467#ifdef YYERRORSYMBOL
138468  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
138469#endif
138470  yyParser *yypParser;  /* The parser */
138471
138472  yypParser = (yyParser*)yyp;
138473  assert( yypParser->yytos!=0 );
138474#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
138475  yyendofinput = (yymajor==0);
138476#endif
138477  sqlite3ParserARG_STORE;
138478
138479#ifndef NDEBUG
138480  if( yyTraceFILE ){
138481    fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
138482  }
138483#endif
138484
138485  do{
138486    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
138487    if( yyact <= YY_MAX_SHIFTREDUCE ){
138488      yy_shift(yypParser,yyact,yymajor,yyminor);
138489#ifndef YYNOERRORRECOVERY
138490      yypParser->yyerrcnt--;
138491#endif
138492      yymajor = YYNOCODE;
138493    }else if( yyact <= YY_MAX_REDUCE ){
138494      yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
138495    }else{
138496      assert( yyact == YY_ERROR_ACTION );
138497      yyminorunion.yy0 = yyminor;
138498#ifdef YYERRORSYMBOL
138499      int yymx;
138500#endif
138501#ifndef NDEBUG
138502      if( yyTraceFILE ){
138503        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
138504      }
138505#endif
138506#ifdef YYERRORSYMBOL
138507      /* A syntax error has occurred.
138508      ** The response to an error depends upon whether or not the
138509      ** grammar defines an error token "ERROR".
138510      **
138511      ** This is what we do if the grammar does define ERROR:
138512      **
138513      **  * Call the %syntax_error function.
138514      **
138515      **  * Begin popping the stack until we enter a state where
138516      **    it is legal to shift the error symbol, then shift
138517      **    the error symbol.
138518      **
138519      **  * Set the error count to three.
138520      **
138521      **  * Begin accepting and shifting new tokens.  No new error
138522      **    processing will occur until three tokens have been
138523      **    shifted successfully.
138524      **
138525      */
138526      if( yypParser->yyerrcnt<0 ){
138527        yy_syntax_error(yypParser,yymajor,yyminor);
138528      }
138529      yymx = yypParser->yytos->major;
138530      if( yymx==YYERRORSYMBOL || yyerrorhit ){
138531#ifndef NDEBUG
138532        if( yyTraceFILE ){
138533          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
138534             yyTracePrompt,yyTokenName[yymajor]);
138535        }
138536#endif
138537        yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
138538        yymajor = YYNOCODE;
138539      }else{
138540        while( yypParser->yytos >= yypParser->yystack
138541            && yymx != YYERRORSYMBOL
138542            && (yyact = yy_find_reduce_action(
138543                        yypParser->yytos->stateno,
138544                        YYERRORSYMBOL)) >= YY_MIN_REDUCE
138545        ){
138546          yy_pop_parser_stack(yypParser);
138547        }
138548        if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
138549          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
138550          yy_parse_failed(yypParser);
138551#ifndef YYNOERRORRECOVERY
138552          yypParser->yyerrcnt = -1;
138553#endif
138554          yymajor = YYNOCODE;
138555        }else if( yymx!=YYERRORSYMBOL ){
138556          yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
138557        }
138558      }
138559      yypParser->yyerrcnt = 3;
138560      yyerrorhit = 1;
138561#elif defined(YYNOERRORRECOVERY)
138562      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
138563      ** do any kind of error recovery.  Instead, simply invoke the syntax
138564      ** error routine and continue going as if nothing had happened.
138565      **
138566      ** Applications can set this macro (for example inside %include) if
138567      ** they intend to abandon the parse upon the first syntax error seen.
138568      */
138569      yy_syntax_error(yypParser,yymajor, yyminor);
138570      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
138571      yymajor = YYNOCODE;
138572
138573#else  /* YYERRORSYMBOL is not defined */
138574      /* This is what we do if the grammar does not define ERROR:
138575      **
138576      **  * Report an error message, and throw away the input token.
138577      **
138578      **  * If the input token is $, then fail the parse.
138579      **
138580      ** As before, subsequent error messages are suppressed until
138581      ** three input tokens have been successfully shifted.
138582      */
138583      if( yypParser->yyerrcnt<=0 ){
138584        yy_syntax_error(yypParser,yymajor, yyminor);
138585      }
138586      yypParser->yyerrcnt = 3;
138587      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
138588      if( yyendofinput ){
138589        yy_parse_failed(yypParser);
138590#ifndef YYNOERRORRECOVERY
138591        yypParser->yyerrcnt = -1;
138592#endif
138593      }
138594      yymajor = YYNOCODE;
138595#endif
138596    }
138597  }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack );
138598#ifndef NDEBUG
138599  if( yyTraceFILE ){
138600    yyStackEntry *i;
138601    char cDiv = '[';
138602    fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
138603    for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
138604      fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
138605      cDiv = ' ';
138606    }
138607    fprintf(yyTraceFILE,"]\n");
138608  }
138609#endif
138610  return;
138611}
138612
138613/************** End of parse.c ***********************************************/
138614/************** Begin file tokenize.c ****************************************/
138615/*
138616** 2001 September 15
138617**
138618** The author disclaims copyright to this source code.  In place of
138619** a legal notice, here is a blessing:
138620**
138621**    May you do good and not evil.
138622**    May you find forgiveness for yourself and forgive others.
138623**    May you share freely, never taking more than you give.
138624**
138625*************************************************************************
138626** An tokenizer for SQL
138627**
138628** This file contains C code that splits an SQL input string up into
138629** individual tokens and sends those tokens one-by-one over to the
138630** parser for analysis.
138631*/
138632/* #include "sqliteInt.h" */
138633/* #include <stdlib.h> */
138634
138635/* Character classes for tokenizing
138636**
138637** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
138638** using a lookup table, whereas a switch() directly on c uses a binary search.
138639** The lookup table is much faster.  To maximize speed, and to ensure that
138640** a lookup table is used, all of the classes need to be small integers and
138641** all of them need to be used within the switch.
138642*/
138643#define CC_X          0    /* The letter 'x', or start of BLOB literal */
138644#define CC_KYWD       1    /* Alphabetics or '_'.  Usable in a keyword */
138645#define CC_ID         2    /* unicode characters usable in IDs */
138646#define CC_DIGIT      3    /* Digits */
138647#define CC_DOLLAR     4    /* '$' */
138648#define CC_VARALPHA   5    /* '@', '#', ':'.  Alphabetic SQL variables */
138649#define CC_VARNUM     6    /* '?'.  Numeric SQL variables */
138650#define CC_SPACE      7    /* Space characters */
138651#define CC_QUOTE      8    /* '"', '\'', or '`'.  String literals, quoted ids */
138652#define CC_QUOTE2     9    /* '['.   [...] style quoted ids */
138653#define CC_PIPE      10    /* '|'.   Bitwise OR or concatenate */
138654#define CC_MINUS     11    /* '-'.  Minus or SQL-style comment */
138655#define CC_LT        12    /* '<'.  Part of < or <= or <> */
138656#define CC_GT        13    /* '>'.  Part of > or >= */
138657#define CC_EQ        14    /* '='.  Part of = or == */
138658#define CC_BANG      15    /* '!'.  Part of != */
138659#define CC_SLASH     16    /* '/'.  / or c-style comment */
138660#define CC_LP        17    /* '(' */
138661#define CC_RP        18    /* ')' */
138662#define CC_SEMI      19    /* ';' */
138663#define CC_PLUS      20    /* '+' */
138664#define CC_STAR      21    /* '*' */
138665#define CC_PERCENT   22    /* '%' */
138666#define CC_COMMA     23    /* ',' */
138667#define CC_AND       24    /* '&' */
138668#define CC_TILDA     25    /* '~' */
138669#define CC_DOT       26    /* '.' */
138670#define CC_ILLEGAL   27    /* Illegal character */
138671
138672static const unsigned char aiClass[] = {
138673#ifdef SQLITE_ASCII
138674/*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
138675/* 0x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  7,  7, 27,  7,  7, 27, 27,
138676/* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
138677/* 2x */    7, 15,  8,  5,  4, 22, 24,  8, 17, 18, 21, 20, 23, 11, 26, 16,
138678/* 3x */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  5, 19, 12, 14, 13,  6,
138679/* 4x */    5,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
138680/* 5x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  9, 27, 27, 27,  1,
138681/* 6x */    8,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
138682/* 7x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1, 27, 10, 27, 25, 27,
138683/* 8x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
138684/* 9x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
138685/* Ax */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
138686/* Bx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
138687/* Cx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
138688/* Dx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
138689/* Ex */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
138690/* Fx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2
138691#endif
138692#ifdef SQLITE_EBCDIC
138693/*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
138694/* 0x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27,  7,  7, 27, 27,
138695/* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
138696/* 2x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
138697/* 3x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
138698/* 4x */    7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
138699/* 5x */   24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15,  4, 21, 18, 19, 27,
138700/* 6x */   11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22,  1, 13,  6,
138701/* 7x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  8,  5,  5,  5,  8, 14,  8,
138702/* 8x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
138703/* 9x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
138704/* Ax */   27, 25,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
138705/* Bx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  9, 27, 27, 27, 27, 27,
138706/* Cx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
138707/* Dx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
138708/* Ex */   27, 27,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
138709/* Fx */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3, 27, 27, 27, 27, 27, 27,
138710#endif
138711};
138712
138713/*
138714** The charMap() macro maps alphabetic characters (only) into their
138715** lower-case ASCII equivalent.  On ASCII machines, this is just
138716** an upper-to-lower case map.  On EBCDIC machines we also need
138717** to adjust the encoding.  The mapping is only valid for alphabetics
138718** which are the only characters for which this feature is used.
138719**
138720** Used by keywordhash.h
138721*/
138722#ifdef SQLITE_ASCII
138723# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
138724#endif
138725#ifdef SQLITE_EBCDIC
138726# define charMap(X) ebcdicToAscii[(unsigned char)X]
138727const unsigned char ebcdicToAscii[] = {
138728/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
138729   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
138730   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
138731   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
138732   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
138733   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
138734   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
138735   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
138736   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
138737   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
138738   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
138739   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
138740   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
138741   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
138742   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
138743   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
138744   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
138745};
138746#endif
138747
138748/*
138749** The sqlite3KeywordCode function looks up an identifier to determine if
138750** it is a keyword.  If it is a keyword, the token code of that keyword is
138751** returned.  If the input is not a keyword, TK_ID is returned.
138752**
138753** The implementation of this routine was generated by a program,
138754** mkkeywordhash.c, located in the tool subdirectory of the distribution.
138755** The output of the mkkeywordhash.c program is written into a file
138756** named keywordhash.h and then included into this source file by
138757** the #include below.
138758*/
138759/************** Include keywordhash.h in the middle of tokenize.c ************/
138760/************** Begin file keywordhash.h *************************************/
138761/***** This file contains automatically generated code ******
138762**
138763** The code in this file has been automatically generated by
138764**
138765**   sqlite/tool/mkkeywordhash.c
138766**
138767** The code in this file implements a function that determines whether
138768** or not a given identifier is really an SQL keyword.  The same thing
138769** might be implemented more directly using a hand-written hash table.
138770** But by using this automatically generated code, the size of the code
138771** is substantially reduced.  This is important for embedded applications
138772** on platforms with limited memory.
138773*/
138774/* Hash score: 182 */
138775static int keywordCode(const char *z, int n, int *pType){
138776  /* zText[] encodes 834 bytes of keywords in 554 bytes */
138777  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
138778  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
138779  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
138780  /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
138781  /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
138782  /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
138783  /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
138784  /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
138785  /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
138786  /*   VACUUMVIEWINITIALLY                                                */
138787  static const char zText[553] = {
138788    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
138789    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
138790    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
138791    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
138792    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
138793    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
138794    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
138795    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
138796    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
138797    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
138798    'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
138799    'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
138800    'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
138801    'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
138802    'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
138803    'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
138804    'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
138805    'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
138806    'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
138807    'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
138808    'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
138809    'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
138810    'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
138811    'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
138812    'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
138813    'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
138814    'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
138815    'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
138816    'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
138817    'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
138818    'V','I','E','W','I','N','I','T','I','A','L','L','Y',
138819  };
138820  static const unsigned char aHash[127] = {
138821      76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
138822      42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
138823     121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
138824       0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
138825       0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
138826      96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
138827     100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
138828      39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
138829      62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
138830      29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
138831  };
138832  static const unsigned char aNext[124] = {
138833       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
138834       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
138835       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
138836       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
138837       0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
138838       0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
138839       0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
138840      10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
138841       0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
138842      73,  83,   0,  35,  68,   0,   0,
138843  };
138844  static const unsigned char aLen[124] = {
138845       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
138846       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
138847      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
138848       4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
138849       6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
138850       7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
138851       7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
138852      13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
138853       2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
138854       3,   5,   5,   6,   4,   9,   3,
138855  };
138856  static const unsigned short int aOffset[124] = {
138857       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
138858      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
138859      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
138860     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
138861     199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
138862     250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
138863     320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
138864     387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
138865     460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
138866     521, 524, 529, 534, 540, 544, 549,
138867  };
138868  static const unsigned char aCode[124] = {
138869    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
138870    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
138871    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
138872    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
138873    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
138874    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
138875    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
138876    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
138877    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
138878    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,
138879    TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,
138880    TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,
138881    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,
138882    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,
138883    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,
138884    TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,
138885    TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,
138886    TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,
138887    TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,
138888    TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,
138889    TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,
138890    TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,
138891    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,
138892    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,
138893    TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,
138894  };
138895  int i, j;
138896  const char *zKW;
138897  if( n>=2 ){
138898    i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
138899    for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){
138900      if( aLen[i]!=n ) continue;
138901      j = 0;
138902      zKW = &zText[aOffset[i]];
138903#ifdef SQLITE_ASCII
138904      while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
138905#endif
138906#ifdef SQLITE_EBCDIC
138907      while( j<n && toupper(z[j])==zKW[j] ){ j++; }
138908#endif
138909      if( j<n ) continue;
138910      testcase( i==0 ); /* REINDEX */
138911      testcase( i==1 ); /* INDEXED */
138912      testcase( i==2 ); /* INDEX */
138913      testcase( i==3 ); /* DESC */
138914      testcase( i==4 ); /* ESCAPE */
138915      testcase( i==5 ); /* EACH */
138916      testcase( i==6 ); /* CHECK */
138917      testcase( i==7 ); /* KEY */
138918      testcase( i==8 ); /* BEFORE */
138919      testcase( i==9 ); /* FOREIGN */
138920      testcase( i==10 ); /* FOR */
138921      testcase( i==11 ); /* IGNORE */
138922      testcase( i==12 ); /* REGEXP */
138923      testcase( i==13 ); /* EXPLAIN */
138924      testcase( i==14 ); /* INSTEAD */
138925      testcase( i==15 ); /* ADD */
138926      testcase( i==16 ); /* DATABASE */
138927      testcase( i==17 ); /* AS */
138928      testcase( i==18 ); /* SELECT */
138929      testcase( i==19 ); /* TABLE */
138930      testcase( i==20 ); /* LEFT */
138931      testcase( i==21 ); /* THEN */
138932      testcase( i==22 ); /* END */
138933      testcase( i==23 ); /* DEFERRABLE */
138934      testcase( i==24 ); /* ELSE */
138935      testcase( i==25 ); /* EXCEPT */
138936      testcase( i==26 ); /* TRANSACTION */
138937      testcase( i==27 ); /* ACTION */
138938      testcase( i==28 ); /* ON */
138939      testcase( i==29 ); /* NATURAL */
138940      testcase( i==30 ); /* ALTER */
138941      testcase( i==31 ); /* RAISE */
138942      testcase( i==32 ); /* EXCLUSIVE */
138943      testcase( i==33 ); /* EXISTS */
138944      testcase( i==34 ); /* SAVEPOINT */
138945      testcase( i==35 ); /* INTERSECT */
138946      testcase( i==36 ); /* TRIGGER */
138947      testcase( i==37 ); /* REFERENCES */
138948      testcase( i==38 ); /* CONSTRAINT */
138949      testcase( i==39 ); /* INTO */
138950      testcase( i==40 ); /* OFFSET */
138951      testcase( i==41 ); /* OF */
138952      testcase( i==42 ); /* SET */
138953      testcase( i==43 ); /* TEMPORARY */
138954      testcase( i==44 ); /* TEMP */
138955      testcase( i==45 ); /* OR */
138956      testcase( i==46 ); /* UNIQUE */
138957      testcase( i==47 ); /* QUERY */
138958      testcase( i==48 ); /* WITHOUT */
138959      testcase( i==49 ); /* WITH */
138960      testcase( i==50 ); /* OUTER */
138961      testcase( i==51 ); /* RELEASE */
138962      testcase( i==52 ); /* ATTACH */
138963      testcase( i==53 ); /* HAVING */
138964      testcase( i==54 ); /* GROUP */
138965      testcase( i==55 ); /* UPDATE */
138966      testcase( i==56 ); /* BEGIN */
138967      testcase( i==57 ); /* INNER */
138968      testcase( i==58 ); /* RECURSIVE */
138969      testcase( i==59 ); /* BETWEEN */
138970      testcase( i==60 ); /* NOTNULL */
138971      testcase( i==61 ); /* NOT */
138972      testcase( i==62 ); /* NO */
138973      testcase( i==63 ); /* NULL */
138974      testcase( i==64 ); /* LIKE */
138975      testcase( i==65 ); /* CASCADE */
138976      testcase( i==66 ); /* ASC */
138977      testcase( i==67 ); /* DELETE */
138978      testcase( i==68 ); /* CASE */
138979      testcase( i==69 ); /* COLLATE */
138980      testcase( i==70 ); /* CREATE */
138981      testcase( i==71 ); /* CURRENT_DATE */
138982      testcase( i==72 ); /* DETACH */
138983      testcase( i==73 ); /* IMMEDIATE */
138984      testcase( i==74 ); /* JOIN */
138985      testcase( i==75 ); /* INSERT */
138986      testcase( i==76 ); /* MATCH */
138987      testcase( i==77 ); /* PLAN */
138988      testcase( i==78 ); /* ANALYZE */
138989      testcase( i==79 ); /* PRAGMA */
138990      testcase( i==80 ); /* ABORT */
138991      testcase( i==81 ); /* VALUES */
138992      testcase( i==82 ); /* VIRTUAL */
138993      testcase( i==83 ); /* LIMIT */
138994      testcase( i==84 ); /* WHEN */
138995      testcase( i==85 ); /* WHERE */
138996      testcase( i==86 ); /* RENAME */
138997      testcase( i==87 ); /* AFTER */
138998      testcase( i==88 ); /* REPLACE */
138999      testcase( i==89 ); /* AND */
139000      testcase( i==90 ); /* DEFAULT */
139001      testcase( i==91 ); /* AUTOINCREMENT */
139002      testcase( i==92 ); /* TO */
139003      testcase( i==93 ); /* IN */
139004      testcase( i==94 ); /* CAST */
139005      testcase( i==95 ); /* COLUMN */
139006      testcase( i==96 ); /* COMMIT */
139007      testcase( i==97 ); /* CONFLICT */
139008      testcase( i==98 ); /* CROSS */
139009      testcase( i==99 ); /* CURRENT_TIMESTAMP */
139010      testcase( i==100 ); /* CURRENT_TIME */
139011      testcase( i==101 ); /* PRIMARY */
139012      testcase( i==102 ); /* DEFERRED */
139013      testcase( i==103 ); /* DISTINCT */
139014      testcase( i==104 ); /* IS */
139015      testcase( i==105 ); /* DROP */
139016      testcase( i==106 ); /* FAIL */
139017      testcase( i==107 ); /* FROM */
139018      testcase( i==108 ); /* FULL */
139019      testcase( i==109 ); /* GLOB */
139020      testcase( i==110 ); /* BY */
139021      testcase( i==111 ); /* IF */
139022      testcase( i==112 ); /* ISNULL */
139023      testcase( i==113 ); /* ORDER */
139024      testcase( i==114 ); /* RESTRICT */
139025      testcase( i==115 ); /* RIGHT */
139026      testcase( i==116 ); /* ROLLBACK */
139027      testcase( i==117 ); /* ROW */
139028      testcase( i==118 ); /* UNION */
139029      testcase( i==119 ); /* USING */
139030      testcase( i==120 ); /* VACUUM */
139031      testcase( i==121 ); /* VIEW */
139032      testcase( i==122 ); /* INITIALLY */
139033      testcase( i==123 ); /* ALL */
139034      *pType = aCode[i];
139035      break;
139036    }
139037  }
139038  return n;
139039}
139040SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
139041  int id = TK_ID;
139042  keywordCode((char*)z, n, &id);
139043  return id;
139044}
139045#define SQLITE_N_KEYWORD 124
139046
139047/************** End of keywordhash.h *****************************************/
139048/************** Continuing where we left off in tokenize.c *******************/
139049
139050
139051/*
139052** If X is a character that can be used in an identifier then
139053** IdChar(X) will be true.  Otherwise it is false.
139054**
139055** For ASCII, any character with the high-order bit set is
139056** allowed in an identifier.  For 7-bit characters,
139057** sqlite3IsIdChar[X] must be 1.
139058**
139059** For EBCDIC, the rules are more complex but have the same
139060** end result.
139061**
139062** Ticket #1066.  the SQL standard does not allow '$' in the
139063** middle of identifiers.  But many SQL implementations do.
139064** SQLite will allow '$' in identifiers for compatibility.
139065** But the feature is undocumented.
139066*/
139067#ifdef SQLITE_ASCII
139068#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
139069#endif
139070#ifdef SQLITE_EBCDIC
139071SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
139072/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
139073    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
139074    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
139075    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
139076    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
139077    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
139078    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
139079    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
139080    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
139081    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
139082    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
139083    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
139084    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
139085};
139086#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
139087#endif
139088
139089/* Make the IdChar function accessible from ctime.c */
139090#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
139091SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
139092#endif
139093
139094
139095/*
139096** Return the length (in bytes) of the token that begins at z[0].
139097** Store the token type in *tokenType before returning.
139098*/
139099SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
139100  int i, c;
139101  switch( aiClass[*z] ){  /* Switch on the character-class of the first byte
139102                          ** of the token. See the comment on the CC_ defines
139103                          ** above. */
139104    case CC_SPACE: {
139105      testcase( z[0]==' ' );
139106      testcase( z[0]=='\t' );
139107      testcase( z[0]=='\n' );
139108      testcase( z[0]=='\f' );
139109      testcase( z[0]=='\r' );
139110      for(i=1; sqlite3Isspace(z[i]); i++){}
139111      *tokenType = TK_SPACE;
139112      return i;
139113    }
139114    case CC_MINUS: {
139115      if( z[1]=='-' ){
139116        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
139117        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
139118        return i;
139119      }
139120      *tokenType = TK_MINUS;
139121      return 1;
139122    }
139123    case CC_LP: {
139124      *tokenType = TK_LP;
139125      return 1;
139126    }
139127    case CC_RP: {
139128      *tokenType = TK_RP;
139129      return 1;
139130    }
139131    case CC_SEMI: {
139132      *tokenType = TK_SEMI;
139133      return 1;
139134    }
139135    case CC_PLUS: {
139136      *tokenType = TK_PLUS;
139137      return 1;
139138    }
139139    case CC_STAR: {
139140      *tokenType = TK_STAR;
139141      return 1;
139142    }
139143    case CC_SLASH: {
139144      if( z[1]!='*' || z[2]==0 ){
139145        *tokenType = TK_SLASH;
139146        return 1;
139147      }
139148      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
139149      if( c ) i++;
139150      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
139151      return i;
139152    }
139153    case CC_PERCENT: {
139154      *tokenType = TK_REM;
139155      return 1;
139156    }
139157    case CC_EQ: {
139158      *tokenType = TK_EQ;
139159      return 1 + (z[1]=='=');
139160    }
139161    case CC_LT: {
139162      if( (c=z[1])=='=' ){
139163        *tokenType = TK_LE;
139164        return 2;
139165      }else if( c=='>' ){
139166        *tokenType = TK_NE;
139167        return 2;
139168      }else if( c=='<' ){
139169        *tokenType = TK_LSHIFT;
139170        return 2;
139171      }else{
139172        *tokenType = TK_LT;
139173        return 1;
139174      }
139175    }
139176    case CC_GT: {
139177      if( (c=z[1])=='=' ){
139178        *tokenType = TK_GE;
139179        return 2;
139180      }else if( c=='>' ){
139181        *tokenType = TK_RSHIFT;
139182        return 2;
139183      }else{
139184        *tokenType = TK_GT;
139185        return 1;
139186      }
139187    }
139188    case CC_BANG: {
139189      if( z[1]!='=' ){
139190        *tokenType = TK_ILLEGAL;
139191        return 1;
139192      }else{
139193        *tokenType = TK_NE;
139194        return 2;
139195      }
139196    }
139197    case CC_PIPE: {
139198      if( z[1]!='|' ){
139199        *tokenType = TK_BITOR;
139200        return 1;
139201      }else{
139202        *tokenType = TK_CONCAT;
139203        return 2;
139204      }
139205    }
139206    case CC_COMMA: {
139207      *tokenType = TK_COMMA;
139208      return 1;
139209    }
139210    case CC_AND: {
139211      *tokenType = TK_BITAND;
139212      return 1;
139213    }
139214    case CC_TILDA: {
139215      *tokenType = TK_BITNOT;
139216      return 1;
139217    }
139218    case CC_QUOTE: {
139219      int delim = z[0];
139220      testcase( delim=='`' );
139221      testcase( delim=='\'' );
139222      testcase( delim=='"' );
139223      for(i=1; (c=z[i])!=0; i++){
139224        if( c==delim ){
139225          if( z[i+1]==delim ){
139226            i++;
139227          }else{
139228            break;
139229          }
139230        }
139231      }
139232      if( c=='\'' ){
139233        *tokenType = TK_STRING;
139234        return i+1;
139235      }else if( c!=0 ){
139236        *tokenType = TK_ID;
139237        return i+1;
139238      }else{
139239        *tokenType = TK_ILLEGAL;
139240        return i;
139241      }
139242    }
139243    case CC_DOT: {
139244#ifndef SQLITE_OMIT_FLOATING_POINT
139245      if( !sqlite3Isdigit(z[1]) )
139246#endif
139247      {
139248        *tokenType = TK_DOT;
139249        return 1;
139250      }
139251      /* If the next character is a digit, this is a floating point
139252      ** number that begins with ".".  Fall thru into the next case */
139253    }
139254    case CC_DIGIT: {
139255      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
139256      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
139257      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
139258      testcase( z[0]=='9' );
139259      *tokenType = TK_INTEGER;
139260#ifndef SQLITE_OMIT_HEX_INTEGER
139261      if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
139262        for(i=3; sqlite3Isxdigit(z[i]); i++){}
139263        return i;
139264      }
139265#endif
139266      for(i=0; sqlite3Isdigit(z[i]); i++){}
139267#ifndef SQLITE_OMIT_FLOATING_POINT
139268      if( z[i]=='.' ){
139269        i++;
139270        while( sqlite3Isdigit(z[i]) ){ i++; }
139271        *tokenType = TK_FLOAT;
139272      }
139273      if( (z[i]=='e' || z[i]=='E') &&
139274           ( sqlite3Isdigit(z[i+1])
139275            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
139276           )
139277      ){
139278        i += 2;
139279        while( sqlite3Isdigit(z[i]) ){ i++; }
139280        *tokenType = TK_FLOAT;
139281      }
139282#endif
139283      while( IdChar(z[i]) ){
139284        *tokenType = TK_ILLEGAL;
139285        i++;
139286      }
139287      return i;
139288    }
139289    case CC_QUOTE2: {
139290      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
139291      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
139292      return i;
139293    }
139294    case CC_VARNUM: {
139295      *tokenType = TK_VARIABLE;
139296      for(i=1; sqlite3Isdigit(z[i]); i++){}
139297      return i;
139298    }
139299    case CC_DOLLAR:
139300    case CC_VARALPHA: {
139301      int n = 0;
139302      testcase( z[0]=='$' );  testcase( z[0]=='@' );
139303      testcase( z[0]==':' );  testcase( z[0]=='#' );
139304      *tokenType = TK_VARIABLE;
139305      for(i=1; (c=z[i])!=0; i++){
139306        if( IdChar(c) ){
139307          n++;
139308#ifndef SQLITE_OMIT_TCL_VARIABLE
139309        }else if( c=='(' && n>0 ){
139310          do{
139311            i++;
139312          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
139313          if( c==')' ){
139314            i++;
139315          }else{
139316            *tokenType = TK_ILLEGAL;
139317          }
139318          break;
139319        }else if( c==':' && z[i+1]==':' ){
139320          i++;
139321#endif
139322        }else{
139323          break;
139324        }
139325      }
139326      if( n==0 ) *tokenType = TK_ILLEGAL;
139327      return i;
139328    }
139329    case CC_KYWD: {
139330      for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
139331      if( IdChar(z[i]) ){
139332        /* This token started out using characters that can appear in keywords,
139333        ** but z[i] is a character not allowed within keywords, so this must
139334        ** be an identifier instead */
139335        i++;
139336        break;
139337      }
139338      *tokenType = TK_ID;
139339      return keywordCode((char*)z, i, tokenType);
139340    }
139341    case CC_X: {
139342#ifndef SQLITE_OMIT_BLOB_LITERAL
139343      testcase( z[0]=='x' ); testcase( z[0]=='X' );
139344      if( z[1]=='\'' ){
139345        *tokenType = TK_BLOB;
139346        for(i=2; sqlite3Isxdigit(z[i]); i++){}
139347        if( z[i]!='\'' || i%2 ){
139348          *tokenType = TK_ILLEGAL;
139349          while( z[i] && z[i]!='\'' ){ i++; }
139350        }
139351        if( z[i] ) i++;
139352        return i;
139353      }
139354#endif
139355      /* If it is not a BLOB literal, then it must be an ID, since no
139356      ** SQL keywords start with the letter 'x'.  Fall through */
139357    }
139358    case CC_ID: {
139359      i = 1;
139360      break;
139361    }
139362    default: {
139363      *tokenType = TK_ILLEGAL;
139364      return 1;
139365    }
139366  }
139367  while( IdChar(z[i]) ){ i++; }
139368  *tokenType = TK_ID;
139369  return i;
139370}
139371
139372/*
139373** Run the parser on the given SQL string.  The parser structure is
139374** passed in.  An SQLITE_ status code is returned.  If an error occurs
139375** then an and attempt is made to write an error message into
139376** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
139377** error message.
139378*/
139379SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
139380  int nErr = 0;                   /* Number of errors encountered */
139381  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
139382  int n = 0;                      /* Length of the next token token */
139383  int tokenType;                  /* type of the next token */
139384  int lastTokenParsed = -1;       /* type of the previous token */
139385  sqlite3 *db = pParse->db;       /* The database connection */
139386  int mxSqlLen;                   /* Max length of an SQL string */
139387#ifdef sqlite3Parser_ENGINEALWAYSONSTACK
139388  unsigned char zSpace[sizeof(yyParser)];  /* Space for parser engine object */
139389#endif
139390
139391  assert( zSql!=0 );
139392  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
139393  if( db->nVdbeActive==0 ){
139394    db->u1.isInterrupted = 0;
139395  }
139396  pParse->rc = SQLITE_OK;
139397  pParse->zTail = zSql;
139398  assert( pzErrMsg!=0 );
139399  /* sqlite3ParserTrace(stdout, "parser: "); */
139400#ifdef sqlite3Parser_ENGINEALWAYSONSTACK
139401  pEngine = zSpace;
139402  sqlite3ParserInit(pEngine);
139403#else
139404  pEngine = sqlite3ParserAlloc(sqlite3Malloc);
139405  if( pEngine==0 ){
139406    sqlite3OomFault(db);
139407    return SQLITE_NOMEM_BKPT;
139408  }
139409#endif
139410  assert( pParse->pNewTable==0 );
139411  assert( pParse->pNewTrigger==0 );
139412  assert( pParse->nVar==0 );
139413  assert( pParse->pVList==0 );
139414  while( 1 ){
139415    if( zSql[0]!=0 ){
139416      n = sqlite3GetToken((u8*)zSql, &tokenType);
139417      mxSqlLen -= n;
139418      if( mxSqlLen<0 ){
139419        pParse->rc = SQLITE_TOOBIG;
139420        break;
139421      }
139422    }else{
139423      /* Upon reaching the end of input, call the parser two more times
139424      ** with tokens TK_SEMI and 0, in that order. */
139425      if( lastTokenParsed==TK_SEMI ){
139426        tokenType = 0;
139427      }else if( lastTokenParsed==0 ){
139428        break;
139429      }else{
139430        tokenType = TK_SEMI;
139431      }
139432      zSql -= n;
139433    }
139434    if( tokenType>=TK_SPACE ){
139435      assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
139436      if( db->u1.isInterrupted ){
139437        pParse->rc = SQLITE_INTERRUPT;
139438        break;
139439      }
139440      if( tokenType==TK_ILLEGAL ){
139441        sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
139442        break;
139443      }
139444      zSql += n;
139445    }else{
139446      pParse->sLastToken.z = zSql;
139447      pParse->sLastToken.n = n;
139448      sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
139449      lastTokenParsed = tokenType;
139450      zSql += n;
139451      if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
139452    }
139453  }
139454  assert( nErr==0 );
139455  pParse->zTail = zSql;
139456#ifdef YYTRACKMAXSTACKDEPTH
139457  sqlite3_mutex_enter(sqlite3MallocMutex());
139458  sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
139459      sqlite3ParserStackPeak(pEngine)
139460  );
139461  sqlite3_mutex_leave(sqlite3MallocMutex());
139462#endif /* YYDEBUG */
139463#ifdef sqlite3Parser_ENGINEALWAYSONSTACK
139464  sqlite3ParserFinalize(pEngine);
139465#else
139466  sqlite3ParserFree(pEngine, sqlite3_free);
139467#endif
139468  if( db->mallocFailed ){
139469    pParse->rc = SQLITE_NOMEM_BKPT;
139470  }
139471  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
139472    pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
139473  }
139474  assert( pzErrMsg!=0 );
139475  if( pParse->zErrMsg ){
139476    *pzErrMsg = pParse->zErrMsg;
139477    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
139478    pParse->zErrMsg = 0;
139479    nErr++;
139480  }
139481  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
139482    sqlite3VdbeDelete(pParse->pVdbe);
139483    pParse->pVdbe = 0;
139484  }
139485#ifndef SQLITE_OMIT_SHARED_CACHE
139486  if( pParse->nested==0 ){
139487    sqlite3DbFree(db, pParse->aTableLock);
139488    pParse->aTableLock = 0;
139489    pParse->nTableLock = 0;
139490  }
139491#endif
139492#ifndef SQLITE_OMIT_VIRTUALTABLE
139493  sqlite3_free(pParse->apVtabLock);
139494#endif
139495
139496  if( !IN_DECLARE_VTAB ){
139497    /* If the pParse->declareVtab flag is set, do not delete any table
139498    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
139499    ** will take responsibility for freeing the Table structure.
139500    */
139501    sqlite3DeleteTable(db, pParse->pNewTable);
139502  }
139503
139504  if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
139505  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
139506  sqlite3DbFree(db, pParse->pVList);
139507  while( pParse->pAinc ){
139508    AutoincInfo *p = pParse->pAinc;
139509    pParse->pAinc = p->pNext;
139510    sqlite3DbFree(db, p);
139511  }
139512  while( pParse->pZombieTab ){
139513    Table *p = pParse->pZombieTab;
139514    pParse->pZombieTab = p->pNextZombie;
139515    sqlite3DeleteTable(db, p);
139516  }
139517  assert( nErr==0 || pParse->rc!=SQLITE_OK );
139518  return nErr;
139519}
139520
139521/************** End of tokenize.c ********************************************/
139522/************** Begin file complete.c ****************************************/
139523/*
139524** 2001 September 15
139525**
139526** The author disclaims copyright to this source code.  In place of
139527** a legal notice, here is a blessing:
139528**
139529**    May you do good and not evil.
139530**    May you find forgiveness for yourself and forgive others.
139531**    May you share freely, never taking more than you give.
139532**
139533*************************************************************************
139534** An tokenizer for SQL
139535**
139536** This file contains C code that implements the sqlite3_complete() API.
139537** This code used to be part of the tokenizer.c source file.  But by
139538** separating it out, the code will be automatically omitted from
139539** static links that do not use it.
139540*/
139541/* #include "sqliteInt.h" */
139542#ifndef SQLITE_OMIT_COMPLETE
139543
139544/*
139545** This is defined in tokenize.c.  We just have to import the definition.
139546*/
139547#ifndef SQLITE_AMALGAMATION
139548#ifdef SQLITE_ASCII
139549#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
139550#endif
139551#ifdef SQLITE_EBCDIC
139552SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
139553#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
139554#endif
139555#endif /* SQLITE_AMALGAMATION */
139556
139557
139558/*
139559** Token types used by the sqlite3_complete() routine.  See the header
139560** comments on that procedure for additional information.
139561*/
139562#define tkSEMI    0
139563#define tkWS      1
139564#define tkOTHER   2
139565#ifndef SQLITE_OMIT_TRIGGER
139566#define tkEXPLAIN 3
139567#define tkCREATE  4
139568#define tkTEMP    5
139569#define tkTRIGGER 6
139570#define tkEND     7
139571#endif
139572
139573/*
139574** Return TRUE if the given SQL string ends in a semicolon.
139575**
139576** Special handling is require for CREATE TRIGGER statements.
139577** Whenever the CREATE TRIGGER keywords are seen, the statement
139578** must end with ";END;".
139579**
139580** This implementation uses a state machine with 8 states:
139581**
139582**   (0) INVALID   We have not yet seen a non-whitespace character.
139583**
139584**   (1) START     At the beginning or end of an SQL statement.  This routine
139585**                 returns 1 if it ends in the START state and 0 if it ends
139586**                 in any other state.
139587**
139588**   (2) NORMAL    We are in the middle of statement which ends with a single
139589**                 semicolon.
139590**
139591**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
139592**                 a statement.
139593**
139594**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
139595**                 statement, possibly preceded by EXPLAIN and/or followed by
139596**                 TEMP or TEMPORARY
139597**
139598**   (5) TRIGGER   We are in the middle of a trigger definition that must be
139599**                 ended by a semicolon, the keyword END, and another semicolon.
139600**
139601**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
139602**                 the end of a trigger definition.
139603**
139604**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
139605**                 of a trigger definition.
139606**
139607** Transitions between states above are determined by tokens extracted
139608** from the input.  The following tokens are significant:
139609**
139610**   (0) tkSEMI      A semicolon.
139611**   (1) tkWS        Whitespace.
139612**   (2) tkOTHER     Any other SQL token.
139613**   (3) tkEXPLAIN   The "explain" keyword.
139614**   (4) tkCREATE    The "create" keyword.
139615**   (5) tkTEMP      The "temp" or "temporary" keyword.
139616**   (6) tkTRIGGER   The "trigger" keyword.
139617**   (7) tkEND       The "end" keyword.
139618**
139619** Whitespace never causes a state transition and is always ignored.
139620** This means that a SQL string of all whitespace is invalid.
139621**
139622** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
139623** to recognize the end of a trigger can be omitted.  All we have to do
139624** is look for a semicolon that is not part of an string or comment.
139625*/
139626SQLITE_API int sqlite3_complete(const char *zSql){
139627  u8 state = 0;   /* Current state, using numbers defined in header comment */
139628  u8 token;       /* Value of the next token */
139629
139630#ifndef SQLITE_OMIT_TRIGGER
139631  /* A complex statement machine used to detect the end of a CREATE TRIGGER
139632  ** statement.  This is the normal case.
139633  */
139634  static const u8 trans[8][8] = {
139635                     /* Token:                                                */
139636     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
139637     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
139638     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
139639     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
139640     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
139641     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
139642     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
139643     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
139644     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
139645  };
139646#else
139647  /* If triggers are not supported by this compile then the statement machine
139648  ** used to detect the end of a statement is much simpler
139649  */
139650  static const u8 trans[3][3] = {
139651                     /* Token:           */
139652     /* State:       **  SEMI  WS  OTHER */
139653     /* 0 INVALID: */ {    1,  0,     2, },
139654     /* 1   START: */ {    1,  1,     2, },
139655     /* 2  NORMAL: */ {    1,  2,     2, },
139656  };
139657#endif /* SQLITE_OMIT_TRIGGER */
139658
139659#ifdef SQLITE_ENABLE_API_ARMOR
139660  if( zSql==0 ){
139661    (void)SQLITE_MISUSE_BKPT;
139662    return 0;
139663  }
139664#endif
139665
139666  while( *zSql ){
139667    switch( *zSql ){
139668      case ';': {  /* A semicolon */
139669        token = tkSEMI;
139670        break;
139671      }
139672      case ' ':
139673      case '\r':
139674      case '\t':
139675      case '\n':
139676      case '\f': {  /* White space is ignored */
139677        token = tkWS;
139678        break;
139679      }
139680      case '/': {   /* C-style comments */
139681        if( zSql[1]!='*' ){
139682          token = tkOTHER;
139683          break;
139684        }
139685        zSql += 2;
139686        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
139687        if( zSql[0]==0 ) return 0;
139688        zSql++;
139689        token = tkWS;
139690        break;
139691      }
139692      case '-': {   /* SQL-style comments from "--" to end of line */
139693        if( zSql[1]!='-' ){
139694          token = tkOTHER;
139695          break;
139696        }
139697        while( *zSql && *zSql!='\n' ){ zSql++; }
139698        if( *zSql==0 ) return state==1;
139699        token = tkWS;
139700        break;
139701      }
139702      case '[': {   /* Microsoft-style identifiers in [...] */
139703        zSql++;
139704        while( *zSql && *zSql!=']' ){ zSql++; }
139705        if( *zSql==0 ) return 0;
139706        token = tkOTHER;
139707        break;
139708      }
139709      case '`':     /* Grave-accent quoted symbols used by MySQL */
139710      case '"':     /* single- and double-quoted strings */
139711      case '\'': {
139712        int c = *zSql;
139713        zSql++;
139714        while( *zSql && *zSql!=c ){ zSql++; }
139715        if( *zSql==0 ) return 0;
139716        token = tkOTHER;
139717        break;
139718      }
139719      default: {
139720#ifdef SQLITE_EBCDIC
139721        unsigned char c;
139722#endif
139723        if( IdChar((u8)*zSql) ){
139724          /* Keywords and unquoted identifiers */
139725          int nId;
139726          for(nId=1; IdChar(zSql[nId]); nId++){}
139727#ifdef SQLITE_OMIT_TRIGGER
139728          token = tkOTHER;
139729#else
139730          switch( *zSql ){
139731            case 'c': case 'C': {
139732              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
139733                token = tkCREATE;
139734              }else{
139735                token = tkOTHER;
139736              }
139737              break;
139738            }
139739            case 't': case 'T': {
139740              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
139741                token = tkTRIGGER;
139742              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
139743                token = tkTEMP;
139744              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
139745                token = tkTEMP;
139746              }else{
139747                token = tkOTHER;
139748              }
139749              break;
139750            }
139751            case 'e':  case 'E': {
139752              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
139753                token = tkEND;
139754              }else
139755#ifndef SQLITE_OMIT_EXPLAIN
139756              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
139757                token = tkEXPLAIN;
139758              }else
139759#endif
139760              {
139761                token = tkOTHER;
139762              }
139763              break;
139764            }
139765            default: {
139766              token = tkOTHER;
139767              break;
139768            }
139769          }
139770#endif /* SQLITE_OMIT_TRIGGER */
139771          zSql += nId-1;
139772        }else{
139773          /* Operators and special symbols */
139774          token = tkOTHER;
139775        }
139776        break;
139777      }
139778    }
139779    state = trans[state][token];
139780    zSql++;
139781  }
139782  return state==1;
139783}
139784
139785#ifndef SQLITE_OMIT_UTF16
139786/*
139787** This routine is the same as the sqlite3_complete() routine described
139788** above, except that the parameter is required to be UTF-16 encoded, not
139789** UTF-8.
139790*/
139791SQLITE_API int sqlite3_complete16(const void *zSql){
139792  sqlite3_value *pVal;
139793  char const *zSql8;
139794  int rc;
139795
139796#ifndef SQLITE_OMIT_AUTOINIT
139797  rc = sqlite3_initialize();
139798  if( rc ) return rc;
139799#endif
139800  pVal = sqlite3ValueNew(0);
139801  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
139802  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
139803  if( zSql8 ){
139804    rc = sqlite3_complete(zSql8);
139805  }else{
139806    rc = SQLITE_NOMEM_BKPT;
139807  }
139808  sqlite3ValueFree(pVal);
139809  return rc & 0xff;
139810}
139811#endif /* SQLITE_OMIT_UTF16 */
139812#endif /* SQLITE_OMIT_COMPLETE */
139813
139814/************** End of complete.c ********************************************/
139815/************** Begin file main.c ********************************************/
139816/*
139817** 2001 September 15
139818**
139819** The author disclaims copyright to this source code.  In place of
139820** a legal notice, here is a blessing:
139821**
139822**    May you do good and not evil.
139823**    May you find forgiveness for yourself and forgive others.
139824**    May you share freely, never taking more than you give.
139825**
139826*************************************************************************
139827** Main file for the SQLite library.  The routines in this file
139828** implement the programmer interface to the library.  Routines in
139829** other files are for internal use by SQLite and should not be
139830** accessed by users of the library.
139831*/
139832/* #include "sqliteInt.h" */
139833
139834#ifdef SQLITE_ENABLE_FTS3
139835/************** Include fts3.h in the middle of main.c ***********************/
139836/************** Begin file fts3.h ********************************************/
139837/*
139838** 2006 Oct 10
139839**
139840** The author disclaims copyright to this source code.  In place of
139841** a legal notice, here is a blessing:
139842**
139843**    May you do good and not evil.
139844**    May you find forgiveness for yourself and forgive others.
139845**    May you share freely, never taking more than you give.
139846**
139847******************************************************************************
139848**
139849** This header file is used by programs that want to link against the
139850** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
139851*/
139852/* #include "sqlite3.h" */
139853
139854#if 0
139855extern "C" {
139856#endif  /* __cplusplus */
139857
139858SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
139859
139860#if 0
139861}  /* extern "C" */
139862#endif  /* __cplusplus */
139863
139864/************** End of fts3.h ************************************************/
139865/************** Continuing where we left off in main.c ***********************/
139866#endif
139867#ifdef SQLITE_ENABLE_RTREE
139868/************** Include rtree.h in the middle of main.c **********************/
139869/************** Begin file rtree.h *******************************************/
139870/*
139871** 2008 May 26
139872**
139873** The author disclaims copyright to this source code.  In place of
139874** a legal notice, here is a blessing:
139875**
139876**    May you do good and not evil.
139877**    May you find forgiveness for yourself and forgive others.
139878**    May you share freely, never taking more than you give.
139879**
139880******************************************************************************
139881**
139882** This header file is used by programs that want to link against the
139883** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
139884*/
139885/* #include "sqlite3.h" */
139886
139887#if 0
139888extern "C" {
139889#endif  /* __cplusplus */
139890
139891SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
139892
139893#if 0
139894}  /* extern "C" */
139895#endif  /* __cplusplus */
139896
139897/************** End of rtree.h ***********************************************/
139898/************** Continuing where we left off in main.c ***********************/
139899#endif
139900#ifdef SQLITE_ENABLE_ICU
139901/************** Include sqliteicu.h in the middle of main.c ******************/
139902/************** Begin file sqliteicu.h ***************************************/
139903/*
139904** 2008 May 26
139905**
139906** The author disclaims copyright to this source code.  In place of
139907** a legal notice, here is a blessing:
139908**
139909**    May you do good and not evil.
139910**    May you find forgiveness for yourself and forgive others.
139911**    May you share freely, never taking more than you give.
139912**
139913******************************************************************************
139914**
139915** This header file is used by programs that want to link against the
139916** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
139917*/
139918/* #include "sqlite3.h" */
139919
139920#if 0
139921extern "C" {
139922#endif  /* __cplusplus */
139923
139924SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
139925
139926#if 0
139927}  /* extern "C" */
139928#endif  /* __cplusplus */
139929
139930
139931/************** End of sqliteicu.h *******************************************/
139932/************** Continuing where we left off in main.c ***********************/
139933#endif
139934#ifdef SQLITE_ENABLE_JSON1
139935SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
139936#endif
139937#ifdef SQLITE_ENABLE_FTS5
139938SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
139939#endif
139940
139941#ifndef SQLITE_AMALGAMATION
139942/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
139943** contains the text of SQLITE_VERSION macro.
139944*/
139945SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
139946#endif
139947
139948/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
139949** a pointer to the to the sqlite3_version[] string constant.
139950*/
139951SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
139952
139953/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
139954** pointer to a string constant whose value is the same as the
139955** SQLITE_SOURCE_ID C preprocessor macro.
139956*/
139957SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
139958
139959/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
139960** returns an integer equal to SQLITE_VERSION_NUMBER.
139961*/
139962SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
139963
139964/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
139965** zero if and only if SQLite was compiled with mutexing code omitted due to
139966** the SQLITE_THREADSAFE compile-time option being set to 0.
139967*/
139968SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
139969
139970/*
139971** When compiling the test fixture or with debugging enabled (on Win32),
139972** this variable being set to non-zero will cause OSTRACE macros to emit
139973** extra diagnostic information.
139974*/
139975#ifdef SQLITE_HAVE_OS_TRACE
139976# ifndef SQLITE_DEBUG_OS_TRACE
139977#   define SQLITE_DEBUG_OS_TRACE 0
139978# endif
139979  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
139980#endif
139981
139982#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
139983/*
139984** If the following function pointer is not NULL and if
139985** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
139986** I/O active are written using this function.  These messages
139987** are intended for debugging activity only.
139988*/
139989SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
139990#endif
139991
139992/*
139993** If the following global variable points to a string which is the
139994** name of a directory, then that directory will be used to store
139995** temporary files.
139996**
139997** See also the "PRAGMA temp_store_directory" SQL command.
139998*/
139999SQLITE_API char *sqlite3_temp_directory = 0;
140000
140001/*
140002** If the following global variable points to a string which is the
140003** name of a directory, then that directory will be used to store
140004** all database files specified with a relative pathname.
140005**
140006** See also the "PRAGMA data_store_directory" SQL command.
140007*/
140008SQLITE_API char *sqlite3_data_directory = 0;
140009
140010/*
140011** Initialize SQLite.
140012**
140013** This routine must be called to initialize the memory allocation,
140014** VFS, and mutex subsystems prior to doing any serious work with
140015** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
140016** this routine will be called automatically by key routines such as
140017** sqlite3_open().
140018**
140019** This routine is a no-op except on its very first call for the process,
140020** or for the first call after a call to sqlite3_shutdown.
140021**
140022** The first thread to call this routine runs the initialization to
140023** completion.  If subsequent threads call this routine before the first
140024** thread has finished the initialization process, then the subsequent
140025** threads must block until the first thread finishes with the initialization.
140026**
140027** The first thread might call this routine recursively.  Recursive
140028** calls to this routine should not block, of course.  Otherwise the
140029** initialization process would never complete.
140030**
140031** Let X be the first thread to enter this routine.  Let Y be some other
140032** thread.  Then while the initial invocation of this routine by X is
140033** incomplete, it is required that:
140034**
140035**    *  Calls to this routine from Y must block until the outer-most
140036**       call by X completes.
140037**
140038**    *  Recursive calls to this routine from thread X return immediately
140039**       without blocking.
140040*/
140041SQLITE_API int sqlite3_initialize(void){
140042  MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
140043  int rc;                                      /* Result code */
140044#ifdef SQLITE_EXTRA_INIT
140045  int bRunExtraInit = 0;                       /* Extra initialization needed */
140046#endif
140047
140048#ifdef SQLITE_OMIT_WSD
140049  rc = sqlite3_wsd_init(4096, 24);
140050  if( rc!=SQLITE_OK ){
140051    return rc;
140052  }
140053#endif
140054
140055  /* If the following assert() fails on some obscure processor/compiler
140056  ** combination, the work-around is to set the correct pointer
140057  ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
140058  assert( SQLITE_PTRSIZE==sizeof(char*) );
140059
140060  /* If SQLite is already completely initialized, then this call
140061  ** to sqlite3_initialize() should be a no-op.  But the initialization
140062  ** must be complete.  So isInit must not be set until the very end
140063  ** of this routine.
140064  */
140065  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
140066
140067  /* Make sure the mutex subsystem is initialized.  If unable to
140068  ** initialize the mutex subsystem, return early with the error.
140069  ** If the system is so sick that we are unable to allocate a mutex,
140070  ** there is not much SQLite is going to be able to do.
140071  **
140072  ** The mutex subsystem must take care of serializing its own
140073  ** initialization.
140074  */
140075  rc = sqlite3MutexInit();
140076  if( rc ) return rc;
140077
140078  /* Initialize the malloc() system and the recursive pInitMutex mutex.
140079  ** This operation is protected by the STATIC_MASTER mutex.  Note that
140080  ** MutexAlloc() is called for a static mutex prior to initializing the
140081  ** malloc subsystem - this implies that the allocation of a static
140082  ** mutex must not require support from the malloc subsystem.
140083  */
140084  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
140085  sqlite3_mutex_enter(pMaster);
140086  sqlite3GlobalConfig.isMutexInit = 1;
140087  if( !sqlite3GlobalConfig.isMallocInit ){
140088    rc = sqlite3MallocInit();
140089  }
140090  if( rc==SQLITE_OK ){
140091    sqlite3GlobalConfig.isMallocInit = 1;
140092    if( !sqlite3GlobalConfig.pInitMutex ){
140093      sqlite3GlobalConfig.pInitMutex =
140094           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
140095      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
140096        rc = SQLITE_NOMEM_BKPT;
140097      }
140098    }
140099  }
140100  if( rc==SQLITE_OK ){
140101    sqlite3GlobalConfig.nRefInitMutex++;
140102  }
140103  sqlite3_mutex_leave(pMaster);
140104
140105  /* If rc is not SQLITE_OK at this point, then either the malloc
140106  ** subsystem could not be initialized or the system failed to allocate
140107  ** the pInitMutex mutex. Return an error in either case.  */
140108  if( rc!=SQLITE_OK ){
140109    return rc;
140110  }
140111
140112  /* Do the rest of the initialization under the recursive mutex so
140113  ** that we will be able to handle recursive calls into
140114  ** sqlite3_initialize().  The recursive calls normally come through
140115  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
140116  ** recursive calls might also be possible.
140117  **
140118  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
140119  ** to the xInit method, so the xInit method need not be threadsafe.
140120  **
140121  ** The following mutex is what serializes access to the appdef pcache xInit
140122  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
140123  ** call to sqlite3PcacheInitialize().
140124  */
140125  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
140126  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
140127    sqlite3GlobalConfig.inProgress = 1;
140128#ifdef SQLITE_ENABLE_SQLLOG
140129    {
140130      extern void sqlite3_init_sqllog(void);
140131      sqlite3_init_sqllog();
140132    }
140133#endif
140134    memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
140135    sqlite3RegisterBuiltinFunctions();
140136    if( sqlite3GlobalConfig.isPCacheInit==0 ){
140137      rc = sqlite3PcacheInitialize();
140138    }
140139    if( rc==SQLITE_OK ){
140140      sqlite3GlobalConfig.isPCacheInit = 1;
140141      rc = sqlite3OsInit();
140142    }
140143    if( rc==SQLITE_OK ){
140144      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
140145          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
140146      sqlite3GlobalConfig.isInit = 1;
140147#ifdef SQLITE_EXTRA_INIT
140148      bRunExtraInit = 1;
140149#endif
140150    }
140151    sqlite3GlobalConfig.inProgress = 0;
140152  }
140153  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
140154
140155  /* Go back under the static mutex and clean up the recursive
140156  ** mutex to prevent a resource leak.
140157  */
140158  sqlite3_mutex_enter(pMaster);
140159  sqlite3GlobalConfig.nRefInitMutex--;
140160  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
140161    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
140162    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
140163    sqlite3GlobalConfig.pInitMutex = 0;
140164  }
140165  sqlite3_mutex_leave(pMaster);
140166
140167  /* The following is just a sanity check to make sure SQLite has
140168  ** been compiled correctly.  It is important to run this code, but
140169  ** we don't want to run it too often and soak up CPU cycles for no
140170  ** reason.  So we run it once during initialization.
140171  */
140172#ifndef NDEBUG
140173#ifndef SQLITE_OMIT_FLOATING_POINT
140174  /* This section of code's only "output" is via assert() statements. */
140175  if ( rc==SQLITE_OK ){
140176    u64 x = (((u64)1)<<63)-1;
140177    double y;
140178    assert(sizeof(x)==8);
140179    assert(sizeof(x)==sizeof(y));
140180    memcpy(&y, &x, 8);
140181    assert( sqlite3IsNaN(y) );
140182  }
140183#endif
140184#endif
140185
140186  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
140187  ** compile-time option.
140188  */
140189#ifdef SQLITE_EXTRA_INIT
140190  if( bRunExtraInit ){
140191    int SQLITE_EXTRA_INIT(const char*);
140192    rc = SQLITE_EXTRA_INIT(0);
140193  }
140194#endif
140195
140196  return rc;
140197}
140198
140199/*
140200** Undo the effects of sqlite3_initialize().  Must not be called while
140201** there are outstanding database connections or memory allocations or
140202** while any part of SQLite is otherwise in use in any thread.  This
140203** routine is not threadsafe.  But it is safe to invoke this routine
140204** on when SQLite is already shut down.  If SQLite is already shut down
140205** when this routine is invoked, then this routine is a harmless no-op.
140206*/
140207SQLITE_API int sqlite3_shutdown(void){
140208#ifdef SQLITE_OMIT_WSD
140209  int rc = sqlite3_wsd_init(4096, 24);
140210  if( rc!=SQLITE_OK ){
140211    return rc;
140212  }
140213#endif
140214
140215  if( sqlite3GlobalConfig.isInit ){
140216#ifdef SQLITE_EXTRA_SHUTDOWN
140217    void SQLITE_EXTRA_SHUTDOWN(void);
140218    SQLITE_EXTRA_SHUTDOWN();
140219#endif
140220    sqlite3_os_end();
140221    sqlite3_reset_auto_extension();
140222    sqlite3GlobalConfig.isInit = 0;
140223  }
140224  if( sqlite3GlobalConfig.isPCacheInit ){
140225    sqlite3PcacheShutdown();
140226    sqlite3GlobalConfig.isPCacheInit = 0;
140227  }
140228  if( sqlite3GlobalConfig.isMallocInit ){
140229    sqlite3MallocEnd();
140230    sqlite3GlobalConfig.isMallocInit = 0;
140231
140232#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
140233    /* The heap subsystem has now been shutdown and these values are supposed
140234    ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
140235    ** which would rely on that heap subsystem; therefore, make sure these
140236    ** values cannot refer to heap memory that was just invalidated when the
140237    ** heap subsystem was shutdown.  This is only done if the current call to
140238    ** this function resulted in the heap subsystem actually being shutdown.
140239    */
140240    sqlite3_data_directory = 0;
140241    sqlite3_temp_directory = 0;
140242#endif
140243  }
140244  if( sqlite3GlobalConfig.isMutexInit ){
140245    sqlite3MutexEnd();
140246    sqlite3GlobalConfig.isMutexInit = 0;
140247  }
140248
140249  return SQLITE_OK;
140250}
140251
140252/*
140253** This API allows applications to modify the global configuration of
140254** the SQLite library at run-time.
140255**
140256** This routine should only be called when there are no outstanding
140257** database connections or memory allocations.  This routine is not
140258** threadsafe.  Failure to heed these warnings can lead to unpredictable
140259** behavior.
140260*/
140261SQLITE_API int sqlite3_config(int op, ...){
140262  va_list ap;
140263  int rc = SQLITE_OK;
140264
140265  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
140266  ** the SQLite library is in use. */
140267  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
140268
140269  va_start(ap, op);
140270  switch( op ){
140271
140272    /* Mutex configuration options are only available in a threadsafe
140273    ** compile.
140274    */
140275#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
140276    case SQLITE_CONFIG_SINGLETHREAD: {
140277      /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
140278      ** Single-thread. */
140279      sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
140280      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
140281      break;
140282    }
140283#endif
140284#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
140285    case SQLITE_CONFIG_MULTITHREAD: {
140286      /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
140287      ** Multi-thread. */
140288      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
140289      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
140290      break;
140291    }
140292#endif
140293#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
140294    case SQLITE_CONFIG_SERIALIZED: {
140295      /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
140296      ** Serialized. */
140297      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
140298      sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
140299      break;
140300    }
140301#endif
140302#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
140303    case SQLITE_CONFIG_MUTEX: {
140304      /* Specify an alternative mutex implementation */
140305      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
140306      break;
140307    }
140308#endif
140309#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
140310    case SQLITE_CONFIG_GETMUTEX: {
140311      /* Retrieve the current mutex implementation */
140312      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
140313      break;
140314    }
140315#endif
140316
140317    case SQLITE_CONFIG_MALLOC: {
140318      /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
140319      ** single argument which is a pointer to an instance of the
140320      ** sqlite3_mem_methods structure. The argument specifies alternative
140321      ** low-level memory allocation routines to be used in place of the memory
140322      ** allocation routines built into SQLite. */
140323      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
140324      break;
140325    }
140326    case SQLITE_CONFIG_GETMALLOC: {
140327      /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
140328      ** single argument which is a pointer to an instance of the
140329      ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
140330      ** filled with the currently defined memory allocation routines. */
140331      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
140332      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
140333      break;
140334    }
140335    case SQLITE_CONFIG_MEMSTATUS: {
140336      /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
140337      ** single argument of type int, interpreted as a boolean, which enables
140338      ** or disables the collection of memory allocation statistics. */
140339      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
140340      break;
140341    }
140342    case SQLITE_CONFIG_SCRATCH: {
140343      /* EVIDENCE-OF: R-08404-60887 There are three arguments to
140344      ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
140345      ** which the scratch allocations will be drawn, the size of each scratch
140346      ** allocation (sz), and the maximum number of scratch allocations (N). */
140347      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
140348      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
140349      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
140350      break;
140351    }
140352    case SQLITE_CONFIG_PAGECACHE: {
140353      /* EVIDENCE-OF: R-18761-36601 There are three arguments to
140354      ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
140355      ** the size of each page cache line (sz), and the number of cache lines
140356      ** (N). */
140357      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
140358      sqlite3GlobalConfig.szPage = va_arg(ap, int);
140359      sqlite3GlobalConfig.nPage = va_arg(ap, int);
140360      break;
140361    }
140362    case SQLITE_CONFIG_PCACHE_HDRSZ: {
140363      /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
140364      ** a single parameter which is a pointer to an integer and writes into
140365      ** that integer the number of extra bytes per page required for each page
140366      ** in SQLITE_CONFIG_PAGECACHE. */
140367      *va_arg(ap, int*) =
140368          sqlite3HeaderSizeBtree() +
140369          sqlite3HeaderSizePcache() +
140370          sqlite3HeaderSizePcache1();
140371      break;
140372    }
140373
140374    case SQLITE_CONFIG_PCACHE: {
140375      /* no-op */
140376      break;
140377    }
140378    case SQLITE_CONFIG_GETPCACHE: {
140379      /* now an error */
140380      rc = SQLITE_ERROR;
140381      break;
140382    }
140383
140384    case SQLITE_CONFIG_PCACHE2: {
140385      /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
140386      ** single argument which is a pointer to an sqlite3_pcache_methods2
140387      ** object. This object specifies the interface to a custom page cache
140388      ** implementation. */
140389      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
140390      break;
140391    }
140392    case SQLITE_CONFIG_GETPCACHE2: {
140393      /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
140394      ** single argument which is a pointer to an sqlite3_pcache_methods2
140395      ** object. SQLite copies of the current page cache implementation into
140396      ** that object. */
140397      if( sqlite3GlobalConfig.pcache2.xInit==0 ){
140398        sqlite3PCacheSetDefault();
140399      }
140400      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
140401      break;
140402    }
140403
140404/* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
140405** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
140406** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
140407#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
140408    case SQLITE_CONFIG_HEAP: {
140409      /* EVIDENCE-OF: R-19854-42126 There are three arguments to
140410      ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
140411      ** number of bytes in the memory buffer, and the minimum allocation size.
140412      */
140413      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
140414      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
140415      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
140416
140417      if( sqlite3GlobalConfig.mnReq<1 ){
140418        sqlite3GlobalConfig.mnReq = 1;
140419      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
140420        /* cap min request size at 2^12 */
140421        sqlite3GlobalConfig.mnReq = (1<<12);
140422      }
140423
140424      if( sqlite3GlobalConfig.pHeap==0 ){
140425        /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
140426        ** is NULL, then SQLite reverts to using its default memory allocator
140427        ** (the system malloc() implementation), undoing any prior invocation of
140428        ** SQLITE_CONFIG_MALLOC.
140429        **
140430        ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
140431        ** revert to its default implementation when sqlite3_initialize() is run
140432        */
140433        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
140434      }else{
140435        /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
140436        ** alternative memory allocator is engaged to handle all of SQLites
140437        ** memory allocation needs. */
140438#ifdef SQLITE_ENABLE_MEMSYS3
140439        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
140440#endif
140441#ifdef SQLITE_ENABLE_MEMSYS5
140442        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
140443#endif
140444      }
140445      break;
140446    }
140447#endif
140448
140449    case SQLITE_CONFIG_LOOKASIDE: {
140450      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
140451      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
140452      break;
140453    }
140454
140455    /* Record a pointer to the logger function and its first argument.
140456    ** The default is NULL.  Logging is disabled if the function pointer is
140457    ** NULL.
140458    */
140459    case SQLITE_CONFIG_LOG: {
140460      /* MSVC is picky about pulling func ptrs from va lists.
140461      ** http://support.microsoft.com/kb/47961
140462      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
140463      */
140464      typedef void(*LOGFUNC_t)(void*,int,const char*);
140465      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
140466      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
140467      break;
140468    }
140469
140470    /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
140471    ** can be changed at start-time using the
140472    ** sqlite3_config(SQLITE_CONFIG_URI,1) or
140473    ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
140474    */
140475    case SQLITE_CONFIG_URI: {
140476      /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
140477      ** argument of type int. If non-zero, then URI handling is globally
140478      ** enabled. If the parameter is zero, then URI handling is globally
140479      ** disabled. */
140480      sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
140481      break;
140482    }
140483
140484    case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
140485      /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
140486      ** option takes a single integer argument which is interpreted as a
140487      ** boolean in order to enable or disable the use of covering indices for
140488      ** full table scans in the query optimizer. */
140489      sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
140490      break;
140491    }
140492
140493#ifdef SQLITE_ENABLE_SQLLOG
140494    case SQLITE_CONFIG_SQLLOG: {
140495      typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
140496      sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
140497      sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
140498      break;
140499    }
140500#endif
140501
140502    case SQLITE_CONFIG_MMAP_SIZE: {
140503      /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
140504      ** integer (sqlite3_int64) values that are the default mmap size limit
140505      ** (the default setting for PRAGMA mmap_size) and the maximum allowed
140506      ** mmap size limit. */
140507      sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
140508      sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
140509      /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
140510      ** negative, then that argument is changed to its compile-time default.
140511      **
140512      ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
140513      ** silently truncated if necessary so that it does not exceed the
140514      ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
140515      ** compile-time option.
140516      */
140517      if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
140518        mxMmap = SQLITE_MAX_MMAP_SIZE;
140519      }
140520      if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
140521      if( szMmap>mxMmap) szMmap = mxMmap;
140522      sqlite3GlobalConfig.mxMmap = mxMmap;
140523      sqlite3GlobalConfig.szMmap = szMmap;
140524      break;
140525    }
140526
140527#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
140528    case SQLITE_CONFIG_WIN32_HEAPSIZE: {
140529      /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
140530      ** unsigned integer value that specifies the maximum size of the created
140531      ** heap. */
140532      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
140533      break;
140534    }
140535#endif
140536
140537    case SQLITE_CONFIG_PMASZ: {
140538      sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
140539      break;
140540    }
140541
140542    case SQLITE_CONFIG_STMTJRNL_SPILL: {
140543      sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
140544      break;
140545    }
140546
140547    default: {
140548      rc = SQLITE_ERROR;
140549      break;
140550    }
140551  }
140552  va_end(ap);
140553  return rc;
140554}
140555
140556/*
140557** Set up the lookaside buffers for a database connection.
140558** Return SQLITE_OK on success.
140559** If lookaside is already active, return SQLITE_BUSY.
140560**
140561** The sz parameter is the number of bytes in each lookaside slot.
140562** The cnt parameter is the number of slots.  If pStart is NULL the
140563** space for the lookaside memory is obtained from sqlite3_malloc().
140564** If pStart is not NULL then it is sz*cnt bytes of memory to use for
140565** the lookaside memory.
140566*/
140567static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
140568#ifndef SQLITE_OMIT_LOOKASIDE
140569  void *pStart;
140570  if( db->lookaside.nOut ){
140571    return SQLITE_BUSY;
140572  }
140573  /* Free any existing lookaside buffer for this handle before
140574  ** allocating a new one so we don't have to have space for
140575  ** both at the same time.
140576  */
140577  if( db->lookaside.bMalloced ){
140578    sqlite3_free(db->lookaside.pStart);
140579  }
140580  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
140581  ** than a pointer to be useful.
140582  */
140583  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
140584  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
140585  if( cnt<0 ) cnt = 0;
140586  if( sz==0 || cnt==0 ){
140587    sz = 0;
140588    pStart = 0;
140589  }else if( pBuf==0 ){
140590    sqlite3BeginBenignMalloc();
140591    pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
140592    sqlite3EndBenignMalloc();
140593    if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
140594  }else{
140595    pStart = pBuf;
140596  }
140597  db->lookaside.pStart = pStart;
140598  db->lookaside.pFree = 0;
140599  db->lookaside.sz = (u16)sz;
140600  if( pStart ){
140601    int i;
140602    LookasideSlot *p;
140603    assert( sz > (int)sizeof(LookasideSlot*) );
140604    p = (LookasideSlot*)pStart;
140605    for(i=cnt-1; i>=0; i--){
140606      p->pNext = db->lookaside.pFree;
140607      db->lookaside.pFree = p;
140608      p = (LookasideSlot*)&((u8*)p)[sz];
140609    }
140610    db->lookaside.pEnd = p;
140611    db->lookaside.bDisable = 0;
140612    db->lookaside.bMalloced = pBuf==0 ?1:0;
140613  }else{
140614    db->lookaside.pStart = db;
140615    db->lookaside.pEnd = db;
140616    db->lookaside.bDisable = 1;
140617    db->lookaside.bMalloced = 0;
140618  }
140619#endif /* SQLITE_OMIT_LOOKASIDE */
140620  return SQLITE_OK;
140621}
140622
140623/*
140624** Return the mutex associated with a database connection.
140625*/
140626SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
140627#ifdef SQLITE_ENABLE_API_ARMOR
140628  if( !sqlite3SafetyCheckOk(db) ){
140629    (void)SQLITE_MISUSE_BKPT;
140630    return 0;
140631  }
140632#endif
140633  return db->mutex;
140634}
140635
140636/*
140637** Free up as much memory as we can from the given database
140638** connection.
140639*/
140640SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
140641  int i;
140642
140643#ifdef SQLITE_ENABLE_API_ARMOR
140644  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
140645#endif
140646  sqlite3_mutex_enter(db->mutex);
140647  sqlite3BtreeEnterAll(db);
140648  for(i=0; i<db->nDb; i++){
140649    Btree *pBt = db->aDb[i].pBt;
140650    if( pBt ){
140651      Pager *pPager = sqlite3BtreePager(pBt);
140652      sqlite3PagerShrink(pPager);
140653    }
140654  }
140655  sqlite3BtreeLeaveAll(db);
140656  sqlite3_mutex_leave(db->mutex);
140657  return SQLITE_OK;
140658}
140659
140660/*
140661** Flush any dirty pages in the pager-cache for any attached database
140662** to disk.
140663*/
140664SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
140665  int i;
140666  int rc = SQLITE_OK;
140667  int bSeenBusy = 0;
140668
140669#ifdef SQLITE_ENABLE_API_ARMOR
140670  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
140671#endif
140672  sqlite3_mutex_enter(db->mutex);
140673  sqlite3BtreeEnterAll(db);
140674  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
140675    Btree *pBt = db->aDb[i].pBt;
140676    if( pBt && sqlite3BtreeIsInTrans(pBt) ){
140677      Pager *pPager = sqlite3BtreePager(pBt);
140678      rc = sqlite3PagerFlush(pPager);
140679      if( rc==SQLITE_BUSY ){
140680        bSeenBusy = 1;
140681        rc = SQLITE_OK;
140682      }
140683    }
140684  }
140685  sqlite3BtreeLeaveAll(db);
140686  sqlite3_mutex_leave(db->mutex);
140687  return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
140688}
140689
140690/*
140691** Configuration settings for an individual database connection
140692*/
140693SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
140694  va_list ap;
140695  int rc;
140696  va_start(ap, op);
140697  switch( op ){
140698    case SQLITE_DBCONFIG_MAINDBNAME: {
140699      db->aDb[0].zDbSName = va_arg(ap,char*);
140700      rc = SQLITE_OK;
140701      break;
140702    }
140703    case SQLITE_DBCONFIG_LOOKASIDE: {
140704      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
140705      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
140706      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
140707      rc = setupLookaside(db, pBuf, sz, cnt);
140708      break;
140709    }
140710    default: {
140711      static const struct {
140712        int op;      /* The opcode */
140713        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
140714      } aFlagOp[] = {
140715        { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },
140716        { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
140717        { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
140718        { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
140719        { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,      SQLITE_NoCkptOnClose  },
140720      };
140721      unsigned int i;
140722      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
140723      for(i=0; i<ArraySize(aFlagOp); i++){
140724        if( aFlagOp[i].op==op ){
140725          int onoff = va_arg(ap, int);
140726          int *pRes = va_arg(ap, int*);
140727          int oldFlags = db->flags;
140728          if( onoff>0 ){
140729            db->flags |= aFlagOp[i].mask;
140730          }else if( onoff==0 ){
140731            db->flags &= ~aFlagOp[i].mask;
140732          }
140733          if( oldFlags!=db->flags ){
140734            sqlite3ExpirePreparedStatements(db);
140735          }
140736          if( pRes ){
140737            *pRes = (db->flags & aFlagOp[i].mask)!=0;
140738          }
140739          rc = SQLITE_OK;
140740          break;
140741        }
140742      }
140743      break;
140744    }
140745  }
140746  va_end(ap);
140747  return rc;
140748}
140749
140750
140751/*
140752** Return true if the buffer z[0..n-1] contains all spaces.
140753*/
140754static int allSpaces(const char *z, int n){
140755  while( n>0 && z[n-1]==' ' ){ n--; }
140756  return n==0;
140757}
140758
140759/*
140760** This is the default collating function named "BINARY" which is always
140761** available.
140762**
140763** If the padFlag argument is not NULL then space padding at the end
140764** of strings is ignored.  This implements the RTRIM collation.
140765*/
140766static int binCollFunc(
140767  void *padFlag,
140768  int nKey1, const void *pKey1,
140769  int nKey2, const void *pKey2
140770){
140771  int rc, n;
140772  n = nKey1<nKey2 ? nKey1 : nKey2;
140773  /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
140774  ** strings byte by byte using the memcmp() function from the standard C
140775  ** library. */
140776  rc = memcmp(pKey1, pKey2, n);
140777  if( rc==0 ){
140778    if( padFlag
140779     && allSpaces(((char*)pKey1)+n, nKey1-n)
140780     && allSpaces(((char*)pKey2)+n, nKey2-n)
140781    ){
140782      /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
140783      ** spaces at the end of either string do not change the result. In other
140784      ** words, strings will compare equal to one another as long as they
140785      ** differ only in the number of spaces at the end.
140786      */
140787    }else{
140788      rc = nKey1 - nKey2;
140789    }
140790  }
140791  return rc;
140792}
140793
140794/*
140795** Another built-in collating sequence: NOCASE.
140796**
140797** This collating sequence is intended to be used for "case independent
140798** comparison". SQLite's knowledge of upper and lower case equivalents
140799** extends only to the 26 characters used in the English language.
140800**
140801** At the moment there is only a UTF-8 implementation.
140802*/
140803static int nocaseCollatingFunc(
140804  void *NotUsed,
140805  int nKey1, const void *pKey1,
140806  int nKey2, const void *pKey2
140807){
140808  int r = sqlite3StrNICmp(
140809      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
140810  UNUSED_PARAMETER(NotUsed);
140811  if( 0==r ){
140812    r = nKey1-nKey2;
140813  }
140814  return r;
140815}
140816
140817/*
140818** Return the ROWID of the most recent insert
140819*/
140820SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
140821#ifdef SQLITE_ENABLE_API_ARMOR
140822  if( !sqlite3SafetyCheckOk(db) ){
140823    (void)SQLITE_MISUSE_BKPT;
140824    return 0;
140825  }
140826#endif
140827  return db->lastRowid;
140828}
140829
140830/*
140831** Set the value returned by the sqlite3_last_insert_rowid() API function.
140832*/
140833SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
140834#ifdef SQLITE_ENABLE_API_ARMOR
140835  if( !sqlite3SafetyCheckOk(db) ){
140836    (void)SQLITE_MISUSE_BKPT;
140837    return;
140838  }
140839#endif
140840  sqlite3_mutex_enter(db->mutex);
140841  db->lastRowid = iRowid;
140842  sqlite3_mutex_leave(db->mutex);
140843}
140844
140845/*
140846** Return the number of changes in the most recent call to sqlite3_exec().
140847*/
140848SQLITE_API int sqlite3_changes(sqlite3 *db){
140849#ifdef SQLITE_ENABLE_API_ARMOR
140850  if( !sqlite3SafetyCheckOk(db) ){
140851    (void)SQLITE_MISUSE_BKPT;
140852    return 0;
140853  }
140854#endif
140855  return db->nChange;
140856}
140857
140858/*
140859** Return the number of changes since the database handle was opened.
140860*/
140861SQLITE_API int sqlite3_total_changes(sqlite3 *db){
140862#ifdef SQLITE_ENABLE_API_ARMOR
140863  if( !sqlite3SafetyCheckOk(db) ){
140864    (void)SQLITE_MISUSE_BKPT;
140865    return 0;
140866  }
140867#endif
140868  return db->nTotalChange;
140869}
140870
140871/*
140872** Close all open savepoints. This function only manipulates fields of the
140873** database handle object, it does not close any savepoints that may be open
140874** at the b-tree/pager level.
140875*/
140876SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
140877  while( db->pSavepoint ){
140878    Savepoint *pTmp = db->pSavepoint;
140879    db->pSavepoint = pTmp->pNext;
140880    sqlite3DbFree(db, pTmp);
140881  }
140882  db->nSavepoint = 0;
140883  db->nStatement = 0;
140884  db->isTransactionSavepoint = 0;
140885}
140886
140887/*
140888** Invoke the destructor function associated with FuncDef p, if any. Except,
140889** if this is not the last copy of the function, do not invoke it. Multiple
140890** copies of a single function are created when create_function() is called
140891** with SQLITE_ANY as the encoding.
140892*/
140893static void functionDestroy(sqlite3 *db, FuncDef *p){
140894  FuncDestructor *pDestructor = p->u.pDestructor;
140895  if( pDestructor ){
140896    pDestructor->nRef--;
140897    if( pDestructor->nRef==0 ){
140898      pDestructor->xDestroy(pDestructor->pUserData);
140899      sqlite3DbFree(db, pDestructor);
140900    }
140901  }
140902}
140903
140904/*
140905** Disconnect all sqlite3_vtab objects that belong to database connection
140906** db. This is called when db is being closed.
140907*/
140908static void disconnectAllVtab(sqlite3 *db){
140909#ifndef SQLITE_OMIT_VIRTUALTABLE
140910  int i;
140911  HashElem *p;
140912  sqlite3BtreeEnterAll(db);
140913  for(i=0; i<db->nDb; i++){
140914    Schema *pSchema = db->aDb[i].pSchema;
140915    if( db->aDb[i].pSchema ){
140916      for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
140917        Table *pTab = (Table *)sqliteHashData(p);
140918        if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
140919      }
140920    }
140921  }
140922  for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
140923    Module *pMod = (Module *)sqliteHashData(p);
140924    if( pMod->pEpoTab ){
140925      sqlite3VtabDisconnect(db, pMod->pEpoTab);
140926    }
140927  }
140928  sqlite3VtabUnlockList(db);
140929  sqlite3BtreeLeaveAll(db);
140930#else
140931  UNUSED_PARAMETER(db);
140932#endif
140933}
140934
140935/*
140936** Return TRUE if database connection db has unfinalized prepared
140937** statements or unfinished sqlite3_backup objects.
140938*/
140939static int connectionIsBusy(sqlite3 *db){
140940  int j;
140941  assert( sqlite3_mutex_held(db->mutex) );
140942  if( db->pVdbe ) return 1;
140943  for(j=0; j<db->nDb; j++){
140944    Btree *pBt = db->aDb[j].pBt;
140945    if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
140946  }
140947  return 0;
140948}
140949
140950/*
140951** Close an existing SQLite database
140952*/
140953static int sqlite3Close(sqlite3 *db, int forceZombie){
140954  if( !db ){
140955    /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
140956    ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
140957    return SQLITE_OK;
140958  }
140959  if( !sqlite3SafetyCheckSickOrOk(db) ){
140960    return SQLITE_MISUSE_BKPT;
140961  }
140962  sqlite3_mutex_enter(db->mutex);
140963  if( db->mTrace & SQLITE_TRACE_CLOSE ){
140964    db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
140965  }
140966
140967  /* Force xDisconnect calls on all virtual tables */
140968  disconnectAllVtab(db);
140969
140970  /* If a transaction is open, the disconnectAllVtab() call above
140971  ** will not have called the xDisconnect() method on any virtual
140972  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
140973  ** call will do so. We need to do this before the check for active
140974  ** SQL statements below, as the v-table implementation may be storing
140975  ** some prepared statements internally.
140976  */
140977  sqlite3VtabRollback(db);
140978
140979  /* Legacy behavior (sqlite3_close() behavior) is to return
140980  ** SQLITE_BUSY if the connection can not be closed immediately.
140981  */
140982  if( !forceZombie && connectionIsBusy(db) ){
140983    sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
140984       "statements or unfinished backups");
140985    sqlite3_mutex_leave(db->mutex);
140986    return SQLITE_BUSY;
140987  }
140988
140989#ifdef SQLITE_ENABLE_SQLLOG
140990  if( sqlite3GlobalConfig.xSqllog ){
140991    /* Closing the handle. Fourth parameter is passed the value 2. */
140992    sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
140993  }
140994#endif
140995
140996  /* Convert the connection into a zombie and then close it.
140997  */
140998  db->magic = SQLITE_MAGIC_ZOMBIE;
140999  sqlite3LeaveMutexAndCloseZombie(db);
141000  return SQLITE_OK;
141001}
141002
141003/*
141004** Two variations on the public interface for closing a database
141005** connection. The sqlite3_close() version returns SQLITE_BUSY and
141006** leaves the connection option if there are unfinalized prepared
141007** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
141008** version forces the connection to become a zombie if there are
141009** unclosed resources, and arranges for deallocation when the last
141010** prepare statement or sqlite3_backup closes.
141011*/
141012SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
141013SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
141014
141015
141016/*
141017** Close the mutex on database connection db.
141018**
141019** Furthermore, if database connection db is a zombie (meaning that there
141020** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
141021** every sqlite3_stmt has now been finalized and every sqlite3_backup has
141022** finished, then free all resources.
141023*/
141024SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
141025  HashElem *i;                    /* Hash table iterator */
141026  int j;
141027
141028  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
141029  ** or if the connection has not yet been closed by sqlite3_close_v2(),
141030  ** then just leave the mutex and return.
141031  */
141032  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
141033    sqlite3_mutex_leave(db->mutex);
141034    return;
141035  }
141036
141037  /* If we reach this point, it means that the database connection has
141038  ** closed all sqlite3_stmt and sqlite3_backup objects and has been
141039  ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
141040  ** go ahead and free all resources.
141041  */
141042
141043  /* If a transaction is open, roll it back. This also ensures that if
141044  ** any database schemas have been modified by an uncommitted transaction
141045  ** they are reset. And that the required b-tree mutex is held to make
141046  ** the pager rollback and schema reset an atomic operation. */
141047  sqlite3RollbackAll(db, SQLITE_OK);
141048
141049  /* Free any outstanding Savepoint structures. */
141050  sqlite3CloseSavepoints(db);
141051
141052  /* Close all database connections */
141053  for(j=0; j<db->nDb; j++){
141054    struct Db *pDb = &db->aDb[j];
141055    if( pDb->pBt ){
141056      sqlite3BtreeClose(pDb->pBt);
141057      pDb->pBt = 0;
141058      if( j!=1 ){
141059        pDb->pSchema = 0;
141060      }
141061    }
141062  }
141063  /* Clear the TEMP schema separately and last */
141064  if( db->aDb[1].pSchema ){
141065    sqlite3SchemaClear(db->aDb[1].pSchema);
141066  }
141067  sqlite3VtabUnlockList(db);
141068
141069  /* Free up the array of auxiliary databases */
141070  sqlite3CollapseDatabaseArray(db);
141071  assert( db->nDb<=2 );
141072  assert( db->aDb==db->aDbStatic );
141073
141074  /* Tell the code in notify.c that the connection no longer holds any
141075  ** locks and does not require any further unlock-notify callbacks.
141076  */
141077  sqlite3ConnectionClosed(db);
141078
141079  for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
141080    FuncDef *pNext, *p;
141081    p = sqliteHashData(i);
141082    do{
141083      functionDestroy(db, p);
141084      pNext = p->pNext;
141085      sqlite3DbFree(db, p);
141086      p = pNext;
141087    }while( p );
141088  }
141089  sqlite3HashClear(&db->aFunc);
141090  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
141091    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
141092    /* Invoke any destructors registered for collation sequence user data. */
141093    for(j=0; j<3; j++){
141094      if( pColl[j].xDel ){
141095        pColl[j].xDel(pColl[j].pUser);
141096      }
141097    }
141098    sqlite3DbFree(db, pColl);
141099  }
141100  sqlite3HashClear(&db->aCollSeq);
141101#ifndef SQLITE_OMIT_VIRTUALTABLE
141102  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
141103    Module *pMod = (Module *)sqliteHashData(i);
141104    if( pMod->xDestroy ){
141105      pMod->xDestroy(pMod->pAux);
141106    }
141107    sqlite3VtabEponymousTableClear(db, pMod);
141108    sqlite3DbFree(db, pMod);
141109  }
141110  sqlite3HashClear(&db->aModule);
141111#endif
141112
141113  sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
141114  sqlite3ValueFree(db->pErr);
141115  sqlite3CloseExtensions(db);
141116#if SQLITE_USER_AUTHENTICATION
141117  sqlite3_free(db->auth.zAuthUser);
141118  sqlite3_free(db->auth.zAuthPW);
141119#endif
141120
141121  db->magic = SQLITE_MAGIC_ERROR;
141122
141123  /* The temp-database schema is allocated differently from the other schema
141124  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
141125  ** So it needs to be freed here. Todo: Why not roll the temp schema into
141126  ** the same sqliteMalloc() as the one that allocates the database
141127  ** structure?
141128  */
141129  sqlite3DbFree(db, db->aDb[1].pSchema);
141130  sqlite3_mutex_leave(db->mutex);
141131  db->magic = SQLITE_MAGIC_CLOSED;
141132  sqlite3_mutex_free(db->mutex);
141133  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
141134  if( db->lookaside.bMalloced ){
141135    sqlite3_free(db->lookaside.pStart);
141136  }
141137  sqlite3_free(db);
141138}
141139
141140/*
141141** Rollback all database files.  If tripCode is not SQLITE_OK, then
141142** any write cursors are invalidated ("tripped" - as in "tripping a circuit
141143** breaker") and made to return tripCode if there are any further
141144** attempts to use that cursor.  Read cursors remain open and valid
141145** but are "saved" in case the table pages are moved around.
141146*/
141147SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
141148  int i;
141149  int inTrans = 0;
141150  int schemaChange;
141151  assert( sqlite3_mutex_held(db->mutex) );
141152  sqlite3BeginBenignMalloc();
141153
141154  /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
141155  ** This is important in case the transaction being rolled back has
141156  ** modified the database schema. If the b-tree mutexes are not taken
141157  ** here, then another shared-cache connection might sneak in between
141158  ** the database rollback and schema reset, which can cause false
141159  ** corruption reports in some cases.  */
141160  sqlite3BtreeEnterAll(db);
141161  schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
141162
141163  for(i=0; i<db->nDb; i++){
141164    Btree *p = db->aDb[i].pBt;
141165    if( p ){
141166      if( sqlite3BtreeIsInTrans(p) ){
141167        inTrans = 1;
141168      }
141169      sqlite3BtreeRollback(p, tripCode, !schemaChange);
141170    }
141171  }
141172  sqlite3VtabRollback(db);
141173  sqlite3EndBenignMalloc();
141174
141175  if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
141176    sqlite3ExpirePreparedStatements(db);
141177    sqlite3ResetAllSchemasOfConnection(db);
141178  }
141179  sqlite3BtreeLeaveAll(db);
141180
141181  /* Any deferred constraint violations have now been resolved. */
141182  db->nDeferredCons = 0;
141183  db->nDeferredImmCons = 0;
141184  db->flags &= ~SQLITE_DeferFKs;
141185
141186  /* If one has been configured, invoke the rollback-hook callback */
141187  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
141188    db->xRollbackCallback(db->pRollbackArg);
141189  }
141190}
141191
141192/*
141193** Return a static string containing the name corresponding to the error code
141194** specified in the argument.
141195*/
141196#if defined(SQLITE_NEED_ERR_NAME)
141197SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
141198  const char *zName = 0;
141199  int i, origRc = rc;
141200  for(i=0; i<2 && zName==0; i++, rc &= 0xff){
141201    switch( rc ){
141202      case SQLITE_OK:                 zName = "SQLITE_OK";                break;
141203      case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
141204      case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
141205      case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
141206      case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
141207      case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
141208      case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
141209      case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
141210      case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
141211      case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
141212      case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
141213      case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
141214      case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
141215      case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
141216      case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
141217      case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
141218      case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
141219      case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
141220      case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
141221      case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
141222      case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
141223      case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
141224      case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
141225      case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
141226      case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
141227      case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
141228      case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
141229      case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
141230      case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
141231      case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
141232      case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
141233      case SQLITE_IOERR_CHECKRESERVEDLOCK:
141234                                zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
141235      case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
141236      case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
141237      case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
141238      case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
141239      case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
141240      case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
141241      case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
141242      case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
141243      case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
141244      case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
141245      case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
141246      case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
141247      case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
141248      case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
141249      case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
141250      case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
141251      case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
141252      case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
141253      case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
141254      case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
141255      case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
141256      case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
141257      case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
141258      case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
141259      case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
141260      case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
141261      case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
141262      case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
141263      case SQLITE_CONSTRAINT_FOREIGNKEY:
141264                                zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
141265      case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
141266      case SQLITE_CONSTRAINT_PRIMARYKEY:
141267                                zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
141268      case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
141269      case SQLITE_CONSTRAINT_COMMITHOOK:
141270                                zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
141271      case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
141272      case SQLITE_CONSTRAINT_FUNCTION:
141273                                zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
141274      case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
141275      case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
141276      case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
141277      case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
141278      case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
141279      case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
141280      case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
141281      case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
141282      case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
141283      case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
141284      case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
141285      case SQLITE_NOTICE_RECOVER_ROLLBACK:
141286                                zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
141287      case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
141288      case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
141289      case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
141290    }
141291  }
141292  if( zName==0 ){
141293    static char zBuf[50];
141294    sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
141295    zName = zBuf;
141296  }
141297  return zName;
141298}
141299#endif
141300
141301/*
141302** Return a static string that describes the kind of error specified in the
141303** argument.
141304*/
141305SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
141306  static const char* const aMsg[] = {
141307    /* SQLITE_OK          */ "not an error",
141308    /* SQLITE_ERROR       */ "SQL logic error or missing database",
141309    /* SQLITE_INTERNAL    */ 0,
141310    /* SQLITE_PERM        */ "access permission denied",
141311    /* SQLITE_ABORT       */ "callback requested query abort",
141312    /* SQLITE_BUSY        */ "database is locked",
141313    /* SQLITE_LOCKED      */ "database table is locked",
141314    /* SQLITE_NOMEM       */ "out of memory",
141315    /* SQLITE_READONLY    */ "attempt to write a readonly database",
141316    /* SQLITE_INTERRUPT   */ "interrupted",
141317    /* SQLITE_IOERR       */ "disk I/O error",
141318    /* SQLITE_CORRUPT     */ "database disk image is malformed",
141319    /* SQLITE_NOTFOUND    */ "unknown operation",
141320    /* SQLITE_FULL        */ "database or disk is full",
141321    /* SQLITE_CANTOPEN    */ "unable to open database file",
141322    /* SQLITE_PROTOCOL    */ "locking protocol",
141323    /* SQLITE_EMPTY       */ "table contains no data",
141324    /* SQLITE_SCHEMA      */ "database schema has changed",
141325    /* SQLITE_TOOBIG      */ "string or blob too big",
141326    /* SQLITE_CONSTRAINT  */ "constraint failed",
141327    /* SQLITE_MISMATCH    */ "datatype mismatch",
141328    /* SQLITE_MISUSE      */ "library routine called out of sequence",
141329    /* SQLITE_NOLFS       */ "large file support is disabled",
141330    /* SQLITE_AUTH        */ "authorization denied",
141331    /* SQLITE_FORMAT      */ "auxiliary database format error",
141332    /* SQLITE_RANGE       */ "bind or column index out of range",
141333    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
141334  };
141335  const char *zErr = "unknown error";
141336  switch( rc ){
141337    case SQLITE_ABORT_ROLLBACK: {
141338      zErr = "abort due to ROLLBACK";
141339      break;
141340    }
141341    default: {
141342      rc &= 0xff;
141343      if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
141344        zErr = aMsg[rc];
141345      }
141346      break;
141347    }
141348  }
141349  return zErr;
141350}
141351
141352/*
141353** This routine implements a busy callback that sleeps and tries
141354** again until a timeout value is reached.  The timeout value is
141355** an integer number of milliseconds passed in as the first
141356** argument.
141357*/
141358static int sqliteDefaultBusyCallback(
141359 void *ptr,               /* Database connection */
141360 int count                /* Number of times table has been busy */
141361){
141362#if SQLITE_OS_WIN || HAVE_USLEEP
141363  static const u8 delays[] =
141364     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
141365  static const u8 totals[] =
141366     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
141367# define NDELAY ArraySize(delays)
141368  sqlite3 *db = (sqlite3 *)ptr;
141369  int timeout = db->busyTimeout;
141370  int delay, prior;
141371
141372  assert( count>=0 );
141373  if( count < NDELAY ){
141374    delay = delays[count];
141375    prior = totals[count];
141376  }else{
141377    delay = delays[NDELAY-1];
141378    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
141379  }
141380  if( prior + delay > timeout ){
141381    delay = timeout - prior;
141382    if( delay<=0 ) return 0;
141383  }
141384  sqlite3OsSleep(db->pVfs, delay*1000);
141385  return 1;
141386#else
141387  sqlite3 *db = (sqlite3 *)ptr;
141388  int timeout = ((sqlite3 *)ptr)->busyTimeout;
141389  if( (count+1)*1000 > timeout ){
141390    return 0;
141391  }
141392  sqlite3OsSleep(db->pVfs, 1000000);
141393  return 1;
141394#endif
141395}
141396
141397/*
141398** Invoke the given busy handler.
141399**
141400** This routine is called when an operation failed with a lock.
141401** If this routine returns non-zero, the lock is retried.  If it
141402** returns 0, the operation aborts with an SQLITE_BUSY error.
141403*/
141404SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
141405  int rc;
141406  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
141407  rc = p->xFunc(p->pArg, p->nBusy);
141408  if( rc==0 ){
141409    p->nBusy = -1;
141410  }else{
141411    p->nBusy++;
141412  }
141413  return rc;
141414}
141415
141416/*
141417** This routine sets the busy callback for an Sqlite database to the
141418** given callback function with the given argument.
141419*/
141420SQLITE_API int sqlite3_busy_handler(
141421  sqlite3 *db,
141422  int (*xBusy)(void*,int),
141423  void *pArg
141424){
141425#ifdef SQLITE_ENABLE_API_ARMOR
141426  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
141427#endif
141428  sqlite3_mutex_enter(db->mutex);
141429  db->busyHandler.xFunc = xBusy;
141430  db->busyHandler.pArg = pArg;
141431  db->busyHandler.nBusy = 0;
141432  db->busyTimeout = 0;
141433  sqlite3_mutex_leave(db->mutex);
141434  return SQLITE_OK;
141435}
141436
141437#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
141438/*
141439** This routine sets the progress callback for an Sqlite database to the
141440** given callback function with the given argument. The progress callback will
141441** be invoked every nOps opcodes.
141442*/
141443SQLITE_API void sqlite3_progress_handler(
141444  sqlite3 *db,
141445  int nOps,
141446  int (*xProgress)(void*),
141447  void *pArg
141448){
141449#ifdef SQLITE_ENABLE_API_ARMOR
141450  if( !sqlite3SafetyCheckOk(db) ){
141451    (void)SQLITE_MISUSE_BKPT;
141452    return;
141453  }
141454#endif
141455  sqlite3_mutex_enter(db->mutex);
141456  if( nOps>0 ){
141457    db->xProgress = xProgress;
141458    db->nProgressOps = (unsigned)nOps;
141459    db->pProgressArg = pArg;
141460  }else{
141461    db->xProgress = 0;
141462    db->nProgressOps = 0;
141463    db->pProgressArg = 0;
141464  }
141465  sqlite3_mutex_leave(db->mutex);
141466}
141467#endif
141468
141469
141470/*
141471** This routine installs a default busy handler that waits for the
141472** specified number of milliseconds before returning 0.
141473*/
141474SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
141475#ifdef SQLITE_ENABLE_API_ARMOR
141476  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
141477#endif
141478  if( ms>0 ){
141479    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
141480    db->busyTimeout = ms;
141481  }else{
141482    sqlite3_busy_handler(db, 0, 0);
141483  }
141484  return SQLITE_OK;
141485}
141486
141487/*
141488** Cause any pending operation to stop at its earliest opportunity.
141489*/
141490SQLITE_API void sqlite3_interrupt(sqlite3 *db){
141491#ifdef SQLITE_ENABLE_API_ARMOR
141492  if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
141493    (void)SQLITE_MISUSE_BKPT;
141494    return;
141495  }
141496#endif
141497  db->u1.isInterrupted = 1;
141498}
141499
141500
141501/*
141502** This function is exactly the same as sqlite3_create_function(), except
141503** that it is designed to be called by internal code. The difference is
141504** that if a malloc() fails in sqlite3_create_function(), an error code
141505** is returned and the mallocFailed flag cleared.
141506*/
141507SQLITE_PRIVATE int sqlite3CreateFunc(
141508  sqlite3 *db,
141509  const char *zFunctionName,
141510  int nArg,
141511  int enc,
141512  void *pUserData,
141513  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
141514  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
141515  void (*xFinal)(sqlite3_context*),
141516  FuncDestructor *pDestructor
141517){
141518  FuncDef *p;
141519  int nName;
141520  int extraFlags;
141521
141522  assert( sqlite3_mutex_held(db->mutex) );
141523  if( zFunctionName==0 ||
141524      (xSFunc && (xFinal || xStep)) ||
141525      (!xSFunc && (xFinal && !xStep)) ||
141526      (!xSFunc && (!xFinal && xStep)) ||
141527      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
141528      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
141529    return SQLITE_MISUSE_BKPT;
141530  }
141531
141532  assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
141533  extraFlags = enc &  SQLITE_DETERMINISTIC;
141534  enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
141535
141536#ifndef SQLITE_OMIT_UTF16
141537  /* If SQLITE_UTF16 is specified as the encoding type, transform this
141538  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
141539  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
141540  **
141541  ** If SQLITE_ANY is specified, add three versions of the function
141542  ** to the hash table.
141543  */
141544  if( enc==SQLITE_UTF16 ){
141545    enc = SQLITE_UTF16NATIVE;
141546  }else if( enc==SQLITE_ANY ){
141547    int rc;
141548    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
141549         pUserData, xSFunc, xStep, xFinal, pDestructor);
141550    if( rc==SQLITE_OK ){
141551      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
141552          pUserData, xSFunc, xStep, xFinal, pDestructor);
141553    }
141554    if( rc!=SQLITE_OK ){
141555      return rc;
141556    }
141557    enc = SQLITE_UTF16BE;
141558  }
141559#else
141560  enc = SQLITE_UTF8;
141561#endif
141562
141563  /* Check if an existing function is being overridden or deleted. If so,
141564  ** and there are active VMs, then return SQLITE_BUSY. If a function
141565  ** is being overridden/deleted but there are no active VMs, allow the
141566  ** operation to continue but invalidate all precompiled statements.
141567  */
141568  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
141569  if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
141570    if( db->nVdbeActive ){
141571      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
141572        "unable to delete/modify user-function due to active statements");
141573      assert( !db->mallocFailed );
141574      return SQLITE_BUSY;
141575    }else{
141576      sqlite3ExpirePreparedStatements(db);
141577    }
141578  }
141579
141580  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
141581  assert(p || db->mallocFailed);
141582  if( !p ){
141583    return SQLITE_NOMEM_BKPT;
141584  }
141585
141586  /* If an older version of the function with a configured destructor is
141587  ** being replaced invoke the destructor function here. */
141588  functionDestroy(db, p);
141589
141590  if( pDestructor ){
141591    pDestructor->nRef++;
141592  }
141593  p->u.pDestructor = pDestructor;
141594  p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
141595  testcase( p->funcFlags & SQLITE_DETERMINISTIC );
141596  p->xSFunc = xSFunc ? xSFunc : xStep;
141597  p->xFinalize = xFinal;
141598  p->pUserData = pUserData;
141599  p->nArg = (u16)nArg;
141600  return SQLITE_OK;
141601}
141602
141603/*
141604** Create new user functions.
141605*/
141606SQLITE_API int sqlite3_create_function(
141607  sqlite3 *db,
141608  const char *zFunc,
141609  int nArg,
141610  int enc,
141611  void *p,
141612  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
141613  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
141614  void (*xFinal)(sqlite3_context*)
141615){
141616  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
141617                                    xFinal, 0);
141618}
141619
141620SQLITE_API int sqlite3_create_function_v2(
141621  sqlite3 *db,
141622  const char *zFunc,
141623  int nArg,
141624  int enc,
141625  void *p,
141626  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
141627  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
141628  void (*xFinal)(sqlite3_context*),
141629  void (*xDestroy)(void *)
141630){
141631  int rc = SQLITE_ERROR;
141632  FuncDestructor *pArg = 0;
141633
141634#ifdef SQLITE_ENABLE_API_ARMOR
141635  if( !sqlite3SafetyCheckOk(db) ){
141636    return SQLITE_MISUSE_BKPT;
141637  }
141638#endif
141639  sqlite3_mutex_enter(db->mutex);
141640  if( xDestroy ){
141641    pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
141642    if( !pArg ){
141643      xDestroy(p);
141644      goto out;
141645    }
141646    pArg->xDestroy = xDestroy;
141647    pArg->pUserData = p;
141648  }
141649  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
141650  if( pArg && pArg->nRef==0 ){
141651    assert( rc!=SQLITE_OK );
141652    xDestroy(p);
141653    sqlite3DbFree(db, pArg);
141654  }
141655
141656 out:
141657  rc = sqlite3ApiExit(db, rc);
141658  sqlite3_mutex_leave(db->mutex);
141659  return rc;
141660}
141661
141662#ifndef SQLITE_OMIT_UTF16
141663SQLITE_API int sqlite3_create_function16(
141664  sqlite3 *db,
141665  const void *zFunctionName,
141666  int nArg,
141667  int eTextRep,
141668  void *p,
141669  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
141670  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
141671  void (*xFinal)(sqlite3_context*)
141672){
141673  int rc;
141674  char *zFunc8;
141675
141676#ifdef SQLITE_ENABLE_API_ARMOR
141677  if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
141678#endif
141679  sqlite3_mutex_enter(db->mutex);
141680  assert( !db->mallocFailed );
141681  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
141682  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
141683  sqlite3DbFree(db, zFunc8);
141684  rc = sqlite3ApiExit(db, rc);
141685  sqlite3_mutex_leave(db->mutex);
141686  return rc;
141687}
141688#endif
141689
141690
141691/*
141692** Declare that a function has been overloaded by a virtual table.
141693**
141694** If the function already exists as a regular global function, then
141695** this routine is a no-op.  If the function does not exist, then create
141696** a new one that always throws a run-time error.
141697**
141698** When virtual tables intend to provide an overloaded function, they
141699** should call this routine to make sure the global function exists.
141700** A global function must exist in order for name resolution to work
141701** properly.
141702*/
141703SQLITE_API int sqlite3_overload_function(
141704  sqlite3 *db,
141705  const char *zName,
141706  int nArg
141707){
141708  int rc = SQLITE_OK;
141709
141710#ifdef SQLITE_ENABLE_API_ARMOR
141711  if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
141712    return SQLITE_MISUSE_BKPT;
141713  }
141714#endif
141715  sqlite3_mutex_enter(db->mutex);
141716  if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
141717    rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
141718                           0, sqlite3InvalidFunction, 0, 0, 0);
141719  }
141720  rc = sqlite3ApiExit(db, rc);
141721  sqlite3_mutex_leave(db->mutex);
141722  return rc;
141723}
141724
141725#ifndef SQLITE_OMIT_TRACE
141726/*
141727** Register a trace function.  The pArg from the previously registered trace
141728** is returned.
141729**
141730** A NULL trace function means that no tracing is executes.  A non-NULL
141731** trace is a pointer to a function that is invoked at the start of each
141732** SQL statement.
141733*/
141734#ifndef SQLITE_OMIT_DEPRECATED
141735SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
141736  void *pOld;
141737
141738#ifdef SQLITE_ENABLE_API_ARMOR
141739  if( !sqlite3SafetyCheckOk(db) ){
141740    (void)SQLITE_MISUSE_BKPT;
141741    return 0;
141742  }
141743#endif
141744  sqlite3_mutex_enter(db->mutex);
141745  pOld = db->pTraceArg;
141746  db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
141747  db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
141748  db->pTraceArg = pArg;
141749  sqlite3_mutex_leave(db->mutex);
141750  return pOld;
141751}
141752#endif /* SQLITE_OMIT_DEPRECATED */
141753
141754/* Register a trace callback using the version-2 interface.
141755*/
141756SQLITE_API int sqlite3_trace_v2(
141757  sqlite3 *db,                               /* Trace this connection */
141758  unsigned mTrace,                           /* Mask of events to be traced */
141759  int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */
141760  void *pArg                                 /* Context */
141761){
141762#ifdef SQLITE_ENABLE_API_ARMOR
141763  if( !sqlite3SafetyCheckOk(db) ){
141764    return SQLITE_MISUSE_BKPT;
141765  }
141766#endif
141767  sqlite3_mutex_enter(db->mutex);
141768  if( mTrace==0 ) xTrace = 0;
141769  if( xTrace==0 ) mTrace = 0;
141770  db->mTrace = mTrace;
141771  db->xTrace = xTrace;
141772  db->pTraceArg = pArg;
141773  sqlite3_mutex_leave(db->mutex);
141774  return SQLITE_OK;
141775}
141776
141777#ifndef SQLITE_OMIT_DEPRECATED
141778/*
141779** Register a profile function.  The pArg from the previously registered
141780** profile function is returned.
141781**
141782** A NULL profile function means that no profiling is executes.  A non-NULL
141783** profile is a pointer to a function that is invoked at the conclusion of
141784** each SQL statement that is run.
141785*/
141786SQLITE_API void *sqlite3_profile(
141787  sqlite3 *db,
141788  void (*xProfile)(void*,const char*,sqlite_uint64),
141789  void *pArg
141790){
141791  void *pOld;
141792
141793#ifdef SQLITE_ENABLE_API_ARMOR
141794  if( !sqlite3SafetyCheckOk(db) ){
141795    (void)SQLITE_MISUSE_BKPT;
141796    return 0;
141797  }
141798#endif
141799  sqlite3_mutex_enter(db->mutex);
141800  pOld = db->pProfileArg;
141801  db->xProfile = xProfile;
141802  db->pProfileArg = pArg;
141803  sqlite3_mutex_leave(db->mutex);
141804  return pOld;
141805}
141806#endif /* SQLITE_OMIT_DEPRECATED */
141807#endif /* SQLITE_OMIT_TRACE */
141808
141809/*
141810** Register a function to be invoked when a transaction commits.
141811** If the invoked function returns non-zero, then the commit becomes a
141812** rollback.
141813*/
141814SQLITE_API void *sqlite3_commit_hook(
141815  sqlite3 *db,              /* Attach the hook to this database */
141816  int (*xCallback)(void*),  /* Function to invoke on each commit */
141817  void *pArg                /* Argument to the function */
141818){
141819  void *pOld;
141820
141821#ifdef SQLITE_ENABLE_API_ARMOR
141822  if( !sqlite3SafetyCheckOk(db) ){
141823    (void)SQLITE_MISUSE_BKPT;
141824    return 0;
141825  }
141826#endif
141827  sqlite3_mutex_enter(db->mutex);
141828  pOld = db->pCommitArg;
141829  db->xCommitCallback = xCallback;
141830  db->pCommitArg = pArg;
141831  sqlite3_mutex_leave(db->mutex);
141832  return pOld;
141833}
141834
141835/*
141836** Register a callback to be invoked each time a row is updated,
141837** inserted or deleted using this database connection.
141838*/
141839SQLITE_API void *sqlite3_update_hook(
141840  sqlite3 *db,              /* Attach the hook to this database */
141841  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
141842  void *pArg                /* Argument to the function */
141843){
141844  void *pRet;
141845
141846#ifdef SQLITE_ENABLE_API_ARMOR
141847  if( !sqlite3SafetyCheckOk(db) ){
141848    (void)SQLITE_MISUSE_BKPT;
141849    return 0;
141850  }
141851#endif
141852  sqlite3_mutex_enter(db->mutex);
141853  pRet = db->pUpdateArg;
141854  db->xUpdateCallback = xCallback;
141855  db->pUpdateArg = pArg;
141856  sqlite3_mutex_leave(db->mutex);
141857  return pRet;
141858}
141859
141860/*
141861** Register a callback to be invoked each time a transaction is rolled
141862** back by this database connection.
141863*/
141864SQLITE_API void *sqlite3_rollback_hook(
141865  sqlite3 *db,              /* Attach the hook to this database */
141866  void (*xCallback)(void*), /* Callback function */
141867  void *pArg                /* Argument to the function */
141868){
141869  void *pRet;
141870
141871#ifdef SQLITE_ENABLE_API_ARMOR
141872  if( !sqlite3SafetyCheckOk(db) ){
141873    (void)SQLITE_MISUSE_BKPT;
141874    return 0;
141875  }
141876#endif
141877  sqlite3_mutex_enter(db->mutex);
141878  pRet = db->pRollbackArg;
141879  db->xRollbackCallback = xCallback;
141880  db->pRollbackArg = pArg;
141881  sqlite3_mutex_leave(db->mutex);
141882  return pRet;
141883}
141884
141885#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
141886/*
141887** Register a callback to be invoked each time a row is updated,
141888** inserted or deleted using this database connection.
141889*/
141890SQLITE_API void *sqlite3_preupdate_hook(
141891  sqlite3 *db,              /* Attach the hook to this database */
141892  void(*xCallback)(         /* Callback function */
141893    void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
141894  void *pArg                /* First callback argument */
141895){
141896  void *pRet;
141897  sqlite3_mutex_enter(db->mutex);
141898  pRet = db->pPreUpdateArg;
141899  db->xPreUpdateCallback = xCallback;
141900  db->pPreUpdateArg = pArg;
141901  sqlite3_mutex_leave(db->mutex);
141902  return pRet;
141903}
141904#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
141905
141906#ifndef SQLITE_OMIT_WAL
141907/*
141908** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
141909** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
141910** is greater than sqlite3.pWalArg cast to an integer (the value configured by
141911** wal_autocheckpoint()).
141912*/
141913SQLITE_PRIVATE int sqlite3WalDefaultHook(
141914  void *pClientData,     /* Argument */
141915  sqlite3 *db,           /* Connection */
141916  const char *zDb,       /* Database */
141917  int nFrame             /* Size of WAL */
141918){
141919  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
141920    sqlite3BeginBenignMalloc();
141921    sqlite3_wal_checkpoint(db, zDb);
141922    sqlite3EndBenignMalloc();
141923  }
141924  return SQLITE_OK;
141925}
141926#endif /* SQLITE_OMIT_WAL */
141927
141928/*
141929** Configure an sqlite3_wal_hook() callback to automatically checkpoint
141930** a database after committing a transaction if there are nFrame or
141931** more frames in the log file. Passing zero or a negative value as the
141932** nFrame parameter disables automatic checkpoints entirely.
141933**
141934** The callback registered by this function replaces any existing callback
141935** registered using sqlite3_wal_hook(). Likewise, registering a callback
141936** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
141937** configured by this function.
141938*/
141939SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
141940#ifdef SQLITE_OMIT_WAL
141941  UNUSED_PARAMETER(db);
141942  UNUSED_PARAMETER(nFrame);
141943#else
141944#ifdef SQLITE_ENABLE_API_ARMOR
141945  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
141946#endif
141947  if( nFrame>0 ){
141948    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
141949  }else{
141950    sqlite3_wal_hook(db, 0, 0);
141951  }
141952#endif
141953  return SQLITE_OK;
141954}
141955
141956/*
141957** Register a callback to be invoked each time a transaction is written
141958** into the write-ahead-log by this database connection.
141959*/
141960SQLITE_API void *sqlite3_wal_hook(
141961  sqlite3 *db,                    /* Attach the hook to this db handle */
141962  int(*xCallback)(void *, sqlite3*, const char*, int),
141963  void *pArg                      /* First argument passed to xCallback() */
141964){
141965#ifndef SQLITE_OMIT_WAL
141966  void *pRet;
141967#ifdef SQLITE_ENABLE_API_ARMOR
141968  if( !sqlite3SafetyCheckOk(db) ){
141969    (void)SQLITE_MISUSE_BKPT;
141970    return 0;
141971  }
141972#endif
141973  sqlite3_mutex_enter(db->mutex);
141974  pRet = db->pWalArg;
141975  db->xWalCallback = xCallback;
141976  db->pWalArg = pArg;
141977  sqlite3_mutex_leave(db->mutex);
141978  return pRet;
141979#else
141980  return 0;
141981#endif
141982}
141983
141984/*
141985** Checkpoint database zDb.
141986*/
141987SQLITE_API int sqlite3_wal_checkpoint_v2(
141988  sqlite3 *db,                    /* Database handle */
141989  const char *zDb,                /* Name of attached database (or NULL) */
141990  int eMode,                      /* SQLITE_CHECKPOINT_* value */
141991  int *pnLog,                     /* OUT: Size of WAL log in frames */
141992  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
141993){
141994#ifdef SQLITE_OMIT_WAL
141995  return SQLITE_OK;
141996#else
141997  int rc;                         /* Return code */
141998  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
141999
142000#ifdef SQLITE_ENABLE_API_ARMOR
142001  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
142002#endif
142003
142004  /* Initialize the output variables to -1 in case an error occurs. */
142005  if( pnLog ) *pnLog = -1;
142006  if( pnCkpt ) *pnCkpt = -1;
142007
142008  assert( SQLITE_CHECKPOINT_PASSIVE==0 );
142009  assert( SQLITE_CHECKPOINT_FULL==1 );
142010  assert( SQLITE_CHECKPOINT_RESTART==2 );
142011  assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
142012  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
142013    /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
142014    ** mode: */
142015    return SQLITE_MISUSE;
142016  }
142017
142018  sqlite3_mutex_enter(db->mutex);
142019  if( zDb && zDb[0] ){
142020    iDb = sqlite3FindDbName(db, zDb);
142021  }
142022  if( iDb<0 ){
142023    rc = SQLITE_ERROR;
142024    sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
142025  }else{
142026    db->busyHandler.nBusy = 0;
142027    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
142028    sqlite3Error(db, rc);
142029  }
142030  rc = sqlite3ApiExit(db, rc);
142031
142032  /* If there are no active statements, clear the interrupt flag at this
142033  ** point.  */
142034  if( db->nVdbeActive==0 ){
142035    db->u1.isInterrupted = 0;
142036  }
142037
142038  sqlite3_mutex_leave(db->mutex);
142039  return rc;
142040#endif
142041}
142042
142043
142044/*
142045** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
142046** to contains a zero-length string, all attached databases are
142047** checkpointed.
142048*/
142049SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
142050  /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
142051  ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
142052  return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
142053}
142054
142055#ifndef SQLITE_OMIT_WAL
142056/*
142057** Run a checkpoint on database iDb. This is a no-op if database iDb is
142058** not currently open in WAL mode.
142059**
142060** If a transaction is open on the database being checkpointed, this
142061** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
142062** an error occurs while running the checkpoint, an SQLite error code is
142063** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
142064**
142065** The mutex on database handle db should be held by the caller. The mutex
142066** associated with the specific b-tree being checkpointed is taken by
142067** this function while the checkpoint is running.
142068**
142069** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
142070** checkpointed. If an error is encountered it is returned immediately -
142071** no attempt is made to checkpoint any remaining databases.
142072**
142073** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
142074*/
142075SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
142076  int rc = SQLITE_OK;             /* Return code */
142077  int i;                          /* Used to iterate through attached dbs */
142078  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
142079
142080  assert( sqlite3_mutex_held(db->mutex) );
142081  assert( !pnLog || *pnLog==-1 );
142082  assert( !pnCkpt || *pnCkpt==-1 );
142083
142084  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
142085    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
142086      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
142087      pnLog = 0;
142088      pnCkpt = 0;
142089      if( rc==SQLITE_BUSY ){
142090        bBusy = 1;
142091        rc = SQLITE_OK;
142092      }
142093    }
142094  }
142095
142096  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
142097}
142098#endif /* SQLITE_OMIT_WAL */
142099
142100/*
142101** This function returns true if main-memory should be used instead of
142102** a temporary file for transient pager files and statement journals.
142103** The value returned depends on the value of db->temp_store (runtime
142104** parameter) and the compile time value of SQLITE_TEMP_STORE. The
142105** following table describes the relationship between these two values
142106** and this functions return value.
142107**
142108**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
142109**   -----------------     --------------     ------------------------------
142110**   0                     any                file      (return 0)
142111**   1                     1                  file      (return 0)
142112**   1                     2                  memory    (return 1)
142113**   1                     0                  file      (return 0)
142114**   2                     1                  file      (return 0)
142115**   2                     2                  memory    (return 1)
142116**   2                     0                  memory    (return 1)
142117**   3                     any                memory    (return 1)
142118*/
142119SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
142120#if SQLITE_TEMP_STORE==1
142121  return ( db->temp_store==2 );
142122#endif
142123#if SQLITE_TEMP_STORE==2
142124  return ( db->temp_store!=1 );
142125#endif
142126#if SQLITE_TEMP_STORE==3
142127  UNUSED_PARAMETER(db);
142128  return 1;
142129#endif
142130#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
142131  UNUSED_PARAMETER(db);
142132  return 0;
142133#endif
142134}
142135
142136/*
142137** Return UTF-8 encoded English language explanation of the most recent
142138** error.
142139*/
142140SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
142141  const char *z;
142142  if( !db ){
142143    return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
142144  }
142145  if( !sqlite3SafetyCheckSickOrOk(db) ){
142146    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
142147  }
142148  sqlite3_mutex_enter(db->mutex);
142149  if( db->mallocFailed ){
142150    z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
142151  }else{
142152    testcase( db->pErr==0 );
142153    z = (char*)sqlite3_value_text(db->pErr);
142154    assert( !db->mallocFailed );
142155    if( z==0 ){
142156      z = sqlite3ErrStr(db->errCode);
142157    }
142158  }
142159  sqlite3_mutex_leave(db->mutex);
142160  return z;
142161}
142162
142163#ifndef SQLITE_OMIT_UTF16
142164/*
142165** Return UTF-16 encoded English language explanation of the most recent
142166** error.
142167*/
142168SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
142169  static const u16 outOfMem[] = {
142170    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
142171  };
142172  static const u16 misuse[] = {
142173    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
142174    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
142175    'c', 'a', 'l', 'l', 'e', 'd', ' ',
142176    'o', 'u', 't', ' ',
142177    'o', 'f', ' ',
142178    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
142179  };
142180
142181  const void *z;
142182  if( !db ){
142183    return (void *)outOfMem;
142184  }
142185  if( !sqlite3SafetyCheckSickOrOk(db) ){
142186    return (void *)misuse;
142187  }
142188  sqlite3_mutex_enter(db->mutex);
142189  if( db->mallocFailed ){
142190    z = (void *)outOfMem;
142191  }else{
142192    z = sqlite3_value_text16(db->pErr);
142193    if( z==0 ){
142194      sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
142195      z = sqlite3_value_text16(db->pErr);
142196    }
142197    /* A malloc() may have failed within the call to sqlite3_value_text16()
142198    ** above. If this is the case, then the db->mallocFailed flag needs to
142199    ** be cleared before returning. Do this directly, instead of via
142200    ** sqlite3ApiExit(), to avoid setting the database handle error message.
142201    */
142202    sqlite3OomClear(db);
142203  }
142204  sqlite3_mutex_leave(db->mutex);
142205  return z;
142206}
142207#endif /* SQLITE_OMIT_UTF16 */
142208
142209/*
142210** Return the most recent error code generated by an SQLite routine. If NULL is
142211** passed to this function, we assume a malloc() failed during sqlite3_open().
142212*/
142213SQLITE_API int sqlite3_errcode(sqlite3 *db){
142214  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
142215    return SQLITE_MISUSE_BKPT;
142216  }
142217  if( !db || db->mallocFailed ){
142218    return SQLITE_NOMEM_BKPT;
142219  }
142220  return db->errCode & db->errMask;
142221}
142222SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
142223  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
142224    return SQLITE_MISUSE_BKPT;
142225  }
142226  if( !db || db->mallocFailed ){
142227    return SQLITE_NOMEM_BKPT;
142228  }
142229  return db->errCode;
142230}
142231SQLITE_API int sqlite3_system_errno(sqlite3 *db){
142232  return db ? db->iSysErrno : 0;
142233}
142234
142235/*
142236** Return a string that describes the kind of error specified in the
142237** argument.  For now, this simply calls the internal sqlite3ErrStr()
142238** function.
142239*/
142240SQLITE_API const char *sqlite3_errstr(int rc){
142241  return sqlite3ErrStr(rc);
142242}
142243
142244/*
142245** Create a new collating function for database "db".  The name is zName
142246** and the encoding is enc.
142247*/
142248static int createCollation(
142249  sqlite3* db,
142250  const char *zName,
142251  u8 enc,
142252  void* pCtx,
142253  int(*xCompare)(void*,int,const void*,int,const void*),
142254  void(*xDel)(void*)
142255){
142256  CollSeq *pColl;
142257  int enc2;
142258
142259  assert( sqlite3_mutex_held(db->mutex) );
142260
142261  /* If SQLITE_UTF16 is specified as the encoding type, transform this
142262  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
142263  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
142264  */
142265  enc2 = enc;
142266  testcase( enc2==SQLITE_UTF16 );
142267  testcase( enc2==SQLITE_UTF16_ALIGNED );
142268  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
142269    enc2 = SQLITE_UTF16NATIVE;
142270  }
142271  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
142272    return SQLITE_MISUSE_BKPT;
142273  }
142274
142275  /* Check if this call is removing or replacing an existing collation
142276  ** sequence. If so, and there are active VMs, return busy. If there
142277  ** are no active VMs, invalidate any pre-compiled statements.
142278  */
142279  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
142280  if( pColl && pColl->xCmp ){
142281    if( db->nVdbeActive ){
142282      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
142283        "unable to delete/modify collation sequence due to active statements");
142284      return SQLITE_BUSY;
142285    }
142286    sqlite3ExpirePreparedStatements(db);
142287
142288    /* If collation sequence pColl was created directly by a call to
142289    ** sqlite3_create_collation, and not generated by synthCollSeq(),
142290    ** then any copies made by synthCollSeq() need to be invalidated.
142291    ** Also, collation destructor - CollSeq.xDel() - function may need
142292    ** to be called.
142293    */
142294    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
142295      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
142296      int j;
142297      for(j=0; j<3; j++){
142298        CollSeq *p = &aColl[j];
142299        if( p->enc==pColl->enc ){
142300          if( p->xDel ){
142301            p->xDel(p->pUser);
142302          }
142303          p->xCmp = 0;
142304        }
142305      }
142306    }
142307  }
142308
142309  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
142310  if( pColl==0 ) return SQLITE_NOMEM_BKPT;
142311  pColl->xCmp = xCompare;
142312  pColl->pUser = pCtx;
142313  pColl->xDel = xDel;
142314  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
142315  sqlite3Error(db, SQLITE_OK);
142316  return SQLITE_OK;
142317}
142318
142319
142320/*
142321** This array defines hard upper bounds on limit values.  The
142322** initializer must be kept in sync with the SQLITE_LIMIT_*
142323** #defines in sqlite3.h.
142324*/
142325static const int aHardLimit[] = {
142326  SQLITE_MAX_LENGTH,
142327  SQLITE_MAX_SQL_LENGTH,
142328  SQLITE_MAX_COLUMN,
142329  SQLITE_MAX_EXPR_DEPTH,
142330  SQLITE_MAX_COMPOUND_SELECT,
142331  SQLITE_MAX_VDBE_OP,
142332  SQLITE_MAX_FUNCTION_ARG,
142333  SQLITE_MAX_ATTACHED,
142334  SQLITE_MAX_LIKE_PATTERN_LENGTH,
142335  SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
142336  SQLITE_MAX_TRIGGER_DEPTH,
142337  SQLITE_MAX_WORKER_THREADS,
142338};
142339
142340/*
142341** Make sure the hard limits are set to reasonable values
142342*/
142343#if SQLITE_MAX_LENGTH<100
142344# error SQLITE_MAX_LENGTH must be at least 100
142345#endif
142346#if SQLITE_MAX_SQL_LENGTH<100
142347# error SQLITE_MAX_SQL_LENGTH must be at least 100
142348#endif
142349#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
142350# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
142351#endif
142352#if SQLITE_MAX_COMPOUND_SELECT<2
142353# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
142354#endif
142355#if SQLITE_MAX_VDBE_OP<40
142356# error SQLITE_MAX_VDBE_OP must be at least 40
142357#endif
142358#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
142359# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
142360#endif
142361#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
142362# error SQLITE_MAX_ATTACHED must be between 0 and 125
142363#endif
142364#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
142365# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
142366#endif
142367#if SQLITE_MAX_COLUMN>32767
142368# error SQLITE_MAX_COLUMN must not exceed 32767
142369#endif
142370#if SQLITE_MAX_TRIGGER_DEPTH<1
142371# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
142372#endif
142373#if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
142374# error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
142375#endif
142376
142377
142378/*
142379** Change the value of a limit.  Report the old value.
142380** If an invalid limit index is supplied, report -1.
142381** Make no changes but still report the old value if the
142382** new limit is negative.
142383**
142384** A new lower limit does not shrink existing constructs.
142385** It merely prevents new constructs that exceed the limit
142386** from forming.
142387*/
142388SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
142389  int oldLimit;
142390
142391#ifdef SQLITE_ENABLE_API_ARMOR
142392  if( !sqlite3SafetyCheckOk(db) ){
142393    (void)SQLITE_MISUSE_BKPT;
142394    return -1;
142395  }
142396#endif
142397
142398  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
142399  ** there is a hard upper bound set at compile-time by a C preprocessor
142400  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
142401  ** "_MAX_".)
142402  */
142403  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
142404  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
142405  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
142406  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
142407  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
142408  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
142409  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
142410  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
142411  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
142412                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );
142413  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
142414  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
142415  assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
142416  assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
142417
142418
142419  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
142420    return -1;
142421  }
142422  oldLimit = db->aLimit[limitId];
142423  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
142424    if( newLimit>aHardLimit[limitId] ){
142425      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
142426    }
142427    db->aLimit[limitId] = newLimit;
142428  }
142429  return oldLimit;                     /* IMP: R-53341-35419 */
142430}
142431
142432/*
142433** This function is used to parse both URIs and non-URI filenames passed by the
142434** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
142435** URIs specified as part of ATTACH statements.
142436**
142437** The first argument to this function is the name of the VFS to use (or
142438** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
142439** query parameter. The second argument contains the URI (or non-URI filename)
142440** itself. When this function is called the *pFlags variable should contain
142441** the default flags to open the database handle with. The value stored in
142442** *pFlags may be updated before returning if the URI filename contains
142443** "cache=xxx" or "mode=xxx" query parameters.
142444**
142445** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
142446** the VFS that should be used to open the database file. *pzFile is set to
142447** point to a buffer containing the name of the file to open. It is the
142448** responsibility of the caller to eventually call sqlite3_free() to release
142449** this buffer.
142450**
142451** If an error occurs, then an SQLite error code is returned and *pzErrMsg
142452** may be set to point to a buffer containing an English language error
142453** message. It is the responsibility of the caller to eventually release
142454** this buffer by calling sqlite3_free().
142455*/
142456SQLITE_PRIVATE int sqlite3ParseUri(
142457  const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
142458  const char *zUri,               /* Nul-terminated URI to parse */
142459  unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
142460  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
142461  char **pzFile,                  /* OUT: Filename component of URI */
142462  char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
142463){
142464  int rc = SQLITE_OK;
142465  unsigned int flags = *pFlags;
142466  const char *zVfs = zDefaultVfs;
142467  char *zFile;
142468  char c;
142469  int nUri = sqlite3Strlen30(zUri);
142470
142471  assert( *pzErrMsg==0 );
142472
142473  if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
142474            || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
142475   && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
142476  ){
142477    char *zOpt;
142478    int eState;                   /* Parser state when parsing URI */
142479    int iIn;                      /* Input character index */
142480    int iOut = 0;                 /* Output character index */
142481    u64 nByte = nUri+2;           /* Bytes of space to allocate */
142482
142483    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
142484    ** method that there may be extra parameters following the file-name.  */
142485    flags |= SQLITE_OPEN_URI;
142486
142487    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
142488    zFile = sqlite3_malloc64(nByte);
142489    if( !zFile ) return SQLITE_NOMEM_BKPT;
142490
142491    iIn = 5;
142492#ifdef SQLITE_ALLOW_URI_AUTHORITY
142493    if( strncmp(zUri+5, "///", 3)==0 ){
142494      iIn = 7;
142495      /* The following condition causes URIs with five leading / characters
142496      ** like file://///host/path to be converted into UNCs like //host/path.
142497      ** The correct URI for that UNC has only two or four leading / characters
142498      ** file://host/path or file:////host/path.  But 5 leading slashes is a
142499      ** common error, we are told, so we handle it as a special case. */
142500      if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
142501    }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
142502      iIn = 16;
142503    }
142504#else
142505    /* Discard the scheme and authority segments of the URI. */
142506    if( zUri[5]=='/' && zUri[6]=='/' ){
142507      iIn = 7;
142508      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
142509      if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
142510        *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
142511            iIn-7, &zUri[7]);
142512        rc = SQLITE_ERROR;
142513        goto parse_uri_out;
142514      }
142515    }
142516#endif
142517
142518    /* Copy the filename and any query parameters into the zFile buffer.
142519    ** Decode %HH escape codes along the way.
142520    **
142521    ** Within this loop, variable eState may be set to 0, 1 or 2, depending
142522    ** on the parsing context. As follows:
142523    **
142524    **   0: Parsing file-name.
142525    **   1: Parsing name section of a name=value query parameter.
142526    **   2: Parsing value section of a name=value query parameter.
142527    */
142528    eState = 0;
142529    while( (c = zUri[iIn])!=0 && c!='#' ){
142530      iIn++;
142531      if( c=='%'
142532       && sqlite3Isxdigit(zUri[iIn])
142533       && sqlite3Isxdigit(zUri[iIn+1])
142534      ){
142535        int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
142536        octet += sqlite3HexToInt(zUri[iIn++]);
142537
142538        assert( octet>=0 && octet<256 );
142539        if( octet==0 ){
142540#ifndef SQLITE_ENABLE_URI_00_ERROR
142541          /* This branch is taken when "%00" appears within the URI. In this
142542          ** case we ignore all text in the remainder of the path, name or
142543          ** value currently being parsed. So ignore the current character
142544          ** and skip to the next "?", "=" or "&", as appropriate. */
142545          while( (c = zUri[iIn])!=0 && c!='#'
142546              && (eState!=0 || c!='?')
142547              && (eState!=1 || (c!='=' && c!='&'))
142548              && (eState!=2 || c!='&')
142549          ){
142550            iIn++;
142551          }
142552          continue;
142553#else
142554          /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
142555          *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
142556          rc = SQLITE_ERROR;
142557          goto parse_uri_out;
142558#endif
142559        }
142560        c = octet;
142561      }else if( eState==1 && (c=='&' || c=='=') ){
142562        if( zFile[iOut-1]==0 ){
142563          /* An empty option name. Ignore this option altogether. */
142564          while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
142565          continue;
142566        }
142567        if( c=='&' ){
142568          zFile[iOut++] = '\0';
142569        }else{
142570          eState = 2;
142571        }
142572        c = 0;
142573      }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
142574        c = 0;
142575        eState = 1;
142576      }
142577      zFile[iOut++] = c;
142578    }
142579    if( eState==1 ) zFile[iOut++] = '\0';
142580    zFile[iOut++] = '\0';
142581    zFile[iOut++] = '\0';
142582
142583    /* Check if there were any options specified that should be interpreted
142584    ** here. Options that are interpreted here include "vfs" and those that
142585    ** correspond to flags that may be passed to the sqlite3_open_v2()
142586    ** method. */
142587    zOpt = &zFile[sqlite3Strlen30(zFile)+1];
142588    while( zOpt[0] ){
142589      int nOpt = sqlite3Strlen30(zOpt);
142590      char *zVal = &zOpt[nOpt+1];
142591      int nVal = sqlite3Strlen30(zVal);
142592
142593      if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
142594        zVfs = zVal;
142595      }else{
142596        struct OpenMode {
142597          const char *z;
142598          int mode;
142599        } *aMode = 0;
142600        char *zModeType = 0;
142601        int mask = 0;
142602        int limit = 0;
142603
142604        if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
142605          static struct OpenMode aCacheMode[] = {
142606            { "shared",  SQLITE_OPEN_SHAREDCACHE },
142607            { "private", SQLITE_OPEN_PRIVATECACHE },
142608            { 0, 0 }
142609          };
142610
142611          mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
142612          aMode = aCacheMode;
142613          limit = mask;
142614          zModeType = "cache";
142615        }
142616        if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
142617          static struct OpenMode aOpenMode[] = {
142618            { "ro",  SQLITE_OPEN_READONLY },
142619            { "rw",  SQLITE_OPEN_READWRITE },
142620            { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
142621            { "memory", SQLITE_OPEN_MEMORY },
142622            { 0, 0 }
142623          };
142624
142625          mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
142626                   | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
142627          aMode = aOpenMode;
142628          limit = mask & flags;
142629          zModeType = "access";
142630        }
142631
142632        if( aMode ){
142633          int i;
142634          int mode = 0;
142635          for(i=0; aMode[i].z; i++){
142636            const char *z = aMode[i].z;
142637            if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
142638              mode = aMode[i].mode;
142639              break;
142640            }
142641          }
142642          if( mode==0 ){
142643            *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
142644            rc = SQLITE_ERROR;
142645            goto parse_uri_out;
142646          }
142647          if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
142648            *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
142649                                        zModeType, zVal);
142650            rc = SQLITE_PERM;
142651            goto parse_uri_out;
142652          }
142653          flags = (flags & ~mask) | mode;
142654        }
142655      }
142656
142657      zOpt = &zVal[nVal+1];
142658    }
142659
142660  }else{
142661    zFile = sqlite3_malloc64(nUri+2);
142662    if( !zFile ) return SQLITE_NOMEM_BKPT;
142663    if( nUri ){
142664      memcpy(zFile, zUri, nUri);
142665    }
142666    zFile[nUri] = '\0';
142667    zFile[nUri+1] = '\0';
142668    flags &= ~SQLITE_OPEN_URI;
142669  }
142670
142671  *ppVfs = sqlite3_vfs_find(zVfs);
142672  if( *ppVfs==0 ){
142673    *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
142674    rc = SQLITE_ERROR;
142675  }
142676 parse_uri_out:
142677  if( rc!=SQLITE_OK ){
142678    sqlite3_free(zFile);
142679    zFile = 0;
142680  }
142681  *pFlags = flags;
142682  *pzFile = zFile;
142683  return rc;
142684}
142685
142686
142687/*
142688** This routine does the work of opening a database on behalf of
142689** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
142690** is UTF-8 encoded.
142691*/
142692static int openDatabase(
142693  const char *zFilename, /* Database filename UTF-8 encoded */
142694  sqlite3 **ppDb,        /* OUT: Returned database handle */
142695  unsigned int flags,    /* Operational flags */
142696  const char *zVfs       /* Name of the VFS to use */
142697){
142698  sqlite3 *db;                    /* Store allocated handle here */
142699  int rc;                         /* Return code */
142700  int isThreadsafe;               /* True for threadsafe connections */
142701  char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
142702  char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
142703
142704#ifdef SQLITE_ENABLE_API_ARMOR
142705  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
142706#endif
142707  *ppDb = 0;
142708#ifndef SQLITE_OMIT_AUTOINIT
142709  rc = sqlite3_initialize();
142710  if( rc ) return rc;
142711#endif
142712
142713  /* Only allow sensible combinations of bits in the flags argument.
142714  ** Throw an error if any non-sense combination is used.  If we
142715  ** do not block illegal combinations here, it could trigger
142716  ** assert() statements in deeper layers.  Sensible combinations
142717  ** are:
142718  **
142719  **  1:  SQLITE_OPEN_READONLY
142720  **  2:  SQLITE_OPEN_READWRITE
142721  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
142722  */
142723  assert( SQLITE_OPEN_READONLY  == 0x01 );
142724  assert( SQLITE_OPEN_READWRITE == 0x02 );
142725  assert( SQLITE_OPEN_CREATE    == 0x04 );
142726  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
142727  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
142728  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
142729  if( ((1<<(flags&7)) & 0x46)==0 ){
142730    return SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
142731  }
142732
142733  if( sqlite3GlobalConfig.bCoreMutex==0 ){
142734    isThreadsafe = 0;
142735  }else if( flags & SQLITE_OPEN_NOMUTEX ){
142736    isThreadsafe = 0;
142737  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
142738    isThreadsafe = 1;
142739  }else{
142740    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
142741  }
142742  if( flags & SQLITE_OPEN_PRIVATECACHE ){
142743    flags &= ~SQLITE_OPEN_SHAREDCACHE;
142744  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
142745    flags |= SQLITE_OPEN_SHAREDCACHE;
142746  }
142747
142748  /* Remove harmful bits from the flags parameter
142749  **
142750  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
142751  ** dealt with in the previous code block.  Besides these, the only
142752  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
142753  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
142754  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
142755  ** off all other flags.
142756  */
142757  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
142758               SQLITE_OPEN_EXCLUSIVE |
142759               SQLITE_OPEN_MAIN_DB |
142760               SQLITE_OPEN_TEMP_DB |
142761               SQLITE_OPEN_TRANSIENT_DB |
142762               SQLITE_OPEN_MAIN_JOURNAL |
142763               SQLITE_OPEN_TEMP_JOURNAL |
142764               SQLITE_OPEN_SUBJOURNAL |
142765               SQLITE_OPEN_MASTER_JOURNAL |
142766               SQLITE_OPEN_NOMUTEX |
142767               SQLITE_OPEN_FULLMUTEX |
142768               SQLITE_OPEN_WAL
142769             );
142770
142771  /* Allocate the sqlite data structure */
142772  db = sqlite3MallocZero( sizeof(sqlite3) );
142773  if( db==0 ) goto opendb_out;
142774  if( isThreadsafe ){
142775    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
142776    if( db->mutex==0 ){
142777      sqlite3_free(db);
142778      db = 0;
142779      goto opendb_out;
142780    }
142781  }
142782  sqlite3_mutex_enter(db->mutex);
142783  db->errMask = 0xff;
142784  db->nDb = 2;
142785  db->magic = SQLITE_MAGIC_BUSY;
142786  db->aDb = db->aDbStatic;
142787
142788  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
142789  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
142790  db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
142791  db->autoCommit = 1;
142792  db->nextAutovac = -1;
142793  db->szMmap = sqlite3GlobalConfig.szMmap;
142794  db->nextPagesize = 0;
142795  db->nMaxSorterMmap = 0x7FFFFFFF;
142796  db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
142797#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
142798                 | SQLITE_AutoIndex
142799#endif
142800#if SQLITE_DEFAULT_CKPTFULLFSYNC
142801                 | SQLITE_CkptFullFSync
142802#endif
142803#if SQLITE_DEFAULT_FILE_FORMAT<4
142804                 | SQLITE_LegacyFileFmt
142805#endif
142806#ifdef SQLITE_ENABLE_LOAD_EXTENSION
142807                 | SQLITE_LoadExtension
142808#endif
142809#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
142810                 | SQLITE_RecTriggers
142811#endif
142812#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
142813                 | SQLITE_ForeignKeys
142814#endif
142815#if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
142816                 | SQLITE_ReverseOrder
142817#endif
142818#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
142819                 | SQLITE_CellSizeCk
142820#endif
142821#if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
142822                 | SQLITE_Fts3Tokenizer
142823#endif
142824      ;
142825  sqlite3HashInit(&db->aCollSeq);
142826#ifndef SQLITE_OMIT_VIRTUALTABLE
142827  sqlite3HashInit(&db->aModule);
142828#endif
142829
142830  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
142831  ** and UTF-16, so add a version for each to avoid any unnecessary
142832  ** conversions. The only error that can occur here is a malloc() failure.
142833  **
142834  ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
142835  ** functions:
142836  */
142837  createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
142838  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
142839  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
142840  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
142841  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
142842  if( db->mallocFailed ){
142843    goto opendb_out;
142844  }
142845  /* EVIDENCE-OF: R-08308-17224 The default collating function for all
142846  ** strings is BINARY.
142847  */
142848  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
142849  assert( db->pDfltColl!=0 );
142850
142851  /* Parse the filename/URI argument. */
142852  db->openFlags = flags;
142853  rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
142854  if( rc!=SQLITE_OK ){
142855    if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
142856    sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
142857    sqlite3_free(zErrMsg);
142858    goto opendb_out;
142859  }
142860
142861  /* Open the backend database driver */
142862  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
142863                        flags | SQLITE_OPEN_MAIN_DB);
142864  if( rc!=SQLITE_OK ){
142865    if( rc==SQLITE_IOERR_NOMEM ){
142866      rc = SQLITE_NOMEM_BKPT;
142867    }
142868    sqlite3Error(db, rc);
142869    goto opendb_out;
142870  }
142871  sqlite3BtreeEnter(db->aDb[0].pBt);
142872  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
142873  if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
142874  sqlite3BtreeLeave(db->aDb[0].pBt);
142875  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
142876
142877  /* The default safety_level for the main database is FULL; for the temp
142878  ** database it is OFF. This matches the pager layer defaults.
142879  */
142880  db->aDb[0].zDbSName = "main";
142881  db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
142882  db->aDb[1].zDbSName = "temp";
142883  db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
142884
142885  db->magic = SQLITE_MAGIC_OPEN;
142886  if( db->mallocFailed ){
142887    goto opendb_out;
142888  }
142889
142890  /* Register all built-in functions, but do not attempt to read the
142891  ** database schema yet. This is delayed until the first time the database
142892  ** is accessed.
142893  */
142894  sqlite3Error(db, SQLITE_OK);
142895  sqlite3RegisterPerConnectionBuiltinFunctions(db);
142896  rc = sqlite3_errcode(db);
142897
142898#ifdef SQLITE_ENABLE_FTS5
142899  /* Register any built-in FTS5 module before loading the automatic
142900  ** extensions. This allows automatic extensions to register FTS5
142901  ** tokenizers and auxiliary functions.  */
142902  if( !db->mallocFailed && rc==SQLITE_OK ){
142903    rc = sqlite3Fts5Init(db);
142904  }
142905#endif
142906
142907  /* Load automatic extensions - extensions that have been registered
142908  ** using the sqlite3_automatic_extension() API.
142909  */
142910  if( rc==SQLITE_OK ){
142911    sqlite3AutoLoadExtensions(db);
142912    rc = sqlite3_errcode(db);
142913    if( rc!=SQLITE_OK ){
142914      goto opendb_out;
142915    }
142916  }
142917
142918#ifdef SQLITE_ENABLE_FTS1
142919  if( !db->mallocFailed ){
142920    extern int sqlite3Fts1Init(sqlite3*);
142921    rc = sqlite3Fts1Init(db);
142922  }
142923#endif
142924
142925#ifdef SQLITE_ENABLE_FTS2
142926  if( !db->mallocFailed && rc==SQLITE_OK ){
142927    extern int sqlite3Fts2Init(sqlite3*);
142928    rc = sqlite3Fts2Init(db);
142929  }
142930#endif
142931
142932#ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
142933  if( !db->mallocFailed && rc==SQLITE_OK ){
142934    rc = sqlite3Fts3Init(db);
142935  }
142936#endif
142937
142938#ifdef SQLITE_ENABLE_ICU
142939  if( !db->mallocFailed && rc==SQLITE_OK ){
142940    rc = sqlite3IcuInit(db);
142941  }
142942#endif
142943
142944#ifdef SQLITE_ENABLE_RTREE
142945  if( !db->mallocFailed && rc==SQLITE_OK){
142946    rc = sqlite3RtreeInit(db);
142947  }
142948#endif
142949
142950#ifdef SQLITE_ENABLE_DBSTAT_VTAB
142951  if( !db->mallocFailed && rc==SQLITE_OK){
142952    rc = sqlite3DbstatRegister(db);
142953  }
142954#endif
142955
142956#ifdef SQLITE_ENABLE_JSON1
142957  if( !db->mallocFailed && rc==SQLITE_OK){
142958    rc = sqlite3Json1Init(db);
142959  }
142960#endif
142961
142962  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
142963  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
142964  ** mode.  Doing nothing at all also makes NORMAL the default.
142965  */
142966#ifdef SQLITE_DEFAULT_LOCKING_MODE
142967  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
142968  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
142969                          SQLITE_DEFAULT_LOCKING_MODE);
142970#endif
142971
142972  if( rc ) sqlite3Error(db, rc);
142973
142974  /* Enable the lookaside-malloc subsystem */
142975  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
142976                        sqlite3GlobalConfig.nLookaside);
142977
142978  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
142979
142980opendb_out:
142981  if( db ){
142982    assert( db->mutex!=0 || isThreadsafe==0
142983           || sqlite3GlobalConfig.bFullMutex==0 );
142984    sqlite3_mutex_leave(db->mutex);
142985  }
142986  rc = sqlite3_errcode(db);
142987  assert( db!=0 || rc==SQLITE_NOMEM );
142988  if( rc==SQLITE_NOMEM ){
142989    sqlite3_close(db);
142990    db = 0;
142991  }else if( rc!=SQLITE_OK ){
142992    db->magic = SQLITE_MAGIC_SICK;
142993  }
142994  *ppDb = db;
142995#ifdef SQLITE_ENABLE_SQLLOG
142996  if( sqlite3GlobalConfig.xSqllog ){
142997    /* Opening a db handle. Fourth parameter is passed 0. */
142998    void *pArg = sqlite3GlobalConfig.pSqllogArg;
142999    sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
143000  }
143001#endif
143002#if defined(SQLITE_HAS_CODEC)
143003  if( rc==SQLITE_OK ){
143004    const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey");
143005    if( zHexKey && zHexKey[0] ){
143006      u8 iByte;
143007      int i;
143008      char zKey[40];
143009      for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){
143010        iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]);
143011        if( (i&1)!=0 ) zKey[i/2] = iByte;
143012      }
143013      sqlite3_key_v2(db, 0, zKey, i/2);
143014    }
143015  }
143016#endif
143017  sqlite3_free(zOpen);
143018  return rc & 0xff;
143019}
143020
143021/*
143022** Open a new database handle.
143023*/
143024SQLITE_API int sqlite3_open(
143025  const char *zFilename,
143026  sqlite3 **ppDb
143027){
143028  return openDatabase(zFilename, ppDb,
143029                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
143030}
143031SQLITE_API int sqlite3_open_v2(
143032  const char *filename,   /* Database filename (UTF-8) */
143033  sqlite3 **ppDb,         /* OUT: SQLite db handle */
143034  int flags,              /* Flags */
143035  const char *zVfs        /* Name of VFS module to use */
143036){
143037  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
143038}
143039
143040#ifndef SQLITE_OMIT_UTF16
143041/*
143042** Open a new database handle.
143043*/
143044SQLITE_API int sqlite3_open16(
143045  const void *zFilename,
143046  sqlite3 **ppDb
143047){
143048  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
143049  sqlite3_value *pVal;
143050  int rc;
143051
143052#ifdef SQLITE_ENABLE_API_ARMOR
143053  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
143054#endif
143055  *ppDb = 0;
143056#ifndef SQLITE_OMIT_AUTOINIT
143057  rc = sqlite3_initialize();
143058  if( rc ) return rc;
143059#endif
143060  if( zFilename==0 ) zFilename = "\000\000";
143061  pVal = sqlite3ValueNew(0);
143062  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
143063  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
143064  if( zFilename8 ){
143065    rc = openDatabase(zFilename8, ppDb,
143066                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
143067    assert( *ppDb || rc==SQLITE_NOMEM );
143068    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
143069      SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
143070    }
143071  }else{
143072    rc = SQLITE_NOMEM_BKPT;
143073  }
143074  sqlite3ValueFree(pVal);
143075
143076  return rc & 0xff;
143077}
143078#endif /* SQLITE_OMIT_UTF16 */
143079
143080/*
143081** Register a new collation sequence with the database handle db.
143082*/
143083SQLITE_API int sqlite3_create_collation(
143084  sqlite3* db,
143085  const char *zName,
143086  int enc,
143087  void* pCtx,
143088  int(*xCompare)(void*,int,const void*,int,const void*)
143089){
143090  return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
143091}
143092
143093/*
143094** Register a new collation sequence with the database handle db.
143095*/
143096SQLITE_API int sqlite3_create_collation_v2(
143097  sqlite3* db,
143098  const char *zName,
143099  int enc,
143100  void* pCtx,
143101  int(*xCompare)(void*,int,const void*,int,const void*),
143102  void(*xDel)(void*)
143103){
143104  int rc;
143105
143106#ifdef SQLITE_ENABLE_API_ARMOR
143107  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
143108#endif
143109  sqlite3_mutex_enter(db->mutex);
143110  assert( !db->mallocFailed );
143111  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
143112  rc = sqlite3ApiExit(db, rc);
143113  sqlite3_mutex_leave(db->mutex);
143114  return rc;
143115}
143116
143117#ifndef SQLITE_OMIT_UTF16
143118/*
143119** Register a new collation sequence with the database handle db.
143120*/
143121SQLITE_API int sqlite3_create_collation16(
143122  sqlite3* db,
143123  const void *zName,
143124  int enc,
143125  void* pCtx,
143126  int(*xCompare)(void*,int,const void*,int,const void*)
143127){
143128  int rc = SQLITE_OK;
143129  char *zName8;
143130
143131#ifdef SQLITE_ENABLE_API_ARMOR
143132  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
143133#endif
143134  sqlite3_mutex_enter(db->mutex);
143135  assert( !db->mallocFailed );
143136  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
143137  if( zName8 ){
143138    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
143139    sqlite3DbFree(db, zName8);
143140  }
143141  rc = sqlite3ApiExit(db, rc);
143142  sqlite3_mutex_leave(db->mutex);
143143  return rc;
143144}
143145#endif /* SQLITE_OMIT_UTF16 */
143146
143147/*
143148** Register a collation sequence factory callback with the database handle
143149** db. Replace any previously installed collation sequence factory.
143150*/
143151SQLITE_API int sqlite3_collation_needed(
143152  sqlite3 *db,
143153  void *pCollNeededArg,
143154  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
143155){
143156#ifdef SQLITE_ENABLE_API_ARMOR
143157  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
143158#endif
143159  sqlite3_mutex_enter(db->mutex);
143160  db->xCollNeeded = xCollNeeded;
143161  db->xCollNeeded16 = 0;
143162  db->pCollNeededArg = pCollNeededArg;
143163  sqlite3_mutex_leave(db->mutex);
143164  return SQLITE_OK;
143165}
143166
143167#ifndef SQLITE_OMIT_UTF16
143168/*
143169** Register a collation sequence factory callback with the database handle
143170** db. Replace any previously installed collation sequence factory.
143171*/
143172SQLITE_API int sqlite3_collation_needed16(
143173  sqlite3 *db,
143174  void *pCollNeededArg,
143175  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
143176){
143177#ifdef SQLITE_ENABLE_API_ARMOR
143178  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
143179#endif
143180  sqlite3_mutex_enter(db->mutex);
143181  db->xCollNeeded = 0;
143182  db->xCollNeeded16 = xCollNeeded16;
143183  db->pCollNeededArg = pCollNeededArg;
143184  sqlite3_mutex_leave(db->mutex);
143185  return SQLITE_OK;
143186}
143187#endif /* SQLITE_OMIT_UTF16 */
143188
143189#ifndef SQLITE_OMIT_DEPRECATED
143190/*
143191** This function is now an anachronism. It used to be used to recover from a
143192** malloc() failure, but SQLite now does this automatically.
143193*/
143194SQLITE_API int sqlite3_global_recover(void){
143195  return SQLITE_OK;
143196}
143197#endif
143198
143199/*
143200** Test to see whether or not the database connection is in autocommit
143201** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
143202** by default.  Autocommit is disabled by a BEGIN statement and reenabled
143203** by the next COMMIT or ROLLBACK.
143204*/
143205SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
143206#ifdef SQLITE_ENABLE_API_ARMOR
143207  if( !sqlite3SafetyCheckOk(db) ){
143208    (void)SQLITE_MISUSE_BKPT;
143209    return 0;
143210  }
143211#endif
143212  return db->autoCommit;
143213}
143214
143215/*
143216** The following routines are substitutes for constants SQLITE_CORRUPT,
143217** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
143218** constants.  They serve two purposes:
143219**
143220**   1.  Serve as a convenient place to set a breakpoint in a debugger
143221**       to detect when version error conditions occurs.
143222**
143223**   2.  Invoke sqlite3_log() to provide the source code location where
143224**       a low-level error is first detected.
143225*/
143226static int reportError(int iErr, int lineno, const char *zType){
143227  sqlite3_log(iErr, "%s at line %d of [%.10s]",
143228              zType, lineno, 20+sqlite3_sourceid());
143229  return iErr;
143230}
143231SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
143232  testcase( sqlite3GlobalConfig.xLog!=0 );
143233  return reportError(SQLITE_CORRUPT, lineno, "database corruption");
143234}
143235SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
143236  testcase( sqlite3GlobalConfig.xLog!=0 );
143237  return reportError(SQLITE_MISUSE, lineno, "misuse");
143238}
143239SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
143240  testcase( sqlite3GlobalConfig.xLog!=0 );
143241  return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
143242}
143243#ifdef SQLITE_DEBUG
143244SQLITE_PRIVATE int sqlite3NomemError(int lineno){
143245  testcase( sqlite3GlobalConfig.xLog!=0 );
143246  return reportError(SQLITE_NOMEM, lineno, "OOM");
143247}
143248SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
143249  testcase( sqlite3GlobalConfig.xLog!=0 );
143250  return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
143251}
143252#endif
143253
143254#ifndef SQLITE_OMIT_DEPRECATED
143255/*
143256** This is a convenience routine that makes sure that all thread-specific
143257** data for this thread has been deallocated.
143258**
143259** SQLite no longer uses thread-specific data so this routine is now a
143260** no-op.  It is retained for historical compatibility.
143261*/
143262SQLITE_API void sqlite3_thread_cleanup(void){
143263}
143264#endif
143265
143266/*
143267** Return meta information about a specific column of a database table.
143268** See comment in sqlite3.h (sqlite.h.in) for details.
143269*/
143270SQLITE_API int sqlite3_table_column_metadata(
143271  sqlite3 *db,                /* Connection handle */
143272  const char *zDbName,        /* Database name or NULL */
143273  const char *zTableName,     /* Table name */
143274  const char *zColumnName,    /* Column name */
143275  char const **pzDataType,    /* OUTPUT: Declared data type */
143276  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
143277  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
143278  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
143279  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
143280){
143281  int rc;
143282  char *zErrMsg = 0;
143283  Table *pTab = 0;
143284  Column *pCol = 0;
143285  int iCol = 0;
143286  char const *zDataType = 0;
143287  char const *zCollSeq = 0;
143288  int notnull = 0;
143289  int primarykey = 0;
143290  int autoinc = 0;
143291
143292
143293#ifdef SQLITE_ENABLE_API_ARMOR
143294  if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
143295    return SQLITE_MISUSE_BKPT;
143296  }
143297#endif
143298
143299  /* Ensure the database schema has been loaded */
143300  sqlite3_mutex_enter(db->mutex);
143301  sqlite3BtreeEnterAll(db);
143302  rc = sqlite3Init(db, &zErrMsg);
143303  if( SQLITE_OK!=rc ){
143304    goto error_out;
143305  }
143306
143307  /* Locate the table in question */
143308  pTab = sqlite3FindTable(db, zTableName, zDbName);
143309  if( !pTab || pTab->pSelect ){
143310    pTab = 0;
143311    goto error_out;
143312  }
143313
143314  /* Find the column for which info is requested */
143315  if( zColumnName==0 ){
143316    /* Query for existance of table only */
143317  }else{
143318    for(iCol=0; iCol<pTab->nCol; iCol++){
143319      pCol = &pTab->aCol[iCol];
143320      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
143321        break;
143322      }
143323    }
143324    if( iCol==pTab->nCol ){
143325      if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
143326        iCol = pTab->iPKey;
143327        pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
143328      }else{
143329        pTab = 0;
143330        goto error_out;
143331      }
143332    }
143333  }
143334
143335  /* The following block stores the meta information that will be returned
143336  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
143337  ** and autoinc. At this point there are two possibilities:
143338  **
143339  **     1. The specified column name was rowid", "oid" or "_rowid_"
143340  **        and there is no explicitly declared IPK column.
143341  **
143342  **     2. The table is not a view and the column name identified an
143343  **        explicitly declared column. Copy meta information from *pCol.
143344  */
143345  if( pCol ){
143346    zDataType = sqlite3ColumnType(pCol,0);
143347    zCollSeq = pCol->zColl;
143348    notnull = pCol->notNull!=0;
143349    primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
143350    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
143351  }else{
143352    zDataType = "INTEGER";
143353    primarykey = 1;
143354  }
143355  if( !zCollSeq ){
143356    zCollSeq = sqlite3StrBINARY;
143357  }
143358
143359error_out:
143360  sqlite3BtreeLeaveAll(db);
143361
143362  /* Whether the function call succeeded or failed, set the output parameters
143363  ** to whatever their local counterparts contain. If an error did occur,
143364  ** this has the effect of zeroing all output parameters.
143365  */
143366  if( pzDataType ) *pzDataType = zDataType;
143367  if( pzCollSeq ) *pzCollSeq = zCollSeq;
143368  if( pNotNull ) *pNotNull = notnull;
143369  if( pPrimaryKey ) *pPrimaryKey = primarykey;
143370  if( pAutoinc ) *pAutoinc = autoinc;
143371
143372  if( SQLITE_OK==rc && !pTab ){
143373    sqlite3DbFree(db, zErrMsg);
143374    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
143375        zColumnName);
143376    rc = SQLITE_ERROR;
143377  }
143378  sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
143379  sqlite3DbFree(db, zErrMsg);
143380  rc = sqlite3ApiExit(db, rc);
143381  sqlite3_mutex_leave(db->mutex);
143382  return rc;
143383}
143384
143385/*
143386** Sleep for a little while.  Return the amount of time slept.
143387*/
143388SQLITE_API int sqlite3_sleep(int ms){
143389  sqlite3_vfs *pVfs;
143390  int rc;
143391  pVfs = sqlite3_vfs_find(0);
143392  if( pVfs==0 ) return 0;
143393
143394  /* This function works in milliseconds, but the underlying OsSleep()
143395  ** API uses microseconds. Hence the 1000's.
143396  */
143397  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
143398  return rc;
143399}
143400
143401/*
143402** Enable or disable the extended result codes.
143403*/
143404SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
143405#ifdef SQLITE_ENABLE_API_ARMOR
143406  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
143407#endif
143408  sqlite3_mutex_enter(db->mutex);
143409  db->errMask = onoff ? 0xffffffff : 0xff;
143410  sqlite3_mutex_leave(db->mutex);
143411  return SQLITE_OK;
143412}
143413
143414/*
143415** Invoke the xFileControl method on a particular database.
143416*/
143417SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
143418  int rc = SQLITE_ERROR;
143419  Btree *pBtree;
143420
143421#ifdef SQLITE_ENABLE_API_ARMOR
143422  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
143423#endif
143424  sqlite3_mutex_enter(db->mutex);
143425  pBtree = sqlite3DbNameToBtree(db, zDbName);
143426  if( pBtree ){
143427    Pager *pPager;
143428    sqlite3_file *fd;
143429    sqlite3BtreeEnter(pBtree);
143430    pPager = sqlite3BtreePager(pBtree);
143431    assert( pPager!=0 );
143432    fd = sqlite3PagerFile(pPager);
143433    assert( fd!=0 );
143434    if( op==SQLITE_FCNTL_FILE_POINTER ){
143435      *(sqlite3_file**)pArg = fd;
143436      rc = SQLITE_OK;
143437    }else if( op==SQLITE_FCNTL_VFS_POINTER ){
143438      *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
143439      rc = SQLITE_OK;
143440    }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
143441      *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
143442      rc = SQLITE_OK;
143443    }else if( fd->pMethods ){
143444      rc = sqlite3OsFileControl(fd, op, pArg);
143445    }else{
143446      rc = SQLITE_NOTFOUND;
143447    }
143448    sqlite3BtreeLeave(pBtree);
143449  }
143450  sqlite3_mutex_leave(db->mutex);
143451  return rc;
143452}
143453
143454/*
143455** Interface to the testing logic.
143456*/
143457SQLITE_API int sqlite3_test_control(int op, ...){
143458  int rc = 0;
143459#ifdef SQLITE_UNTESTABLE
143460  UNUSED_PARAMETER(op);
143461#else
143462  va_list ap;
143463  va_start(ap, op);
143464  switch( op ){
143465
143466    /*
143467    ** Save the current state of the PRNG.
143468    */
143469    case SQLITE_TESTCTRL_PRNG_SAVE: {
143470      sqlite3PrngSaveState();
143471      break;
143472    }
143473
143474    /*
143475    ** Restore the state of the PRNG to the last state saved using
143476    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
143477    ** this verb acts like PRNG_RESET.
143478    */
143479    case SQLITE_TESTCTRL_PRNG_RESTORE: {
143480      sqlite3PrngRestoreState();
143481      break;
143482    }
143483
143484    /*
143485    ** Reset the PRNG back to its uninitialized state.  The next call
143486    ** to sqlite3_randomness() will reseed the PRNG using a single call
143487    ** to the xRandomness method of the default VFS.
143488    */
143489    case SQLITE_TESTCTRL_PRNG_RESET: {
143490      sqlite3_randomness(0,0);
143491      break;
143492    }
143493
143494    /*
143495    **  sqlite3_test_control(BITVEC_TEST, size, program)
143496    **
143497    ** Run a test against a Bitvec object of size.  The program argument
143498    ** is an array of integers that defines the test.  Return -1 on a
143499    ** memory allocation error, 0 on success, or non-zero for an error.
143500    ** See the sqlite3BitvecBuiltinTest() for additional information.
143501    */
143502    case SQLITE_TESTCTRL_BITVEC_TEST: {
143503      int sz = va_arg(ap, int);
143504      int *aProg = va_arg(ap, int*);
143505      rc = sqlite3BitvecBuiltinTest(sz, aProg);
143506      break;
143507    }
143508
143509    /*
143510    **  sqlite3_test_control(FAULT_INSTALL, xCallback)
143511    **
143512    ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
143513    ** if xCallback is not NULL.
143514    **
143515    ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
143516    ** is called immediately after installing the new callback and the return
143517    ** value from sqlite3FaultSim(0) becomes the return from
143518    ** sqlite3_test_control().
143519    */
143520    case SQLITE_TESTCTRL_FAULT_INSTALL: {
143521      /* MSVC is picky about pulling func ptrs from va lists.
143522      ** http://support.microsoft.com/kb/47961
143523      ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
143524      */
143525      typedef int(*TESTCALLBACKFUNC_t)(int);
143526      sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
143527      rc = sqlite3FaultSim(0);
143528      break;
143529    }
143530
143531    /*
143532    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
143533    **
143534    ** Register hooks to call to indicate which malloc() failures
143535    ** are benign.
143536    */
143537    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
143538      typedef void (*void_function)(void);
143539      void_function xBenignBegin;
143540      void_function xBenignEnd;
143541      xBenignBegin = va_arg(ap, void_function);
143542      xBenignEnd = va_arg(ap, void_function);
143543      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
143544      break;
143545    }
143546
143547    /*
143548    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
143549    **
143550    ** Set the PENDING byte to the value in the argument, if X>0.
143551    ** Make no changes if X==0.  Return the value of the pending byte
143552    ** as it existing before this routine was called.
143553    **
143554    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
143555    ** an incompatible database file format.  Changing the PENDING byte
143556    ** while any database connection is open results in undefined and
143557    ** deleterious behavior.
143558    */
143559    case SQLITE_TESTCTRL_PENDING_BYTE: {
143560      rc = PENDING_BYTE;
143561#ifndef SQLITE_OMIT_WSD
143562      {
143563        unsigned int newVal = va_arg(ap, unsigned int);
143564        if( newVal ) sqlite3PendingByte = newVal;
143565      }
143566#endif
143567      break;
143568    }
143569
143570    /*
143571    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
143572    **
143573    ** This action provides a run-time test to see whether or not
143574    ** assert() was enabled at compile-time.  If X is true and assert()
143575    ** is enabled, then the return value is true.  If X is true and
143576    ** assert() is disabled, then the return value is zero.  If X is
143577    ** false and assert() is enabled, then the assertion fires and the
143578    ** process aborts.  If X is false and assert() is disabled, then the
143579    ** return value is zero.
143580    */
143581    case SQLITE_TESTCTRL_ASSERT: {
143582      volatile int x = 0;
143583      assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
143584      rc = x;
143585      break;
143586    }
143587
143588
143589    /*
143590    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
143591    **
143592    ** This action provides a run-time test to see how the ALWAYS and
143593    ** NEVER macros were defined at compile-time.
143594    **
143595    ** The return value is ALWAYS(X).
143596    **
143597    ** The recommended test is X==2.  If the return value is 2, that means
143598    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
143599    ** default setting.  If the return value is 1, then ALWAYS() is either
143600    ** hard-coded to true or else it asserts if its argument is false.
143601    ** The first behavior (hard-coded to true) is the case if
143602    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
143603    ** behavior (assert if the argument to ALWAYS() is false) is the case if
143604    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
143605    **
143606    ** The run-time test procedure might look something like this:
143607    **
143608    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
143609    **      // ALWAYS() and NEVER() are no-op pass-through macros
143610    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
143611    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
143612    **    }else{
143613    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
143614    **    }
143615    */
143616    case SQLITE_TESTCTRL_ALWAYS: {
143617      int x = va_arg(ap,int);
143618      rc = ALWAYS(x);
143619      break;
143620    }
143621
143622    /*
143623    **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
143624    **
143625    ** The integer returned reveals the byte-order of the computer on which
143626    ** SQLite is running:
143627    **
143628    **       1     big-endian,    determined at run-time
143629    **      10     little-endian, determined at run-time
143630    **  432101     big-endian,    determined at compile-time
143631    **  123410     little-endian, determined at compile-time
143632    */
143633    case SQLITE_TESTCTRL_BYTEORDER: {
143634      rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
143635      break;
143636    }
143637
143638    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
143639    **
143640    ** Set the nReserve size to N for the main database on the database
143641    ** connection db.
143642    */
143643    case SQLITE_TESTCTRL_RESERVE: {
143644      sqlite3 *db = va_arg(ap, sqlite3*);
143645      int x = va_arg(ap,int);
143646      sqlite3_mutex_enter(db->mutex);
143647      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
143648      sqlite3_mutex_leave(db->mutex);
143649      break;
143650    }
143651
143652    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
143653    **
143654    ** Enable or disable various optimizations for testing purposes.  The
143655    ** argument N is a bitmask of optimizations to be disabled.  For normal
143656    ** operation N should be 0.  The idea is that a test program (like the
143657    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
143658    ** with various optimizations disabled to verify that the same answer
143659    ** is obtained in every case.
143660    */
143661    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
143662      sqlite3 *db = va_arg(ap, sqlite3*);
143663      db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
143664      break;
143665    }
143666
143667#ifdef SQLITE_N_KEYWORD
143668    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
143669    **
143670    ** If zWord is a keyword recognized by the parser, then return the
143671    ** number of keywords.  Or if zWord is not a keyword, return 0.
143672    **
143673    ** This test feature is only available in the amalgamation since
143674    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
143675    ** is built using separate source files.
143676    */
143677    case SQLITE_TESTCTRL_ISKEYWORD: {
143678      const char *zWord = va_arg(ap, const char*);
143679      int n = sqlite3Strlen30(zWord);
143680      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
143681      break;
143682    }
143683#endif
143684
143685    /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
143686    **
143687    ** Pass pFree into sqlite3ScratchFree().
143688    ** If sz>0 then allocate a scratch buffer into pNew.
143689    */
143690    case SQLITE_TESTCTRL_SCRATCHMALLOC: {
143691      void *pFree, **ppNew;
143692      int sz;
143693      sz = va_arg(ap, int);
143694      ppNew = va_arg(ap, void**);
143695      pFree = va_arg(ap, void*);
143696      if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
143697      sqlite3ScratchFree(pFree);
143698      break;
143699    }
143700
143701    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
143702    **
143703    ** If parameter onoff is non-zero, configure the wrappers so that all
143704    ** subsequent calls to localtime() and variants fail. If onoff is zero,
143705    ** undo this setting.
143706    */
143707    case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
143708      sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
143709      break;
143710    }
143711
143712    /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
143713    **
143714    ** Set or clear a flag that indicates that the database file is always well-
143715    ** formed and never corrupt.  This flag is clear by default, indicating that
143716    ** database files might have arbitrary corruption.  Setting the flag during
143717    ** testing causes certain assert() statements in the code to be activated
143718    ** that demonstrat invariants on well-formed database files.
143719    */
143720    case SQLITE_TESTCTRL_NEVER_CORRUPT: {
143721      sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
143722      break;
143723    }
143724
143725    /* Set the threshold at which OP_Once counters reset back to zero.
143726    ** By default this is 0x7ffffffe (over 2 billion), but that value is
143727    ** too big to test in a reasonable amount of time, so this control is
143728    ** provided to set a small and easily reachable reset value.
143729    */
143730    case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
143731      sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
143732      break;
143733    }
143734
143735    /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
143736    **
143737    ** Set the VDBE coverage callback function to xCallback with context
143738    ** pointer ptr.
143739    */
143740    case SQLITE_TESTCTRL_VDBE_COVERAGE: {
143741#ifdef SQLITE_VDBE_COVERAGE
143742      typedef void (*branch_callback)(void*,int,u8,u8);
143743      sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
143744      sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
143745#endif
143746      break;
143747    }
143748
143749    /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
143750    case SQLITE_TESTCTRL_SORTER_MMAP: {
143751      sqlite3 *db = va_arg(ap, sqlite3*);
143752      db->nMaxSorterMmap = va_arg(ap, int);
143753      break;
143754    }
143755
143756    /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
143757    **
143758    ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
143759    ** not.
143760    */
143761    case SQLITE_TESTCTRL_ISINIT: {
143762      if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
143763      break;
143764    }
143765
143766    /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
143767    **
143768    ** This test control is used to create imposter tables.  "db" is a pointer
143769    ** to the database connection.  dbName is the database name (ex: "main" or
143770    ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
143771    ** or off.  "tnum" is the root page of the b-tree to which the imposter
143772    ** table should connect.
143773    **
143774    ** Enable imposter mode only when the schema has already been parsed.  Then
143775    ** run a single CREATE TABLE statement to construct the imposter table in
143776    ** the parsed schema.  Then turn imposter mode back off again.
143777    **
143778    ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
143779    ** the schema to be reparsed the next time it is needed.  This has the
143780    ** effect of erasing all imposter tables.
143781    */
143782    case SQLITE_TESTCTRL_IMPOSTER: {
143783      sqlite3 *db = va_arg(ap, sqlite3*);
143784      sqlite3_mutex_enter(db->mutex);
143785      db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
143786      db->init.busy = db->init.imposterTable = va_arg(ap,int);
143787      db->init.newTnum = va_arg(ap,int);
143788      if( db->init.busy==0 && db->init.newTnum>0 ){
143789        sqlite3ResetAllSchemasOfConnection(db);
143790      }
143791      sqlite3_mutex_leave(db->mutex);
143792      break;
143793    }
143794  }
143795  va_end(ap);
143796#endif /* SQLITE_UNTESTABLE */
143797  return rc;
143798}
143799
143800/*
143801** This is a utility routine, useful to VFS implementations, that checks
143802** to see if a database file was a URI that contained a specific query
143803** parameter, and if so obtains the value of the query parameter.
143804**
143805** The zFilename argument is the filename pointer passed into the xOpen()
143806** method of a VFS implementation.  The zParam argument is the name of the
143807** query parameter we seek.  This routine returns the value of the zParam
143808** parameter if it exists.  If the parameter does not exist, this routine
143809** returns a NULL pointer.
143810*/
143811SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
143812  if( zFilename==0 || zParam==0 ) return 0;
143813  zFilename += sqlite3Strlen30(zFilename) + 1;
143814  while( zFilename[0] ){
143815    int x = strcmp(zFilename, zParam);
143816    zFilename += sqlite3Strlen30(zFilename) + 1;
143817    if( x==0 ) return zFilename;
143818    zFilename += sqlite3Strlen30(zFilename) + 1;
143819  }
143820  return 0;
143821}
143822
143823/*
143824** Return a boolean value for a query parameter.
143825*/
143826SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
143827  const char *z = sqlite3_uri_parameter(zFilename, zParam);
143828  bDflt = bDflt!=0;
143829  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
143830}
143831
143832/*
143833** Return a 64-bit integer value for a query parameter.
143834*/
143835SQLITE_API sqlite3_int64 sqlite3_uri_int64(
143836  const char *zFilename,    /* Filename as passed to xOpen */
143837  const char *zParam,       /* URI parameter sought */
143838  sqlite3_int64 bDflt       /* return if parameter is missing */
143839){
143840  const char *z = sqlite3_uri_parameter(zFilename, zParam);
143841  sqlite3_int64 v;
143842  if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
143843    bDflt = v;
143844  }
143845  return bDflt;
143846}
143847
143848/*
143849** Return the Btree pointer identified by zDbName.  Return NULL if not found.
143850*/
143851SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
143852  int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
143853  return iDb<0 ? 0 : db->aDb[iDb].pBt;
143854}
143855
143856/*
143857** Return the filename of the database associated with a database
143858** connection.
143859*/
143860SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
143861  Btree *pBt;
143862#ifdef SQLITE_ENABLE_API_ARMOR
143863  if( !sqlite3SafetyCheckOk(db) ){
143864    (void)SQLITE_MISUSE_BKPT;
143865    return 0;
143866  }
143867#endif
143868  pBt = sqlite3DbNameToBtree(db, zDbName);
143869  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
143870}
143871
143872/*
143873** Return 1 if database is read-only or 0 if read/write.  Return -1 if
143874** no such database exists.
143875*/
143876SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
143877  Btree *pBt;
143878#ifdef SQLITE_ENABLE_API_ARMOR
143879  if( !sqlite3SafetyCheckOk(db) ){
143880    (void)SQLITE_MISUSE_BKPT;
143881    return -1;
143882  }
143883#endif
143884  pBt = sqlite3DbNameToBtree(db, zDbName);
143885  return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
143886}
143887
143888#ifdef SQLITE_ENABLE_SNAPSHOT
143889/*
143890** Obtain a snapshot handle for the snapshot of database zDb currently
143891** being read by handle db.
143892*/
143893SQLITE_API int sqlite3_snapshot_get(
143894  sqlite3 *db,
143895  const char *zDb,
143896  sqlite3_snapshot **ppSnapshot
143897){
143898  int rc = SQLITE_ERROR;
143899#ifndef SQLITE_OMIT_WAL
143900
143901#ifdef SQLITE_ENABLE_API_ARMOR
143902  if( !sqlite3SafetyCheckOk(db) ){
143903    return SQLITE_MISUSE_BKPT;
143904  }
143905#endif
143906  sqlite3_mutex_enter(db->mutex);
143907
143908  if( db->autoCommit==0 ){
143909    int iDb = sqlite3FindDbName(db, zDb);
143910    if( iDb==0 || iDb>1 ){
143911      Btree *pBt = db->aDb[iDb].pBt;
143912      if( 0==sqlite3BtreeIsInTrans(pBt) ){
143913        rc = sqlite3BtreeBeginTrans(pBt, 0);
143914        if( rc==SQLITE_OK ){
143915          rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
143916        }
143917      }
143918    }
143919  }
143920
143921  sqlite3_mutex_leave(db->mutex);
143922#endif   /* SQLITE_OMIT_WAL */
143923  return rc;
143924}
143925
143926/*
143927** Open a read-transaction on the snapshot idendified by pSnapshot.
143928*/
143929SQLITE_API int sqlite3_snapshot_open(
143930  sqlite3 *db,
143931  const char *zDb,
143932  sqlite3_snapshot *pSnapshot
143933){
143934  int rc = SQLITE_ERROR;
143935#ifndef SQLITE_OMIT_WAL
143936
143937#ifdef SQLITE_ENABLE_API_ARMOR
143938  if( !sqlite3SafetyCheckOk(db) ){
143939    return SQLITE_MISUSE_BKPT;
143940  }
143941#endif
143942  sqlite3_mutex_enter(db->mutex);
143943  if( db->autoCommit==0 ){
143944    int iDb;
143945    iDb = sqlite3FindDbName(db, zDb);
143946    if( iDb==0 || iDb>1 ){
143947      Btree *pBt = db->aDb[iDb].pBt;
143948      if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
143949        rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
143950        if( rc==SQLITE_OK ){
143951          rc = sqlite3BtreeBeginTrans(pBt, 0);
143952          sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
143953        }
143954      }
143955    }
143956  }
143957
143958  sqlite3_mutex_leave(db->mutex);
143959#endif   /* SQLITE_OMIT_WAL */
143960  return rc;
143961}
143962
143963/*
143964** Recover as many snapshots as possible from the wal file associated with
143965** schema zDb of database db.
143966*/
143967SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
143968  int rc = SQLITE_ERROR;
143969  int iDb;
143970#ifndef SQLITE_OMIT_WAL
143971
143972#ifdef SQLITE_ENABLE_API_ARMOR
143973  if( !sqlite3SafetyCheckOk(db) ){
143974    return SQLITE_MISUSE_BKPT;
143975  }
143976#endif
143977
143978  sqlite3_mutex_enter(db->mutex);
143979  iDb = sqlite3FindDbName(db, zDb);
143980  if( iDb==0 || iDb>1 ){
143981    Btree *pBt = db->aDb[iDb].pBt;
143982    if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
143983      rc = sqlite3BtreeBeginTrans(pBt, 0);
143984      if( rc==SQLITE_OK ){
143985        rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
143986        sqlite3BtreeCommit(pBt);
143987      }
143988    }
143989  }
143990  sqlite3_mutex_leave(db->mutex);
143991#endif   /* SQLITE_OMIT_WAL */
143992  return rc;
143993}
143994
143995/*
143996** Free a snapshot handle obtained from sqlite3_snapshot_get().
143997*/
143998SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
143999  sqlite3_free(pSnapshot);
144000}
144001#endif /* SQLITE_ENABLE_SNAPSHOT */
144002
144003/************** End of main.c ************************************************/
144004/************** Begin file notify.c ******************************************/
144005/*
144006** 2009 March 3
144007**
144008** The author disclaims copyright to this source code.  In place of
144009** a legal notice, here is a blessing:
144010**
144011**    May you do good and not evil.
144012**    May you find forgiveness for yourself and forgive others.
144013**    May you share freely, never taking more than you give.
144014**
144015*************************************************************************
144016**
144017** This file contains the implementation of the sqlite3_unlock_notify()
144018** API method and its associated functionality.
144019*/
144020/* #include "sqliteInt.h" */
144021/* #include "btreeInt.h" */
144022
144023/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
144024#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
144025
144026/*
144027** Public interfaces:
144028**
144029**   sqlite3ConnectionBlocked()
144030**   sqlite3ConnectionUnlocked()
144031**   sqlite3ConnectionClosed()
144032**   sqlite3_unlock_notify()
144033*/
144034
144035#define assertMutexHeld() \
144036  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
144037
144038/*
144039** Head of a linked list of all sqlite3 objects created by this process
144040** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
144041** is not NULL. This variable may only accessed while the STATIC_MASTER
144042** mutex is held.
144043*/
144044static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
144045
144046#ifndef NDEBUG
144047/*
144048** This function is a complex assert() that verifies the following
144049** properties of the blocked connections list:
144050**
144051**   1) Each entry in the list has a non-NULL value for either
144052**      pUnlockConnection or pBlockingConnection, or both.
144053**
144054**   2) All entries in the list that share a common value for
144055**      xUnlockNotify are grouped together.
144056**
144057**   3) If the argument db is not NULL, then none of the entries in the
144058**      blocked connections list have pUnlockConnection or pBlockingConnection
144059**      set to db. This is used when closing connection db.
144060*/
144061static void checkListProperties(sqlite3 *db){
144062  sqlite3 *p;
144063  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
144064    int seen = 0;
144065    sqlite3 *p2;
144066
144067    /* Verify property (1) */
144068    assert( p->pUnlockConnection || p->pBlockingConnection );
144069
144070    /* Verify property (2) */
144071    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
144072      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
144073      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
144074      assert( db==0 || p->pUnlockConnection!=db );
144075      assert( db==0 || p->pBlockingConnection!=db );
144076    }
144077  }
144078}
144079#else
144080# define checkListProperties(x)
144081#endif
144082
144083/*
144084** Remove connection db from the blocked connections list. If connection
144085** db is not currently a part of the list, this function is a no-op.
144086*/
144087static void removeFromBlockedList(sqlite3 *db){
144088  sqlite3 **pp;
144089  assertMutexHeld();
144090  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
144091    if( *pp==db ){
144092      *pp = (*pp)->pNextBlocked;
144093      break;
144094    }
144095  }
144096}
144097
144098/*
144099** Add connection db to the blocked connections list. It is assumed
144100** that it is not already a part of the list.
144101*/
144102static void addToBlockedList(sqlite3 *db){
144103  sqlite3 **pp;
144104  assertMutexHeld();
144105  for(
144106    pp=&sqlite3BlockedList;
144107    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
144108    pp=&(*pp)->pNextBlocked
144109  );
144110  db->pNextBlocked = *pp;
144111  *pp = db;
144112}
144113
144114/*
144115** Obtain the STATIC_MASTER mutex.
144116*/
144117static void enterMutex(void){
144118  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
144119  checkListProperties(0);
144120}
144121
144122/*
144123** Release the STATIC_MASTER mutex.
144124*/
144125static void leaveMutex(void){
144126  assertMutexHeld();
144127  checkListProperties(0);
144128  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
144129}
144130
144131/*
144132** Register an unlock-notify callback.
144133**
144134** This is called after connection "db" has attempted some operation
144135** but has received an SQLITE_LOCKED error because another connection
144136** (call it pOther) in the same process was busy using the same shared
144137** cache.  pOther is found by looking at db->pBlockingConnection.
144138**
144139** If there is no blocking connection, the callback is invoked immediately,
144140** before this routine returns.
144141**
144142** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
144143** a deadlock.
144144**
144145** Otherwise, make arrangements to invoke xNotify when pOther drops
144146** its locks.
144147**
144148** Each call to this routine overrides any prior callbacks registered
144149** on the same "db".  If xNotify==0 then any prior callbacks are immediately
144150** cancelled.
144151*/
144152SQLITE_API int sqlite3_unlock_notify(
144153  sqlite3 *db,
144154  void (*xNotify)(void **, int),
144155  void *pArg
144156){
144157  int rc = SQLITE_OK;
144158
144159  sqlite3_mutex_enter(db->mutex);
144160  enterMutex();
144161
144162  if( xNotify==0 ){
144163    removeFromBlockedList(db);
144164    db->pBlockingConnection = 0;
144165    db->pUnlockConnection = 0;
144166    db->xUnlockNotify = 0;
144167    db->pUnlockArg = 0;
144168  }else if( 0==db->pBlockingConnection ){
144169    /* The blocking transaction has been concluded. Or there never was a
144170    ** blocking transaction. In either case, invoke the notify callback
144171    ** immediately.
144172    */
144173    xNotify(&pArg, 1);
144174  }else{
144175    sqlite3 *p;
144176
144177    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
144178    if( p ){
144179      rc = SQLITE_LOCKED;              /* Deadlock detected. */
144180    }else{
144181      db->pUnlockConnection = db->pBlockingConnection;
144182      db->xUnlockNotify = xNotify;
144183      db->pUnlockArg = pArg;
144184      removeFromBlockedList(db);
144185      addToBlockedList(db);
144186    }
144187  }
144188
144189  leaveMutex();
144190  assert( !db->mallocFailed );
144191  sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
144192  sqlite3_mutex_leave(db->mutex);
144193  return rc;
144194}
144195
144196/*
144197** This function is called while stepping or preparing a statement
144198** associated with connection db. The operation will return SQLITE_LOCKED
144199** to the user because it requires a lock that will not be available
144200** until connection pBlocker concludes its current transaction.
144201*/
144202SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
144203  enterMutex();
144204  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
144205    addToBlockedList(db);
144206  }
144207  db->pBlockingConnection = pBlocker;
144208  leaveMutex();
144209}
144210
144211/*
144212** This function is called when
144213** the transaction opened by database db has just finished. Locks held
144214** by database connection db have been released.
144215**
144216** This function loops through each entry in the blocked connections
144217** list and does the following:
144218**
144219**   1) If the sqlite3.pBlockingConnection member of a list entry is
144220**      set to db, then set pBlockingConnection=0.
144221**
144222**   2) If the sqlite3.pUnlockConnection member of a list entry is
144223**      set to db, then invoke the configured unlock-notify callback and
144224**      set pUnlockConnection=0.
144225**
144226**   3) If the two steps above mean that pBlockingConnection==0 and
144227**      pUnlockConnection==0, remove the entry from the blocked connections
144228**      list.
144229*/
144230SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
144231  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
144232  int nArg = 0;                            /* Number of entries in aArg[] */
144233  sqlite3 **pp;                            /* Iterator variable */
144234  void **aArg;               /* Arguments to the unlock callback */
144235  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
144236  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
144237
144238  aArg = aStatic;
144239  enterMutex();         /* Enter STATIC_MASTER mutex */
144240
144241  /* This loop runs once for each entry in the blocked-connections list. */
144242  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
144243    sqlite3 *p = *pp;
144244
144245    /* Step 1. */
144246    if( p->pBlockingConnection==db ){
144247      p->pBlockingConnection = 0;
144248    }
144249
144250    /* Step 2. */
144251    if( p->pUnlockConnection==db ){
144252      assert( p->xUnlockNotify );
144253      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
144254        xUnlockNotify(aArg, nArg);
144255        nArg = 0;
144256      }
144257
144258      sqlite3BeginBenignMalloc();
144259      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
144260      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
144261      if( (!aDyn && nArg==(int)ArraySize(aStatic))
144262       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
144263      ){
144264        /* The aArg[] array needs to grow. */
144265        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
144266        if( pNew ){
144267          memcpy(pNew, aArg, nArg*sizeof(void *));
144268          sqlite3_free(aDyn);
144269          aDyn = aArg = pNew;
144270        }else{
144271          /* This occurs when the array of context pointers that need to
144272          ** be passed to the unlock-notify callback is larger than the
144273          ** aStatic[] array allocated on the stack and the attempt to
144274          ** allocate a larger array from the heap has failed.
144275          **
144276          ** This is a difficult situation to handle. Returning an error
144277          ** code to the caller is insufficient, as even if an error code
144278          ** is returned the transaction on connection db will still be
144279          ** closed and the unlock-notify callbacks on blocked connections
144280          ** will go unissued. This might cause the application to wait
144281          ** indefinitely for an unlock-notify callback that will never
144282          ** arrive.
144283          **
144284          ** Instead, invoke the unlock-notify callback with the context
144285          ** array already accumulated. We can then clear the array and
144286          ** begin accumulating any further context pointers without
144287          ** requiring any dynamic allocation. This is sub-optimal because
144288          ** it means that instead of one callback with a large array of
144289          ** context pointers the application will receive two or more
144290          ** callbacks with smaller arrays of context pointers, which will
144291          ** reduce the applications ability to prioritize multiple
144292          ** connections. But it is the best that can be done under the
144293          ** circumstances.
144294          */
144295          xUnlockNotify(aArg, nArg);
144296          nArg = 0;
144297        }
144298      }
144299      sqlite3EndBenignMalloc();
144300
144301      aArg[nArg++] = p->pUnlockArg;
144302      xUnlockNotify = p->xUnlockNotify;
144303      p->pUnlockConnection = 0;
144304      p->xUnlockNotify = 0;
144305      p->pUnlockArg = 0;
144306    }
144307
144308    /* Step 3. */
144309    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
144310      /* Remove connection p from the blocked connections list. */
144311      *pp = p->pNextBlocked;
144312      p->pNextBlocked = 0;
144313    }else{
144314      pp = &p->pNextBlocked;
144315    }
144316  }
144317
144318  if( nArg!=0 ){
144319    xUnlockNotify(aArg, nArg);
144320  }
144321  sqlite3_free(aDyn);
144322  leaveMutex();         /* Leave STATIC_MASTER mutex */
144323}
144324
144325/*
144326** This is called when the database connection passed as an argument is
144327** being closed. The connection is removed from the blocked list.
144328*/
144329SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
144330  sqlite3ConnectionUnlocked(db);
144331  enterMutex();
144332  removeFromBlockedList(db);
144333  checkListProperties(db);
144334  leaveMutex();
144335}
144336#endif
144337
144338/************** End of notify.c **********************************************/
144339/************** Begin file fts3.c ********************************************/
144340/*
144341** 2006 Oct 10
144342**
144343** The author disclaims copyright to this source code.  In place of
144344** a legal notice, here is a blessing:
144345**
144346**    May you do good and not evil.
144347**    May you find forgiveness for yourself and forgive others.
144348**    May you share freely, never taking more than you give.
144349**
144350******************************************************************************
144351**
144352** This is an SQLite module implementing full-text search.
144353*/
144354
144355/*
144356** The code in this file is only compiled if:
144357**
144358**     * The FTS3 module is being built as an extension
144359**       (in which case SQLITE_CORE is not defined), or
144360**
144361**     * The FTS3 module is being built into the core of
144362**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
144363*/
144364
144365/* The full-text index is stored in a series of b+tree (-like)
144366** structures called segments which map terms to doclists.  The
144367** structures are like b+trees in layout, but are constructed from the
144368** bottom up in optimal fashion and are not updatable.  Since trees
144369** are built from the bottom up, things will be described from the
144370** bottom up.
144371**
144372**
144373**** Varints ****
144374** The basic unit of encoding is a variable-length integer called a
144375** varint.  We encode variable-length integers in little-endian order
144376** using seven bits * per byte as follows:
144377**
144378** KEY:
144379**         A = 0xxxxxxx    7 bits of data and one flag bit
144380**         B = 1xxxxxxx    7 bits of data and one flag bit
144381**
144382**  7 bits - A
144383** 14 bits - BA
144384** 21 bits - BBA
144385** and so on.
144386**
144387** This is similar in concept to how sqlite encodes "varints" but
144388** the encoding is not the same.  SQLite varints are big-endian
144389** are are limited to 9 bytes in length whereas FTS3 varints are
144390** little-endian and can be up to 10 bytes in length (in theory).
144391**
144392** Example encodings:
144393**
144394**     1:    0x01
144395**   127:    0x7f
144396**   128:    0x81 0x00
144397**
144398**
144399**** Document lists ****
144400** A doclist (document list) holds a docid-sorted list of hits for a
144401** given term.  Doclists hold docids and associated token positions.
144402** A docid is the unique integer identifier for a single document.
144403** A position is the index of a word within the document.  The first
144404** word of the document has a position of 0.
144405**
144406** FTS3 used to optionally store character offsets using a compile-time
144407** option.  But that functionality is no longer supported.
144408**
144409** A doclist is stored like this:
144410**
144411** array {
144412**   varint docid;          (delta from previous doclist)
144413**   array {                (position list for column 0)
144414**     varint position;     (2 more than the delta from previous position)
144415**   }
144416**   array {
144417**     varint POS_COLUMN;   (marks start of position list for new column)
144418**     varint column;       (index of new column)
144419**     array {
144420**       varint position;   (2 more than the delta from previous position)
144421**     }
144422**   }
144423**   varint POS_END;        (marks end of positions for this document.
144424** }
144425**
144426** Here, array { X } means zero or more occurrences of X, adjacent in
144427** memory.  A "position" is an index of a token in the token stream
144428** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
144429** in the same logical place as the position element, and act as sentinals
144430** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
144431** The positions numbers are not stored literally but rather as two more
144432** than the difference from the prior position, or the just the position plus
144433** 2 for the first position.  Example:
144434**
144435**   label:       A B C D E  F  G H   I  J K
144436**   value:     123 5 9 1 1 14 35 0 234 72 0
144437**
144438** The 123 value is the first docid.  For column zero in this document
144439** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
144440** at D signals the start of a new column; the 1 at E indicates that the
144441** new column is column number 1.  There are two positions at 12 and 45
144442** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
144443** 234 at I is the delta to next docid (357).  It has one position 70
144444** (72-2) and then terminates with the 0 at K.
144445**
144446** A "position-list" is the list of positions for multiple columns for
144447** a single docid.  A "column-list" is the set of positions for a single
144448** column.  Hence, a position-list consists of one or more column-lists,
144449** a document record consists of a docid followed by a position-list and
144450** a doclist consists of one or more document records.
144451**
144452** A bare doclist omits the position information, becoming an
144453** array of varint-encoded docids.
144454**
144455**** Segment leaf nodes ****
144456** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
144457** nodes are written using LeafWriter, and read using LeafReader (to
144458** iterate through a single leaf node's data) and LeavesReader (to
144459** iterate through a segment's entire leaf layer).  Leaf nodes have
144460** the format:
144461**
144462** varint iHeight;             (height from leaf level, always 0)
144463** varint nTerm;               (length of first term)
144464** char pTerm[nTerm];          (content of first term)
144465** varint nDoclist;            (length of term's associated doclist)
144466** char pDoclist[nDoclist];    (content of doclist)
144467** array {
144468**                             (further terms are delta-encoded)
144469**   varint nPrefix;           (length of prefix shared with previous term)
144470**   varint nSuffix;           (length of unshared suffix)
144471**   char pTermSuffix[nSuffix];(unshared suffix of next term)
144472**   varint nDoclist;          (length of term's associated doclist)
144473**   char pDoclist[nDoclist];  (content of doclist)
144474** }
144475**
144476** Here, array { X } means zero or more occurrences of X, adjacent in
144477** memory.
144478**
144479** Leaf nodes are broken into blocks which are stored contiguously in
144480** the %_segments table in sorted order.  This means that when the end
144481** of a node is reached, the next term is in the node with the next
144482** greater node id.
144483**
144484** New data is spilled to a new leaf node when the current node
144485** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
144486** larger than STANDALONE_MIN (default 1024) is placed in a standalone
144487** node (a leaf node with a single term and doclist).  The goal of
144488** these settings is to pack together groups of small doclists while
144489** making it efficient to directly access large doclists.  The
144490** assumption is that large doclists represent terms which are more
144491** likely to be query targets.
144492**
144493** TODO(shess) It may be useful for blocking decisions to be more
144494** dynamic.  For instance, it may make more sense to have a 2.5k leaf
144495** node rather than splitting into 2k and .5k nodes.  My intuition is
144496** that this might extend through 2x or 4x the pagesize.
144497**
144498**
144499**** Segment interior nodes ****
144500** Segment interior nodes store blockids for subtree nodes and terms
144501** to describe what data is stored by the each subtree.  Interior
144502** nodes are written using InteriorWriter, and read using
144503** InteriorReader.  InteriorWriters are created as needed when
144504** SegmentWriter creates new leaf nodes, or when an interior node
144505** itself grows too big and must be split.  The format of interior
144506** nodes:
144507**
144508** varint iHeight;           (height from leaf level, always >0)
144509** varint iBlockid;          (block id of node's leftmost subtree)
144510** optional {
144511**   varint nTerm;           (length of first term)
144512**   char pTerm[nTerm];      (content of first term)
144513**   array {
144514**                                (further terms are delta-encoded)
144515**     varint nPrefix;            (length of shared prefix with previous term)
144516**     varint nSuffix;            (length of unshared suffix)
144517**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
144518**   }
144519** }
144520**
144521** Here, optional { X } means an optional element, while array { X }
144522** means zero or more occurrences of X, adjacent in memory.
144523**
144524** An interior node encodes n terms separating n+1 subtrees.  The
144525** subtree blocks are contiguous, so only the first subtree's blockid
144526** is encoded.  The subtree at iBlockid will contain all terms less
144527** than the first term encoded (or all terms if no term is encoded).
144528** Otherwise, for terms greater than or equal to pTerm[i] but less
144529** than pTerm[i+1], the subtree for that term will be rooted at
144530** iBlockid+i.  Interior nodes only store enough term data to
144531** distinguish adjacent children (if the rightmost term of the left
144532** child is "something", and the leftmost term of the right child is
144533** "wicked", only "w" is stored).
144534**
144535** New data is spilled to a new interior node at the same height when
144536** the current node exceeds INTERIOR_MAX bytes (default 2048).
144537** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
144538** interior nodes and making the tree too skinny.  The interior nodes
144539** at a given height are naturally tracked by interior nodes at
144540** height+1, and so on.
144541**
144542**
144543**** Segment directory ****
144544** The segment directory in table %_segdir stores meta-information for
144545** merging and deleting segments, and also the root node of the
144546** segment's tree.
144547**
144548** The root node is the top node of the segment's tree after encoding
144549** the entire segment, restricted to ROOT_MAX bytes (default 1024).
144550** This could be either a leaf node or an interior node.  If the top
144551** node requires more than ROOT_MAX bytes, it is flushed to %_segments
144552** and a new root interior node is generated (which should always fit
144553** within ROOT_MAX because it only needs space for 2 varints, the
144554** height and the blockid of the previous root).
144555**
144556** The meta-information in the segment directory is:
144557**   level               - segment level (see below)
144558**   idx                 - index within level
144559**                       - (level,idx uniquely identify a segment)
144560**   start_block         - first leaf node
144561**   leaves_end_block    - last leaf node
144562**   end_block           - last block (including interior nodes)
144563**   root                - contents of root node
144564**
144565** If the root node is a leaf node, then start_block,
144566** leaves_end_block, and end_block are all 0.
144567**
144568**
144569**** Segment merging ****
144570** To amortize update costs, segments are grouped into levels and
144571** merged in batches.  Each increase in level represents exponentially
144572** more documents.
144573**
144574** New documents (actually, document updates) are tokenized and
144575** written individually (using LeafWriter) to a level 0 segment, with
144576** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
144577** level 0 segments are merged into a single level 1 segment.  Level 1
144578** is populated like level 0, and eventually MERGE_COUNT level 1
144579** segments are merged to a single level 2 segment (representing
144580** MERGE_COUNT^2 updates), and so on.
144581**
144582** A segment merge traverses all segments at a given level in
144583** parallel, performing a straightforward sorted merge.  Since segment
144584** leaf nodes are written in to the %_segments table in order, this
144585** merge traverses the underlying sqlite disk structures efficiently.
144586** After the merge, all segment blocks from the merged level are
144587** deleted.
144588**
144589** MERGE_COUNT controls how often we merge segments.  16 seems to be
144590** somewhat of a sweet spot for insertion performance.  32 and 64 show
144591** very similar performance numbers to 16 on insertion, though they're
144592** a tiny bit slower (perhaps due to more overhead in merge-time
144593** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
144594** 16, 2 about 66% slower than 16.
144595**
144596** At query time, high MERGE_COUNT increases the number of segments
144597** which need to be scanned and merged.  For instance, with 100k docs
144598** inserted:
144599**
144600**    MERGE_COUNT   segments
144601**       16           25
144602**        8           12
144603**        4           10
144604**        2            6
144605**
144606** This appears to have only a moderate impact on queries for very
144607** frequent terms (which are somewhat dominated by segment merge
144608** costs), and infrequent and non-existent terms still seem to be fast
144609** even with many segments.
144610**
144611** TODO(shess) That said, it would be nice to have a better query-side
144612** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
144613** optimizations to things like doclist merging will swing the sweet
144614** spot around.
144615**
144616**
144617**
144618**** Handling of deletions and updates ****
144619** Since we're using a segmented structure, with no docid-oriented
144620** index into the term index, we clearly cannot simply update the term
144621** index when a document is deleted or updated.  For deletions, we
144622** write an empty doclist (varint(docid) varint(POS_END)), for updates
144623** we simply write the new doclist.  Segment merges overwrite older
144624** data for a particular docid with newer data, so deletes or updates
144625** will eventually overtake the earlier data and knock it out.  The
144626** query logic likewise merges doclists so that newer data knocks out
144627** older data.
144628*/
144629
144630/************** Include fts3Int.h in the middle of fts3.c ********************/
144631/************** Begin file fts3Int.h *****************************************/
144632/*
144633** 2009 Nov 12
144634**
144635** The author disclaims copyright to this source code.  In place of
144636** a legal notice, here is a blessing:
144637**
144638**    May you do good and not evil.
144639**    May you find forgiveness for yourself and forgive others.
144640**    May you share freely, never taking more than you give.
144641**
144642******************************************************************************
144643**
144644*/
144645#ifndef _FTSINT_H
144646#define _FTSINT_H
144647
144648#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
144649# define NDEBUG 1
144650#endif
144651
144652/* FTS3/FTS4 require virtual tables */
144653#ifdef SQLITE_OMIT_VIRTUALTABLE
144654# undef SQLITE_ENABLE_FTS3
144655# undef SQLITE_ENABLE_FTS4
144656#endif
144657
144658/*
144659** FTS4 is really an extension for FTS3.  It is enabled using the
144660** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
144661** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
144662*/
144663#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
144664# define SQLITE_ENABLE_FTS3
144665#endif
144666
144667#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
144668
144669/* If not building as part of the core, include sqlite3ext.h. */
144670#ifndef SQLITE_CORE
144671/* # include "sqlite3ext.h"  */
144672SQLITE_EXTENSION_INIT3
144673#endif
144674
144675/* #include "sqlite3.h" */
144676/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
144677/************** Begin file fts3_tokenizer.h **********************************/
144678/*
144679** 2006 July 10
144680**
144681** The author disclaims copyright to this source code.
144682**
144683*************************************************************************
144684** Defines the interface to tokenizers used by fulltext-search.  There
144685** are three basic components:
144686**
144687** sqlite3_tokenizer_module is a singleton defining the tokenizer
144688** interface functions.  This is essentially the class structure for
144689** tokenizers.
144690**
144691** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
144692** including customization information defined at creation time.
144693**
144694** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
144695** tokens from a particular input.
144696*/
144697#ifndef _FTS3_TOKENIZER_H_
144698#define _FTS3_TOKENIZER_H_
144699
144700/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
144701** If tokenizers are to be allowed to call sqlite3_*() functions, then
144702** we will need a way to register the API consistently.
144703*/
144704/* #include "sqlite3.h" */
144705
144706/*
144707** Structures used by the tokenizer interface. When a new tokenizer
144708** implementation is registered, the caller provides a pointer to
144709** an sqlite3_tokenizer_module containing pointers to the callback
144710** functions that make up an implementation.
144711**
144712** When an fts3 table is created, it passes any arguments passed to
144713** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
144714** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
144715** implementation. The xCreate() function in turn returns an
144716** sqlite3_tokenizer structure representing the specific tokenizer to
144717** be used for the fts3 table (customized by the tokenizer clause arguments).
144718**
144719** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
144720** method is called. It returns an sqlite3_tokenizer_cursor object
144721** that may be used to tokenize a specific input buffer based on
144722** the tokenization rules supplied by a specific sqlite3_tokenizer
144723** object.
144724*/
144725typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
144726typedef struct sqlite3_tokenizer sqlite3_tokenizer;
144727typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
144728
144729struct sqlite3_tokenizer_module {
144730
144731  /*
144732  ** Structure version. Should always be set to 0 or 1.
144733  */
144734  int iVersion;
144735
144736  /*
144737  ** Create a new tokenizer. The values in the argv[] array are the
144738  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
144739  ** TABLE statement that created the fts3 table. For example, if
144740  ** the following SQL is executed:
144741  **
144742  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
144743  **
144744  ** then argc is set to 2, and the argv[] array contains pointers
144745  ** to the strings "arg1" and "arg2".
144746  **
144747  ** This method should return either SQLITE_OK (0), or an SQLite error
144748  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
144749  ** to point at the newly created tokenizer structure. The generic
144750  ** sqlite3_tokenizer.pModule variable should not be initialized by
144751  ** this callback. The caller will do so.
144752  */
144753  int (*xCreate)(
144754    int argc,                           /* Size of argv array */
144755    const char *const*argv,             /* Tokenizer argument strings */
144756    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
144757  );
144758
144759  /*
144760  ** Destroy an existing tokenizer. The fts3 module calls this method
144761  ** exactly once for each successful call to xCreate().
144762  */
144763  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
144764
144765  /*
144766  ** Create a tokenizer cursor to tokenize an input buffer. The caller
144767  ** is responsible for ensuring that the input buffer remains valid
144768  ** until the cursor is closed (using the xClose() method).
144769  */
144770  int (*xOpen)(
144771    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
144772    const char *pInput, int nBytes,      /* Input buffer */
144773    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
144774  );
144775
144776  /*
144777  ** Destroy an existing tokenizer cursor. The fts3 module calls this
144778  ** method exactly once for each successful call to xOpen().
144779  */
144780  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
144781
144782  /*
144783  ** Retrieve the next token from the tokenizer cursor pCursor. This
144784  ** method should either return SQLITE_OK and set the values of the
144785  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
144786  ** the end of the buffer has been reached, or an SQLite error code.
144787  **
144788  ** *ppToken should be set to point at a buffer containing the
144789  ** normalized version of the token (i.e. after any case-folding and/or
144790  ** stemming has been performed). *pnBytes should be set to the length
144791  ** of this buffer in bytes. The input text that generated the token is
144792  ** identified by the byte offsets returned in *piStartOffset and
144793  ** *piEndOffset. *piStartOffset should be set to the index of the first
144794  ** byte of the token in the input buffer. *piEndOffset should be set
144795  ** to the index of the first byte just past the end of the token in
144796  ** the input buffer.
144797  **
144798  ** The buffer *ppToken is set to point at is managed by the tokenizer
144799  ** implementation. It is only required to be valid until the next call
144800  ** to xNext() or xClose().
144801  */
144802  /* TODO(shess) current implementation requires pInput to be
144803  ** nul-terminated.  This should either be fixed, or pInput/nBytes
144804  ** should be converted to zInput.
144805  */
144806  int (*xNext)(
144807    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
144808    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
144809    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
144810    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
144811    int *piPosition      /* OUT: Number of tokens returned before this one */
144812  );
144813
144814  /***********************************************************************
144815  ** Methods below this point are only available if iVersion>=1.
144816  */
144817
144818  /*
144819  ** Configure the language id of a tokenizer cursor.
144820  */
144821  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
144822};
144823
144824struct sqlite3_tokenizer {
144825  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
144826  /* Tokenizer implementations will typically add additional fields */
144827};
144828
144829struct sqlite3_tokenizer_cursor {
144830  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
144831  /* Tokenizer implementations will typically add additional fields */
144832};
144833
144834int fts3_global_term_cnt(int iTerm, int iCol);
144835int fts3_term_cnt(int iTerm, int iCol);
144836
144837
144838#endif /* _FTS3_TOKENIZER_H_ */
144839
144840/************** End of fts3_tokenizer.h **************************************/
144841/************** Continuing where we left off in fts3Int.h ********************/
144842/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
144843/************** Begin file fts3_hash.h ***************************************/
144844/*
144845** 2001 September 22
144846**
144847** The author disclaims copyright to this source code.  In place of
144848** a legal notice, here is a blessing:
144849**
144850**    May you do good and not evil.
144851**    May you find forgiveness for yourself and forgive others.
144852**    May you share freely, never taking more than you give.
144853**
144854*************************************************************************
144855** This is the header file for the generic hash-table implementation
144856** used in SQLite.  We've modified it slightly to serve as a standalone
144857** hash table implementation for the full-text indexing module.
144858**
144859*/
144860#ifndef _FTS3_HASH_H_
144861#define _FTS3_HASH_H_
144862
144863/* Forward declarations of structures. */
144864typedef struct Fts3Hash Fts3Hash;
144865typedef struct Fts3HashElem Fts3HashElem;
144866
144867/* A complete hash table is an instance of the following structure.
144868** The internals of this structure are intended to be opaque -- client
144869** code should not attempt to access or modify the fields of this structure
144870** directly.  Change this structure only by using the routines below.
144871** However, many of the "procedures" and "functions" for modifying and
144872** accessing this structure are really macros, so we can't really make
144873** this structure opaque.
144874*/
144875struct Fts3Hash {
144876  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
144877  char copyKey;           /* True if copy of key made on insert */
144878  int count;              /* Number of entries in this table */
144879  Fts3HashElem *first;    /* The first element of the array */
144880  int htsize;             /* Number of buckets in the hash table */
144881  struct _fts3ht {        /* the hash table */
144882    int count;               /* Number of entries with this hash */
144883    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
144884  } *ht;
144885};
144886
144887/* Each element in the hash table is an instance of the following
144888** structure.  All elements are stored on a single doubly-linked list.
144889**
144890** Again, this structure is intended to be opaque, but it can't really
144891** be opaque because it is used by macros.
144892*/
144893struct Fts3HashElem {
144894  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
144895  void *data;                /* Data associated with this element */
144896  void *pKey; int nKey;      /* Key associated with this element */
144897};
144898
144899/*
144900** There are 2 different modes of operation for a hash table:
144901**
144902**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
144903**                           (including the null-terminator, if any).  Case
144904**                           is respected in comparisons.
144905**
144906**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
144907**                           memcmp() is used to compare keys.
144908**
144909** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
144910*/
144911#define FTS3_HASH_STRING    1
144912#define FTS3_HASH_BINARY    2
144913
144914/*
144915** Access routines.  To delete, insert a NULL pointer.
144916*/
144917SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
144918SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
144919SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
144920SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
144921SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
144922
144923/*
144924** Shorthand for the functions above
144925*/
144926#define fts3HashInit     sqlite3Fts3HashInit
144927#define fts3HashInsert   sqlite3Fts3HashInsert
144928#define fts3HashFind     sqlite3Fts3HashFind
144929#define fts3HashClear    sqlite3Fts3HashClear
144930#define fts3HashFindElem sqlite3Fts3HashFindElem
144931
144932/*
144933** Macros for looping over all elements of a hash table.  The idiom is
144934** like this:
144935**
144936**   Fts3Hash h;
144937**   Fts3HashElem *p;
144938**   ...
144939**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
144940**     SomeStructure *pData = fts3HashData(p);
144941**     // do something with pData
144942**   }
144943*/
144944#define fts3HashFirst(H)  ((H)->first)
144945#define fts3HashNext(E)   ((E)->next)
144946#define fts3HashData(E)   ((E)->data)
144947#define fts3HashKey(E)    ((E)->pKey)
144948#define fts3HashKeysize(E) ((E)->nKey)
144949
144950/*
144951** Number of entries in a hash table
144952*/
144953#define fts3HashCount(H)  ((H)->count)
144954
144955#endif /* _FTS3_HASH_H_ */
144956
144957/************** End of fts3_hash.h *******************************************/
144958/************** Continuing where we left off in fts3Int.h ********************/
144959
144960/*
144961** This constant determines the maximum depth of an FTS expression tree
144962** that the library will create and use. FTS uses recursion to perform
144963** various operations on the query tree, so the disadvantage of a large
144964** limit is that it may allow very large queries to use large amounts
144965** of stack space (perhaps causing a stack overflow).
144966*/
144967#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
144968# define SQLITE_FTS3_MAX_EXPR_DEPTH 12
144969#endif
144970
144971
144972/*
144973** This constant controls how often segments are merged. Once there are
144974** FTS3_MERGE_COUNT segments of level N, they are merged into a single
144975** segment of level N+1.
144976*/
144977#define FTS3_MERGE_COUNT 16
144978
144979/*
144980** This is the maximum amount of data (in bytes) to store in the
144981** Fts3Table.pendingTerms hash table. Normally, the hash table is
144982** populated as documents are inserted/updated/deleted in a transaction
144983** and used to create a new segment when the transaction is committed.
144984** However if this limit is reached midway through a transaction, a new
144985** segment is created and the hash table cleared immediately.
144986*/
144987#define FTS3_MAX_PENDING_DATA (1*1024*1024)
144988
144989/*
144990** Macro to return the number of elements in an array. SQLite has a
144991** similar macro called ArraySize(). Use a different name to avoid
144992** a collision when building an amalgamation with built-in FTS3.
144993*/
144994#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
144995
144996
144997#ifndef MIN
144998# define MIN(x,y) ((x)<(y)?(x):(y))
144999#endif
145000#ifndef MAX
145001# define MAX(x,y) ((x)>(y)?(x):(y))
145002#endif
145003
145004/*
145005** Maximum length of a varint encoded integer. The varint format is different
145006** from that used by SQLite, so the maximum length is 10, not 9.
145007*/
145008#define FTS3_VARINT_MAX 10
145009
145010/*
145011** FTS4 virtual tables may maintain multiple indexes - one index of all terms
145012** in the document set and zero or more prefix indexes. All indexes are stored
145013** as one or more b+-trees in the %_segments and %_segdir tables.
145014**
145015** It is possible to determine which index a b+-tree belongs to based on the
145016** value stored in the "%_segdir.level" column. Given this value L, the index
145017** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
145018** level values between 0 and 1023 (inclusive) belong to index 0, all levels
145019** between 1024 and 2047 to index 1, and so on.
145020**
145021** It is considered impossible for an index to use more than 1024 levels. In
145022** theory though this may happen, but only after at least
145023** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
145024*/
145025#define FTS3_SEGDIR_MAXLEVEL      1024
145026#define FTS3_SEGDIR_MAXLEVEL_STR "1024"
145027
145028/*
145029** The testcase() macro is only used by the amalgamation.  If undefined,
145030** make it a no-op.
145031*/
145032#ifndef testcase
145033# define testcase(X)
145034#endif
145035
145036/*
145037** Terminator values for position-lists and column-lists.
145038*/
145039#define POS_COLUMN  (1)     /* Column-list terminator */
145040#define POS_END     (0)     /* Position-list terminator */
145041
145042/*
145043** This section provides definitions to allow the
145044** FTS3 extension to be compiled outside of the
145045** amalgamation.
145046*/
145047#ifndef SQLITE_AMALGAMATION
145048/*
145049** Macros indicating that conditional expressions are always true or
145050** false.
145051*/
145052#ifdef SQLITE_COVERAGE_TEST
145053# define ALWAYS(x) (1)
145054# define NEVER(X)  (0)
145055#elif defined(SQLITE_DEBUG)
145056# define ALWAYS(x) sqlite3Fts3Always((x)!=0)
145057# define NEVER(x) sqlite3Fts3Never((x)!=0)
145058SQLITE_PRIVATE int sqlite3Fts3Always(int b);
145059SQLITE_PRIVATE int sqlite3Fts3Never(int b);
145060#else
145061# define ALWAYS(x) (x)
145062# define NEVER(x)  (x)
145063#endif
145064
145065/*
145066** Internal types used by SQLite.
145067*/
145068typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
145069typedef short int i16;            /* 2-byte (or larger) signed integer */
145070typedef unsigned int u32;         /* 4-byte unsigned integer */
145071typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
145072typedef sqlite3_int64 i64;        /* 8-byte signed integer */
145073
145074/*
145075** Macro used to suppress compiler warnings for unused parameters.
145076*/
145077#define UNUSED_PARAMETER(x) (void)(x)
145078
145079/*
145080** Activate assert() only if SQLITE_TEST is enabled.
145081*/
145082#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
145083# define NDEBUG 1
145084#endif
145085
145086/*
145087** The TESTONLY macro is used to enclose variable declarations or
145088** other bits of code that are needed to support the arguments
145089** within testcase() and assert() macros.
145090*/
145091#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
145092# define TESTONLY(X)  X
145093#else
145094# define TESTONLY(X)
145095#endif
145096
145097#endif /* SQLITE_AMALGAMATION */
145098
145099#ifdef SQLITE_DEBUG
145100SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
145101# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
145102#else
145103# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
145104#endif
145105
145106typedef struct Fts3Table Fts3Table;
145107typedef struct Fts3Cursor Fts3Cursor;
145108typedef struct Fts3Expr Fts3Expr;
145109typedef struct Fts3Phrase Fts3Phrase;
145110typedef struct Fts3PhraseToken Fts3PhraseToken;
145111
145112typedef struct Fts3Doclist Fts3Doclist;
145113typedef struct Fts3SegFilter Fts3SegFilter;
145114typedef struct Fts3DeferredToken Fts3DeferredToken;
145115typedef struct Fts3SegReader Fts3SegReader;
145116typedef struct Fts3MultiSegReader Fts3MultiSegReader;
145117
145118typedef struct MatchinfoBuffer MatchinfoBuffer;
145119
145120/*
145121** A connection to a fulltext index is an instance of the following
145122** structure. The xCreate and xConnect methods create an instance
145123** of this structure and xDestroy and xDisconnect free that instance.
145124** All other methods receive a pointer to the structure as one of their
145125** arguments.
145126*/
145127struct Fts3Table {
145128  sqlite3_vtab base;              /* Base class used by SQLite core */
145129  sqlite3 *db;                    /* The database connection */
145130  const char *zDb;                /* logical database name */
145131  const char *zName;              /* virtual table name */
145132  int nColumn;                    /* number of named columns in virtual table */
145133  char **azColumn;                /* column names.  malloced */
145134  u8 *abNotindexed;               /* True for 'notindexed' columns */
145135  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
145136  char *zContentTbl;              /* content=xxx option, or NULL */
145137  char *zLanguageid;              /* languageid=xxx option, or NULL */
145138  int nAutoincrmerge;             /* Value configured by 'automerge' */
145139  u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
145140
145141  /* Precompiled statements used by the implementation. Each of these
145142  ** statements is run and reset within a single virtual table API call.
145143  */
145144  sqlite3_stmt *aStmt[40];
145145  sqlite3_stmt *pSeekStmt;        /* Cache for fts3CursorSeekStmt() */
145146
145147  char *zReadExprlist;
145148  char *zWriteExprlist;
145149
145150  int nNodeSize;                  /* Soft limit for node size */
145151  u8 bFts4;                       /* True for FTS4, false for FTS3 */
145152  u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
145153  u8 bHasDocsize;                 /* True if %_docsize table exists */
145154  u8 bDescIdx;                    /* True if doclists are in reverse order */
145155  u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
145156  int nPgsz;                      /* Page size for host database */
145157  char *zSegmentsTbl;             /* Name of %_segments table */
145158  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
145159
145160  /*
145161  ** The following array of hash tables is used to buffer pending index
145162  ** updates during transactions. All pending updates buffered at any one
145163  ** time must share a common language-id (see the FTS4 langid= feature).
145164  ** The current language id is stored in variable iPrevLangid.
145165  **
145166  ** A single FTS4 table may have multiple full-text indexes. For each index
145167  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
145168  ** terms that appear in the document set. Each subsequent index in aIndex[]
145169  ** is an index of prefixes of a specific length.
145170  **
145171  ** Variable nPendingData contains an estimate the memory consumed by the
145172  ** pending data structures, including hash table overhead, but not including
145173  ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
145174  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
145175  ** recently inserted record.
145176  */
145177  int nIndex;                     /* Size of aIndex[] */
145178  struct Fts3Index {
145179    int nPrefix;                  /* Prefix length (0 for main terms index) */
145180    Fts3Hash hPending;            /* Pending terms table for this index */
145181  } *aIndex;
145182  int nMaxPendingData;            /* Max pending data before flush to disk */
145183  int nPendingData;               /* Current bytes of pending data */
145184  sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
145185  int iPrevLangid;                /* Langid of recently inserted document */
145186  int bPrevDelete;                /* True if last operation was a delete */
145187
145188#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
145189  /* State variables used for validating that the transaction control
145190  ** methods of the virtual table are called at appropriate times.  These
145191  ** values do not contribute to FTS functionality; they are used for
145192  ** verifying the operation of the SQLite core.
145193  */
145194  int inTransaction;     /* True after xBegin but before xCommit/xRollback */
145195  int mxSavepoint;       /* Largest valid xSavepoint integer */
145196#endif
145197
145198#ifdef SQLITE_TEST
145199  /* True to disable the incremental doclist optimization. This is controled
145200  ** by special insert command 'test-no-incr-doclist'.  */
145201  int bNoIncrDoclist;
145202#endif
145203};
145204
145205/*
145206** When the core wants to read from the virtual table, it creates a
145207** virtual table cursor (an instance of the following structure) using
145208** the xOpen method. Cursors are destroyed using the xClose method.
145209*/
145210struct Fts3Cursor {
145211  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
145212  i16 eSearch;                    /* Search strategy (see below) */
145213  u8 isEof;                       /* True if at End Of Results */
145214  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
145215  u8 bSeekStmt;                   /* True if pStmt is a seek */
145216  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
145217  Fts3Expr *pExpr;                /* Parsed MATCH query string */
145218  int iLangid;                    /* Language being queried for */
145219  int nPhrase;                    /* Number of matchable phrases in query */
145220  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
145221  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
145222  char *pNextId;                  /* Pointer into the body of aDoclist */
145223  char *aDoclist;                 /* List of docids for full-text queries */
145224  int nDoclist;                   /* Size of buffer at aDoclist */
145225  u8 bDesc;                       /* True to sort in descending order */
145226  int eEvalmode;                  /* An FTS3_EVAL_XX constant */
145227  int nRowAvg;                    /* Average size of database rows, in pages */
145228  sqlite3_int64 nDoc;             /* Documents in table */
145229  i64 iMinDocid;                  /* Minimum docid to return */
145230  i64 iMaxDocid;                  /* Maximum docid to return */
145231  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
145232  MatchinfoBuffer *pMIBuffer;     /* Buffer for matchinfo data */
145233};
145234
145235#define FTS3_EVAL_FILTER    0
145236#define FTS3_EVAL_NEXT      1
145237#define FTS3_EVAL_MATCHINFO 2
145238
145239/*
145240** The Fts3Cursor.eSearch member is always set to one of the following.
145241** Actualy, Fts3Cursor.eSearch can be greater than or equal to
145242** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
145243** of the column to be searched.  For example, in
145244**
145245**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
145246**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
145247**
145248** Because the LHS of the MATCH operator is 2nd column "b",
145249** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
145250** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
145251** indicating that all columns should be searched,
145252** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
145253*/
145254#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
145255#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
145256#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
145257
145258/*
145259** The lower 16-bits of the sqlite3_index_info.idxNum value set by
145260** the xBestIndex() method contains the Fts3Cursor.eSearch value described
145261** above. The upper 16-bits contain a combination of the following
145262** bits, used to describe extra constraints on full-text searches.
145263*/
145264#define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
145265#define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
145266#define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
145267
145268struct Fts3Doclist {
145269  char *aAll;                    /* Array containing doclist (or NULL) */
145270  int nAll;                      /* Size of a[] in bytes */
145271  char *pNextDocid;              /* Pointer to next docid */
145272
145273  sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
145274  int bFreeList;                 /* True if pList should be sqlite3_free()d */
145275  char *pList;                   /* Pointer to position list following iDocid */
145276  int nList;                     /* Length of position list */
145277};
145278
145279/*
145280** A "phrase" is a sequence of one or more tokens that must match in
145281** sequence.  A single token is the base case and the most common case.
145282** For a sequence of tokens contained in double-quotes (i.e. "one two three")
145283** nToken will be the number of tokens in the string.
145284*/
145285struct Fts3PhraseToken {
145286  char *z;                        /* Text of the token */
145287  int n;                          /* Number of bytes in buffer z */
145288  int isPrefix;                   /* True if token ends with a "*" character */
145289  int bFirst;                     /* True if token must appear at position 0 */
145290
145291  /* Variables above this point are populated when the expression is
145292  ** parsed (by code in fts3_expr.c). Below this point the variables are
145293  ** used when evaluating the expression. */
145294  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
145295  Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
145296};
145297
145298struct Fts3Phrase {
145299  /* Cache of doclist for this phrase. */
145300  Fts3Doclist doclist;
145301  int bIncr;                 /* True if doclist is loaded incrementally */
145302  int iDoclistToken;
145303
145304  /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
145305  ** OR condition.  */
145306  char *pOrPoslist;
145307  i64 iOrDocid;
145308
145309  /* Variables below this point are populated by fts3_expr.c when parsing
145310  ** a MATCH expression. Everything above is part of the evaluation phase.
145311  */
145312  int nToken;                /* Number of tokens in the phrase */
145313  int iColumn;               /* Index of column this phrase must match */
145314  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
145315};
145316
145317/*
145318** A tree of these objects forms the RHS of a MATCH operator.
145319**
145320** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
145321** points to a malloced buffer, size nDoclist bytes, containing the results
145322** of this phrase query in FTS3 doclist format. As usual, the initial
145323** "Length" field found in doclists stored on disk is omitted from this
145324** buffer.
145325**
145326** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
145327** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
145328** where nCol is the number of columns in the queried FTS table. The array
145329** is populated as follows:
145330**
145331**   aMI[iCol*3 + 0] = Undefined
145332**   aMI[iCol*3 + 1] = Number of occurrences
145333**   aMI[iCol*3 + 2] = Number of rows containing at least one instance
145334**
145335** The aMI array is allocated using sqlite3_malloc(). It should be freed
145336** when the expression node is.
145337*/
145338struct Fts3Expr {
145339  int eType;                 /* One of the FTSQUERY_XXX values defined below */
145340  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
145341  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
145342  Fts3Expr *pLeft;           /* Left operand */
145343  Fts3Expr *pRight;          /* Right operand */
145344  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
145345
145346  /* The following are used by the fts3_eval.c module. */
145347  sqlite3_int64 iDocid;      /* Current docid */
145348  u8 bEof;                   /* True this expression is at EOF already */
145349  u8 bStart;                 /* True if iDocid is valid */
145350  u8 bDeferred;              /* True if this expression is entirely deferred */
145351
145352  /* The following are used by the fts3_snippet.c module. */
145353  int iPhrase;               /* Index of this phrase in matchinfo() results */
145354  u32 *aMI;                  /* See above */
145355};
145356
145357/*
145358** Candidate values for Fts3Query.eType. Note that the order of the first
145359** four values is in order of precedence when parsing expressions. For
145360** example, the following:
145361**
145362**   "a OR b AND c NOT d NEAR e"
145363**
145364** is equivalent to:
145365**
145366**   "a OR (b AND (c NOT (d NEAR e)))"
145367*/
145368#define FTSQUERY_NEAR   1
145369#define FTSQUERY_NOT    2
145370#define FTSQUERY_AND    3
145371#define FTSQUERY_OR     4
145372#define FTSQUERY_PHRASE 5
145373
145374
145375/* fts3_write.c */
145376SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
145377SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
145378SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
145379SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
145380SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
145381  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
145382SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
145383  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
145384SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
145385SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
145386SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
145387
145388SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
145389SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
145390
145391#ifndef SQLITE_DISABLE_FTS4_DEFERRED
145392SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
145393SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
145394SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
145395SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
145396SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
145397#else
145398# define sqlite3Fts3FreeDeferredTokens(x)
145399# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
145400# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
145401# define sqlite3Fts3FreeDeferredDoclists(x)
145402# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
145403#endif
145404
145405SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
145406SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
145407
145408/* Special values interpreted by sqlite3SegReaderCursor() */
145409#define FTS3_SEGCURSOR_PENDING        -1
145410#define FTS3_SEGCURSOR_ALL            -2
145411
145412SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
145413SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
145414SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
145415
145416SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
145417    int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
145418
145419/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
145420#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
145421#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
145422#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
145423#define FTS3_SEGMENT_PREFIX        0x00000008
145424#define FTS3_SEGMENT_SCAN          0x00000010
145425#define FTS3_SEGMENT_FIRST         0x00000020
145426
145427/* Type passed as 4th argument to SegmentReaderIterate() */
145428struct Fts3SegFilter {
145429  const char *zTerm;
145430  int nTerm;
145431  int iCol;
145432  int flags;
145433};
145434
145435struct Fts3MultiSegReader {
145436  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
145437  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
145438  int nSegment;                   /* Size of apSegment array */
145439  int nAdvance;                   /* How many seg-readers to advance */
145440  Fts3SegFilter *pFilter;         /* Pointer to filter object */
145441  char *aBuffer;                  /* Buffer to merge doclists in */
145442  int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
145443
145444  int iColFilter;                 /* If >=0, filter for this column */
145445  int bRestart;
145446
145447  /* Used by fts3.c only. */
145448  int nCost;                      /* Cost of running iterator */
145449  int bLookup;                    /* True if a lookup of a single entry. */
145450
145451  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
145452  char *zTerm;                    /* Pointer to term buffer */
145453  int nTerm;                      /* Size of zTerm in bytes */
145454  char *aDoclist;                 /* Pointer to doclist buffer */
145455  int nDoclist;                   /* Size of aDoclist[] in bytes */
145456};
145457
145458SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
145459
145460#define fts3GetVarint32(p, piVal) (                                           \
145461  (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
145462)
145463
145464/* fts3.c */
145465SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
145466SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
145467SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
145468SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
145469SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
145470SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
145471SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
145472SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
145473SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
145474SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
145475SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
145476
145477/* fts3_tokenizer.c */
145478SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
145479SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
145480SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
145481    sqlite3_tokenizer **, char **
145482);
145483SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
145484
145485/* fts3_snippet.c */
145486SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
145487SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
145488  const char *, const char *, int, int
145489);
145490SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
145491SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
145492
145493/* fts3_expr.c */
145494SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
145495  char **, int, int, int, const char *, int, Fts3Expr **, char **
145496);
145497SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
145498#ifdef SQLITE_TEST
145499SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
145500SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
145501#endif
145502
145503SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
145504  sqlite3_tokenizer_cursor **
145505);
145506
145507/* fts3_aux.c */
145508SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
145509
145510SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
145511
145512SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
145513    Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
145514SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
145515    Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
145516SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
145517SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
145518SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
145519
145520/* fts3_tokenize_vtab.c */
145521SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
145522
145523/* fts3_unicode2.c (functions generated by parsing unicode text files) */
145524#ifndef SQLITE_DISABLE_FTS3_UNICODE
145525SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
145526SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
145527SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
145528#endif
145529
145530#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
145531#endif /* _FTSINT_H */
145532
145533/************** End of fts3Int.h *********************************************/
145534/************** Continuing where we left off in fts3.c ***********************/
145535#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
145536
145537#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
145538# define SQLITE_CORE 1
145539#endif
145540
145541/* #include <assert.h> */
145542/* #include <stdlib.h> */
145543/* #include <stddef.h> */
145544/* #include <stdio.h> */
145545/* #include <string.h> */
145546/* #include <stdarg.h> */
145547
145548/* #include "fts3.h" */
145549#ifndef SQLITE_CORE
145550/* # include "sqlite3ext.h" */
145551  SQLITE_EXTENSION_INIT1
145552#endif
145553
145554static int fts3EvalNext(Fts3Cursor *pCsr);
145555static int fts3EvalStart(Fts3Cursor *pCsr);
145556static int fts3TermSegReaderCursor(
145557    Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
145558
145559#ifndef SQLITE_AMALGAMATION
145560# if defined(SQLITE_DEBUG)
145561SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
145562SQLITE_PRIVATE int sqlite3Fts3Never(int b)  { assert( !b ); return b; }
145563# endif
145564#endif
145565
145566/*
145567** Write a 64-bit variable-length integer to memory starting at p[0].
145568** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
145569** The number of bytes written is returned.
145570*/
145571SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
145572  unsigned char *q = (unsigned char *) p;
145573  sqlite_uint64 vu = v;
145574  do{
145575    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
145576    vu >>= 7;
145577  }while( vu!=0 );
145578  q[-1] &= 0x7f;  /* turn off high bit in final byte */
145579  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
145580  return (int) (q - (unsigned char *)p);
145581}
145582
145583#define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
145584  v = (v & mask1) | ( (*ptr++) << shift );                    \
145585  if( (v & mask2)==0 ){ var = v; return ret; }
145586#define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
145587  v = (*ptr++);                                               \
145588  if( (v & mask2)==0 ){ var = v; return ret; }
145589
145590/*
145591** Read a 64-bit variable-length integer from memory starting at p[0].
145592** Return the number of bytes read, or 0 on error.
145593** The value is stored in *v.
145594*/
145595SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
145596  const unsigned char *p = (const unsigned char*)pBuf;
145597  const unsigned char *pStart = p;
145598  u32 a;
145599  u64 b;
145600  int shift;
145601
145602  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
145603  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
145604  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
145605  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
145606  b = (a & 0x0FFFFFFF );
145607
145608  for(shift=28; shift<=63; shift+=7){
145609    u64 c = *p++;
145610    b += (c&0x7F) << shift;
145611    if( (c & 0x80)==0 ) break;
145612  }
145613  *v = b;
145614  return (int)(p - pStart);
145615}
145616
145617/*
145618** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
145619** 32-bit integer before it is returned.
145620*/
145621SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
145622  u32 a;
145623
145624#ifndef fts3GetVarint32
145625  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
145626#else
145627  a = (*p++);
145628  assert( a & 0x80 );
145629#endif
145630
145631  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
145632  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
145633  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
145634  a = (a & 0x0FFFFFFF );
145635  *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
145636  return 5;
145637}
145638
145639/*
145640** Return the number of bytes required to encode v as a varint
145641*/
145642SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
145643  int i = 0;
145644  do{
145645    i++;
145646    v >>= 7;
145647  }while( v!=0 );
145648  return i;
145649}
145650
145651/*
145652** Convert an SQL-style quoted string into a normal string by removing
145653** the quote characters.  The conversion is done in-place.  If the
145654** input does not begin with a quote character, then this routine
145655** is a no-op.
145656**
145657** Examples:
145658**
145659**     "abc"   becomes   abc
145660**     'xyz'   becomes   xyz
145661**     [pqr]   becomes   pqr
145662**     `mno`   becomes   mno
145663**
145664*/
145665SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
145666  char quote;                     /* Quote character (if any ) */
145667
145668  quote = z[0];
145669  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
145670    int iIn = 1;                  /* Index of next byte to read from input */
145671    int iOut = 0;                 /* Index of next byte to write to output */
145672
145673    /* If the first byte was a '[', then the close-quote character is a ']' */
145674    if( quote=='[' ) quote = ']';
145675
145676    while( z[iIn] ){
145677      if( z[iIn]==quote ){
145678        if( z[iIn+1]!=quote ) break;
145679        z[iOut++] = quote;
145680        iIn += 2;
145681      }else{
145682        z[iOut++] = z[iIn++];
145683      }
145684    }
145685    z[iOut] = '\0';
145686  }
145687}
145688
145689/*
145690** Read a single varint from the doclist at *pp and advance *pp to point
145691** to the first byte past the end of the varint.  Add the value of the varint
145692** to *pVal.
145693*/
145694static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
145695  sqlite3_int64 iVal;
145696  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
145697  *pVal += iVal;
145698}
145699
145700/*
145701** When this function is called, *pp points to the first byte following a
145702** varint that is part of a doclist (or position-list, or any other list
145703** of varints). This function moves *pp to point to the start of that varint,
145704** and sets *pVal by the varint value.
145705**
145706** Argument pStart points to the first byte of the doclist that the
145707** varint is part of.
145708*/
145709static void fts3GetReverseVarint(
145710  char **pp,
145711  char *pStart,
145712  sqlite3_int64 *pVal
145713){
145714  sqlite3_int64 iVal;
145715  char *p;
145716
145717  /* Pointer p now points at the first byte past the varint we are
145718  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
145719  ** clear on character p[-1]. */
145720  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
145721  p++;
145722  *pp = p;
145723
145724  sqlite3Fts3GetVarint(p, &iVal);
145725  *pVal = iVal;
145726}
145727
145728/*
145729** The xDisconnect() virtual table method.
145730*/
145731static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
145732  Fts3Table *p = (Fts3Table *)pVtab;
145733  int i;
145734
145735  assert( p->nPendingData==0 );
145736  assert( p->pSegments==0 );
145737
145738  /* Free any prepared statements held */
145739  sqlite3_finalize(p->pSeekStmt);
145740  for(i=0; i<SizeofArray(p->aStmt); i++){
145741    sqlite3_finalize(p->aStmt[i]);
145742  }
145743  sqlite3_free(p->zSegmentsTbl);
145744  sqlite3_free(p->zReadExprlist);
145745  sqlite3_free(p->zWriteExprlist);
145746  sqlite3_free(p->zContentTbl);
145747  sqlite3_free(p->zLanguageid);
145748
145749  /* Invoke the tokenizer destructor to free the tokenizer. */
145750  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
145751
145752  sqlite3_free(p);
145753  return SQLITE_OK;
145754}
145755
145756/*
145757** Write an error message into *pzErr
145758*/
145759SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
145760  va_list ap;
145761  sqlite3_free(*pzErr);
145762  va_start(ap, zFormat);
145763  *pzErr = sqlite3_vmprintf(zFormat, ap);
145764  va_end(ap);
145765}
145766
145767/*
145768** Construct one or more SQL statements from the format string given
145769** and then evaluate those statements. The success code is written
145770** into *pRc.
145771**
145772** If *pRc is initially non-zero then this routine is a no-op.
145773*/
145774static void fts3DbExec(
145775  int *pRc,              /* Success code */
145776  sqlite3 *db,           /* Database in which to run SQL */
145777  const char *zFormat,   /* Format string for SQL */
145778  ...                    /* Arguments to the format string */
145779){
145780  va_list ap;
145781  char *zSql;
145782  if( *pRc ) return;
145783  va_start(ap, zFormat);
145784  zSql = sqlite3_vmprintf(zFormat, ap);
145785  va_end(ap);
145786  if( zSql==0 ){
145787    *pRc = SQLITE_NOMEM;
145788  }else{
145789    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
145790    sqlite3_free(zSql);
145791  }
145792}
145793
145794/*
145795** The xDestroy() virtual table method.
145796*/
145797static int fts3DestroyMethod(sqlite3_vtab *pVtab){
145798  Fts3Table *p = (Fts3Table *)pVtab;
145799  int rc = SQLITE_OK;              /* Return code */
145800  const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
145801  sqlite3 *db = p->db;             /* Database handle */
145802
145803  /* Drop the shadow tables */
145804  if( p->zContentTbl==0 ){
145805    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
145806  }
145807  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
145808  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
145809  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
145810  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
145811
145812  /* If everything has worked, invoke fts3DisconnectMethod() to free the
145813  ** memory associated with the Fts3Table structure and return SQLITE_OK.
145814  ** Otherwise, return an SQLite error code.
145815  */
145816  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
145817}
145818
145819
145820/*
145821** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
145822** passed as the first argument. This is done as part of the xConnect()
145823** and xCreate() methods.
145824**
145825** If *pRc is non-zero when this function is called, it is a no-op.
145826** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
145827** before returning.
145828*/
145829static void fts3DeclareVtab(int *pRc, Fts3Table *p){
145830  if( *pRc==SQLITE_OK ){
145831    int i;                        /* Iterator variable */
145832    int rc;                       /* Return code */
145833    char *zSql;                   /* SQL statement passed to declare_vtab() */
145834    char *zCols;                  /* List of user defined columns */
145835    const char *zLanguageid;
145836
145837    zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
145838    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
145839
145840    /* Create a list of user columns for the virtual table */
145841    zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
145842    for(i=1; zCols && i<p->nColumn; i++){
145843      zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
145844    }
145845
145846    /* Create the whole "CREATE TABLE" statement to pass to SQLite */
145847    zSql = sqlite3_mprintf(
145848        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
145849        zCols, p->zName, zLanguageid
145850    );
145851    if( !zCols || !zSql ){
145852      rc = SQLITE_NOMEM;
145853    }else{
145854      rc = sqlite3_declare_vtab(p->db, zSql);
145855    }
145856
145857    sqlite3_free(zSql);
145858    sqlite3_free(zCols);
145859    *pRc = rc;
145860  }
145861}
145862
145863/*
145864** Create the %_stat table if it does not already exist.
145865*/
145866SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
145867  fts3DbExec(pRc, p->db,
145868      "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
145869          "(id INTEGER PRIMARY KEY, value BLOB);",
145870      p->zDb, p->zName
145871  );
145872  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
145873}
145874
145875/*
145876** Create the backing store tables (%_content, %_segments and %_segdir)
145877** required by the FTS3 table passed as the only argument. This is done
145878** as part of the vtab xCreate() method.
145879**
145880** If the p->bHasDocsize boolean is true (indicating that this is an
145881** FTS4 table, not an FTS3 table) then also create the %_docsize and
145882** %_stat tables required by FTS4.
145883*/
145884static int fts3CreateTables(Fts3Table *p){
145885  int rc = SQLITE_OK;             /* Return code */
145886  int i;                          /* Iterator variable */
145887  sqlite3 *db = p->db;            /* The database connection */
145888
145889  if( p->zContentTbl==0 ){
145890    const char *zLanguageid = p->zLanguageid;
145891    char *zContentCols;           /* Columns of %_content table */
145892
145893    /* Create a list of user columns for the content table */
145894    zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
145895    for(i=0; zContentCols && i<p->nColumn; i++){
145896      char *z = p->azColumn[i];
145897      zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
145898    }
145899    if( zLanguageid && zContentCols ){
145900      zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
145901    }
145902    if( zContentCols==0 ) rc = SQLITE_NOMEM;
145903
145904    /* Create the content table */
145905    fts3DbExec(&rc, db,
145906       "CREATE TABLE %Q.'%q_content'(%s)",
145907       p->zDb, p->zName, zContentCols
145908    );
145909    sqlite3_free(zContentCols);
145910  }
145911
145912  /* Create other tables */
145913  fts3DbExec(&rc, db,
145914      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
145915      p->zDb, p->zName
145916  );
145917  fts3DbExec(&rc, db,
145918      "CREATE TABLE %Q.'%q_segdir'("
145919        "level INTEGER,"
145920        "idx INTEGER,"
145921        "start_block INTEGER,"
145922        "leaves_end_block INTEGER,"
145923        "end_block INTEGER,"
145924        "root BLOB,"
145925        "PRIMARY KEY(level, idx)"
145926      ");",
145927      p->zDb, p->zName
145928  );
145929  if( p->bHasDocsize ){
145930    fts3DbExec(&rc, db,
145931        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
145932        p->zDb, p->zName
145933    );
145934  }
145935  assert( p->bHasStat==p->bFts4 );
145936  if( p->bHasStat ){
145937    sqlite3Fts3CreateStatTable(&rc, p);
145938  }
145939  return rc;
145940}
145941
145942/*
145943** Store the current database page-size in bytes in p->nPgsz.
145944**
145945** If *pRc is non-zero when this function is called, it is a no-op.
145946** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
145947** before returning.
145948*/
145949static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
145950  if( *pRc==SQLITE_OK ){
145951    int rc;                       /* Return code */
145952    char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
145953    sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
145954
145955    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
145956    if( !zSql ){
145957      rc = SQLITE_NOMEM;
145958    }else{
145959      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
145960      if( rc==SQLITE_OK ){
145961        sqlite3_step(pStmt);
145962        p->nPgsz = sqlite3_column_int(pStmt, 0);
145963        rc = sqlite3_finalize(pStmt);
145964      }else if( rc==SQLITE_AUTH ){
145965        p->nPgsz = 1024;
145966        rc = SQLITE_OK;
145967      }
145968    }
145969    assert( p->nPgsz>0 || rc!=SQLITE_OK );
145970    sqlite3_free(zSql);
145971    *pRc = rc;
145972  }
145973}
145974
145975/*
145976** "Special" FTS4 arguments are column specifications of the following form:
145977**
145978**   <key> = <value>
145979**
145980** There may not be whitespace surrounding the "=" character. The <value>
145981** term may be quoted, but the <key> may not.
145982*/
145983static int fts3IsSpecialColumn(
145984  const char *z,
145985  int *pnKey,
145986  char **pzValue
145987){
145988  char *zValue;
145989  const char *zCsr = z;
145990
145991  while( *zCsr!='=' ){
145992    if( *zCsr=='\0' ) return 0;
145993    zCsr++;
145994  }
145995
145996  *pnKey = (int)(zCsr-z);
145997  zValue = sqlite3_mprintf("%s", &zCsr[1]);
145998  if( zValue ){
145999    sqlite3Fts3Dequote(zValue);
146000  }
146001  *pzValue = zValue;
146002  return 1;
146003}
146004
146005/*
146006** Append the output of a printf() style formatting to an existing string.
146007*/
146008static void fts3Appendf(
146009  int *pRc,                       /* IN/OUT: Error code */
146010  char **pz,                      /* IN/OUT: Pointer to string buffer */
146011  const char *zFormat,            /* Printf format string to append */
146012  ...                             /* Arguments for printf format string */
146013){
146014  if( *pRc==SQLITE_OK ){
146015    va_list ap;
146016    char *z;
146017    va_start(ap, zFormat);
146018    z = sqlite3_vmprintf(zFormat, ap);
146019    va_end(ap);
146020    if( z && *pz ){
146021      char *z2 = sqlite3_mprintf("%s%s", *pz, z);
146022      sqlite3_free(z);
146023      z = z2;
146024    }
146025    if( z==0 ) *pRc = SQLITE_NOMEM;
146026    sqlite3_free(*pz);
146027    *pz = z;
146028  }
146029}
146030
146031/*
146032** Return a copy of input string zInput enclosed in double-quotes (") and
146033** with all double quote characters escaped. For example:
146034**
146035**     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
146036**
146037** The pointer returned points to memory obtained from sqlite3_malloc(). It
146038** is the callers responsibility to call sqlite3_free() to release this
146039** memory.
146040*/
146041static char *fts3QuoteId(char const *zInput){
146042  int nRet;
146043  char *zRet;
146044  nRet = 2 + (int)strlen(zInput)*2 + 1;
146045  zRet = sqlite3_malloc(nRet);
146046  if( zRet ){
146047    int i;
146048    char *z = zRet;
146049    *(z++) = '"';
146050    for(i=0; zInput[i]; i++){
146051      if( zInput[i]=='"' ) *(z++) = '"';
146052      *(z++) = zInput[i];
146053    }
146054    *(z++) = '"';
146055    *(z++) = '\0';
146056  }
146057  return zRet;
146058}
146059
146060/*
146061** Return a list of comma separated SQL expressions and a FROM clause that
146062** could be used in a SELECT statement such as the following:
146063**
146064**     SELECT <list of expressions> FROM %_content AS x ...
146065**
146066** to return the docid, followed by each column of text data in order
146067** from left to write. If parameter zFunc is not NULL, then instead of
146068** being returned directly each column of text data is passed to an SQL
146069** function named zFunc first. For example, if zFunc is "unzip" and the
146070** table has the three user-defined columns "a", "b", and "c", the following
146071** string is returned:
146072**
146073**     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
146074**
146075** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
146076** is the responsibility of the caller to eventually free it.
146077**
146078** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
146079** a NULL pointer is returned). Otherwise, if an OOM error is encountered
146080** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
146081** no error occurs, *pRc is left unmodified.
146082*/
146083static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
146084  char *zRet = 0;
146085  char *zFree = 0;
146086  char *zFunction;
146087  int i;
146088
146089  if( p->zContentTbl==0 ){
146090    if( !zFunc ){
146091      zFunction = "";
146092    }else{
146093      zFree = zFunction = fts3QuoteId(zFunc);
146094    }
146095    fts3Appendf(pRc, &zRet, "docid");
146096    for(i=0; i<p->nColumn; i++){
146097      fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
146098    }
146099    if( p->zLanguageid ){
146100      fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
146101    }
146102    sqlite3_free(zFree);
146103  }else{
146104    fts3Appendf(pRc, &zRet, "rowid");
146105    for(i=0; i<p->nColumn; i++){
146106      fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
146107    }
146108    if( p->zLanguageid ){
146109      fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
146110    }
146111  }
146112  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
146113      p->zDb,
146114      (p->zContentTbl ? p->zContentTbl : p->zName),
146115      (p->zContentTbl ? "" : "_content")
146116  );
146117  return zRet;
146118}
146119
146120/*
146121** Return a list of N comma separated question marks, where N is the number
146122** of columns in the %_content table (one for the docid plus one for each
146123** user-defined text column).
146124**
146125** If argument zFunc is not NULL, then all but the first question mark
146126** is preceded by zFunc and an open bracket, and followed by a closed
146127** bracket. For example, if zFunc is "zip" and the FTS3 table has three
146128** user-defined text columns, the following string is returned:
146129**
146130**     "?, zip(?), zip(?), zip(?)"
146131**
146132** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
146133** is the responsibility of the caller to eventually free it.
146134**
146135** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
146136** a NULL pointer is returned). Otherwise, if an OOM error is encountered
146137** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
146138** no error occurs, *pRc is left unmodified.
146139*/
146140static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
146141  char *zRet = 0;
146142  char *zFree = 0;
146143  char *zFunction;
146144  int i;
146145
146146  if( !zFunc ){
146147    zFunction = "";
146148  }else{
146149    zFree = zFunction = fts3QuoteId(zFunc);
146150  }
146151  fts3Appendf(pRc, &zRet, "?");
146152  for(i=0; i<p->nColumn; i++){
146153    fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
146154  }
146155  if( p->zLanguageid ){
146156    fts3Appendf(pRc, &zRet, ", ?");
146157  }
146158  sqlite3_free(zFree);
146159  return zRet;
146160}
146161
146162/*
146163** This function interprets the string at (*pp) as a non-negative integer
146164** value. It reads the integer and sets *pnOut to the value read, then
146165** sets *pp to point to the byte immediately following the last byte of
146166** the integer value.
146167**
146168** Only decimal digits ('0'..'9') may be part of an integer value.
146169**
146170** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
146171** the output value undefined. Otherwise SQLITE_OK is returned.
146172**
146173** This function is used when parsing the "prefix=" FTS4 parameter.
146174*/
146175static int fts3GobbleInt(const char **pp, int *pnOut){
146176  const int MAX_NPREFIX = 10000000;
146177  const char *p;                  /* Iterator pointer */
146178  int nInt = 0;                   /* Output value */
146179
146180  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
146181    nInt = nInt * 10 + (p[0] - '0');
146182    if( nInt>MAX_NPREFIX ){
146183      nInt = 0;
146184      break;
146185    }
146186  }
146187  if( p==*pp ) return SQLITE_ERROR;
146188  *pnOut = nInt;
146189  *pp = p;
146190  return SQLITE_OK;
146191}
146192
146193/*
146194** This function is called to allocate an array of Fts3Index structures
146195** representing the indexes maintained by the current FTS table. FTS tables
146196** always maintain the main "terms" index, but may also maintain one or
146197** more "prefix" indexes, depending on the value of the "prefix=" parameter
146198** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
146199**
146200** Argument zParam is passed the value of the "prefix=" option if one was
146201** specified, or NULL otherwise.
146202**
146203** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
146204** the allocated array. *pnIndex is set to the number of elements in the
146205** array. If an error does occur, an SQLite error code is returned.
146206**
146207** Regardless of whether or not an error is returned, it is the responsibility
146208** of the caller to call sqlite3_free() on the output array to free it.
146209*/
146210static int fts3PrefixParameter(
146211  const char *zParam,             /* ABC in prefix=ABC parameter to parse */
146212  int *pnIndex,                   /* OUT: size of *apIndex[] array */
146213  struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
146214){
146215  struct Fts3Index *aIndex;       /* Allocated array */
146216  int nIndex = 1;                 /* Number of entries in array */
146217
146218  if( zParam && zParam[0] ){
146219    const char *p;
146220    nIndex++;
146221    for(p=zParam; *p; p++){
146222      if( *p==',' ) nIndex++;
146223    }
146224  }
146225
146226  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
146227  *apIndex = aIndex;
146228  if( !aIndex ){
146229    return SQLITE_NOMEM;
146230  }
146231
146232  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
146233  if( zParam ){
146234    const char *p = zParam;
146235    int i;
146236    for(i=1; i<nIndex; i++){
146237      int nPrefix = 0;
146238      if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
146239      assert( nPrefix>=0 );
146240      if( nPrefix==0 ){
146241        nIndex--;
146242        i--;
146243      }else{
146244        aIndex[i].nPrefix = nPrefix;
146245      }
146246      p++;
146247    }
146248  }
146249
146250  *pnIndex = nIndex;
146251  return SQLITE_OK;
146252}
146253
146254/*
146255** This function is called when initializing an FTS4 table that uses the
146256** content=xxx option. It determines the number of and names of the columns
146257** of the new FTS4 table.
146258**
146259** The third argument passed to this function is the value passed to the
146260** config=xxx option (i.e. "xxx"). This function queries the database for
146261** a table of that name. If found, the output variables are populated
146262** as follows:
146263**
146264**   *pnCol:   Set to the number of columns table xxx has,
146265**
146266**   *pnStr:   Set to the total amount of space required to store a copy
146267**             of each columns name, including the nul-terminator.
146268**
146269**   *pazCol:  Set to point to an array of *pnCol strings. Each string is
146270**             the name of the corresponding column in table xxx. The array
146271**             and its contents are allocated using a single allocation. It
146272**             is the responsibility of the caller to free this allocation
146273**             by eventually passing the *pazCol value to sqlite3_free().
146274**
146275** If the table cannot be found, an error code is returned and the output
146276** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
146277** returned (and the output variables are undefined).
146278*/
146279static int fts3ContentColumns(
146280  sqlite3 *db,                    /* Database handle */
146281  const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
146282  const char *zTbl,               /* Name of content table */
146283  const char ***pazCol,           /* OUT: Malloc'd array of column names */
146284  int *pnCol,                     /* OUT: Size of array *pazCol */
146285  int *pnStr,                     /* OUT: Bytes of string content */
146286  char **pzErr                    /* OUT: error message */
146287){
146288  int rc = SQLITE_OK;             /* Return code */
146289  char *zSql;                     /* "SELECT *" statement on zTbl */
146290  sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
146291
146292  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
146293  if( !zSql ){
146294    rc = SQLITE_NOMEM;
146295  }else{
146296    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
146297    if( rc!=SQLITE_OK ){
146298      sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
146299    }
146300  }
146301  sqlite3_free(zSql);
146302
146303  if( rc==SQLITE_OK ){
146304    const char **azCol;           /* Output array */
146305    int nStr = 0;                 /* Size of all column names (incl. 0x00) */
146306    int nCol;                     /* Number of table columns */
146307    int i;                        /* Used to iterate through columns */
146308
146309    /* Loop through the returned columns. Set nStr to the number of bytes of
146310    ** space required to store a copy of each column name, including the
146311    ** nul-terminator byte.  */
146312    nCol = sqlite3_column_count(pStmt);
146313    for(i=0; i<nCol; i++){
146314      const char *zCol = sqlite3_column_name(pStmt, i);
146315      nStr += (int)strlen(zCol) + 1;
146316    }
146317
146318    /* Allocate and populate the array to return. */
146319    azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
146320    if( azCol==0 ){
146321      rc = SQLITE_NOMEM;
146322    }else{
146323      char *p = (char *)&azCol[nCol];
146324      for(i=0; i<nCol; i++){
146325        const char *zCol = sqlite3_column_name(pStmt, i);
146326        int n = (int)strlen(zCol)+1;
146327        memcpy(p, zCol, n);
146328        azCol[i] = p;
146329        p += n;
146330      }
146331    }
146332    sqlite3_finalize(pStmt);
146333
146334    /* Set the output variables. */
146335    *pnCol = nCol;
146336    *pnStr = nStr;
146337    *pazCol = azCol;
146338  }
146339
146340  return rc;
146341}
146342
146343/*
146344** This function is the implementation of both the xConnect and xCreate
146345** methods of the FTS3 virtual table.
146346**
146347** The argv[] array contains the following:
146348**
146349**   argv[0]   -> module name  ("fts3" or "fts4")
146350**   argv[1]   -> database name
146351**   argv[2]   -> table name
146352**   argv[...] -> "column name" and other module argument fields.
146353*/
146354static int fts3InitVtab(
146355  int isCreate,                   /* True for xCreate, false for xConnect */
146356  sqlite3 *db,                    /* The SQLite database connection */
146357  void *pAux,                     /* Hash table containing tokenizers */
146358  int argc,                       /* Number of elements in argv array */
146359  const char * const *argv,       /* xCreate/xConnect argument array */
146360  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
146361  char **pzErr                    /* Write any error message here */
146362){
146363  Fts3Hash *pHash = (Fts3Hash *)pAux;
146364  Fts3Table *p = 0;               /* Pointer to allocated vtab */
146365  int rc = SQLITE_OK;             /* Return code */
146366  int i;                          /* Iterator variable */
146367  int nByte;                      /* Size of allocation used for *p */
146368  int iCol;                       /* Column index */
146369  int nString = 0;                /* Bytes required to hold all column names */
146370  int nCol = 0;                   /* Number of columns in the FTS table */
146371  char *zCsr;                     /* Space for holding column names */
146372  int nDb;                        /* Bytes required to hold database name */
146373  int nName;                      /* Bytes required to hold table name */
146374  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
146375  const char **aCol;              /* Array of column names */
146376  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
146377
146378  int nIndex = 0;                 /* Size of aIndex[] array */
146379  struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
146380
146381  /* The results of parsing supported FTS4 key=value options: */
146382  int bNoDocsize = 0;             /* True to omit %_docsize table */
146383  int bDescIdx = 0;               /* True to store descending indexes */
146384  char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
146385  char *zCompress = 0;            /* compress=? parameter (or NULL) */
146386  char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
146387  char *zContent = 0;             /* content=? parameter (or NULL) */
146388  char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
146389  char **azNotindexed = 0;        /* The set of notindexed= columns */
146390  int nNotindexed = 0;            /* Size of azNotindexed[] array */
146391
146392  assert( strlen(argv[0])==4 );
146393  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
146394       || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
146395  );
146396
146397  nDb = (int)strlen(argv[1]) + 1;
146398  nName = (int)strlen(argv[2]) + 1;
146399
146400  nByte = sizeof(const char *) * (argc-2);
146401  aCol = (const char **)sqlite3_malloc(nByte);
146402  if( aCol ){
146403    memset((void*)aCol, 0, nByte);
146404    azNotindexed = (char **)sqlite3_malloc(nByte);
146405  }
146406  if( azNotindexed ){
146407    memset(azNotindexed, 0, nByte);
146408  }
146409  if( !aCol || !azNotindexed ){
146410    rc = SQLITE_NOMEM;
146411    goto fts3_init_out;
146412  }
146413
146414  /* Loop through all of the arguments passed by the user to the FTS3/4
146415  ** module (i.e. all the column names and special arguments). This loop
146416  ** does the following:
146417  **
146418  **   + Figures out the number of columns the FTSX table will have, and
146419  **     the number of bytes of space that must be allocated to store copies
146420  **     of the column names.
146421  **
146422  **   + If there is a tokenizer specification included in the arguments,
146423  **     initializes the tokenizer pTokenizer.
146424  */
146425  for(i=3; rc==SQLITE_OK && i<argc; i++){
146426    char const *z = argv[i];
146427    int nKey;
146428    char *zVal;
146429
146430    /* Check if this is a tokenizer specification */
146431    if( !pTokenizer
146432     && strlen(z)>8
146433     && 0==sqlite3_strnicmp(z, "tokenize", 8)
146434     && 0==sqlite3Fts3IsIdChar(z[8])
146435    ){
146436      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
146437    }
146438
146439    /* Check if it is an FTS4 special argument. */
146440    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
146441      struct Fts4Option {
146442        const char *zOpt;
146443        int nOpt;
146444      } aFts4Opt[] = {
146445        { "matchinfo",   9 },     /* 0 -> MATCHINFO */
146446        { "prefix",      6 },     /* 1 -> PREFIX */
146447        { "compress",    8 },     /* 2 -> COMPRESS */
146448        { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
146449        { "order",       5 },     /* 4 -> ORDER */
146450        { "content",     7 },     /* 5 -> CONTENT */
146451        { "languageid", 10 },     /* 6 -> LANGUAGEID */
146452        { "notindexed", 10 }      /* 7 -> NOTINDEXED */
146453      };
146454
146455      int iOpt;
146456      if( !zVal ){
146457        rc = SQLITE_NOMEM;
146458      }else{
146459        for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
146460          struct Fts4Option *pOp = &aFts4Opt[iOpt];
146461          if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
146462            break;
146463          }
146464        }
146465        if( iOpt==SizeofArray(aFts4Opt) ){
146466          sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
146467          rc = SQLITE_ERROR;
146468        }else{
146469          switch( iOpt ){
146470            case 0:               /* MATCHINFO */
146471              if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
146472                sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
146473                rc = SQLITE_ERROR;
146474              }
146475              bNoDocsize = 1;
146476              break;
146477
146478            case 1:               /* PREFIX */
146479              sqlite3_free(zPrefix);
146480              zPrefix = zVal;
146481              zVal = 0;
146482              break;
146483
146484            case 2:               /* COMPRESS */
146485              sqlite3_free(zCompress);
146486              zCompress = zVal;
146487              zVal = 0;
146488              break;
146489
146490            case 3:               /* UNCOMPRESS */
146491              sqlite3_free(zUncompress);
146492              zUncompress = zVal;
146493              zVal = 0;
146494              break;
146495
146496            case 4:               /* ORDER */
146497              if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
146498               && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
146499              ){
146500                sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
146501                rc = SQLITE_ERROR;
146502              }
146503              bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
146504              break;
146505
146506            case 5:              /* CONTENT */
146507              sqlite3_free(zContent);
146508              zContent = zVal;
146509              zVal = 0;
146510              break;
146511
146512            case 6:              /* LANGUAGEID */
146513              assert( iOpt==6 );
146514              sqlite3_free(zLanguageid);
146515              zLanguageid = zVal;
146516              zVal = 0;
146517              break;
146518
146519            case 7:              /* NOTINDEXED */
146520              azNotindexed[nNotindexed++] = zVal;
146521              zVal = 0;
146522              break;
146523          }
146524        }
146525        sqlite3_free(zVal);
146526      }
146527    }
146528
146529    /* Otherwise, the argument is a column name. */
146530    else {
146531      nString += (int)(strlen(z) + 1);
146532      aCol[nCol++] = z;
146533    }
146534  }
146535
146536  /* If a content=xxx option was specified, the following:
146537  **
146538  **   1. Ignore any compress= and uncompress= options.
146539  **
146540  **   2. If no column names were specified as part of the CREATE VIRTUAL
146541  **      TABLE statement, use all columns from the content table.
146542  */
146543  if( rc==SQLITE_OK && zContent ){
146544    sqlite3_free(zCompress);
146545    sqlite3_free(zUncompress);
146546    zCompress = 0;
146547    zUncompress = 0;
146548    if( nCol==0 ){
146549      sqlite3_free((void*)aCol);
146550      aCol = 0;
146551      rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
146552
146553      /* If a languageid= option was specified, remove the language id
146554      ** column from the aCol[] array. */
146555      if( rc==SQLITE_OK && zLanguageid ){
146556        int j;
146557        for(j=0; j<nCol; j++){
146558          if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
146559            int k;
146560            for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
146561            nCol--;
146562            break;
146563          }
146564        }
146565      }
146566    }
146567  }
146568  if( rc!=SQLITE_OK ) goto fts3_init_out;
146569
146570  if( nCol==0 ){
146571    assert( nString==0 );
146572    aCol[0] = "content";
146573    nString = 8;
146574    nCol = 1;
146575  }
146576
146577  if( pTokenizer==0 ){
146578    rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
146579    if( rc!=SQLITE_OK ) goto fts3_init_out;
146580  }
146581  assert( pTokenizer );
146582
146583  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
146584  if( rc==SQLITE_ERROR ){
146585    assert( zPrefix );
146586    sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
146587  }
146588  if( rc!=SQLITE_OK ) goto fts3_init_out;
146589
146590  /* Allocate and populate the Fts3Table structure. */
146591  nByte = sizeof(Fts3Table) +                  /* Fts3Table */
146592          nCol * sizeof(char *) +              /* azColumn */
146593          nIndex * sizeof(struct Fts3Index) +  /* aIndex */
146594          nCol * sizeof(u8) +                  /* abNotindexed */
146595          nName +                              /* zName */
146596          nDb +                                /* zDb */
146597          nString;                             /* Space for azColumn strings */
146598  p = (Fts3Table*)sqlite3_malloc(nByte);
146599  if( p==0 ){
146600    rc = SQLITE_NOMEM;
146601    goto fts3_init_out;
146602  }
146603  memset(p, 0, nByte);
146604  p->db = db;
146605  p->nColumn = nCol;
146606  p->nPendingData = 0;
146607  p->azColumn = (char **)&p[1];
146608  p->pTokenizer = pTokenizer;
146609  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
146610  p->bHasDocsize = (isFts4 && bNoDocsize==0);
146611  p->bHasStat = (u8)isFts4;
146612  p->bFts4 = (u8)isFts4;
146613  p->bDescIdx = (u8)bDescIdx;
146614  p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
146615  p->zContentTbl = zContent;
146616  p->zLanguageid = zLanguageid;
146617  zContent = 0;
146618  zLanguageid = 0;
146619  TESTONLY( p->inTransaction = -1 );
146620  TESTONLY( p->mxSavepoint = -1 );
146621
146622  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
146623  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
146624  p->nIndex = nIndex;
146625  for(i=0; i<nIndex; i++){
146626    fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
146627  }
146628  p->abNotindexed = (u8 *)&p->aIndex[nIndex];
146629
146630  /* Fill in the zName and zDb fields of the vtab structure. */
146631  zCsr = (char *)&p->abNotindexed[nCol];
146632  p->zName = zCsr;
146633  memcpy(zCsr, argv[2], nName);
146634  zCsr += nName;
146635  p->zDb = zCsr;
146636  memcpy(zCsr, argv[1], nDb);
146637  zCsr += nDb;
146638
146639  /* Fill in the azColumn array */
146640  for(iCol=0; iCol<nCol; iCol++){
146641    char *z;
146642    int n = 0;
146643    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
146644    if( n>0 ){
146645      memcpy(zCsr, z, n);
146646    }
146647    zCsr[n] = '\0';
146648    sqlite3Fts3Dequote(zCsr);
146649    p->azColumn[iCol] = zCsr;
146650    zCsr += n+1;
146651    assert( zCsr <= &((char *)p)[nByte] );
146652  }
146653
146654  /* Fill in the abNotindexed array */
146655  for(iCol=0; iCol<nCol; iCol++){
146656    int n = (int)strlen(p->azColumn[iCol]);
146657    for(i=0; i<nNotindexed; i++){
146658      char *zNot = azNotindexed[i];
146659      if( zNot && n==(int)strlen(zNot)
146660       && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
146661      ){
146662        p->abNotindexed[iCol] = 1;
146663        sqlite3_free(zNot);
146664        azNotindexed[i] = 0;
146665      }
146666    }
146667  }
146668  for(i=0; i<nNotindexed; i++){
146669    if( azNotindexed[i] ){
146670      sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
146671      rc = SQLITE_ERROR;
146672    }
146673  }
146674
146675  if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
146676    char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
146677    rc = SQLITE_ERROR;
146678    sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
146679  }
146680  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
146681  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
146682  if( rc!=SQLITE_OK ) goto fts3_init_out;
146683
146684  /* If this is an xCreate call, create the underlying tables in the
146685  ** database. TODO: For xConnect(), it could verify that said tables exist.
146686  */
146687  if( isCreate ){
146688    rc = fts3CreateTables(p);
146689  }
146690
146691  /* Check to see if a legacy fts3 table has been "upgraded" by the
146692  ** addition of a %_stat table so that it can use incremental merge.
146693  */
146694  if( !isFts4 && !isCreate ){
146695    p->bHasStat = 2;
146696  }
146697
146698  /* Figure out the page-size for the database. This is required in order to
146699  ** estimate the cost of loading large doclists from the database.  */
146700  fts3DatabasePageSize(&rc, p);
146701  p->nNodeSize = p->nPgsz-35;
146702
146703  /* Declare the table schema to SQLite. */
146704  fts3DeclareVtab(&rc, p);
146705
146706fts3_init_out:
146707  sqlite3_free(zPrefix);
146708  sqlite3_free(aIndex);
146709  sqlite3_free(zCompress);
146710  sqlite3_free(zUncompress);
146711  sqlite3_free(zContent);
146712  sqlite3_free(zLanguageid);
146713  for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
146714  sqlite3_free((void *)aCol);
146715  sqlite3_free((void *)azNotindexed);
146716  if( rc!=SQLITE_OK ){
146717    if( p ){
146718      fts3DisconnectMethod((sqlite3_vtab *)p);
146719    }else if( pTokenizer ){
146720      pTokenizer->pModule->xDestroy(pTokenizer);
146721    }
146722  }else{
146723    assert( p->pSegments==0 );
146724    *ppVTab = &p->base;
146725  }
146726  return rc;
146727}
146728
146729/*
146730** The xConnect() and xCreate() methods for the virtual table. All the
146731** work is done in function fts3InitVtab().
146732*/
146733static int fts3ConnectMethod(
146734  sqlite3 *db,                    /* Database connection */
146735  void *pAux,                     /* Pointer to tokenizer hash table */
146736  int argc,                       /* Number of elements in argv array */
146737  const char * const *argv,       /* xCreate/xConnect argument array */
146738  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
146739  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
146740){
146741  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
146742}
146743static int fts3CreateMethod(
146744  sqlite3 *db,                    /* Database connection */
146745  void *pAux,                     /* Pointer to tokenizer hash table */
146746  int argc,                       /* Number of elements in argv array */
146747  const char * const *argv,       /* xCreate/xConnect argument array */
146748  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
146749  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
146750){
146751  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
146752}
146753
146754/*
146755** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
146756** extension is currently being used by a version of SQLite too old to
146757** support estimatedRows. In that case this function is a no-op.
146758*/
146759static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
146760#if SQLITE_VERSION_NUMBER>=3008002
146761  if( sqlite3_libversion_number()>=3008002 ){
146762    pIdxInfo->estimatedRows = nRow;
146763  }
146764#endif
146765}
146766
146767/*
146768** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
146769** extension is currently being used by a version of SQLite too old to
146770** support index-info flags. In that case this function is a no-op.
146771*/
146772static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
146773#if SQLITE_VERSION_NUMBER>=3008012
146774  if( sqlite3_libversion_number()>=3008012 ){
146775    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
146776  }
146777#endif
146778}
146779
146780/*
146781** Implementation of the xBestIndex method for FTS3 tables. There
146782** are three possible strategies, in order of preference:
146783**
146784**   1. Direct lookup by rowid or docid.
146785**   2. Full-text search using a MATCH operator on a non-docid column.
146786**   3. Linear scan of %_content table.
146787*/
146788static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
146789  Fts3Table *p = (Fts3Table *)pVTab;
146790  int i;                          /* Iterator variable */
146791  int iCons = -1;                 /* Index of constraint to use */
146792
146793  int iLangidCons = -1;           /* Index of langid=x constraint, if present */
146794  int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
146795  int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
146796  int iIdx;
146797
146798  /* By default use a full table scan. This is an expensive option,
146799  ** so search through the constraints to see if a more efficient
146800  ** strategy is possible.
146801  */
146802  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
146803  pInfo->estimatedCost = 5000000;
146804  for(i=0; i<pInfo->nConstraint; i++){
146805    int bDocid;                 /* True if this constraint is on docid */
146806    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
146807    if( pCons->usable==0 ){
146808      if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
146809        /* There exists an unusable MATCH constraint. This means that if
146810        ** the planner does elect to use the results of this call as part
146811        ** of the overall query plan the user will see an "unable to use
146812        ** function MATCH in the requested context" error. To discourage
146813        ** this, return a very high cost here.  */
146814        pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
146815        pInfo->estimatedCost = 1e50;
146816        fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
146817        return SQLITE_OK;
146818      }
146819      continue;
146820    }
146821
146822    bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
146823
146824    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
146825    if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
146826      pInfo->idxNum = FTS3_DOCID_SEARCH;
146827      pInfo->estimatedCost = 1.0;
146828      iCons = i;
146829    }
146830
146831    /* A MATCH constraint. Use a full-text search.
146832    **
146833    ** If there is more than one MATCH constraint available, use the first
146834    ** one encountered. If there is both a MATCH constraint and a direct
146835    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
146836    ** though the rowid/docid lookup is faster than a MATCH query, selecting
146837    ** it would lead to an "unable to use function MATCH in the requested
146838    ** context" error.
146839    */
146840    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
146841     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
146842    ){
146843      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
146844      pInfo->estimatedCost = 2.0;
146845      iCons = i;
146846    }
146847
146848    /* Equality constraint on the langid column */
146849    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
146850     && pCons->iColumn==p->nColumn + 2
146851    ){
146852      iLangidCons = i;
146853    }
146854
146855    if( bDocid ){
146856      switch( pCons->op ){
146857        case SQLITE_INDEX_CONSTRAINT_GE:
146858        case SQLITE_INDEX_CONSTRAINT_GT:
146859          iDocidGe = i;
146860          break;
146861
146862        case SQLITE_INDEX_CONSTRAINT_LE:
146863        case SQLITE_INDEX_CONSTRAINT_LT:
146864          iDocidLe = i;
146865          break;
146866      }
146867    }
146868  }
146869
146870  /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
146871  if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
146872
146873  iIdx = 1;
146874  if( iCons>=0 ){
146875    pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
146876    pInfo->aConstraintUsage[iCons].omit = 1;
146877  }
146878  if( iLangidCons>=0 ){
146879    pInfo->idxNum |= FTS3_HAVE_LANGID;
146880    pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
146881  }
146882  if( iDocidGe>=0 ){
146883    pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
146884    pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
146885  }
146886  if( iDocidLe>=0 ){
146887    pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
146888    pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
146889  }
146890
146891  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
146892  ** docid) order. Both ascending and descending are possible.
146893  */
146894  if( pInfo->nOrderBy==1 ){
146895    struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
146896    if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
146897      if( pOrder->desc ){
146898        pInfo->idxStr = "DESC";
146899      }else{
146900        pInfo->idxStr = "ASC";
146901      }
146902      pInfo->orderByConsumed = 1;
146903    }
146904  }
146905
146906  assert( p->pSegments==0 );
146907  return SQLITE_OK;
146908}
146909
146910/*
146911** Implementation of xOpen method.
146912*/
146913static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
146914  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
146915
146916  UNUSED_PARAMETER(pVTab);
146917
146918  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
146919  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
146920  ** if the allocation fails, return SQLITE_NOMEM.
146921  */
146922  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
146923  if( !pCsr ){
146924    return SQLITE_NOMEM;
146925  }
146926  memset(pCsr, 0, sizeof(Fts3Cursor));
146927  return SQLITE_OK;
146928}
146929
146930/*
146931** Finalize the statement handle at pCsr->pStmt.
146932**
146933** Or, if that statement handle is one created by fts3CursorSeekStmt(),
146934** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
146935** pointer there instead of finalizing it.
146936*/
146937static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
146938  if( pCsr->bSeekStmt ){
146939    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
146940    if( p->pSeekStmt==0 ){
146941      p->pSeekStmt = pCsr->pStmt;
146942      sqlite3_reset(pCsr->pStmt);
146943      pCsr->pStmt = 0;
146944    }
146945    pCsr->bSeekStmt = 0;
146946  }
146947  sqlite3_finalize(pCsr->pStmt);
146948}
146949
146950/*
146951** Close the cursor.  For additional information see the documentation
146952** on the xClose method of the virtual table interface.
146953*/
146954static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
146955  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
146956  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
146957  fts3CursorFinalizeStmt(pCsr);
146958  sqlite3Fts3ExprFree(pCsr->pExpr);
146959  sqlite3Fts3FreeDeferredTokens(pCsr);
146960  sqlite3_free(pCsr->aDoclist);
146961  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
146962  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
146963  sqlite3_free(pCsr);
146964  return SQLITE_OK;
146965}
146966
146967/*
146968** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
146969** compose and prepare an SQL statement of the form:
146970**
146971**    "SELECT <columns> FROM %_content WHERE rowid = ?"
146972**
146973** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
146974** it. If an error occurs, return an SQLite error code.
146975*/
146976static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
146977  int rc = SQLITE_OK;
146978  if( pCsr->pStmt==0 ){
146979    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
146980    char *zSql;
146981    if( p->pSeekStmt ){
146982      pCsr->pStmt = p->pSeekStmt;
146983      p->pSeekStmt = 0;
146984    }else{
146985      zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
146986      if( !zSql ) return SQLITE_NOMEM;
146987      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
146988      sqlite3_free(zSql);
146989    }
146990    if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
146991  }
146992  return rc;
146993}
146994
146995/*
146996** Position the pCsr->pStmt statement so that it is on the row
146997** of the %_content table that contains the last match.  Return
146998** SQLITE_OK on success.
146999*/
147000static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
147001  int rc = SQLITE_OK;
147002  if( pCsr->isRequireSeek ){
147003    rc = fts3CursorSeekStmt(pCsr);
147004    if( rc==SQLITE_OK ){
147005      sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
147006      pCsr->isRequireSeek = 0;
147007      if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
147008        return SQLITE_OK;
147009      }else{
147010        rc = sqlite3_reset(pCsr->pStmt);
147011        if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
147012          /* If no row was found and no error has occurred, then the %_content
147013          ** table is missing a row that is present in the full-text index.
147014          ** The data structures are corrupt.  */
147015          rc = FTS_CORRUPT_VTAB;
147016          pCsr->isEof = 1;
147017        }
147018      }
147019    }
147020  }
147021
147022  if( rc!=SQLITE_OK && pContext ){
147023    sqlite3_result_error_code(pContext, rc);
147024  }
147025  return rc;
147026}
147027
147028/*
147029** This function is used to process a single interior node when searching
147030** a b-tree for a term or term prefix. The node data is passed to this
147031** function via the zNode/nNode parameters. The term to search for is
147032** passed in zTerm/nTerm.
147033**
147034** If piFirst is not NULL, then this function sets *piFirst to the blockid
147035** of the child node that heads the sub-tree that may contain the term.
147036**
147037** If piLast is not NULL, then *piLast is set to the right-most child node
147038** that heads a sub-tree that may contain a term for which zTerm/nTerm is
147039** a prefix.
147040**
147041** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
147042*/
147043static int fts3ScanInteriorNode(
147044  const char *zTerm,              /* Term to select leaves for */
147045  int nTerm,                      /* Size of term zTerm in bytes */
147046  const char *zNode,              /* Buffer containing segment interior node */
147047  int nNode,                      /* Size of buffer at zNode */
147048  sqlite3_int64 *piFirst,         /* OUT: Selected child node */
147049  sqlite3_int64 *piLast           /* OUT: Selected child node */
147050){
147051  int rc = SQLITE_OK;             /* Return code */
147052  const char *zCsr = zNode;       /* Cursor to iterate through node */
147053  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
147054  char *zBuffer = 0;              /* Buffer to load terms into */
147055  int nAlloc = 0;                 /* Size of allocated buffer */
147056  int isFirstTerm = 1;            /* True when processing first term on page */
147057  sqlite3_int64 iChild;           /* Block id of child node to descend to */
147058
147059  /* Skip over the 'height' varint that occurs at the start of every
147060  ** interior node. Then load the blockid of the left-child of the b-tree
147061  ** node into variable iChild.
147062  **
147063  ** Even if the data structure on disk is corrupted, this (reading two
147064  ** varints from the buffer) does not risk an overread. If zNode is a
147065  ** root node, then the buffer comes from a SELECT statement. SQLite does
147066  ** not make this guarantee explicitly, but in practice there are always
147067  ** either more than 20 bytes of allocated space following the nNode bytes of
147068  ** contents, or two zero bytes. Or, if the node is read from the %_segments
147069  ** table, then there are always 20 bytes of zeroed padding following the
147070  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
147071  */
147072  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
147073  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
147074  if( zCsr>zEnd ){
147075    return FTS_CORRUPT_VTAB;
147076  }
147077
147078  while( zCsr<zEnd && (piFirst || piLast) ){
147079    int cmp;                      /* memcmp() result */
147080    int nSuffix;                  /* Size of term suffix */
147081    int nPrefix = 0;              /* Size of term prefix */
147082    int nBuffer;                  /* Total term size */
147083
147084    /* Load the next term on the node into zBuffer. Use realloc() to expand
147085    ** the size of zBuffer if required.  */
147086    if( !isFirstTerm ){
147087      zCsr += fts3GetVarint32(zCsr, &nPrefix);
147088    }
147089    isFirstTerm = 0;
147090    zCsr += fts3GetVarint32(zCsr, &nSuffix);
147091
147092    if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
147093      rc = FTS_CORRUPT_VTAB;
147094      goto finish_scan;
147095    }
147096    if( nPrefix+nSuffix>nAlloc ){
147097      char *zNew;
147098      nAlloc = (nPrefix+nSuffix) * 2;
147099      zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
147100      if( !zNew ){
147101        rc = SQLITE_NOMEM;
147102        goto finish_scan;
147103      }
147104      zBuffer = zNew;
147105    }
147106    assert( zBuffer );
147107    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
147108    nBuffer = nPrefix + nSuffix;
147109    zCsr += nSuffix;
147110
147111    /* Compare the term we are searching for with the term just loaded from
147112    ** the interior node. If the specified term is greater than or equal
147113    ** to the term from the interior node, then all terms on the sub-tree
147114    ** headed by node iChild are smaller than zTerm. No need to search
147115    ** iChild.
147116    **
147117    ** If the interior node term is larger than the specified term, then
147118    ** the tree headed by iChild may contain the specified term.
147119    */
147120    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
147121    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
147122      *piFirst = iChild;
147123      piFirst = 0;
147124    }
147125
147126    if( piLast && cmp<0 ){
147127      *piLast = iChild;
147128      piLast = 0;
147129    }
147130
147131    iChild++;
147132  };
147133
147134  if( piFirst ) *piFirst = iChild;
147135  if( piLast ) *piLast = iChild;
147136
147137 finish_scan:
147138  sqlite3_free(zBuffer);
147139  return rc;
147140}
147141
147142
147143/*
147144** The buffer pointed to by argument zNode (size nNode bytes) contains an
147145** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
147146** contains a term. This function searches the sub-tree headed by the zNode
147147** node for the range of leaf nodes that may contain the specified term
147148** or terms for which the specified term is a prefix.
147149**
147150** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
147151** left-most leaf node in the tree that may contain the specified term.
147152** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
147153** right-most leaf node that may contain a term for which the specified
147154** term is a prefix.
147155**
147156** It is possible that the range of returned leaf nodes does not contain
147157** the specified term or any terms for which it is a prefix. However, if the
147158** segment does contain any such terms, they are stored within the identified
147159** range. Because this function only inspects interior segment nodes (and
147160** never loads leaf nodes into memory), it is not possible to be sure.
147161**
147162** If an error occurs, an error code other than SQLITE_OK is returned.
147163*/
147164static int fts3SelectLeaf(
147165  Fts3Table *p,                   /* Virtual table handle */
147166  const char *zTerm,              /* Term to select leaves for */
147167  int nTerm,                      /* Size of term zTerm in bytes */
147168  const char *zNode,              /* Buffer containing segment interior node */
147169  int nNode,                      /* Size of buffer at zNode */
147170  sqlite3_int64 *piLeaf,          /* Selected leaf node */
147171  sqlite3_int64 *piLeaf2          /* Selected leaf node */
147172){
147173  int rc = SQLITE_OK;             /* Return code */
147174  int iHeight;                    /* Height of this node in tree */
147175
147176  assert( piLeaf || piLeaf2 );
147177
147178  fts3GetVarint32(zNode, &iHeight);
147179  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
147180  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
147181
147182  if( rc==SQLITE_OK && iHeight>1 ){
147183    char *zBlob = 0;              /* Blob read from %_segments table */
147184    int nBlob = 0;                /* Size of zBlob in bytes */
147185
147186    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
147187      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
147188      if( rc==SQLITE_OK ){
147189        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
147190      }
147191      sqlite3_free(zBlob);
147192      piLeaf = 0;
147193      zBlob = 0;
147194    }
147195
147196    if( rc==SQLITE_OK ){
147197      rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
147198    }
147199    if( rc==SQLITE_OK ){
147200      rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
147201    }
147202    sqlite3_free(zBlob);
147203  }
147204
147205  return rc;
147206}
147207
147208/*
147209** This function is used to create delta-encoded serialized lists of FTS3
147210** varints. Each call to this function appends a single varint to a list.
147211*/
147212static void fts3PutDeltaVarint(
147213  char **pp,                      /* IN/OUT: Output pointer */
147214  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
147215  sqlite3_int64 iVal              /* Write this value to the list */
147216){
147217  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
147218  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
147219  *piPrev = iVal;
147220}
147221
147222/*
147223** When this function is called, *ppPoslist is assumed to point to the
147224** start of a position-list. After it returns, *ppPoslist points to the
147225** first byte after the position-list.
147226**
147227** A position list is list of positions (delta encoded) and columns for
147228** a single document record of a doclist.  So, in other words, this
147229** routine advances *ppPoslist so that it points to the next docid in
147230** the doclist, or to the first byte past the end of the doclist.
147231**
147232** If pp is not NULL, then the contents of the position list are copied
147233** to *pp. *pp is set to point to the first byte past the last byte copied
147234** before this function returns.
147235*/
147236static void fts3PoslistCopy(char **pp, char **ppPoslist){
147237  char *pEnd = *ppPoslist;
147238  char c = 0;
147239
147240  /* The end of a position list is marked by a zero encoded as an FTS3
147241  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
147242  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
147243  ** of some other, multi-byte, value.
147244  **
147245  ** The following while-loop moves pEnd to point to the first byte that is not
147246  ** immediately preceded by a byte with the 0x80 bit set. Then increments
147247  ** pEnd once more so that it points to the byte immediately following the
147248  ** last byte in the position-list.
147249  */
147250  while( *pEnd | c ){
147251    c = *pEnd++ & 0x80;
147252    testcase( c!=0 && (*pEnd)==0 );
147253  }
147254  pEnd++;  /* Advance past the POS_END terminator byte */
147255
147256  if( pp ){
147257    int n = (int)(pEnd - *ppPoslist);
147258    char *p = *pp;
147259    memcpy(p, *ppPoslist, n);
147260    p += n;
147261    *pp = p;
147262  }
147263  *ppPoslist = pEnd;
147264}
147265
147266/*
147267** When this function is called, *ppPoslist is assumed to point to the
147268** start of a column-list. After it returns, *ppPoslist points to the
147269** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
147270**
147271** A column-list is list of delta-encoded positions for a single column
147272** within a single document within a doclist.
147273**
147274** The column-list is terminated either by a POS_COLUMN varint (1) or
147275** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
147276** the POS_COLUMN or POS_END that terminates the column-list.
147277**
147278** If pp is not NULL, then the contents of the column-list are copied
147279** to *pp. *pp is set to point to the first byte past the last byte copied
147280** before this function returns.  The POS_COLUMN or POS_END terminator
147281** is not copied into *pp.
147282*/
147283static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
147284  char *pEnd = *ppPoslist;
147285  char c = 0;
147286
147287  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
147288  ** not part of a multi-byte varint.
147289  */
147290  while( 0xFE & (*pEnd | c) ){
147291    c = *pEnd++ & 0x80;
147292    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
147293  }
147294  if( pp ){
147295    int n = (int)(pEnd - *ppPoslist);
147296    char *p = *pp;
147297    memcpy(p, *ppPoslist, n);
147298    p += n;
147299    *pp = p;
147300  }
147301  *ppPoslist = pEnd;
147302}
147303
147304/*
147305** Value used to signify the end of an position-list. This is safe because
147306** it is not possible to have a document with 2^31 terms.
147307*/
147308#define POSITION_LIST_END 0x7fffffff
147309
147310/*
147311** This function is used to help parse position-lists. When this function is
147312** called, *pp may point to the start of the next varint in the position-list
147313** being parsed, or it may point to 1 byte past the end of the position-list
147314** (in which case **pp will be a terminator bytes POS_END (0) or
147315** (1)).
147316**
147317** If *pp points past the end of the current position-list, set *pi to
147318** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
147319** increment the current value of *pi by the value read, and set *pp to
147320** point to the next value before returning.
147321**
147322** Before calling this routine *pi must be initialized to the value of
147323** the previous position, or zero if we are reading the first position
147324** in the position-list.  Because positions are delta-encoded, the value
147325** of the previous position is needed in order to compute the value of
147326** the next position.
147327*/
147328static void fts3ReadNextPos(
147329  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
147330  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
147331){
147332  if( (**pp)&0xFE ){
147333    fts3GetDeltaVarint(pp, pi);
147334    *pi -= 2;
147335  }else{
147336    *pi = POSITION_LIST_END;
147337  }
147338}
147339
147340/*
147341** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
147342** the value of iCol encoded as a varint to *pp.   This will start a new
147343** column list.
147344**
147345** Set *pp to point to the byte just after the last byte written before
147346** returning (do not modify it if iCol==0). Return the total number of bytes
147347** written (0 if iCol==0).
147348*/
147349static int fts3PutColNumber(char **pp, int iCol){
147350  int n = 0;                      /* Number of bytes written */
147351  if( iCol ){
147352    char *p = *pp;                /* Output pointer */
147353    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
147354    *p = 0x01;
147355    *pp = &p[n];
147356  }
147357  return n;
147358}
147359
147360/*
147361** Compute the union of two position lists.  The output written
147362** into *pp contains all positions of both *pp1 and *pp2 in sorted
147363** order and with any duplicates removed.  All pointers are
147364** updated appropriately.   The caller is responsible for insuring
147365** that there is enough space in *pp to hold the complete output.
147366*/
147367static void fts3PoslistMerge(
147368  char **pp,                      /* Output buffer */
147369  char **pp1,                     /* Left input list */
147370  char **pp2                      /* Right input list */
147371){
147372  char *p = *pp;
147373  char *p1 = *pp1;
147374  char *p2 = *pp2;
147375
147376  while( *p1 || *p2 ){
147377    int iCol1;         /* The current column index in pp1 */
147378    int iCol2;         /* The current column index in pp2 */
147379
147380    if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
147381    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
147382    else iCol1 = 0;
147383
147384    if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
147385    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
147386    else iCol2 = 0;
147387
147388    if( iCol1==iCol2 ){
147389      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
147390      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
147391      sqlite3_int64 iPrev = 0;
147392      int n = fts3PutColNumber(&p, iCol1);
147393      p1 += n;
147394      p2 += n;
147395
147396      /* At this point, both p1 and p2 point to the start of column-lists
147397      ** for the same column (the column with index iCol1 and iCol2).
147398      ** A column-list is a list of non-negative delta-encoded varints, each
147399      ** incremented by 2 before being stored. Each list is terminated by a
147400      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
147401      ** and writes the results to buffer p. p is left pointing to the byte
147402      ** after the list written. No terminator (POS_END or POS_COLUMN) is
147403      ** written to the output.
147404      */
147405      fts3GetDeltaVarint(&p1, &i1);
147406      fts3GetDeltaVarint(&p2, &i2);
147407      do {
147408        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
147409        iPrev -= 2;
147410        if( i1==i2 ){
147411          fts3ReadNextPos(&p1, &i1);
147412          fts3ReadNextPos(&p2, &i2);
147413        }else if( i1<i2 ){
147414          fts3ReadNextPos(&p1, &i1);
147415        }else{
147416          fts3ReadNextPos(&p2, &i2);
147417        }
147418      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
147419    }else if( iCol1<iCol2 ){
147420      p1 += fts3PutColNumber(&p, iCol1);
147421      fts3ColumnlistCopy(&p, &p1);
147422    }else{
147423      p2 += fts3PutColNumber(&p, iCol2);
147424      fts3ColumnlistCopy(&p, &p2);
147425    }
147426  }
147427
147428  *p++ = POS_END;
147429  *pp = p;
147430  *pp1 = p1 + 1;
147431  *pp2 = p2 + 1;
147432}
147433
147434/*
147435** This function is used to merge two position lists into one. When it is
147436** called, *pp1 and *pp2 must both point to position lists. A position-list is
147437** the part of a doclist that follows each document id. For example, if a row
147438** contains:
147439**
147440**     'a b c'|'x y z'|'a b b a'
147441**
147442** Then the position list for this row for token 'b' would consist of:
147443**
147444**     0x02 0x01 0x02 0x03 0x03 0x00
147445**
147446** When this function returns, both *pp1 and *pp2 are left pointing to the
147447** byte following the 0x00 terminator of their respective position lists.
147448**
147449** If isSaveLeft is 0, an entry is added to the output position list for
147450** each position in *pp2 for which there exists one or more positions in
147451** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
147452** when the *pp1 token appears before the *pp2 token, but not more than nToken
147453** slots before it.
147454**
147455** e.g. nToken==1 searches for adjacent positions.
147456*/
147457static int fts3PoslistPhraseMerge(
147458  char **pp,                      /* IN/OUT: Preallocated output buffer */
147459  int nToken,                     /* Maximum difference in token positions */
147460  int isSaveLeft,                 /* Save the left position */
147461  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
147462  char **pp1,                     /* IN/OUT: Left input list */
147463  char **pp2                      /* IN/OUT: Right input list */
147464){
147465  char *p = *pp;
147466  char *p1 = *pp1;
147467  char *p2 = *pp2;
147468  int iCol1 = 0;
147469  int iCol2 = 0;
147470
147471  /* Never set both isSaveLeft and isExact for the same invocation. */
147472  assert( isSaveLeft==0 || isExact==0 );
147473
147474  assert( p!=0 && *p1!=0 && *p2!=0 );
147475  if( *p1==POS_COLUMN ){
147476    p1++;
147477    p1 += fts3GetVarint32(p1, &iCol1);
147478  }
147479  if( *p2==POS_COLUMN ){
147480    p2++;
147481    p2 += fts3GetVarint32(p2, &iCol2);
147482  }
147483
147484  while( 1 ){
147485    if( iCol1==iCol2 ){
147486      char *pSave = p;
147487      sqlite3_int64 iPrev = 0;
147488      sqlite3_int64 iPos1 = 0;
147489      sqlite3_int64 iPos2 = 0;
147490
147491      if( iCol1 ){
147492        *p++ = POS_COLUMN;
147493        p += sqlite3Fts3PutVarint(p, iCol1);
147494      }
147495
147496      assert( *p1!=POS_END && *p1!=POS_COLUMN );
147497      assert( *p2!=POS_END && *p2!=POS_COLUMN );
147498      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
147499      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
147500
147501      while( 1 ){
147502        if( iPos2==iPos1+nToken
147503         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
147504        ){
147505          sqlite3_int64 iSave;
147506          iSave = isSaveLeft ? iPos1 : iPos2;
147507          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
147508          pSave = 0;
147509          assert( p );
147510        }
147511        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
147512          if( (*p2&0xFE)==0 ) break;
147513          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
147514        }else{
147515          if( (*p1&0xFE)==0 ) break;
147516          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
147517        }
147518      }
147519
147520      if( pSave ){
147521        assert( pp && p );
147522        p = pSave;
147523      }
147524
147525      fts3ColumnlistCopy(0, &p1);
147526      fts3ColumnlistCopy(0, &p2);
147527      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
147528      if( 0==*p1 || 0==*p2 ) break;
147529
147530      p1++;
147531      p1 += fts3GetVarint32(p1, &iCol1);
147532      p2++;
147533      p2 += fts3GetVarint32(p2, &iCol2);
147534    }
147535
147536    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
147537    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
147538    ** end of the position list, or the 0x01 that precedes the next
147539    ** column-number in the position list.
147540    */
147541    else if( iCol1<iCol2 ){
147542      fts3ColumnlistCopy(0, &p1);
147543      if( 0==*p1 ) break;
147544      p1++;
147545      p1 += fts3GetVarint32(p1, &iCol1);
147546    }else{
147547      fts3ColumnlistCopy(0, &p2);
147548      if( 0==*p2 ) break;
147549      p2++;
147550      p2 += fts3GetVarint32(p2, &iCol2);
147551    }
147552  }
147553
147554  fts3PoslistCopy(0, &p2);
147555  fts3PoslistCopy(0, &p1);
147556  *pp1 = p1;
147557  *pp2 = p2;
147558  if( *pp==p ){
147559    return 0;
147560  }
147561  *p++ = 0x00;
147562  *pp = p;
147563  return 1;
147564}
147565
147566/*
147567** Merge two position-lists as required by the NEAR operator. The argument
147568** position lists correspond to the left and right phrases of an expression
147569** like:
147570**
147571**     "phrase 1" NEAR "phrase number 2"
147572**
147573** Position list *pp1 corresponds to the left-hand side of the NEAR
147574** expression and *pp2 to the right. As usual, the indexes in the position
147575** lists are the offsets of the last token in each phrase (tokens "1" and "2"
147576** in the example above).
147577**
147578** The output position list - written to *pp - is a copy of *pp2 with those
147579** entries that are not sufficiently NEAR entries in *pp1 removed.
147580*/
147581static int fts3PoslistNearMerge(
147582  char **pp,                      /* Output buffer */
147583  char *aTmp,                     /* Temporary buffer space */
147584  int nRight,                     /* Maximum difference in token positions */
147585  int nLeft,                      /* Maximum difference in token positions */
147586  char **pp1,                     /* IN/OUT: Left input list */
147587  char **pp2                      /* IN/OUT: Right input list */
147588){
147589  char *p1 = *pp1;
147590  char *p2 = *pp2;
147591
147592  char *pTmp1 = aTmp;
147593  char *pTmp2;
147594  char *aTmp2;
147595  int res = 1;
147596
147597  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
147598  aTmp2 = pTmp2 = pTmp1;
147599  *pp1 = p1;
147600  *pp2 = p2;
147601  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
147602  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
147603    fts3PoslistMerge(pp, &aTmp, &aTmp2);
147604  }else if( pTmp1!=aTmp ){
147605    fts3PoslistCopy(pp, &aTmp);
147606  }else if( pTmp2!=aTmp2 ){
147607    fts3PoslistCopy(pp, &aTmp2);
147608  }else{
147609    res = 0;
147610  }
147611
147612  return res;
147613}
147614
147615/*
147616** An instance of this function is used to merge together the (potentially
147617** large number of) doclists for each term that matches a prefix query.
147618** See function fts3TermSelectMerge() for details.
147619*/
147620typedef struct TermSelect TermSelect;
147621struct TermSelect {
147622  char *aaOutput[16];             /* Malloc'd output buffers */
147623  int anOutput[16];               /* Size each output buffer in bytes */
147624};
147625
147626/*
147627** This function is used to read a single varint from a buffer. Parameter
147628** pEnd points 1 byte past the end of the buffer. When this function is
147629** called, if *pp points to pEnd or greater, then the end of the buffer
147630** has been reached. In this case *pp is set to 0 and the function returns.
147631**
147632** If *pp does not point to or past pEnd, then a single varint is read
147633** from *pp. *pp is then set to point 1 byte past the end of the read varint.
147634**
147635** If bDescIdx is false, the value read is added to *pVal before returning.
147636** If it is true, the value read is subtracted from *pVal before this
147637** function returns.
147638*/
147639static void fts3GetDeltaVarint3(
147640  char **pp,                      /* IN/OUT: Point to read varint from */
147641  char *pEnd,                     /* End of buffer */
147642  int bDescIdx,                   /* True if docids are descending */
147643  sqlite3_int64 *pVal             /* IN/OUT: Integer value */
147644){
147645  if( *pp>=pEnd ){
147646    *pp = 0;
147647  }else{
147648    sqlite3_int64 iVal;
147649    *pp += sqlite3Fts3GetVarint(*pp, &iVal);
147650    if( bDescIdx ){
147651      *pVal -= iVal;
147652    }else{
147653      *pVal += iVal;
147654    }
147655  }
147656}
147657
147658/*
147659** This function is used to write a single varint to a buffer. The varint
147660** is written to *pp. Before returning, *pp is set to point 1 byte past the
147661** end of the value written.
147662**
147663** If *pbFirst is zero when this function is called, the value written to
147664** the buffer is that of parameter iVal.
147665**
147666** If *pbFirst is non-zero when this function is called, then the value
147667** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
147668** (if bDescIdx is non-zero).
147669**
147670** Before returning, this function always sets *pbFirst to 1 and *piPrev
147671** to the value of parameter iVal.
147672*/
147673static void fts3PutDeltaVarint3(
147674  char **pp,                      /* IN/OUT: Output pointer */
147675  int bDescIdx,                   /* True for descending docids */
147676  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
147677  int *pbFirst,                   /* IN/OUT: True after first int written */
147678  sqlite3_int64 iVal              /* Write this value to the list */
147679){
147680  sqlite3_int64 iWrite;
147681  if( bDescIdx==0 || *pbFirst==0 ){
147682    iWrite = iVal - *piPrev;
147683  }else{
147684    iWrite = *piPrev - iVal;
147685  }
147686  assert( *pbFirst || *piPrev==0 );
147687  assert( *pbFirst==0 || iWrite>0 );
147688  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
147689  *piPrev = iVal;
147690  *pbFirst = 1;
147691}
147692
147693
147694/*
147695** This macro is used by various functions that merge doclists. The two
147696** arguments are 64-bit docid values. If the value of the stack variable
147697** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
147698** Otherwise, (i2-i1).
147699**
147700** Using this makes it easier to write code that can merge doclists that are
147701** sorted in either ascending or descending order.
147702*/
147703#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
147704
147705/*
147706** This function does an "OR" merge of two doclists (output contains all
147707** positions contained in either argument doclist). If the docids in the
147708** input doclists are sorted in ascending order, parameter bDescDoclist
147709** should be false. If they are sorted in ascending order, it should be
147710** passed a non-zero value.
147711**
147712** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
147713** containing the output doclist and SQLITE_OK is returned. In this case
147714** *pnOut is set to the number of bytes in the output doclist.
147715**
147716** If an error occurs, an SQLite error code is returned. The output values
147717** are undefined in this case.
147718*/
147719static int fts3DoclistOrMerge(
147720  int bDescDoclist,               /* True if arguments are desc */
147721  char *a1, int n1,               /* First doclist */
147722  char *a2, int n2,               /* Second doclist */
147723  char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
147724){
147725  sqlite3_int64 i1 = 0;
147726  sqlite3_int64 i2 = 0;
147727  sqlite3_int64 iPrev = 0;
147728  char *pEnd1 = &a1[n1];
147729  char *pEnd2 = &a2[n2];
147730  char *p1 = a1;
147731  char *p2 = a2;
147732  char *p;
147733  char *aOut;
147734  int bFirstOut = 0;
147735
147736  *paOut = 0;
147737  *pnOut = 0;
147738
147739  /* Allocate space for the output. Both the input and output doclists
147740  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
147741  ** then the first docid in each list is simply encoded as a varint. For
147742  ** each subsequent docid, the varint stored is the difference between the
147743  ** current and previous docid (a positive number - since the list is in
147744  ** ascending order).
147745  **
147746  ** The first docid written to the output is therefore encoded using the
147747  ** same number of bytes as it is in whichever of the input lists it is
147748  ** read from. And each subsequent docid read from the same input list
147749  ** consumes either the same or less bytes as it did in the input (since
147750  ** the difference between it and the previous value in the output must
147751  ** be a positive value less than or equal to the delta value read from
147752  ** the input list). The same argument applies to all but the first docid
147753  ** read from the 'other' list. And to the contents of all position lists
147754  ** that will be copied and merged from the input to the output.
147755  **
147756  ** However, if the first docid copied to the output is a negative number,
147757  ** then the encoding of the first docid from the 'other' input list may
147758  ** be larger in the output than it was in the input (since the delta value
147759  ** may be a larger positive integer than the actual docid).
147760  **
147761  ** The space required to store the output is therefore the sum of the
147762  ** sizes of the two inputs, plus enough space for exactly one of the input
147763  ** docids to grow.
147764  **
147765  ** A symetric argument may be made if the doclists are in descending
147766  ** order.
147767  */
147768  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
147769  if( !aOut ) return SQLITE_NOMEM;
147770
147771  p = aOut;
147772  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
147773  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
147774  while( p1 || p2 ){
147775    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
147776
147777    if( p2 && p1 && iDiff==0 ){
147778      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
147779      fts3PoslistMerge(&p, &p1, &p2);
147780      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
147781      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
147782    }else if( !p2 || (p1 && iDiff<0) ){
147783      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
147784      fts3PoslistCopy(&p, &p1);
147785      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
147786    }else{
147787      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
147788      fts3PoslistCopy(&p, &p2);
147789      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
147790    }
147791  }
147792
147793  *paOut = aOut;
147794  *pnOut = (int)(p-aOut);
147795  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
147796  return SQLITE_OK;
147797}
147798
147799/*
147800** This function does a "phrase" merge of two doclists. In a phrase merge,
147801** the output contains a copy of each position from the right-hand input
147802** doclist for which there is a position in the left-hand input doclist
147803** exactly nDist tokens before it.
147804**
147805** If the docids in the input doclists are sorted in ascending order,
147806** parameter bDescDoclist should be false. If they are sorted in ascending
147807** order, it should be passed a non-zero value.
147808**
147809** The right-hand input doclist is overwritten by this function.
147810*/
147811static int fts3DoclistPhraseMerge(
147812  int bDescDoclist,               /* True if arguments are desc */
147813  int nDist,                      /* Distance from left to right (1=adjacent) */
147814  char *aLeft, int nLeft,         /* Left doclist */
147815  char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */
147816){
147817  sqlite3_int64 i1 = 0;
147818  sqlite3_int64 i2 = 0;
147819  sqlite3_int64 iPrev = 0;
147820  char *aRight = *paRight;
147821  char *pEnd1 = &aLeft[nLeft];
147822  char *pEnd2 = &aRight[*pnRight];
147823  char *p1 = aLeft;
147824  char *p2 = aRight;
147825  char *p;
147826  int bFirstOut = 0;
147827  char *aOut;
147828
147829  assert( nDist>0 );
147830  if( bDescDoclist ){
147831    aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
147832    if( aOut==0 ) return SQLITE_NOMEM;
147833  }else{
147834    aOut = aRight;
147835  }
147836  p = aOut;
147837
147838  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
147839  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
147840
147841  while( p1 && p2 ){
147842    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
147843    if( iDiff==0 ){
147844      char *pSave = p;
147845      sqlite3_int64 iPrevSave = iPrev;
147846      int bFirstOutSave = bFirstOut;
147847
147848      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
147849      if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
147850        p = pSave;
147851        iPrev = iPrevSave;
147852        bFirstOut = bFirstOutSave;
147853      }
147854      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
147855      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
147856    }else if( iDiff<0 ){
147857      fts3PoslistCopy(0, &p1);
147858      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
147859    }else{
147860      fts3PoslistCopy(0, &p2);
147861      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
147862    }
147863  }
147864
147865  *pnRight = (int)(p - aOut);
147866  if( bDescDoclist ){
147867    sqlite3_free(aRight);
147868    *paRight = aOut;
147869  }
147870
147871  return SQLITE_OK;
147872}
147873
147874/*
147875** Argument pList points to a position list nList bytes in size. This
147876** function checks to see if the position list contains any entries for
147877** a token in position 0 (of any column). If so, it writes argument iDelta
147878** to the output buffer pOut, followed by a position list consisting only
147879** of the entries from pList at position 0, and terminated by an 0x00 byte.
147880** The value returned is the number of bytes written to pOut (if any).
147881*/
147882SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
147883  sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
147884  char *pList,                    /* Position list (no 0x00 term) */
147885  int nList,                      /* Size of pList in bytes */
147886  char *pOut                      /* Write output here */
147887){
147888  int nOut = 0;
147889  int bWritten = 0;               /* True once iDelta has been written */
147890  char *p = pList;
147891  char *pEnd = &pList[nList];
147892
147893  if( *p!=0x01 ){
147894    if( *p==0x02 ){
147895      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
147896      pOut[nOut++] = 0x02;
147897      bWritten = 1;
147898    }
147899    fts3ColumnlistCopy(0, &p);
147900  }
147901
147902  while( p<pEnd && *p==0x01 ){
147903    sqlite3_int64 iCol;
147904    p++;
147905    p += sqlite3Fts3GetVarint(p, &iCol);
147906    if( *p==0x02 ){
147907      if( bWritten==0 ){
147908        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
147909        bWritten = 1;
147910      }
147911      pOut[nOut++] = 0x01;
147912      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
147913      pOut[nOut++] = 0x02;
147914    }
147915    fts3ColumnlistCopy(0, &p);
147916  }
147917  if( bWritten ){
147918    pOut[nOut++] = 0x00;
147919  }
147920
147921  return nOut;
147922}
147923
147924
147925/*
147926** Merge all doclists in the TermSelect.aaOutput[] array into a single
147927** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
147928** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
147929**
147930** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
147931** the responsibility of the caller to free any doclists left in the
147932** TermSelect.aaOutput[] array.
147933*/
147934static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
147935  char *aOut = 0;
147936  int nOut = 0;
147937  int i;
147938
147939  /* Loop through the doclists in the aaOutput[] array. Merge them all
147940  ** into a single doclist.
147941  */
147942  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
147943    if( pTS->aaOutput[i] ){
147944      if( !aOut ){
147945        aOut = pTS->aaOutput[i];
147946        nOut = pTS->anOutput[i];
147947        pTS->aaOutput[i] = 0;
147948      }else{
147949        int nNew;
147950        char *aNew;
147951
147952        int rc = fts3DoclistOrMerge(p->bDescIdx,
147953            pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
147954        );
147955        if( rc!=SQLITE_OK ){
147956          sqlite3_free(aOut);
147957          return rc;
147958        }
147959
147960        sqlite3_free(pTS->aaOutput[i]);
147961        sqlite3_free(aOut);
147962        pTS->aaOutput[i] = 0;
147963        aOut = aNew;
147964        nOut = nNew;
147965      }
147966    }
147967  }
147968
147969  pTS->aaOutput[0] = aOut;
147970  pTS->anOutput[0] = nOut;
147971  return SQLITE_OK;
147972}
147973
147974/*
147975** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
147976** as the first argument. The merge is an "OR" merge (see function
147977** fts3DoclistOrMerge() for details).
147978**
147979** This function is called with the doclist for each term that matches
147980** a queried prefix. It merges all these doclists into one, the doclist
147981** for the specified prefix. Since there can be a very large number of
147982** doclists to merge, the merging is done pair-wise using the TermSelect
147983** object.
147984**
147985** This function returns SQLITE_OK if the merge is successful, or an
147986** SQLite error code (SQLITE_NOMEM) if an error occurs.
147987*/
147988static int fts3TermSelectMerge(
147989  Fts3Table *p,                   /* FTS table handle */
147990  TermSelect *pTS,                /* TermSelect object to merge into */
147991  char *aDoclist,                 /* Pointer to doclist */
147992  int nDoclist                    /* Size of aDoclist in bytes */
147993){
147994  if( pTS->aaOutput[0]==0 ){
147995    /* If this is the first term selected, copy the doclist to the output
147996    ** buffer using memcpy().
147997    **
147998    ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
147999    ** allocation. This is so as to ensure that the buffer is big enough
148000    ** to hold the current doclist AND'd with any other doclist. If the
148001    ** doclists are stored in order=ASC order, this padding would not be
148002    ** required (since the size of [doclistA AND doclistB] is always less
148003    ** than or equal to the size of [doclistA] in that case). But this is
148004    ** not true for order=DESC. For example, a doclist containing (1, -1)
148005    ** may be smaller than (-1), as in the first example the -1 may be stored
148006    ** as a single-byte delta, whereas in the second it must be stored as a
148007    ** FTS3_VARINT_MAX byte varint.
148008    **
148009    ** Similar padding is added in the fts3DoclistOrMerge() function.
148010    */
148011    pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
148012    pTS->anOutput[0] = nDoclist;
148013    if( pTS->aaOutput[0] ){
148014      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
148015    }else{
148016      return SQLITE_NOMEM;
148017    }
148018  }else{
148019    char *aMerge = aDoclist;
148020    int nMerge = nDoclist;
148021    int iOut;
148022
148023    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
148024      if( pTS->aaOutput[iOut]==0 ){
148025        assert( iOut>0 );
148026        pTS->aaOutput[iOut] = aMerge;
148027        pTS->anOutput[iOut] = nMerge;
148028        break;
148029      }else{
148030        char *aNew;
148031        int nNew;
148032
148033        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
148034            pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
148035        );
148036        if( rc!=SQLITE_OK ){
148037          if( aMerge!=aDoclist ) sqlite3_free(aMerge);
148038          return rc;
148039        }
148040
148041        if( aMerge!=aDoclist ) sqlite3_free(aMerge);
148042        sqlite3_free(pTS->aaOutput[iOut]);
148043        pTS->aaOutput[iOut] = 0;
148044
148045        aMerge = aNew;
148046        nMerge = nNew;
148047        if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
148048          pTS->aaOutput[iOut] = aMerge;
148049          pTS->anOutput[iOut] = nMerge;
148050        }
148051      }
148052    }
148053  }
148054  return SQLITE_OK;
148055}
148056
148057/*
148058** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
148059*/
148060static int fts3SegReaderCursorAppend(
148061  Fts3MultiSegReader *pCsr,
148062  Fts3SegReader *pNew
148063){
148064  if( (pCsr->nSegment%16)==0 ){
148065    Fts3SegReader **apNew;
148066    int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
148067    apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
148068    if( !apNew ){
148069      sqlite3Fts3SegReaderFree(pNew);
148070      return SQLITE_NOMEM;
148071    }
148072    pCsr->apSegment = apNew;
148073  }
148074  pCsr->apSegment[pCsr->nSegment++] = pNew;
148075  return SQLITE_OK;
148076}
148077
148078/*
148079** Add seg-reader objects to the Fts3MultiSegReader object passed as the
148080** 8th argument.
148081**
148082** This function returns SQLITE_OK if successful, or an SQLite error code
148083** otherwise.
148084*/
148085static int fts3SegReaderCursor(
148086  Fts3Table *p,                   /* FTS3 table handle */
148087  int iLangid,                    /* Language id */
148088  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
148089  int iLevel,                     /* Level of segments to scan */
148090  const char *zTerm,              /* Term to query for */
148091  int nTerm,                      /* Size of zTerm in bytes */
148092  int isPrefix,                   /* True for a prefix search */
148093  int isScan,                     /* True to scan from zTerm to EOF */
148094  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
148095){
148096  int rc = SQLITE_OK;             /* Error code */
148097  sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
148098  int rc2;                        /* Result of sqlite3_reset() */
148099
148100  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
148101  ** for the pending-terms. If this is a scan, then this call must be being
148102  ** made by an fts4aux module, not an FTS table. In this case calling
148103  ** Fts3SegReaderPending might segfault, as the data structures used by
148104  ** fts4aux are not completely populated. So it's easiest to filter these
148105  ** calls out here.  */
148106  if( iLevel<0 && p->aIndex ){
148107    Fts3SegReader *pSeg = 0;
148108    rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
148109    if( rc==SQLITE_OK && pSeg ){
148110      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
148111    }
148112  }
148113
148114  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
148115    if( rc==SQLITE_OK ){
148116      rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
148117    }
148118
148119    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
148120      Fts3SegReader *pSeg = 0;
148121
148122      /* Read the values returned by the SELECT into local variables. */
148123      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
148124      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
148125      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
148126      int nRoot = sqlite3_column_bytes(pStmt, 4);
148127      char const *zRoot = sqlite3_column_blob(pStmt, 4);
148128
148129      /* If zTerm is not NULL, and this segment is not stored entirely on its
148130      ** root node, the range of leaves scanned can be reduced. Do this. */
148131      if( iStartBlock && zTerm ){
148132        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
148133        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
148134        if( rc!=SQLITE_OK ) goto finished;
148135        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
148136      }
148137
148138      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
148139          (isPrefix==0 && isScan==0),
148140          iStartBlock, iLeavesEndBlock,
148141          iEndBlock, zRoot, nRoot, &pSeg
148142      );
148143      if( rc!=SQLITE_OK ) goto finished;
148144      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
148145    }
148146  }
148147
148148 finished:
148149  rc2 = sqlite3_reset(pStmt);
148150  if( rc==SQLITE_DONE ) rc = rc2;
148151
148152  return rc;
148153}
148154
148155/*
148156** Set up a cursor object for iterating through a full-text index or a
148157** single level therein.
148158*/
148159SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
148160  Fts3Table *p,                   /* FTS3 table handle */
148161  int iLangid,                    /* Language-id to search */
148162  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
148163  int iLevel,                     /* Level of segments to scan */
148164  const char *zTerm,              /* Term to query for */
148165  int nTerm,                      /* Size of zTerm in bytes */
148166  int isPrefix,                   /* True for a prefix search */
148167  int isScan,                     /* True to scan from zTerm to EOF */
148168  Fts3MultiSegReader *pCsr       /* Cursor object to populate */
148169){
148170  assert( iIndex>=0 && iIndex<p->nIndex );
148171  assert( iLevel==FTS3_SEGCURSOR_ALL
148172      ||  iLevel==FTS3_SEGCURSOR_PENDING
148173      ||  iLevel>=0
148174  );
148175  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
148176  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
148177  assert( isPrefix==0 || isScan==0 );
148178
148179  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
148180  return fts3SegReaderCursor(
148181      p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
148182  );
148183}
148184
148185/*
148186** In addition to its current configuration, have the Fts3MultiSegReader
148187** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
148188**
148189** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
148190*/
148191static int fts3SegReaderCursorAddZero(
148192  Fts3Table *p,                   /* FTS virtual table handle */
148193  int iLangid,
148194  const char *zTerm,              /* Term to scan doclist of */
148195  int nTerm,                      /* Number of bytes in zTerm */
148196  Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
148197){
148198  return fts3SegReaderCursor(p,
148199      iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
148200  );
148201}
148202
148203/*
148204** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
148205** if isPrefix is true, to scan the doclist for all terms for which
148206** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
148207** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
148208** an SQLite error code.
148209**
148210** It is the responsibility of the caller to free this object by eventually
148211** passing it to fts3SegReaderCursorFree()
148212**
148213** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
148214** Output parameter *ppSegcsr is set to 0 if an error occurs.
148215*/
148216static int fts3TermSegReaderCursor(
148217  Fts3Cursor *pCsr,               /* Virtual table cursor handle */
148218  const char *zTerm,              /* Term to query for */
148219  int nTerm,                      /* Size of zTerm in bytes */
148220  int isPrefix,                   /* True for a prefix search */
148221  Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
148222){
148223  Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
148224  int rc = SQLITE_NOMEM;          /* Return code */
148225
148226  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
148227  if( pSegcsr ){
148228    int i;
148229    int bFound = 0;               /* True once an index has been found */
148230    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
148231
148232    if( isPrefix ){
148233      for(i=1; bFound==0 && i<p->nIndex; i++){
148234        if( p->aIndex[i].nPrefix==nTerm ){
148235          bFound = 1;
148236          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
148237              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
148238          );
148239          pSegcsr->bLookup = 1;
148240        }
148241      }
148242
148243      for(i=1; bFound==0 && i<p->nIndex; i++){
148244        if( p->aIndex[i].nPrefix==nTerm+1 ){
148245          bFound = 1;
148246          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
148247              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
148248          );
148249          if( rc==SQLITE_OK ){
148250            rc = fts3SegReaderCursorAddZero(
148251                p, pCsr->iLangid, zTerm, nTerm, pSegcsr
148252            );
148253          }
148254        }
148255      }
148256    }
148257
148258    if( bFound==0 ){
148259      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
148260          0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
148261      );
148262      pSegcsr->bLookup = !isPrefix;
148263    }
148264  }
148265
148266  *ppSegcsr = pSegcsr;
148267  return rc;
148268}
148269
148270/*
148271** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
148272*/
148273static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
148274  sqlite3Fts3SegReaderFinish(pSegcsr);
148275  sqlite3_free(pSegcsr);
148276}
148277
148278/*
148279** This function retrieves the doclist for the specified term (or term
148280** prefix) from the database.
148281*/
148282static int fts3TermSelect(
148283  Fts3Table *p,                   /* Virtual table handle */
148284  Fts3PhraseToken *pTok,          /* Token to query for */
148285  int iColumn,                    /* Column to query (or -ve for all columns) */
148286  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
148287  char **ppOut                    /* OUT: Malloced result buffer */
148288){
148289  int rc;                         /* Return code */
148290  Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
148291  TermSelect tsc;                 /* Object for pair-wise doclist merging */
148292  Fts3SegFilter filter;           /* Segment term filter configuration */
148293
148294  pSegcsr = pTok->pSegcsr;
148295  memset(&tsc, 0, sizeof(TermSelect));
148296
148297  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
148298        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
148299        | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
148300        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
148301  filter.iCol = iColumn;
148302  filter.zTerm = pTok->z;
148303  filter.nTerm = pTok->n;
148304
148305  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
148306  while( SQLITE_OK==rc
148307      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
148308  ){
148309    rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
148310  }
148311
148312  if( rc==SQLITE_OK ){
148313    rc = fts3TermSelectFinishMerge(p, &tsc);
148314  }
148315  if( rc==SQLITE_OK ){
148316    *ppOut = tsc.aaOutput[0];
148317    *pnOut = tsc.anOutput[0];
148318  }else{
148319    int i;
148320    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
148321      sqlite3_free(tsc.aaOutput[i]);
148322    }
148323  }
148324
148325  fts3SegReaderCursorFree(pSegcsr);
148326  pTok->pSegcsr = 0;
148327  return rc;
148328}
148329
148330/*
148331** This function counts the total number of docids in the doclist stored
148332** in buffer aList[], size nList bytes.
148333**
148334** If the isPoslist argument is true, then it is assumed that the doclist
148335** contains a position-list following each docid. Otherwise, it is assumed
148336** that the doclist is simply a list of docids stored as delta encoded
148337** varints.
148338*/
148339static int fts3DoclistCountDocids(char *aList, int nList){
148340  int nDoc = 0;                   /* Return value */
148341  if( aList ){
148342    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
148343    char *p = aList;              /* Cursor */
148344    while( p<aEnd ){
148345      nDoc++;
148346      while( (*p++)&0x80 );     /* Skip docid varint */
148347      fts3PoslistCopy(0, &p);   /* Skip over position list */
148348    }
148349  }
148350
148351  return nDoc;
148352}
148353
148354/*
148355** Advance the cursor to the next row in the %_content table that
148356** matches the search criteria.  For a MATCH search, this will be
148357** the next row that matches. For a full-table scan, this will be
148358** simply the next row in the %_content table.  For a docid lookup,
148359** this routine simply sets the EOF flag.
148360**
148361** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
148362** even if we reach end-of-file.  The fts3EofMethod() will be called
148363** subsequently to determine whether or not an EOF was hit.
148364*/
148365static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
148366  int rc;
148367  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
148368  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
148369    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
148370      pCsr->isEof = 1;
148371      rc = sqlite3_reset(pCsr->pStmt);
148372    }else{
148373      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
148374      rc = SQLITE_OK;
148375    }
148376  }else{
148377    rc = fts3EvalNext((Fts3Cursor *)pCursor);
148378  }
148379  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
148380  return rc;
148381}
148382
148383/*
148384** The following are copied from sqliteInt.h.
148385**
148386** Constants for the largest and smallest possible 64-bit signed integers.
148387** These macros are designed to work correctly on both 32-bit and 64-bit
148388** compilers.
148389*/
148390#ifndef SQLITE_AMALGAMATION
148391# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
148392# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
148393#endif
148394
148395/*
148396** If the numeric type of argument pVal is "integer", then return it
148397** converted to a 64-bit signed integer. Otherwise, return a copy of
148398** the second parameter, iDefault.
148399*/
148400static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
148401  if( pVal ){
148402    int eType = sqlite3_value_numeric_type(pVal);
148403    if( eType==SQLITE_INTEGER ){
148404      return sqlite3_value_int64(pVal);
148405    }
148406  }
148407  return iDefault;
148408}
148409
148410/*
148411** This is the xFilter interface for the virtual table.  See
148412** the virtual table xFilter method documentation for additional
148413** information.
148414**
148415** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
148416** the %_content table.
148417**
148418** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
148419** in the %_content table.
148420**
148421** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
148422** column on the left-hand side of the MATCH operator is column
148423** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
148424** side of the MATCH operator.
148425*/
148426static int fts3FilterMethod(
148427  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
148428  int idxNum,                     /* Strategy index */
148429  const char *idxStr,             /* Unused */
148430  int nVal,                       /* Number of elements in apVal */
148431  sqlite3_value **apVal           /* Arguments for the indexing scheme */
148432){
148433  int rc = SQLITE_OK;
148434  char *zSql;                     /* SQL statement used to access %_content */
148435  int eSearch;
148436  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
148437  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
148438
148439  sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
148440  sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
148441  sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
148442  sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
148443  int iIdx;
148444
148445  UNUSED_PARAMETER(idxStr);
148446  UNUSED_PARAMETER(nVal);
148447
148448  eSearch = (idxNum & 0x0000FFFF);
148449  assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
148450  assert( p->pSegments==0 );
148451
148452  /* Collect arguments into local variables */
148453  iIdx = 0;
148454  if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
148455  if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
148456  if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
148457  if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
148458  assert( iIdx==nVal );
148459
148460  /* In case the cursor has been used before, clear it now. */
148461  fts3CursorFinalizeStmt(pCsr);
148462  sqlite3_free(pCsr->aDoclist);
148463  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
148464  sqlite3Fts3ExprFree(pCsr->pExpr);
148465  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
148466
148467  /* Set the lower and upper bounds on docids to return */
148468  pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
148469  pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
148470
148471  if( idxStr ){
148472    pCsr->bDesc = (idxStr[0]=='D');
148473  }else{
148474    pCsr->bDesc = p->bDescIdx;
148475  }
148476  pCsr->eSearch = (i16)eSearch;
148477
148478  if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
148479    int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
148480    const char *zQuery = (const char *)sqlite3_value_text(pCons);
148481
148482    if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
148483      return SQLITE_NOMEM;
148484    }
148485
148486    pCsr->iLangid = 0;
148487    if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
148488
148489    assert( p->base.zErrMsg==0 );
148490    rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
148491        p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
148492        &p->base.zErrMsg
148493    );
148494    if( rc!=SQLITE_OK ){
148495      return rc;
148496    }
148497
148498    rc = fts3EvalStart(pCsr);
148499    sqlite3Fts3SegmentsClose(p);
148500    if( rc!=SQLITE_OK ) return rc;
148501    pCsr->pNextId = pCsr->aDoclist;
148502    pCsr->iPrevId = 0;
148503  }
148504
148505  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
148506  ** statement loops through all rows of the %_content table. For a
148507  ** full-text query or docid lookup, the statement retrieves a single
148508  ** row by docid.
148509  */
148510  if( eSearch==FTS3_FULLSCAN_SEARCH ){
148511    if( pDocidGe || pDocidLe ){
148512      zSql = sqlite3_mprintf(
148513          "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
148514          p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
148515          (pCsr->bDesc ? "DESC" : "ASC")
148516      );
148517    }else{
148518      zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
148519          p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
148520      );
148521    }
148522    if( zSql ){
148523      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
148524      sqlite3_free(zSql);
148525    }else{
148526      rc = SQLITE_NOMEM;
148527    }
148528  }else if( eSearch==FTS3_DOCID_SEARCH ){
148529    rc = fts3CursorSeekStmt(pCsr);
148530    if( rc==SQLITE_OK ){
148531      rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
148532    }
148533  }
148534  if( rc!=SQLITE_OK ) return rc;
148535
148536  return fts3NextMethod(pCursor);
148537}
148538
148539/*
148540** This is the xEof method of the virtual table. SQLite calls this
148541** routine to find out if it has reached the end of a result set.
148542*/
148543static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
148544  return ((Fts3Cursor *)pCursor)->isEof;
148545}
148546
148547/*
148548** This is the xRowid method. The SQLite core calls this routine to
148549** retrieve the rowid for the current row of the result set. fts3
148550** exposes %_content.docid as the rowid for the virtual table. The
148551** rowid should be written to *pRowid.
148552*/
148553static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
148554  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
148555  *pRowid = pCsr->iPrevId;
148556  return SQLITE_OK;
148557}
148558
148559/*
148560** This is the xColumn method, called by SQLite to request a value from
148561** the row that the supplied cursor currently points to.
148562**
148563** If:
148564**
148565**   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
148566**   (iCol == p->nColumn)   -> Magic column with the same name as the table.
148567**   (iCol == p->nColumn+1) -> Docid column
148568**   (iCol == p->nColumn+2) -> Langid column
148569*/
148570static int fts3ColumnMethod(
148571  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
148572  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
148573  int iCol                        /* Index of column to read value from */
148574){
148575  int rc = SQLITE_OK;             /* Return Code */
148576  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
148577  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
148578
148579  /* The column value supplied by SQLite must be in range. */
148580  assert( iCol>=0 && iCol<=p->nColumn+2 );
148581
148582  if( iCol==p->nColumn+1 ){
148583    /* This call is a request for the "docid" column. Since "docid" is an
148584    ** alias for "rowid", use the xRowid() method to obtain the value.
148585    */
148586    sqlite3_result_int64(pCtx, pCsr->iPrevId);
148587  }else if( iCol==p->nColumn ){
148588    /* The extra column whose name is the same as the table.
148589    ** Return a blob which is a pointer to the cursor.  */
148590    sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
148591  }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
148592    sqlite3_result_int64(pCtx, pCsr->iLangid);
148593  }else{
148594    /* The requested column is either a user column (one that contains
148595    ** indexed data), or the language-id column.  */
148596    rc = fts3CursorSeek(0, pCsr);
148597
148598    if( rc==SQLITE_OK ){
148599      if( iCol==p->nColumn+2 ){
148600        int iLangid = 0;
148601        if( p->zLanguageid ){
148602          iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
148603        }
148604        sqlite3_result_int(pCtx, iLangid);
148605      }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
148606        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
148607      }
148608    }
148609  }
148610
148611  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
148612  return rc;
148613}
148614
148615/*
148616** This function is the implementation of the xUpdate callback used by
148617** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
148618** inserted, updated or deleted.
148619*/
148620static int fts3UpdateMethod(
148621  sqlite3_vtab *pVtab,            /* Virtual table handle */
148622  int nArg,                       /* Size of argument array */
148623  sqlite3_value **apVal,          /* Array of arguments */
148624  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
148625){
148626  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
148627}
148628
148629/*
148630** Implementation of xSync() method. Flush the contents of the pending-terms
148631** hash-table to the database.
148632*/
148633static int fts3SyncMethod(sqlite3_vtab *pVtab){
148634
148635  /* Following an incremental-merge operation, assuming that the input
148636  ** segments are not completely consumed (the usual case), they are updated
148637  ** in place to remove the entries that have already been merged. This
148638  ** involves updating the leaf block that contains the smallest unmerged
148639  ** entry and each block (if any) between the leaf and the root node. So
148640  ** if the height of the input segment b-trees is N, and input segments
148641  ** are merged eight at a time, updating the input segments at the end
148642  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
148643  ** small - often between 0 and 2. So the overhead of the incremental
148644  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
148645  ** dwarfing the actual productive work accomplished, the incremental merge
148646  ** is only attempted if it will write at least 64 leaf blocks. Hence
148647  ** nMinMerge.
148648  **
148649  ** Of course, updating the input segments also involves deleting a bunch
148650  ** of blocks from the segments table. But this is not considered overhead
148651  ** as it would also be required by a crisis-merge that used the same input
148652  ** segments.
148653  */
148654  const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
148655
148656  Fts3Table *p = (Fts3Table*)pVtab;
148657  int rc;
148658  i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
148659
148660  rc = sqlite3Fts3PendingTermsFlush(p);
148661  if( rc==SQLITE_OK
148662   && p->nLeafAdd>(nMinMerge/16)
148663   && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
148664  ){
148665    int mxLevel = 0;              /* Maximum relative level value in db */
148666    int A;                        /* Incr-merge parameter A */
148667
148668    rc = sqlite3Fts3MaxLevel(p, &mxLevel);
148669    assert( rc==SQLITE_OK || mxLevel==0 );
148670    A = p->nLeafAdd * mxLevel;
148671    A += (A/2);
148672    if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
148673  }
148674  sqlite3Fts3SegmentsClose(p);
148675  sqlite3_set_last_insert_rowid(p->db, iLastRowid);
148676  return rc;
148677}
148678
148679/*
148680** If it is currently unknown whether or not the FTS table has an %_stat
148681** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
148682** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
148683** if an error occurs.
148684*/
148685static int fts3SetHasStat(Fts3Table *p){
148686  int rc = SQLITE_OK;
148687  if( p->bHasStat==2 ){
148688    const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
148689    char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
148690    if( zSql ){
148691      sqlite3_stmt *pStmt = 0;
148692      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
148693      if( rc==SQLITE_OK ){
148694        int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
148695        rc = sqlite3_finalize(pStmt);
148696        if( rc==SQLITE_OK ) p->bHasStat = (u8)bHasStat;
148697      }
148698      sqlite3_free(zSql);
148699    }else{
148700      rc = SQLITE_NOMEM;
148701    }
148702  }
148703  return rc;
148704}
148705
148706/*
148707** Implementation of xBegin() method.
148708*/
148709static int fts3BeginMethod(sqlite3_vtab *pVtab){
148710  Fts3Table *p = (Fts3Table*)pVtab;
148711  UNUSED_PARAMETER(pVtab);
148712  assert( p->pSegments==0 );
148713  assert( p->nPendingData==0 );
148714  assert( p->inTransaction!=1 );
148715  TESTONLY( p->inTransaction = 1 );
148716  TESTONLY( p->mxSavepoint = -1; );
148717  p->nLeafAdd = 0;
148718  return fts3SetHasStat(p);
148719}
148720
148721/*
148722** Implementation of xCommit() method. This is a no-op. The contents of
148723** the pending-terms hash-table have already been flushed into the database
148724** by fts3SyncMethod().
148725*/
148726static int fts3CommitMethod(sqlite3_vtab *pVtab){
148727  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
148728  UNUSED_PARAMETER(pVtab);
148729  assert( p->nPendingData==0 );
148730  assert( p->inTransaction!=0 );
148731  assert( p->pSegments==0 );
148732  TESTONLY( p->inTransaction = 0 );
148733  TESTONLY( p->mxSavepoint = -1; );
148734  return SQLITE_OK;
148735}
148736
148737/*
148738** Implementation of xRollback(). Discard the contents of the pending-terms
148739** hash-table. Any changes made to the database are reverted by SQLite.
148740*/
148741static int fts3RollbackMethod(sqlite3_vtab *pVtab){
148742  Fts3Table *p = (Fts3Table*)pVtab;
148743  sqlite3Fts3PendingTermsClear(p);
148744  assert( p->inTransaction!=0 );
148745  TESTONLY( p->inTransaction = 0 );
148746  TESTONLY( p->mxSavepoint = -1; );
148747  return SQLITE_OK;
148748}
148749
148750/*
148751** When called, *ppPoslist must point to the byte immediately following the
148752** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
148753** moves *ppPoslist so that it instead points to the first byte of the
148754** same position list.
148755*/
148756static void fts3ReversePoslist(char *pStart, char **ppPoslist){
148757  char *p = &(*ppPoslist)[-2];
148758  char c = 0;
148759
148760  /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
148761  while( p>pStart && (c=*p--)==0 );
148762
148763  /* Search backwards for a varint with value zero (the end of the previous
148764  ** poslist). This is an 0x00 byte preceded by some byte that does not
148765  ** have the 0x80 bit set.  */
148766  while( p>pStart && (*p & 0x80) | c ){
148767    c = *p--;
148768  }
148769  assert( p==pStart || c==0 );
148770
148771  /* At this point p points to that preceding byte without the 0x80 bit
148772  ** set. So to find the start of the poslist, skip forward 2 bytes then
148773  ** over a varint.
148774  **
148775  ** Normally. The other case is that p==pStart and the poslist to return
148776  ** is the first in the doclist. In this case do not skip forward 2 bytes.
148777  ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
148778  ** is required for cases where the first byte of a doclist and the
148779  ** doclist is empty. For example, if the first docid is 10, a doclist
148780  ** that begins with:
148781  **
148782  **   0x0A 0x00 <next docid delta varint>
148783  */
148784  if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
148785  while( *p++&0x80 );
148786  *ppPoslist = p;
148787}
148788
148789/*
148790** Helper function used by the implementation of the overloaded snippet(),
148791** offsets() and optimize() SQL functions.
148792**
148793** If the value passed as the third argument is a blob of size
148794** sizeof(Fts3Cursor*), then the blob contents are copied to the
148795** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
148796** message is written to context pContext and SQLITE_ERROR returned. The
148797** string passed via zFunc is used as part of the error message.
148798*/
148799static int fts3FunctionArg(
148800  sqlite3_context *pContext,      /* SQL function call context */
148801  const char *zFunc,              /* Function name */
148802  sqlite3_value *pVal,            /* argv[0] passed to function */
148803  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
148804){
148805  Fts3Cursor *pRet;
148806  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
148807   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
148808  ){
148809    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
148810    sqlite3_result_error(pContext, zErr, -1);
148811    sqlite3_free(zErr);
148812    return SQLITE_ERROR;
148813  }
148814  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
148815  *ppCsr = pRet;
148816  return SQLITE_OK;
148817}
148818
148819/*
148820** Implementation of the snippet() function for FTS3
148821*/
148822static void fts3SnippetFunc(
148823  sqlite3_context *pContext,      /* SQLite function call context */
148824  int nVal,                       /* Size of apVal[] array */
148825  sqlite3_value **apVal           /* Array of arguments */
148826){
148827  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
148828  const char *zStart = "<b>";
148829  const char *zEnd = "</b>";
148830  const char *zEllipsis = "<b>...</b>";
148831  int iCol = -1;
148832  int nToken = 15;                /* Default number of tokens in snippet */
148833
148834  /* There must be at least one argument passed to this function (otherwise
148835  ** the non-overloaded version would have been called instead of this one).
148836  */
148837  assert( nVal>=1 );
148838
148839  if( nVal>6 ){
148840    sqlite3_result_error(pContext,
148841        "wrong number of arguments to function snippet()", -1);
148842    return;
148843  }
148844  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
148845
148846  switch( nVal ){
148847    case 6: nToken = sqlite3_value_int(apVal[5]);
148848    case 5: iCol = sqlite3_value_int(apVal[4]);
148849    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
148850    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
148851    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
148852  }
148853  if( !zEllipsis || !zEnd || !zStart ){
148854    sqlite3_result_error_nomem(pContext);
148855  }else if( nToken==0 ){
148856    sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
148857  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
148858    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
148859  }
148860}
148861
148862/*
148863** Implementation of the offsets() function for FTS3
148864*/
148865static void fts3OffsetsFunc(
148866  sqlite3_context *pContext,      /* SQLite function call context */
148867  int nVal,                       /* Size of argument array */
148868  sqlite3_value **apVal           /* Array of arguments */
148869){
148870  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
148871
148872  UNUSED_PARAMETER(nVal);
148873
148874  assert( nVal==1 );
148875  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
148876  assert( pCsr );
148877  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
148878    sqlite3Fts3Offsets(pContext, pCsr);
148879  }
148880}
148881
148882/*
148883** Implementation of the special optimize() function for FTS3. This
148884** function merges all segments in the database to a single segment.
148885** Example usage is:
148886**
148887**   SELECT optimize(t) FROM t LIMIT 1;
148888**
148889** where 't' is the name of an FTS3 table.
148890*/
148891static void fts3OptimizeFunc(
148892  sqlite3_context *pContext,      /* SQLite function call context */
148893  int nVal,                       /* Size of argument array */
148894  sqlite3_value **apVal           /* Array of arguments */
148895){
148896  int rc;                         /* Return code */
148897  Fts3Table *p;                   /* Virtual table handle */
148898  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
148899
148900  UNUSED_PARAMETER(nVal);
148901
148902  assert( nVal==1 );
148903  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
148904  p = (Fts3Table *)pCursor->base.pVtab;
148905  assert( p );
148906
148907  rc = sqlite3Fts3Optimize(p);
148908
148909  switch( rc ){
148910    case SQLITE_OK:
148911      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
148912      break;
148913    case SQLITE_DONE:
148914      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
148915      break;
148916    default:
148917      sqlite3_result_error_code(pContext, rc);
148918      break;
148919  }
148920}
148921
148922/*
148923** Implementation of the matchinfo() function for FTS3
148924*/
148925static void fts3MatchinfoFunc(
148926  sqlite3_context *pContext,      /* SQLite function call context */
148927  int nVal,                       /* Size of argument array */
148928  sqlite3_value **apVal           /* Array of arguments */
148929){
148930  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
148931  assert( nVal==1 || nVal==2 );
148932  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
148933    const char *zArg = 0;
148934    if( nVal>1 ){
148935      zArg = (const char *)sqlite3_value_text(apVal[1]);
148936    }
148937    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
148938  }
148939}
148940
148941/*
148942** This routine implements the xFindFunction method for the FTS3
148943** virtual table.
148944*/
148945static int fts3FindFunctionMethod(
148946  sqlite3_vtab *pVtab,            /* Virtual table handle */
148947  int nArg,                       /* Number of SQL function arguments */
148948  const char *zName,              /* Name of SQL function */
148949  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
148950  void **ppArg                    /* Unused */
148951){
148952  struct Overloaded {
148953    const char *zName;
148954    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
148955  } aOverload[] = {
148956    { "snippet", fts3SnippetFunc },
148957    { "offsets", fts3OffsetsFunc },
148958    { "optimize", fts3OptimizeFunc },
148959    { "matchinfo", fts3MatchinfoFunc },
148960  };
148961  int i;                          /* Iterator variable */
148962
148963  UNUSED_PARAMETER(pVtab);
148964  UNUSED_PARAMETER(nArg);
148965  UNUSED_PARAMETER(ppArg);
148966
148967  for(i=0; i<SizeofArray(aOverload); i++){
148968    if( strcmp(zName, aOverload[i].zName)==0 ){
148969      *pxFunc = aOverload[i].xFunc;
148970      return 1;
148971    }
148972  }
148973
148974  /* No function of the specified name was found. Return 0. */
148975  return 0;
148976}
148977
148978/*
148979** Implementation of FTS3 xRename method. Rename an fts3 table.
148980*/
148981static int fts3RenameMethod(
148982  sqlite3_vtab *pVtab,            /* Virtual table handle */
148983  const char *zName               /* New name of table */
148984){
148985  Fts3Table *p = (Fts3Table *)pVtab;
148986  sqlite3 *db = p->db;            /* Database connection */
148987  int rc;                         /* Return Code */
148988
148989  /* At this point it must be known if the %_stat table exists or not.
148990  ** So bHasStat may not be 2.  */
148991  rc = fts3SetHasStat(p);
148992
148993  /* As it happens, the pending terms table is always empty here. This is
148994  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
148995  ** always opens a savepoint transaction. And the xSavepoint() method
148996  ** flushes the pending terms table. But leave the (no-op) call to
148997  ** PendingTermsFlush() in in case that changes.
148998  */
148999  assert( p->nPendingData==0 );
149000  if( rc==SQLITE_OK ){
149001    rc = sqlite3Fts3PendingTermsFlush(p);
149002  }
149003
149004  if( p->zContentTbl==0 ){
149005    fts3DbExec(&rc, db,
149006      "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
149007      p->zDb, p->zName, zName
149008    );
149009  }
149010
149011  if( p->bHasDocsize ){
149012    fts3DbExec(&rc, db,
149013      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
149014      p->zDb, p->zName, zName
149015    );
149016  }
149017  if( p->bHasStat ){
149018    fts3DbExec(&rc, db,
149019      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
149020      p->zDb, p->zName, zName
149021    );
149022  }
149023  fts3DbExec(&rc, db,
149024    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
149025    p->zDb, p->zName, zName
149026  );
149027  fts3DbExec(&rc, db,
149028    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
149029    p->zDb, p->zName, zName
149030  );
149031  return rc;
149032}
149033
149034/*
149035** The xSavepoint() method.
149036**
149037** Flush the contents of the pending-terms table to disk.
149038*/
149039static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
149040  int rc = SQLITE_OK;
149041  UNUSED_PARAMETER(iSavepoint);
149042  assert( ((Fts3Table *)pVtab)->inTransaction );
149043  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
149044  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
149045  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
149046    rc = fts3SyncMethod(pVtab);
149047  }
149048  return rc;
149049}
149050
149051/*
149052** The xRelease() method.
149053**
149054** This is a no-op.
149055*/
149056static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
149057  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
149058  UNUSED_PARAMETER(iSavepoint);
149059  UNUSED_PARAMETER(pVtab);
149060  assert( p->inTransaction );
149061  assert( p->mxSavepoint >= iSavepoint );
149062  TESTONLY( p->mxSavepoint = iSavepoint-1 );
149063  return SQLITE_OK;
149064}
149065
149066/*
149067** The xRollbackTo() method.
149068**
149069** Discard the contents of the pending terms table.
149070*/
149071static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
149072  Fts3Table *p = (Fts3Table*)pVtab;
149073  UNUSED_PARAMETER(iSavepoint);
149074  assert( p->inTransaction );
149075  assert( p->mxSavepoint >= iSavepoint );
149076  TESTONLY( p->mxSavepoint = iSavepoint );
149077  sqlite3Fts3PendingTermsClear(p);
149078  return SQLITE_OK;
149079}
149080
149081static const sqlite3_module fts3Module = {
149082  /* iVersion      */ 2,
149083  /* xCreate       */ fts3CreateMethod,
149084  /* xConnect      */ fts3ConnectMethod,
149085  /* xBestIndex    */ fts3BestIndexMethod,
149086  /* xDisconnect   */ fts3DisconnectMethod,
149087  /* xDestroy      */ fts3DestroyMethod,
149088  /* xOpen         */ fts3OpenMethod,
149089  /* xClose        */ fts3CloseMethod,
149090  /* xFilter       */ fts3FilterMethod,
149091  /* xNext         */ fts3NextMethod,
149092  /* xEof          */ fts3EofMethod,
149093  /* xColumn       */ fts3ColumnMethod,
149094  /* xRowid        */ fts3RowidMethod,
149095  /* xUpdate       */ fts3UpdateMethod,
149096  /* xBegin        */ fts3BeginMethod,
149097  /* xSync         */ fts3SyncMethod,
149098  /* xCommit       */ fts3CommitMethod,
149099  /* xRollback     */ fts3RollbackMethod,
149100  /* xFindFunction */ fts3FindFunctionMethod,
149101  /* xRename */       fts3RenameMethod,
149102  /* xSavepoint    */ fts3SavepointMethod,
149103  /* xRelease      */ fts3ReleaseMethod,
149104  /* xRollbackTo   */ fts3RollbackToMethod,
149105};
149106
149107/*
149108** This function is registered as the module destructor (called when an
149109** FTS3 enabled database connection is closed). It frees the memory
149110** allocated for the tokenizer hash table.
149111*/
149112static void hashDestroy(void *p){
149113  Fts3Hash *pHash = (Fts3Hash *)p;
149114  sqlite3Fts3HashClear(pHash);
149115  sqlite3_free(pHash);
149116}
149117
149118/*
149119** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
149120** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
149121** respectively. The following three forward declarations are for functions
149122** declared in these files used to retrieve the respective implementations.
149123**
149124** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
149125** to by the argument to point to the "simple" tokenizer implementation.
149126** And so on.
149127*/
149128SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
149129SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
149130#ifndef SQLITE_DISABLE_FTS3_UNICODE
149131SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
149132#endif
149133#ifdef SQLITE_ENABLE_ICU
149134SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
149135#endif
149136
149137/*
149138** Initialize the fts3 extension. If this extension is built as part
149139** of the sqlite library, then this function is called directly by
149140** SQLite. If fts3 is built as a dynamically loadable extension, this
149141** function is called by the sqlite3_extension_init() entry point.
149142*/
149143SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
149144  int rc = SQLITE_OK;
149145  Fts3Hash *pHash = 0;
149146  const sqlite3_tokenizer_module *pSimple = 0;
149147  const sqlite3_tokenizer_module *pPorter = 0;
149148#ifndef SQLITE_DISABLE_FTS3_UNICODE
149149  const sqlite3_tokenizer_module *pUnicode = 0;
149150#endif
149151
149152#ifdef SQLITE_ENABLE_ICU
149153  const sqlite3_tokenizer_module *pIcu = 0;
149154  sqlite3Fts3IcuTokenizerModule(&pIcu);
149155#endif
149156
149157#ifndef SQLITE_DISABLE_FTS3_UNICODE
149158  sqlite3Fts3UnicodeTokenizer(&pUnicode);
149159#endif
149160
149161#ifdef SQLITE_TEST
149162  rc = sqlite3Fts3InitTerm(db);
149163  if( rc!=SQLITE_OK ) return rc;
149164#endif
149165
149166  rc = sqlite3Fts3InitAux(db);
149167  if( rc!=SQLITE_OK ) return rc;
149168
149169  sqlite3Fts3SimpleTokenizerModule(&pSimple);
149170  sqlite3Fts3PorterTokenizerModule(&pPorter);
149171
149172  /* Allocate and initialize the hash-table used to store tokenizers. */
149173  pHash = sqlite3_malloc(sizeof(Fts3Hash));
149174  if( !pHash ){
149175    rc = SQLITE_NOMEM;
149176  }else{
149177    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
149178  }
149179
149180  /* Load the built-in tokenizers into the hash table */
149181  if( rc==SQLITE_OK ){
149182    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
149183     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
149184
149185#ifndef SQLITE_DISABLE_FTS3_UNICODE
149186     || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
149187#endif
149188#ifdef SQLITE_ENABLE_ICU
149189     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
149190#endif
149191    ){
149192      rc = SQLITE_NOMEM;
149193    }
149194  }
149195
149196#ifdef SQLITE_TEST
149197  if( rc==SQLITE_OK ){
149198    rc = sqlite3Fts3ExprInitTestInterface(db);
149199  }
149200#endif
149201
149202  /* Create the virtual table wrapper around the hash-table and overload
149203  ** the two scalar functions. If this is successful, register the
149204  ** module with sqlite.
149205  */
149206  if( SQLITE_OK==rc
149207#ifndef ANDROID    /* fts3_tokenizer disabled for security reasons */
149208   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
149209#endif
149210   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
149211   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
149212   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
149213   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
149214   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
149215  ){
149216#ifdef SQLITE_ENABLE_FTS3_BACKWARDS
149217    rc = sqlite3_create_module_v2(
149218        db, "fts1", &fts3Module, (void *)pHash, 0
149219        );
149220    if(rc) return rc;
149221    rc = sqlite3_create_module_v2(
149222        db, "fts2", &fts3Module, (void *)pHash, 0
149223        );
149224    if(rc) return rc;
149225#endif
149226    rc = sqlite3_create_module_v2(
149227        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
149228    );
149229    if( rc==SQLITE_OK ){
149230      rc = sqlite3_create_module_v2(
149231          db, "fts4", &fts3Module, (void *)pHash, 0
149232      );
149233    }
149234    if( rc==SQLITE_OK ){
149235      rc = sqlite3Fts3InitTok(db, (void *)pHash);
149236    }
149237    return rc;
149238  }
149239
149240
149241  /* An error has occurred. Delete the hash table and return the error code. */
149242  assert( rc!=SQLITE_OK );
149243  if( pHash ){
149244    sqlite3Fts3HashClear(pHash);
149245    sqlite3_free(pHash);
149246  }
149247  return rc;
149248}
149249
149250/*
149251** Allocate an Fts3MultiSegReader for each token in the expression headed
149252** by pExpr.
149253**
149254** An Fts3SegReader object is a cursor that can seek or scan a range of
149255** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
149256** Fts3SegReader objects internally to provide an interface to seek or scan
149257** within the union of all segments of a b-tree. Hence the name.
149258**
149259** If the allocated Fts3MultiSegReader just seeks to a single entry in a
149260** segment b-tree (if the term is not a prefix or it is a prefix for which
149261** there exists prefix b-tree of the right length) then it may be traversed
149262** and merged incrementally. Otherwise, it has to be merged into an in-memory
149263** doclist and then traversed.
149264*/
149265static void fts3EvalAllocateReaders(
149266  Fts3Cursor *pCsr,               /* FTS cursor handle */
149267  Fts3Expr *pExpr,                /* Allocate readers for this expression */
149268  int *pnToken,                   /* OUT: Total number of tokens in phrase. */
149269  int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
149270  int *pRc                        /* IN/OUT: Error code */
149271){
149272  if( pExpr && SQLITE_OK==*pRc ){
149273    if( pExpr->eType==FTSQUERY_PHRASE ){
149274      int i;
149275      int nToken = pExpr->pPhrase->nToken;
149276      *pnToken += nToken;
149277      for(i=0; i<nToken; i++){
149278        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
149279        int rc = fts3TermSegReaderCursor(pCsr,
149280            pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
149281        );
149282        if( rc!=SQLITE_OK ){
149283          *pRc = rc;
149284          return;
149285        }
149286      }
149287      assert( pExpr->pPhrase->iDoclistToken==0 );
149288      pExpr->pPhrase->iDoclistToken = -1;
149289    }else{
149290      *pnOr += (pExpr->eType==FTSQUERY_OR);
149291      fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
149292      fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
149293    }
149294  }
149295}
149296
149297/*
149298** Arguments pList/nList contain the doclist for token iToken of phrase p.
149299** It is merged into the main doclist stored in p->doclist.aAll/nAll.
149300**
149301** This function assumes that pList points to a buffer allocated using
149302** sqlite3_malloc(). This function takes responsibility for eventually
149303** freeing the buffer.
149304**
149305** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
149306*/
149307static int fts3EvalPhraseMergeToken(
149308  Fts3Table *pTab,                /* FTS Table pointer */
149309  Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
149310  int iToken,                     /* Token pList/nList corresponds to */
149311  char *pList,                    /* Pointer to doclist */
149312  int nList                       /* Number of bytes in pList */
149313){
149314  int rc = SQLITE_OK;
149315  assert( iToken!=p->iDoclistToken );
149316
149317  if( pList==0 ){
149318    sqlite3_free(p->doclist.aAll);
149319    p->doclist.aAll = 0;
149320    p->doclist.nAll = 0;
149321  }
149322
149323  else if( p->iDoclistToken<0 ){
149324    p->doclist.aAll = pList;
149325    p->doclist.nAll = nList;
149326  }
149327
149328  else if( p->doclist.aAll==0 ){
149329    sqlite3_free(pList);
149330  }
149331
149332  else {
149333    char *pLeft;
149334    char *pRight;
149335    int nLeft;
149336    int nRight;
149337    int nDiff;
149338
149339    if( p->iDoclistToken<iToken ){
149340      pLeft = p->doclist.aAll;
149341      nLeft = p->doclist.nAll;
149342      pRight = pList;
149343      nRight = nList;
149344      nDiff = iToken - p->iDoclistToken;
149345    }else{
149346      pRight = p->doclist.aAll;
149347      nRight = p->doclist.nAll;
149348      pLeft = pList;
149349      nLeft = nList;
149350      nDiff = p->iDoclistToken - iToken;
149351    }
149352
149353    rc = fts3DoclistPhraseMerge(
149354        pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
149355    );
149356    sqlite3_free(pLeft);
149357    p->doclist.aAll = pRight;
149358    p->doclist.nAll = nRight;
149359  }
149360
149361  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
149362  return rc;
149363}
149364
149365/*
149366** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
149367** does not take deferred tokens into account.
149368**
149369** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
149370*/
149371static int fts3EvalPhraseLoad(
149372  Fts3Cursor *pCsr,               /* FTS Cursor handle */
149373  Fts3Phrase *p                   /* Phrase object */
149374){
149375  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
149376  int iToken;
149377  int rc = SQLITE_OK;
149378
149379  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
149380    Fts3PhraseToken *pToken = &p->aToken[iToken];
149381    assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
149382
149383    if( pToken->pSegcsr ){
149384      int nThis = 0;
149385      char *pThis = 0;
149386      rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
149387      if( rc==SQLITE_OK ){
149388        rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
149389      }
149390    }
149391    assert( pToken->pSegcsr==0 );
149392  }
149393
149394  return rc;
149395}
149396
149397/*
149398** This function is called on each phrase after the position lists for
149399** any deferred tokens have been loaded into memory. It updates the phrases
149400** current position list to include only those positions that are really
149401** instances of the phrase (after considering deferred tokens). If this
149402** means that the phrase does not appear in the current row, doclist.pList
149403** and doclist.nList are both zeroed.
149404**
149405** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
149406*/
149407static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
149408  int iToken;                     /* Used to iterate through phrase tokens */
149409  char *aPoslist = 0;             /* Position list for deferred tokens */
149410  int nPoslist = 0;               /* Number of bytes in aPoslist */
149411  int iPrev = -1;                 /* Token number of previous deferred token */
149412
149413  assert( pPhrase->doclist.bFreeList==0 );
149414
149415  for(iToken=0; iToken<pPhrase->nToken; iToken++){
149416    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
149417    Fts3DeferredToken *pDeferred = pToken->pDeferred;
149418
149419    if( pDeferred ){
149420      char *pList;
149421      int nList;
149422      int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
149423      if( rc!=SQLITE_OK ) return rc;
149424
149425      if( pList==0 ){
149426        sqlite3_free(aPoslist);
149427        pPhrase->doclist.pList = 0;
149428        pPhrase->doclist.nList = 0;
149429        return SQLITE_OK;
149430
149431      }else if( aPoslist==0 ){
149432        aPoslist = pList;
149433        nPoslist = nList;
149434
149435      }else{
149436        char *aOut = pList;
149437        char *p1 = aPoslist;
149438        char *p2 = aOut;
149439
149440        assert( iPrev>=0 );
149441        fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
149442        sqlite3_free(aPoslist);
149443        aPoslist = pList;
149444        nPoslist = (int)(aOut - aPoslist);
149445        if( nPoslist==0 ){
149446          sqlite3_free(aPoslist);
149447          pPhrase->doclist.pList = 0;
149448          pPhrase->doclist.nList = 0;
149449          return SQLITE_OK;
149450        }
149451      }
149452      iPrev = iToken;
149453    }
149454  }
149455
149456  if( iPrev>=0 ){
149457    int nMaxUndeferred = pPhrase->iDoclistToken;
149458    if( nMaxUndeferred<0 ){
149459      pPhrase->doclist.pList = aPoslist;
149460      pPhrase->doclist.nList = nPoslist;
149461      pPhrase->doclist.iDocid = pCsr->iPrevId;
149462      pPhrase->doclist.bFreeList = 1;
149463    }else{
149464      int nDistance;
149465      char *p1;
149466      char *p2;
149467      char *aOut;
149468
149469      if( nMaxUndeferred>iPrev ){
149470        p1 = aPoslist;
149471        p2 = pPhrase->doclist.pList;
149472        nDistance = nMaxUndeferred - iPrev;
149473      }else{
149474        p1 = pPhrase->doclist.pList;
149475        p2 = aPoslist;
149476        nDistance = iPrev - nMaxUndeferred;
149477      }
149478
149479      aOut = (char *)sqlite3_malloc(nPoslist+8);
149480      if( !aOut ){
149481        sqlite3_free(aPoslist);
149482        return SQLITE_NOMEM;
149483      }
149484
149485      pPhrase->doclist.pList = aOut;
149486      if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
149487        pPhrase->doclist.bFreeList = 1;
149488        pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
149489      }else{
149490        sqlite3_free(aOut);
149491        pPhrase->doclist.pList = 0;
149492        pPhrase->doclist.nList = 0;
149493      }
149494      sqlite3_free(aPoslist);
149495    }
149496  }
149497
149498  return SQLITE_OK;
149499}
149500
149501/*
149502** Maximum number of tokens a phrase may have to be considered for the
149503** incremental doclists strategy.
149504*/
149505#define MAX_INCR_PHRASE_TOKENS 4
149506
149507/*
149508** This function is called for each Fts3Phrase in a full-text query
149509** expression to initialize the mechanism for returning rows. Once this
149510** function has been called successfully on an Fts3Phrase, it may be
149511** used with fts3EvalPhraseNext() to iterate through the matching docids.
149512**
149513** If parameter bOptOk is true, then the phrase may (or may not) use the
149514** incremental loading strategy. Otherwise, the entire doclist is loaded into
149515** memory within this call.
149516**
149517** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
149518*/
149519static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
149520  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
149521  int rc = SQLITE_OK;             /* Error code */
149522  int i;
149523
149524  /* Determine if doclists may be loaded from disk incrementally. This is
149525  ** possible if the bOptOk argument is true, the FTS doclists will be
149526  ** scanned in forward order, and the phrase consists of
149527  ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
149528  ** tokens or prefix tokens that cannot use a prefix-index.  */
149529  int bHaveIncr = 0;
149530  int bIncrOk = (bOptOk
149531   && pCsr->bDesc==pTab->bDescIdx
149532   && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
149533#ifdef SQLITE_TEST
149534   && pTab->bNoIncrDoclist==0
149535#endif
149536  );
149537  for(i=0; bIncrOk==1 && i<p->nToken; i++){
149538    Fts3PhraseToken *pToken = &p->aToken[i];
149539    if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
149540      bIncrOk = 0;
149541    }
149542    if( pToken->pSegcsr ) bHaveIncr = 1;
149543  }
149544
149545  if( bIncrOk && bHaveIncr ){
149546    /* Use the incremental approach. */
149547    int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
149548    for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
149549      Fts3PhraseToken *pToken = &p->aToken[i];
149550      Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
149551      if( pSegcsr ){
149552        rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
149553      }
149554    }
149555    p->bIncr = 1;
149556  }else{
149557    /* Load the full doclist for the phrase into memory. */
149558    rc = fts3EvalPhraseLoad(pCsr, p);
149559    p->bIncr = 0;
149560  }
149561
149562  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
149563  return rc;
149564}
149565
149566/*
149567** This function is used to iterate backwards (from the end to start)
149568** through doclists. It is used by this module to iterate through phrase
149569** doclists in reverse and by the fts3_write.c module to iterate through
149570** pending-terms lists when writing to databases with "order=desc".
149571**
149572** The doclist may be sorted in ascending (parameter bDescIdx==0) or
149573** descending (parameter bDescIdx==1) order of docid. Regardless, this
149574** function iterates from the end of the doclist to the beginning.
149575*/
149576SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
149577  int bDescIdx,                   /* True if the doclist is desc */
149578  char *aDoclist,                 /* Pointer to entire doclist */
149579  int nDoclist,                   /* Length of aDoclist in bytes */
149580  char **ppIter,                  /* IN/OUT: Iterator pointer */
149581  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
149582  int *pnList,                    /* OUT: List length pointer */
149583  u8 *pbEof                       /* OUT: End-of-file flag */
149584){
149585  char *p = *ppIter;
149586
149587  assert( nDoclist>0 );
149588  assert( *pbEof==0 );
149589  assert( p || *piDocid==0 );
149590  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
149591
149592  if( p==0 ){
149593    sqlite3_int64 iDocid = 0;
149594    char *pNext = 0;
149595    char *pDocid = aDoclist;
149596    char *pEnd = &aDoclist[nDoclist];
149597    int iMul = 1;
149598
149599    while( pDocid<pEnd ){
149600      sqlite3_int64 iDelta;
149601      pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
149602      iDocid += (iMul * iDelta);
149603      pNext = pDocid;
149604      fts3PoslistCopy(0, &pDocid);
149605      while( pDocid<pEnd && *pDocid==0 ) pDocid++;
149606      iMul = (bDescIdx ? -1 : 1);
149607    }
149608
149609    *pnList = (int)(pEnd - pNext);
149610    *ppIter = pNext;
149611    *piDocid = iDocid;
149612  }else{
149613    int iMul = (bDescIdx ? -1 : 1);
149614    sqlite3_int64 iDelta;
149615    fts3GetReverseVarint(&p, aDoclist, &iDelta);
149616    *piDocid -= (iMul * iDelta);
149617
149618    if( p==aDoclist ){
149619      *pbEof = 1;
149620    }else{
149621      char *pSave = p;
149622      fts3ReversePoslist(aDoclist, &p);
149623      *pnList = (int)(pSave - p);
149624    }
149625    *ppIter = p;
149626  }
149627}
149628
149629/*
149630** Iterate forwards through a doclist.
149631*/
149632SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
149633  int bDescIdx,                   /* True if the doclist is desc */
149634  char *aDoclist,                 /* Pointer to entire doclist */
149635  int nDoclist,                   /* Length of aDoclist in bytes */
149636  char **ppIter,                  /* IN/OUT: Iterator pointer */
149637  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
149638  u8 *pbEof                       /* OUT: End-of-file flag */
149639){
149640  char *p = *ppIter;
149641
149642  assert( nDoclist>0 );
149643  assert( *pbEof==0 );
149644  assert( p || *piDocid==0 );
149645  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
149646
149647  if( p==0 ){
149648    p = aDoclist;
149649    p += sqlite3Fts3GetVarint(p, piDocid);
149650  }else{
149651    fts3PoslistCopy(0, &p);
149652    while( p<&aDoclist[nDoclist] && *p==0 ) p++;
149653    if( p>=&aDoclist[nDoclist] ){
149654      *pbEof = 1;
149655    }else{
149656      sqlite3_int64 iVar;
149657      p += sqlite3Fts3GetVarint(p, &iVar);
149658      *piDocid += ((bDescIdx ? -1 : 1) * iVar);
149659    }
149660  }
149661
149662  *ppIter = p;
149663}
149664
149665/*
149666** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
149667** to true if EOF is reached.
149668*/
149669static void fts3EvalDlPhraseNext(
149670  Fts3Table *pTab,
149671  Fts3Doclist *pDL,
149672  u8 *pbEof
149673){
149674  char *pIter;                            /* Used to iterate through aAll */
149675  char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
149676
149677  if( pDL->pNextDocid ){
149678    pIter = pDL->pNextDocid;
149679  }else{
149680    pIter = pDL->aAll;
149681  }
149682
149683  if( pIter>=pEnd ){
149684    /* We have already reached the end of this doclist. EOF. */
149685    *pbEof = 1;
149686  }else{
149687    sqlite3_int64 iDelta;
149688    pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
149689    if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
149690      pDL->iDocid += iDelta;
149691    }else{
149692      pDL->iDocid -= iDelta;
149693    }
149694    pDL->pList = pIter;
149695    fts3PoslistCopy(0, &pIter);
149696    pDL->nList = (int)(pIter - pDL->pList);
149697
149698    /* pIter now points just past the 0x00 that terminates the position-
149699    ** list for document pDL->iDocid. However, if this position-list was
149700    ** edited in place by fts3EvalNearTrim(), then pIter may not actually
149701    ** point to the start of the next docid value. The following line deals
149702    ** with this case by advancing pIter past the zero-padding added by
149703    ** fts3EvalNearTrim().  */
149704    while( pIter<pEnd && *pIter==0 ) pIter++;
149705
149706    pDL->pNextDocid = pIter;
149707    assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
149708    *pbEof = 0;
149709  }
149710}
149711
149712/*
149713** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
149714*/
149715typedef struct TokenDoclist TokenDoclist;
149716struct TokenDoclist {
149717  int bIgnore;
149718  sqlite3_int64 iDocid;
149719  char *pList;
149720  int nList;
149721};
149722
149723/*
149724** Token pToken is an incrementally loaded token that is part of a
149725** multi-token phrase. Advance it to the next matching document in the
149726** database and populate output variable *p with the details of the new
149727** entry. Or, if the iterator has reached EOF, set *pbEof to true.
149728**
149729** If an error occurs, return an SQLite error code. Otherwise, return
149730** SQLITE_OK.
149731*/
149732static int incrPhraseTokenNext(
149733  Fts3Table *pTab,                /* Virtual table handle */
149734  Fts3Phrase *pPhrase,            /* Phrase to advance token of */
149735  int iToken,                     /* Specific token to advance */
149736  TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
149737  u8 *pbEof                       /* OUT: True if iterator is at EOF */
149738){
149739  int rc = SQLITE_OK;
149740
149741  if( pPhrase->iDoclistToken==iToken ){
149742    assert( p->bIgnore==0 );
149743    assert( pPhrase->aToken[iToken].pSegcsr==0 );
149744    fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
149745    p->pList = pPhrase->doclist.pList;
149746    p->nList = pPhrase->doclist.nList;
149747    p->iDocid = pPhrase->doclist.iDocid;
149748  }else{
149749    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
149750    assert( pToken->pDeferred==0 );
149751    assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
149752    if( pToken->pSegcsr ){
149753      assert( p->bIgnore==0 );
149754      rc = sqlite3Fts3MsrIncrNext(
149755          pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
149756      );
149757      if( p->pList==0 ) *pbEof = 1;
149758    }else{
149759      p->bIgnore = 1;
149760    }
149761  }
149762
149763  return rc;
149764}
149765
149766
149767/*
149768** The phrase iterator passed as the second argument:
149769**
149770**   * features at least one token that uses an incremental doclist, and
149771**
149772**   * does not contain any deferred tokens.
149773**
149774** Advance it to the next matching documnent in the database and populate
149775** the Fts3Doclist.pList and nList fields.
149776**
149777** If there is no "next" entry and no error occurs, then *pbEof is set to
149778** 1 before returning. Otherwise, if no error occurs and the iterator is
149779** successfully advanced, *pbEof is set to 0.
149780**
149781** If an error occurs, return an SQLite error code. Otherwise, return
149782** SQLITE_OK.
149783*/
149784static int fts3EvalIncrPhraseNext(
149785  Fts3Cursor *pCsr,               /* FTS Cursor handle */
149786  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
149787  u8 *pbEof                       /* OUT: Set to 1 if EOF */
149788){
149789  int rc = SQLITE_OK;
149790  Fts3Doclist *pDL = &p->doclist;
149791  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
149792  u8 bEof = 0;
149793
149794  /* This is only called if it is guaranteed that the phrase has at least
149795  ** one incremental token. In which case the bIncr flag is set. */
149796  assert( p->bIncr==1 );
149797
149798  if( p->nToken==1 && p->bIncr ){
149799    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
149800        &pDL->iDocid, &pDL->pList, &pDL->nList
149801    );
149802    if( pDL->pList==0 ) bEof = 1;
149803  }else{
149804    int bDescDoclist = pCsr->bDesc;
149805    struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
149806
149807    memset(a, 0, sizeof(a));
149808    assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
149809    assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
149810
149811    while( bEof==0 ){
149812      int bMaxSet = 0;
149813      sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
149814      int i;                      /* Used to iterate through tokens */
149815
149816      /* Advance the iterator for each token in the phrase once. */
149817      for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
149818        rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
149819        if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
149820          iMax = a[i].iDocid;
149821          bMaxSet = 1;
149822        }
149823      }
149824      assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
149825      assert( rc!=SQLITE_OK || bMaxSet );
149826
149827      /* Keep advancing iterators until they all point to the same document */
149828      for(i=0; i<p->nToken; i++){
149829        while( rc==SQLITE_OK && bEof==0
149830            && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
149831        ){
149832          rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
149833          if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
149834            iMax = a[i].iDocid;
149835            i = 0;
149836          }
149837        }
149838      }
149839
149840      /* Check if the current entries really are a phrase match */
149841      if( bEof==0 ){
149842        int nList = 0;
149843        int nByte = a[p->nToken-1].nList;
149844        char *aDoclist = sqlite3_malloc(nByte+1);
149845        if( !aDoclist ) return SQLITE_NOMEM;
149846        memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
149847
149848        for(i=0; i<(p->nToken-1); i++){
149849          if( a[i].bIgnore==0 ){
149850            char *pL = a[i].pList;
149851            char *pR = aDoclist;
149852            char *pOut = aDoclist;
149853            int nDist = p->nToken-1-i;
149854            int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
149855            if( res==0 ) break;
149856            nList = (int)(pOut - aDoclist);
149857          }
149858        }
149859        if( i==(p->nToken-1) ){
149860          pDL->iDocid = iMax;
149861          pDL->pList = aDoclist;
149862          pDL->nList = nList;
149863          pDL->bFreeList = 1;
149864          break;
149865        }
149866        sqlite3_free(aDoclist);
149867      }
149868    }
149869  }
149870
149871  *pbEof = bEof;
149872  return rc;
149873}
149874
149875/*
149876** Attempt to move the phrase iterator to point to the next matching docid.
149877** If an error occurs, return an SQLite error code. Otherwise, return
149878** SQLITE_OK.
149879**
149880** If there is no "next" entry and no error occurs, then *pbEof is set to
149881** 1 before returning. Otherwise, if no error occurs and the iterator is
149882** successfully advanced, *pbEof is set to 0.
149883*/
149884static int fts3EvalPhraseNext(
149885  Fts3Cursor *pCsr,               /* FTS Cursor handle */
149886  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
149887  u8 *pbEof                       /* OUT: Set to 1 if EOF */
149888){
149889  int rc = SQLITE_OK;
149890  Fts3Doclist *pDL = &p->doclist;
149891  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
149892
149893  if( p->bIncr ){
149894    rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
149895  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
149896    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
149897        &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
149898    );
149899    pDL->pList = pDL->pNextDocid;
149900  }else{
149901    fts3EvalDlPhraseNext(pTab, pDL, pbEof);
149902  }
149903
149904  return rc;
149905}
149906
149907/*
149908**
149909** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
149910** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
149911** expression. Also the Fts3Expr.bDeferred variable is set to true for any
149912** expressions for which all descendent tokens are deferred.
149913**
149914** If parameter bOptOk is zero, then it is guaranteed that the
149915** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
149916** each phrase in the expression (subject to deferred token processing).
149917** Or, if bOptOk is non-zero, then one or more tokens within the expression
149918** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
149919**
149920** If an error occurs within this function, *pRc is set to an SQLite error
149921** code before returning.
149922*/
149923static void fts3EvalStartReaders(
149924  Fts3Cursor *pCsr,               /* FTS Cursor handle */
149925  Fts3Expr *pExpr,                /* Expression to initialize phrases in */
149926  int *pRc                        /* IN/OUT: Error code */
149927){
149928  if( pExpr && SQLITE_OK==*pRc ){
149929    if( pExpr->eType==FTSQUERY_PHRASE ){
149930      int nToken = pExpr->pPhrase->nToken;
149931      if( nToken ){
149932        int i;
149933        for(i=0; i<nToken; i++){
149934          if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
149935        }
149936        pExpr->bDeferred = (i==nToken);
149937      }
149938      *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
149939    }else{
149940      fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
149941      fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
149942      pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
149943    }
149944  }
149945}
149946
149947/*
149948** An array of the following structures is assembled as part of the process
149949** of selecting tokens to defer before the query starts executing (as part
149950** of the xFilter() method). There is one element in the array for each
149951** token in the FTS expression.
149952**
149953** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
149954** to phrases that are connected only by AND and NEAR operators (not OR or
149955** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
149956** separately. The root of a tokens AND/NEAR cluster is stored in
149957** Fts3TokenAndCost.pRoot.
149958*/
149959typedef struct Fts3TokenAndCost Fts3TokenAndCost;
149960struct Fts3TokenAndCost {
149961  Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
149962  int iToken;                     /* Position of token in phrase */
149963  Fts3PhraseToken *pToken;        /* The token itself */
149964  Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
149965  int nOvfl;                      /* Number of overflow pages to load doclist */
149966  int iCol;                       /* The column the token must match */
149967};
149968
149969/*
149970** This function is used to populate an allocated Fts3TokenAndCost array.
149971**
149972** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
149973** Otherwise, if an error occurs during execution, *pRc is set to an
149974** SQLite error code.
149975*/
149976static void fts3EvalTokenCosts(
149977  Fts3Cursor *pCsr,               /* FTS Cursor handle */
149978  Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
149979  Fts3Expr *pExpr,                /* Expression to consider */
149980  Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
149981  Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
149982  int *pRc                        /* IN/OUT: Error code */
149983){
149984  if( *pRc==SQLITE_OK ){
149985    if( pExpr->eType==FTSQUERY_PHRASE ){
149986      Fts3Phrase *pPhrase = pExpr->pPhrase;
149987      int i;
149988      for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
149989        Fts3TokenAndCost *pTC = (*ppTC)++;
149990        pTC->pPhrase = pPhrase;
149991        pTC->iToken = i;
149992        pTC->pRoot = pRoot;
149993        pTC->pToken = &pPhrase->aToken[i];
149994        pTC->iCol = pPhrase->iColumn;
149995        *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
149996      }
149997    }else if( pExpr->eType!=FTSQUERY_NOT ){
149998      assert( pExpr->eType==FTSQUERY_OR
149999           || pExpr->eType==FTSQUERY_AND
150000           || pExpr->eType==FTSQUERY_NEAR
150001      );
150002      assert( pExpr->pLeft && pExpr->pRight );
150003      if( pExpr->eType==FTSQUERY_OR ){
150004        pRoot = pExpr->pLeft;
150005        **ppOr = pRoot;
150006        (*ppOr)++;
150007      }
150008      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
150009      if( pExpr->eType==FTSQUERY_OR ){
150010        pRoot = pExpr->pRight;
150011        **ppOr = pRoot;
150012        (*ppOr)++;
150013      }
150014      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
150015    }
150016  }
150017}
150018
150019/*
150020** Determine the average document (row) size in pages. If successful,
150021** write this value to *pnPage and return SQLITE_OK. Otherwise, return
150022** an SQLite error code.
150023**
150024** The average document size in pages is calculated by first calculating
150025** determining the average size in bytes, B. If B is less than the amount
150026** of data that will fit on a single leaf page of an intkey table in
150027** this database, then the average docsize is 1. Otherwise, it is 1 plus
150028** the number of overflow pages consumed by a record B bytes in size.
150029*/
150030static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
150031  if( pCsr->nRowAvg==0 ){
150032    /* The average document size, which is required to calculate the cost
150033    ** of each doclist, has not yet been determined. Read the required
150034    ** data from the %_stat table to calculate it.
150035    **
150036    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
150037    ** varints, where nCol is the number of columns in the FTS3 table.
150038    ** The first varint is the number of documents currently stored in
150039    ** the table. The following nCol varints contain the total amount of
150040    ** data stored in all rows of each column of the table, from left
150041    ** to right.
150042    */
150043    int rc;
150044    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
150045    sqlite3_stmt *pStmt;
150046    sqlite3_int64 nDoc = 0;
150047    sqlite3_int64 nByte = 0;
150048    const char *pEnd;
150049    const char *a;
150050
150051    rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
150052    if( rc!=SQLITE_OK ) return rc;
150053    a = sqlite3_column_blob(pStmt, 0);
150054    assert( a );
150055
150056    pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
150057    a += sqlite3Fts3GetVarint(a, &nDoc);
150058    while( a<pEnd ){
150059      a += sqlite3Fts3GetVarint(a, &nByte);
150060    }
150061    if( nDoc==0 || nByte==0 ){
150062      sqlite3_reset(pStmt);
150063      return FTS_CORRUPT_VTAB;
150064    }
150065
150066    pCsr->nDoc = nDoc;
150067    pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
150068    assert( pCsr->nRowAvg>0 );
150069    rc = sqlite3_reset(pStmt);
150070    if( rc!=SQLITE_OK ) return rc;
150071  }
150072
150073  *pnPage = pCsr->nRowAvg;
150074  return SQLITE_OK;
150075}
150076
150077/*
150078** This function is called to select the tokens (if any) that will be
150079** deferred. The array aTC[] has already been populated when this is
150080** called.
150081**
150082** This function is called once for each AND/NEAR cluster in the
150083** expression. Each invocation determines which tokens to defer within
150084** the cluster with root node pRoot. See comments above the definition
150085** of struct Fts3TokenAndCost for more details.
150086**
150087** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
150088** called on each token to defer. Otherwise, an SQLite error code is
150089** returned.
150090*/
150091static int fts3EvalSelectDeferred(
150092  Fts3Cursor *pCsr,               /* FTS Cursor handle */
150093  Fts3Expr *pRoot,                /* Consider tokens with this root node */
150094  Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
150095  int nTC                         /* Number of entries in aTC[] */
150096){
150097  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
150098  int nDocSize = 0;               /* Number of pages per doc loaded */
150099  int rc = SQLITE_OK;             /* Return code */
150100  int ii;                         /* Iterator variable for various purposes */
150101  int nOvfl = 0;                  /* Total overflow pages used by doclists */
150102  int nToken = 0;                 /* Total number of tokens in cluster */
150103
150104  int nMinEst = 0;                /* The minimum count for any phrase so far. */
150105  int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
150106
150107  /* Tokens are never deferred for FTS tables created using the content=xxx
150108  ** option. The reason being that it is not guaranteed that the content
150109  ** table actually contains the same data as the index. To prevent this from
150110  ** causing any problems, the deferred token optimization is completely
150111  ** disabled for content=xxx tables. */
150112  if( pTab->zContentTbl ){
150113    return SQLITE_OK;
150114  }
150115
150116  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
150117  ** associated with the tokens spill onto overflow pages, or if there is
150118  ** only 1 token, exit early. No tokens to defer in this case. */
150119  for(ii=0; ii<nTC; ii++){
150120    if( aTC[ii].pRoot==pRoot ){
150121      nOvfl += aTC[ii].nOvfl;
150122      nToken++;
150123    }
150124  }
150125  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
150126
150127  /* Obtain the average docsize (in pages). */
150128  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
150129  assert( rc!=SQLITE_OK || nDocSize>0 );
150130
150131
150132  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
150133  ** of the number of overflow pages that will be loaded by the pager layer
150134  ** to retrieve the entire doclist for the token from the full-text index.
150135  ** Load the doclists for tokens that are either:
150136  **
150137  **   a. The cheapest token in the entire query (i.e. the one visited by the
150138  **      first iteration of this loop), or
150139  **
150140  **   b. Part of a multi-token phrase.
150141  **
150142  ** After each token doclist is loaded, merge it with the others from the
150143  ** same phrase and count the number of documents that the merged doclist
150144  ** contains. Set variable "nMinEst" to the smallest number of documents in
150145  ** any phrase doclist for which 1 or more token doclists have been loaded.
150146  ** Let nOther be the number of other phrases for which it is certain that
150147  ** one or more tokens will not be deferred.
150148  **
150149  ** Then, for each token, defer it if loading the doclist would result in
150150  ** loading N or more overflow pages into memory, where N is computed as:
150151  **
150152  **    (nMinEst + 4^nOther - 1) / (4^nOther)
150153  */
150154  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
150155    int iTC;                      /* Used to iterate through aTC[] array. */
150156    Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
150157
150158    /* Set pTC to point to the cheapest remaining token. */
150159    for(iTC=0; iTC<nTC; iTC++){
150160      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
150161       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
150162      ){
150163        pTC = &aTC[iTC];
150164      }
150165    }
150166    assert( pTC );
150167
150168    if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
150169      /* The number of overflow pages to load for this (and therefore all
150170      ** subsequent) tokens is greater than the estimated number of pages
150171      ** that will be loaded if all subsequent tokens are deferred.
150172      */
150173      Fts3PhraseToken *pToken = pTC->pToken;
150174      rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
150175      fts3SegReaderCursorFree(pToken->pSegcsr);
150176      pToken->pSegcsr = 0;
150177    }else{
150178      /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
150179      ** for-loop. Except, limit the value to 2^24 to prevent it from
150180      ** overflowing the 32-bit integer it is stored in. */
150181      if( ii<12 ) nLoad4 = nLoad4*4;
150182
150183      if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
150184        /* Either this is the cheapest token in the entire query, or it is
150185        ** part of a multi-token phrase. Either way, the entire doclist will
150186        ** (eventually) be loaded into memory. It may as well be now. */
150187        Fts3PhraseToken *pToken = pTC->pToken;
150188        int nList = 0;
150189        char *pList = 0;
150190        rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
150191        assert( rc==SQLITE_OK || pList==0 );
150192        if( rc==SQLITE_OK ){
150193          rc = fts3EvalPhraseMergeToken(
150194              pTab, pTC->pPhrase, pTC->iToken,pList,nList
150195          );
150196        }
150197        if( rc==SQLITE_OK ){
150198          int nCount;
150199          nCount = fts3DoclistCountDocids(
150200              pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
150201          );
150202          if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
150203        }
150204      }
150205    }
150206    pTC->pToken = 0;
150207  }
150208
150209  return rc;
150210}
150211
150212/*
150213** This function is called from within the xFilter method. It initializes
150214** the full-text query currently stored in pCsr->pExpr. To iterate through
150215** the results of a query, the caller does:
150216**
150217**    fts3EvalStart(pCsr);
150218**    while( 1 ){
150219**      fts3EvalNext(pCsr);
150220**      if( pCsr->bEof ) break;
150221**      ... return row pCsr->iPrevId to the caller ...
150222**    }
150223*/
150224static int fts3EvalStart(Fts3Cursor *pCsr){
150225  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
150226  int rc = SQLITE_OK;
150227  int nToken = 0;
150228  int nOr = 0;
150229
150230  /* Allocate a MultiSegReader for each token in the expression. */
150231  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
150232
150233  /* Determine which, if any, tokens in the expression should be deferred. */
150234#ifndef SQLITE_DISABLE_FTS4_DEFERRED
150235  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
150236    Fts3TokenAndCost *aTC;
150237    Fts3Expr **apOr;
150238    aTC = (Fts3TokenAndCost *)sqlite3_malloc(
150239        sizeof(Fts3TokenAndCost) * nToken
150240      + sizeof(Fts3Expr *) * nOr * 2
150241    );
150242    apOr = (Fts3Expr **)&aTC[nToken];
150243
150244    if( !aTC ){
150245      rc = SQLITE_NOMEM;
150246    }else{
150247      int ii;
150248      Fts3TokenAndCost *pTC = aTC;
150249      Fts3Expr **ppOr = apOr;
150250
150251      fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
150252      nToken = (int)(pTC-aTC);
150253      nOr = (int)(ppOr-apOr);
150254
150255      if( rc==SQLITE_OK ){
150256        rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
150257        for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
150258          rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
150259        }
150260      }
150261
150262      sqlite3_free(aTC);
150263    }
150264  }
150265#endif
150266
150267  fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
150268  return rc;
150269}
150270
150271/*
150272** Invalidate the current position list for phrase pPhrase.
150273*/
150274static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
150275  if( pPhrase->doclist.bFreeList ){
150276    sqlite3_free(pPhrase->doclist.pList);
150277  }
150278  pPhrase->doclist.pList = 0;
150279  pPhrase->doclist.nList = 0;
150280  pPhrase->doclist.bFreeList = 0;
150281}
150282
150283/*
150284** This function is called to edit the position list associated with
150285** the phrase object passed as the fifth argument according to a NEAR
150286** condition. For example:
150287**
150288**     abc NEAR/5 "def ghi"
150289**
150290** Parameter nNear is passed the NEAR distance of the expression (5 in
150291** the example above). When this function is called, *paPoslist points to
150292** the position list, and *pnToken is the number of phrase tokens in, the
150293** phrase on the other side of the NEAR operator to pPhrase. For example,
150294** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
150295** the position list associated with phrase "abc".
150296**
150297** All positions in the pPhrase position list that are not sufficiently
150298** close to a position in the *paPoslist position list are removed. If this
150299** leaves 0 positions, zero is returned. Otherwise, non-zero.
150300**
150301** Before returning, *paPoslist is set to point to the position lsit
150302** associated with pPhrase. And *pnToken is set to the number of tokens in
150303** pPhrase.
150304*/
150305static int fts3EvalNearTrim(
150306  int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
150307  char *aTmp,                     /* Temporary space to use */
150308  char **paPoslist,               /* IN/OUT: Position list */
150309  int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
150310  Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
150311){
150312  int nParam1 = nNear + pPhrase->nToken;
150313  int nParam2 = nNear + *pnToken;
150314  int nNew;
150315  char *p2;
150316  char *pOut;
150317  int res;
150318
150319  assert( pPhrase->doclist.pList );
150320
150321  p2 = pOut = pPhrase->doclist.pList;
150322  res = fts3PoslistNearMerge(
150323    &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
150324  );
150325  if( res ){
150326    nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
150327    assert( pPhrase->doclist.pList[nNew]=='\0' );
150328    assert( nNew<=pPhrase->doclist.nList && nNew>0 );
150329    memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
150330    pPhrase->doclist.nList = nNew;
150331    *paPoslist = pPhrase->doclist.pList;
150332    *pnToken = pPhrase->nToken;
150333  }
150334
150335  return res;
150336}
150337
150338/*
150339** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
150340** Otherwise, it advances the expression passed as the second argument to
150341** point to the next matching row in the database. Expressions iterate through
150342** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
150343** or descending if it is non-zero.
150344**
150345** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
150346** successful, the following variables in pExpr are set:
150347**
150348**   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
150349**   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
150350**
150351** If the expression is of type FTSQUERY_PHRASE, and the expression is not
150352** at EOF, then the following variables are populated with the position list
150353** for the phrase for the visited row:
150354**
150355**   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
150356**   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
150357**
150358** It says above that this function advances the expression to the next
150359** matching row. This is usually true, but there are the following exceptions:
150360**
150361**   1. Deferred tokens are not taken into account. If a phrase consists
150362**      entirely of deferred tokens, it is assumed to match every row in
150363**      the db. In this case the position-list is not populated at all.
150364**
150365**      Or, if a phrase contains one or more deferred tokens and one or
150366**      more non-deferred tokens, then the expression is advanced to the
150367**      next possible match, considering only non-deferred tokens. In other
150368**      words, if the phrase is "A B C", and "B" is deferred, the expression
150369**      is advanced to the next row that contains an instance of "A * C",
150370**      where "*" may match any single token. The position list in this case
150371**      is populated as for "A * C" before returning.
150372**
150373**   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
150374**      advanced to point to the next row that matches "x AND y".
150375**
150376** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
150377** really a match, taking into account deferred tokens and NEAR operators.
150378*/
150379static void fts3EvalNextRow(
150380  Fts3Cursor *pCsr,               /* FTS Cursor handle */
150381  Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
150382  int *pRc                        /* IN/OUT: Error code */
150383){
150384  if( *pRc==SQLITE_OK ){
150385    int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
150386    assert( pExpr->bEof==0 );
150387    pExpr->bStart = 1;
150388
150389    switch( pExpr->eType ){
150390      case FTSQUERY_NEAR:
150391      case FTSQUERY_AND: {
150392        Fts3Expr *pLeft = pExpr->pLeft;
150393        Fts3Expr *pRight = pExpr->pRight;
150394        assert( !pLeft->bDeferred || !pRight->bDeferred );
150395
150396        if( pLeft->bDeferred ){
150397          /* LHS is entirely deferred. So we assume it matches every row.
150398          ** Advance the RHS iterator to find the next row visited. */
150399          fts3EvalNextRow(pCsr, pRight, pRc);
150400          pExpr->iDocid = pRight->iDocid;
150401          pExpr->bEof = pRight->bEof;
150402        }else if( pRight->bDeferred ){
150403          /* RHS is entirely deferred. So we assume it matches every row.
150404          ** Advance the LHS iterator to find the next row visited. */
150405          fts3EvalNextRow(pCsr, pLeft, pRc);
150406          pExpr->iDocid = pLeft->iDocid;
150407          pExpr->bEof = pLeft->bEof;
150408        }else{
150409          /* Neither the RHS or LHS are deferred. */
150410          fts3EvalNextRow(pCsr, pLeft, pRc);
150411          fts3EvalNextRow(pCsr, pRight, pRc);
150412          while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
150413            sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
150414            if( iDiff==0 ) break;
150415            if( iDiff<0 ){
150416              fts3EvalNextRow(pCsr, pLeft, pRc);
150417            }else{
150418              fts3EvalNextRow(pCsr, pRight, pRc);
150419            }
150420          }
150421          pExpr->iDocid = pLeft->iDocid;
150422          pExpr->bEof = (pLeft->bEof || pRight->bEof);
150423          if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
150424            if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
150425              Fts3Doclist *pDl = &pRight->pPhrase->doclist;
150426              while( *pRc==SQLITE_OK && pRight->bEof==0 ){
150427                memset(pDl->pList, 0, pDl->nList);
150428                fts3EvalNextRow(pCsr, pRight, pRc);
150429              }
150430            }
150431            if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
150432              Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
150433              while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
150434                memset(pDl->pList, 0, pDl->nList);
150435                fts3EvalNextRow(pCsr, pLeft, pRc);
150436              }
150437            }
150438          }
150439        }
150440        break;
150441      }
150442
150443      case FTSQUERY_OR: {
150444        Fts3Expr *pLeft = pExpr->pLeft;
150445        Fts3Expr *pRight = pExpr->pRight;
150446        sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
150447
150448        assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
150449        assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
150450
150451        if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
150452          fts3EvalNextRow(pCsr, pLeft, pRc);
150453        }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
150454          fts3EvalNextRow(pCsr, pRight, pRc);
150455        }else{
150456          fts3EvalNextRow(pCsr, pLeft, pRc);
150457          fts3EvalNextRow(pCsr, pRight, pRc);
150458        }
150459
150460        pExpr->bEof = (pLeft->bEof && pRight->bEof);
150461        iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
150462        if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
150463          pExpr->iDocid = pLeft->iDocid;
150464        }else{
150465          pExpr->iDocid = pRight->iDocid;
150466        }
150467
150468        break;
150469      }
150470
150471      case FTSQUERY_NOT: {
150472        Fts3Expr *pLeft = pExpr->pLeft;
150473        Fts3Expr *pRight = pExpr->pRight;
150474
150475        if( pRight->bStart==0 ){
150476          fts3EvalNextRow(pCsr, pRight, pRc);
150477          assert( *pRc!=SQLITE_OK || pRight->bStart );
150478        }
150479
150480        fts3EvalNextRow(pCsr, pLeft, pRc);
150481        if( pLeft->bEof==0 ){
150482          while( !*pRc
150483              && !pRight->bEof
150484              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
150485          ){
150486            fts3EvalNextRow(pCsr, pRight, pRc);
150487          }
150488        }
150489        pExpr->iDocid = pLeft->iDocid;
150490        pExpr->bEof = pLeft->bEof;
150491        break;
150492      }
150493
150494      default: {
150495        Fts3Phrase *pPhrase = pExpr->pPhrase;
150496        fts3EvalInvalidatePoslist(pPhrase);
150497        *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
150498        pExpr->iDocid = pPhrase->doclist.iDocid;
150499        break;
150500      }
150501    }
150502  }
150503}
150504
150505/*
150506** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
150507** cluster, then this function returns 1 immediately.
150508**
150509** Otherwise, it checks if the current row really does match the NEAR
150510** expression, using the data currently stored in the position lists
150511** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
150512**
150513** If the current row is a match, the position list associated with each
150514** phrase in the NEAR expression is edited in place to contain only those
150515** phrase instances sufficiently close to their peers to satisfy all NEAR
150516** constraints. In this case it returns 1. If the NEAR expression does not
150517** match the current row, 0 is returned. The position lists may or may not
150518** be edited if 0 is returned.
150519*/
150520static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
150521  int res = 1;
150522
150523  /* The following block runs if pExpr is the root of a NEAR query.
150524  ** For example, the query:
150525  **
150526  **         "w" NEAR "x" NEAR "y" NEAR "z"
150527  **
150528  ** which is represented in tree form as:
150529  **
150530  **                               |
150531  **                          +--NEAR--+      <-- root of NEAR query
150532  **                          |        |
150533  **                     +--NEAR--+   "z"
150534  **                     |        |
150535  **                +--NEAR--+   "y"
150536  **                |        |
150537  **               "w"      "x"
150538  **
150539  ** The right-hand child of a NEAR node is always a phrase. The
150540  ** left-hand child may be either a phrase or a NEAR node. There are
150541  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
150542  */
150543  if( *pRc==SQLITE_OK
150544   && pExpr->eType==FTSQUERY_NEAR
150545   && pExpr->bEof==0
150546   && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
150547  ){
150548    Fts3Expr *p;
150549    int nTmp = 0;                 /* Bytes of temp space */
150550    char *aTmp;                   /* Temp space for PoslistNearMerge() */
150551
150552    /* Allocate temporary working space. */
150553    for(p=pExpr; p->pLeft; p=p->pLeft){
150554      nTmp += p->pRight->pPhrase->doclist.nList;
150555    }
150556    nTmp += p->pPhrase->doclist.nList;
150557    if( nTmp==0 ){
150558      res = 0;
150559    }else{
150560      aTmp = sqlite3_malloc(nTmp*2);
150561      if( !aTmp ){
150562        *pRc = SQLITE_NOMEM;
150563        res = 0;
150564      }else{
150565        char *aPoslist = p->pPhrase->doclist.pList;
150566        int nToken = p->pPhrase->nToken;
150567
150568        for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
150569          Fts3Phrase *pPhrase = p->pRight->pPhrase;
150570          int nNear = p->nNear;
150571          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
150572        }
150573
150574        aPoslist = pExpr->pRight->pPhrase->doclist.pList;
150575        nToken = pExpr->pRight->pPhrase->nToken;
150576        for(p=pExpr->pLeft; p && res; p=p->pLeft){
150577          int nNear;
150578          Fts3Phrase *pPhrase;
150579          assert( p->pParent && p->pParent->pLeft==p );
150580          nNear = p->pParent->nNear;
150581          pPhrase = (
150582              p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
150583              );
150584          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
150585        }
150586      }
150587
150588      sqlite3_free(aTmp);
150589    }
150590  }
150591
150592  return res;
150593}
150594
150595/*
150596** This function is a helper function for sqlite3Fts3EvalTestDeferred().
150597** Assuming no error occurs or has occurred, It returns non-zero if the
150598** expression passed as the second argument matches the row that pCsr
150599** currently points to, or zero if it does not.
150600**
150601** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
150602** If an error occurs during execution of this function, *pRc is set to
150603** the appropriate SQLite error code. In this case the returned value is
150604** undefined.
150605*/
150606static int fts3EvalTestExpr(
150607  Fts3Cursor *pCsr,               /* FTS cursor handle */
150608  Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
150609  int *pRc                        /* IN/OUT: Error code */
150610){
150611  int bHit = 1;                   /* Return value */
150612  if( *pRc==SQLITE_OK ){
150613    switch( pExpr->eType ){
150614      case FTSQUERY_NEAR:
150615      case FTSQUERY_AND:
150616        bHit = (
150617            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
150618         && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
150619         && fts3EvalNearTest(pExpr, pRc)
150620        );
150621
150622        /* If the NEAR expression does not match any rows, zero the doclist for
150623        ** all phrases involved in the NEAR. This is because the snippet(),
150624        ** offsets() and matchinfo() functions are not supposed to recognize
150625        ** any instances of phrases that are part of unmatched NEAR queries.
150626        ** For example if this expression:
150627        **
150628        **    ... MATCH 'a OR (b NEAR c)'
150629        **
150630        ** is matched against a row containing:
150631        **
150632        **        'a b d e'
150633        **
150634        ** then any snippet() should ony highlight the "a" term, not the "b"
150635        ** (as "b" is part of a non-matching NEAR clause).
150636        */
150637        if( bHit==0
150638         && pExpr->eType==FTSQUERY_NEAR
150639         && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
150640        ){
150641          Fts3Expr *p;
150642          for(p=pExpr; p->pPhrase==0; p=p->pLeft){
150643            if( p->pRight->iDocid==pCsr->iPrevId ){
150644              fts3EvalInvalidatePoslist(p->pRight->pPhrase);
150645            }
150646          }
150647          if( p->iDocid==pCsr->iPrevId ){
150648            fts3EvalInvalidatePoslist(p->pPhrase);
150649          }
150650        }
150651
150652        break;
150653
150654      case FTSQUERY_OR: {
150655        int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
150656        int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
150657        bHit = bHit1 || bHit2;
150658        break;
150659      }
150660
150661      case FTSQUERY_NOT:
150662        bHit = (
150663            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
150664         && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
150665        );
150666        break;
150667
150668      default: {
150669#ifndef SQLITE_DISABLE_FTS4_DEFERRED
150670        if( pCsr->pDeferred
150671         && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
150672        ){
150673          Fts3Phrase *pPhrase = pExpr->pPhrase;
150674          assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
150675          if( pExpr->bDeferred ){
150676            fts3EvalInvalidatePoslist(pPhrase);
150677          }
150678          *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
150679          bHit = (pPhrase->doclist.pList!=0);
150680          pExpr->iDocid = pCsr->iPrevId;
150681        }else
150682#endif
150683        {
150684          bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
150685        }
150686        break;
150687      }
150688    }
150689  }
150690  return bHit;
150691}
150692
150693/*
150694** This function is called as the second part of each xNext operation when
150695** iterating through the results of a full-text query. At this point the
150696** cursor points to a row that matches the query expression, with the
150697** following caveats:
150698**
150699**   * Up until this point, "NEAR" operators in the expression have been
150700**     treated as "AND".
150701**
150702**   * Deferred tokens have not yet been considered.
150703**
150704** If *pRc is not SQLITE_OK when this function is called, it immediately
150705** returns 0. Otherwise, it tests whether or not after considering NEAR
150706** operators and deferred tokens the current row is still a match for the
150707** expression. It returns 1 if both of the following are true:
150708**
150709**   1. *pRc is SQLITE_OK when this function returns, and
150710**
150711**   2. After scanning the current FTS table row for the deferred tokens,
150712**      it is determined that the row does *not* match the query.
150713**
150714** Or, if no error occurs and it seems the current row does match the FTS
150715** query, return 0.
150716*/
150717SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
150718  int rc = *pRc;
150719  int bMiss = 0;
150720  if( rc==SQLITE_OK ){
150721
150722    /* If there are one or more deferred tokens, load the current row into
150723    ** memory and scan it to determine the position list for each deferred
150724    ** token. Then, see if this row is really a match, considering deferred
150725    ** tokens and NEAR operators (neither of which were taken into account
150726    ** earlier, by fts3EvalNextRow()).
150727    */
150728    if( pCsr->pDeferred ){
150729      rc = fts3CursorSeek(0, pCsr);
150730      if( rc==SQLITE_OK ){
150731        rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
150732      }
150733    }
150734    bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
150735
150736    /* Free the position-lists accumulated for each deferred token above. */
150737    sqlite3Fts3FreeDeferredDoclists(pCsr);
150738    *pRc = rc;
150739  }
150740  return (rc==SQLITE_OK && bMiss);
150741}
150742
150743/*
150744** Advance to the next document that matches the FTS expression in
150745** Fts3Cursor.pExpr.
150746*/
150747static int fts3EvalNext(Fts3Cursor *pCsr){
150748  int rc = SQLITE_OK;             /* Return Code */
150749  Fts3Expr *pExpr = pCsr->pExpr;
150750  assert( pCsr->isEof==0 );
150751  if( pExpr==0 ){
150752    pCsr->isEof = 1;
150753  }else{
150754    do {
150755      if( pCsr->isRequireSeek==0 ){
150756        sqlite3_reset(pCsr->pStmt);
150757      }
150758      assert( sqlite3_data_count(pCsr->pStmt)==0 );
150759      fts3EvalNextRow(pCsr, pExpr, &rc);
150760      pCsr->isEof = pExpr->bEof;
150761      pCsr->isRequireSeek = 1;
150762      pCsr->isMatchinfoNeeded = 1;
150763      pCsr->iPrevId = pExpr->iDocid;
150764    }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
150765  }
150766
150767  /* Check if the cursor is past the end of the docid range specified
150768  ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
150769  if( rc==SQLITE_OK && (
150770        (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
150771     || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
150772  )){
150773    pCsr->isEof = 1;
150774  }
150775
150776  return rc;
150777}
150778
150779/*
150780** Restart interation for expression pExpr so that the next call to
150781** fts3EvalNext() visits the first row. Do not allow incremental
150782** loading or merging of phrase doclists for this iteration.
150783**
150784** If *pRc is other than SQLITE_OK when this function is called, it is
150785** a no-op. If an error occurs within this function, *pRc is set to an
150786** SQLite error code before returning.
150787*/
150788static void fts3EvalRestart(
150789  Fts3Cursor *pCsr,
150790  Fts3Expr *pExpr,
150791  int *pRc
150792){
150793  if( pExpr && *pRc==SQLITE_OK ){
150794    Fts3Phrase *pPhrase = pExpr->pPhrase;
150795
150796    if( pPhrase ){
150797      fts3EvalInvalidatePoslist(pPhrase);
150798      if( pPhrase->bIncr ){
150799        int i;
150800        for(i=0; i<pPhrase->nToken; i++){
150801          Fts3PhraseToken *pToken = &pPhrase->aToken[i];
150802          assert( pToken->pDeferred==0 );
150803          if( pToken->pSegcsr ){
150804            sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
150805          }
150806        }
150807        *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
150808      }
150809      pPhrase->doclist.pNextDocid = 0;
150810      pPhrase->doclist.iDocid = 0;
150811      pPhrase->pOrPoslist = 0;
150812    }
150813
150814    pExpr->iDocid = 0;
150815    pExpr->bEof = 0;
150816    pExpr->bStart = 0;
150817
150818    fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
150819    fts3EvalRestart(pCsr, pExpr->pRight, pRc);
150820  }
150821}
150822
150823/*
150824** After allocating the Fts3Expr.aMI[] array for each phrase in the
150825** expression rooted at pExpr, the cursor iterates through all rows matched
150826** by pExpr, calling this function for each row. This function increments
150827** the values in Fts3Expr.aMI[] according to the position-list currently
150828** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
150829** expression nodes.
150830*/
150831static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
150832  if( pExpr ){
150833    Fts3Phrase *pPhrase = pExpr->pPhrase;
150834    if( pPhrase && pPhrase->doclist.pList ){
150835      int iCol = 0;
150836      char *p = pPhrase->doclist.pList;
150837
150838      assert( *p );
150839      while( 1 ){
150840        u8 c = 0;
150841        int iCnt = 0;
150842        while( 0xFE & (*p | c) ){
150843          if( (c&0x80)==0 ) iCnt++;
150844          c = *p++ & 0x80;
150845        }
150846
150847        /* aMI[iCol*3 + 1] = Number of occurrences
150848        ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
150849        */
150850        pExpr->aMI[iCol*3 + 1] += iCnt;
150851        pExpr->aMI[iCol*3 + 2] += (iCnt>0);
150852        if( *p==0x00 ) break;
150853        p++;
150854        p += fts3GetVarint32(p, &iCol);
150855      }
150856    }
150857
150858    fts3EvalUpdateCounts(pExpr->pLeft);
150859    fts3EvalUpdateCounts(pExpr->pRight);
150860  }
150861}
150862
150863/*
150864** Expression pExpr must be of type FTSQUERY_PHRASE.
150865**
150866** If it is not already allocated and populated, this function allocates and
150867** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
150868** of a NEAR expression, then it also allocates and populates the same array
150869** for all other phrases that are part of the NEAR expression.
150870**
150871** SQLITE_OK is returned if the aMI[] array is successfully allocated and
150872** populated. Otherwise, if an error occurs, an SQLite error code is returned.
150873*/
150874static int fts3EvalGatherStats(
150875  Fts3Cursor *pCsr,               /* Cursor object */
150876  Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
150877){
150878  int rc = SQLITE_OK;             /* Return code */
150879
150880  assert( pExpr->eType==FTSQUERY_PHRASE );
150881  if( pExpr->aMI==0 ){
150882    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
150883    Fts3Expr *pRoot;                /* Root of NEAR expression */
150884    Fts3Expr *p;                    /* Iterator used for several purposes */
150885
150886    sqlite3_int64 iPrevId = pCsr->iPrevId;
150887    sqlite3_int64 iDocid;
150888    u8 bEof;
150889
150890    /* Find the root of the NEAR expression */
150891    pRoot = pExpr;
150892    while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
150893      pRoot = pRoot->pParent;
150894    }
150895    iDocid = pRoot->iDocid;
150896    bEof = pRoot->bEof;
150897    assert( pRoot->bStart );
150898
150899    /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
150900    for(p=pRoot; p; p=p->pLeft){
150901      Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
150902      assert( pE->aMI==0 );
150903      pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
150904      if( !pE->aMI ) return SQLITE_NOMEM;
150905      memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
150906    }
150907
150908    fts3EvalRestart(pCsr, pRoot, &rc);
150909
150910    while( pCsr->isEof==0 && rc==SQLITE_OK ){
150911
150912      do {
150913        /* Ensure the %_content statement is reset. */
150914        if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
150915        assert( sqlite3_data_count(pCsr->pStmt)==0 );
150916
150917        /* Advance to the next document */
150918        fts3EvalNextRow(pCsr, pRoot, &rc);
150919        pCsr->isEof = pRoot->bEof;
150920        pCsr->isRequireSeek = 1;
150921        pCsr->isMatchinfoNeeded = 1;
150922        pCsr->iPrevId = pRoot->iDocid;
150923      }while( pCsr->isEof==0
150924           && pRoot->eType==FTSQUERY_NEAR
150925           && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
150926      );
150927
150928      if( rc==SQLITE_OK && pCsr->isEof==0 ){
150929        fts3EvalUpdateCounts(pRoot);
150930      }
150931    }
150932
150933    pCsr->isEof = 0;
150934    pCsr->iPrevId = iPrevId;
150935
150936    if( bEof ){
150937      pRoot->bEof = bEof;
150938    }else{
150939      /* Caution: pRoot may iterate through docids in ascending or descending
150940      ** order. For this reason, even though it seems more defensive, the
150941      ** do loop can not be written:
150942      **
150943      **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
150944      */
150945      fts3EvalRestart(pCsr, pRoot, &rc);
150946      do {
150947        fts3EvalNextRow(pCsr, pRoot, &rc);
150948        assert( pRoot->bEof==0 );
150949      }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
150950    }
150951  }
150952  return rc;
150953}
150954
150955/*
150956** This function is used by the matchinfo() module to query a phrase
150957** expression node for the following information:
150958**
150959**   1. The total number of occurrences of the phrase in each column of
150960**      the FTS table (considering all rows), and
150961**
150962**   2. For each column, the number of rows in the table for which the
150963**      column contains at least one instance of the phrase.
150964**
150965** If no error occurs, SQLITE_OK is returned and the values for each column
150966** written into the array aiOut as follows:
150967**
150968**   aiOut[iCol*3 + 1] = Number of occurrences
150969**   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
150970**
150971** Caveats:
150972**
150973**   * If a phrase consists entirely of deferred tokens, then all output
150974**     values are set to the number of documents in the table. In other
150975**     words we assume that very common tokens occur exactly once in each
150976**     column of each row of the table.
150977**
150978**   * If a phrase contains some deferred tokens (and some non-deferred
150979**     tokens), count the potential occurrence identified by considering
150980**     the non-deferred tokens instead of actual phrase occurrences.
150981**
150982**   * If the phrase is part of a NEAR expression, then only phrase instances
150983**     that meet the NEAR constraint are included in the counts.
150984*/
150985SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
150986  Fts3Cursor *pCsr,               /* FTS cursor handle */
150987  Fts3Expr *pExpr,                /* Phrase expression */
150988  u32 *aiOut                      /* Array to write results into (see above) */
150989){
150990  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
150991  int rc = SQLITE_OK;
150992  int iCol;
150993
150994  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
150995    assert( pCsr->nDoc>0 );
150996    for(iCol=0; iCol<pTab->nColumn; iCol++){
150997      aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
150998      aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
150999    }
151000  }else{
151001    rc = fts3EvalGatherStats(pCsr, pExpr);
151002    if( rc==SQLITE_OK ){
151003      assert( pExpr->aMI );
151004      for(iCol=0; iCol<pTab->nColumn; iCol++){
151005        aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
151006        aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
151007      }
151008    }
151009  }
151010
151011  return rc;
151012}
151013
151014/*
151015** The expression pExpr passed as the second argument to this function
151016** must be of type FTSQUERY_PHRASE.
151017**
151018** The returned value is either NULL or a pointer to a buffer containing
151019** a position-list indicating the occurrences of the phrase in column iCol
151020** of the current row.
151021**
151022** More specifically, the returned buffer contains 1 varint for each
151023** occurrence of the phrase in the column, stored using the normal (delta+2)
151024** compression and is terminated by either an 0x01 or 0x00 byte. For example,
151025** if the requested column contains "a b X c d X X" and the position-list
151026** for 'X' is requested, the buffer returned may contain:
151027**
151028**     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
151029**
151030** This function works regardless of whether or not the phrase is deferred,
151031** incremental, or neither.
151032*/
151033SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
151034  Fts3Cursor *pCsr,               /* FTS3 cursor object */
151035  Fts3Expr *pExpr,                /* Phrase to return doclist for */
151036  int iCol,                       /* Column to return position list for */
151037  char **ppOut                    /* OUT: Pointer to position list */
151038){
151039  Fts3Phrase *pPhrase = pExpr->pPhrase;
151040  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
151041  char *pIter;
151042  int iThis;
151043  sqlite3_int64 iDocid;
151044
151045  /* If this phrase is applies specifically to some column other than
151046  ** column iCol, return a NULL pointer.  */
151047  *ppOut = 0;
151048  assert( iCol>=0 && iCol<pTab->nColumn );
151049  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
151050    return SQLITE_OK;
151051  }
151052
151053  iDocid = pExpr->iDocid;
151054  pIter = pPhrase->doclist.pList;
151055  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
151056    int rc = SQLITE_OK;
151057    int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
151058    int bOr = 0;
151059    u8 bTreeEof = 0;
151060    Fts3Expr *p;                  /* Used to iterate from pExpr to root */
151061    Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
151062    int bMatch;
151063
151064    /* Check if this phrase descends from an OR expression node. If not,
151065    ** return NULL. Otherwise, the entry that corresponds to docid
151066    ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
151067    ** tree that the node is part of has been marked as EOF, but the node
151068    ** itself is not EOF, then it may point to an earlier entry. */
151069    pNear = pExpr;
151070    for(p=pExpr->pParent; p; p=p->pParent){
151071      if( p->eType==FTSQUERY_OR ) bOr = 1;
151072      if( p->eType==FTSQUERY_NEAR ) pNear = p;
151073      if( p->bEof ) bTreeEof = 1;
151074    }
151075    if( bOr==0 ) return SQLITE_OK;
151076
151077    /* This is the descendent of an OR node. In this case we cannot use
151078    ** an incremental phrase. Load the entire doclist for the phrase
151079    ** into memory in this case.  */
151080    if( pPhrase->bIncr ){
151081      int bEofSave = pNear->bEof;
151082      fts3EvalRestart(pCsr, pNear, &rc);
151083      while( rc==SQLITE_OK && !pNear->bEof ){
151084        fts3EvalNextRow(pCsr, pNear, &rc);
151085        if( bEofSave==0 && pNear->iDocid==iDocid ) break;
151086      }
151087      assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
151088    }
151089    if( bTreeEof ){
151090      while( rc==SQLITE_OK && !pNear->bEof ){
151091        fts3EvalNextRow(pCsr, pNear, &rc);
151092      }
151093    }
151094    if( rc!=SQLITE_OK ) return rc;
151095
151096    bMatch = 1;
151097    for(p=pNear; p; p=p->pLeft){
151098      u8 bEof = 0;
151099      Fts3Expr *pTest = p;
151100      Fts3Phrase *pPh;
151101      assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
151102      if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
151103      assert( pTest->eType==FTSQUERY_PHRASE );
151104      pPh = pTest->pPhrase;
151105
151106      pIter = pPh->pOrPoslist;
151107      iDocid = pPh->iOrDocid;
151108      if( pCsr->bDesc==bDescDoclist ){
151109        bEof = !pPh->doclist.nAll ||
151110          (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
151111        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
151112          sqlite3Fts3DoclistNext(
151113              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
151114              &pIter, &iDocid, &bEof
151115          );
151116        }
151117      }else{
151118        bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
151119        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
151120          int dummy;
151121          sqlite3Fts3DoclistPrev(
151122              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
151123              &pIter, &iDocid, &dummy, &bEof
151124              );
151125        }
151126      }
151127      pPh->pOrPoslist = pIter;
151128      pPh->iOrDocid = iDocid;
151129      if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
151130    }
151131
151132    if( bMatch ){
151133      pIter = pPhrase->pOrPoslist;
151134    }else{
151135      pIter = 0;
151136    }
151137  }
151138  if( pIter==0 ) return SQLITE_OK;
151139
151140  if( *pIter==0x01 ){
151141    pIter++;
151142    pIter += fts3GetVarint32(pIter, &iThis);
151143  }else{
151144    iThis = 0;
151145  }
151146  while( iThis<iCol ){
151147    fts3ColumnlistCopy(0, &pIter);
151148    if( *pIter==0x00 ) return SQLITE_OK;
151149    pIter++;
151150    pIter += fts3GetVarint32(pIter, &iThis);
151151  }
151152  if( *pIter==0x00 ){
151153    pIter = 0;
151154  }
151155
151156  *ppOut = ((iCol==iThis)?pIter:0);
151157  return SQLITE_OK;
151158}
151159
151160/*
151161** Free all components of the Fts3Phrase structure that were allocated by
151162** the eval module. Specifically, this means to free:
151163**
151164**   * the contents of pPhrase->doclist, and
151165**   * any Fts3MultiSegReader objects held by phrase tokens.
151166*/
151167SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
151168  if( pPhrase ){
151169    int i;
151170    sqlite3_free(pPhrase->doclist.aAll);
151171    fts3EvalInvalidatePoslist(pPhrase);
151172    memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
151173    for(i=0; i<pPhrase->nToken; i++){
151174      fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
151175      pPhrase->aToken[i].pSegcsr = 0;
151176    }
151177  }
151178}
151179
151180
151181/*
151182** Return SQLITE_CORRUPT_VTAB.
151183*/
151184#ifdef SQLITE_DEBUG
151185SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
151186  return SQLITE_CORRUPT_VTAB;
151187}
151188#endif
151189
151190#if !SQLITE_CORE
151191/*
151192** Initialize API pointer table, if required.
151193*/
151194#ifdef _WIN32
151195__declspec(dllexport)
151196#endif
151197SQLITE_API int sqlite3_fts3_init(
151198  sqlite3 *db,
151199  char **pzErrMsg,
151200  const sqlite3_api_routines *pApi
151201){
151202  SQLITE_EXTENSION_INIT2(pApi)
151203  return sqlite3Fts3Init(db);
151204}
151205#endif
151206
151207#endif
151208
151209/************** End of fts3.c ************************************************/
151210/************** Begin file fts3_aux.c ****************************************/
151211/*
151212** 2011 Jan 27
151213**
151214** The author disclaims copyright to this source code.  In place of
151215** a legal notice, here is a blessing:
151216**
151217**    May you do good and not evil.
151218**    May you find forgiveness for yourself and forgive others.
151219**    May you share freely, never taking more than you give.
151220**
151221******************************************************************************
151222**
151223*/
151224/* #include "fts3Int.h" */
151225#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151226
151227/* #include <string.h> */
151228/* #include <assert.h> */
151229
151230typedef struct Fts3auxTable Fts3auxTable;
151231typedef struct Fts3auxCursor Fts3auxCursor;
151232
151233struct Fts3auxTable {
151234  sqlite3_vtab base;              /* Base class used by SQLite core */
151235  Fts3Table *pFts3Tab;
151236};
151237
151238struct Fts3auxCursor {
151239  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
151240  Fts3MultiSegReader csr;        /* Must be right after "base" */
151241  Fts3SegFilter filter;
151242  char *zStop;
151243  int nStop;                      /* Byte-length of string zStop */
151244  int iLangid;                    /* Language id to query */
151245  int isEof;                      /* True if cursor is at EOF */
151246  sqlite3_int64 iRowid;           /* Current rowid */
151247
151248  int iCol;                       /* Current value of 'col' column */
151249  int nStat;                      /* Size of aStat[] array */
151250  struct Fts3auxColstats {
151251    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
151252    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
151253  } *aStat;
151254};
151255
151256/*
151257** Schema of the terms table.
151258*/
151259#define FTS3_AUX_SCHEMA \
151260  "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
151261
151262/*
151263** This function does all the work for both the xConnect and xCreate methods.
151264** These tables have no persistent representation of their own, so xConnect
151265** and xCreate are identical operations.
151266*/
151267static int fts3auxConnectMethod(
151268  sqlite3 *db,                    /* Database connection */
151269  void *pUnused,                  /* Unused */
151270  int argc,                       /* Number of elements in argv array */
151271  const char * const *argv,       /* xCreate/xConnect argument array */
151272  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
151273  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
151274){
151275  char const *zDb;                /* Name of database (e.g. "main") */
151276  char const *zFts3;              /* Name of fts3 table */
151277  int nDb;                        /* Result of strlen(zDb) */
151278  int nFts3;                      /* Result of strlen(zFts3) */
151279  int nByte;                      /* Bytes of space to allocate here */
151280  int rc;                         /* value returned by declare_vtab() */
151281  Fts3auxTable *p;                /* Virtual table object to return */
151282
151283  UNUSED_PARAMETER(pUnused);
151284
151285  /* The user should invoke this in one of two forms:
151286  **
151287  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
151288  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
151289  */
151290  if( argc!=4 && argc!=5 ) goto bad_args;
151291
151292  zDb = argv[1];
151293  nDb = (int)strlen(zDb);
151294  if( argc==5 ){
151295    if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
151296      zDb = argv[3];
151297      nDb = (int)strlen(zDb);
151298      zFts3 = argv[4];
151299    }else{
151300      goto bad_args;
151301    }
151302  }else{
151303    zFts3 = argv[3];
151304  }
151305  nFts3 = (int)strlen(zFts3);
151306
151307  rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
151308  if( rc!=SQLITE_OK ) return rc;
151309
151310  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
151311  p = (Fts3auxTable *)sqlite3_malloc(nByte);
151312  if( !p ) return SQLITE_NOMEM;
151313  memset(p, 0, nByte);
151314
151315  p->pFts3Tab = (Fts3Table *)&p[1];
151316  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
151317  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
151318  p->pFts3Tab->db = db;
151319  p->pFts3Tab->nIndex = 1;
151320
151321  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
151322  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
151323  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
151324
151325  *ppVtab = (sqlite3_vtab *)p;
151326  return SQLITE_OK;
151327
151328 bad_args:
151329  sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
151330  return SQLITE_ERROR;
151331}
151332
151333/*
151334** This function does the work for both the xDisconnect and xDestroy methods.
151335** These tables have no persistent representation of their own, so xDisconnect
151336** and xDestroy are identical operations.
151337*/
151338static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
151339  Fts3auxTable *p = (Fts3auxTable *)pVtab;
151340  Fts3Table *pFts3 = p->pFts3Tab;
151341  int i;
151342
151343  /* Free any prepared statements held */
151344  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
151345    sqlite3_finalize(pFts3->aStmt[i]);
151346  }
151347  sqlite3_free(pFts3->zSegmentsTbl);
151348  sqlite3_free(p);
151349  return SQLITE_OK;
151350}
151351
151352#define FTS4AUX_EQ_CONSTRAINT 1
151353#define FTS4AUX_GE_CONSTRAINT 2
151354#define FTS4AUX_LE_CONSTRAINT 4
151355
151356/*
151357** xBestIndex - Analyze a WHERE and ORDER BY clause.
151358*/
151359static int fts3auxBestIndexMethod(
151360  sqlite3_vtab *pVTab,
151361  sqlite3_index_info *pInfo
151362){
151363  int i;
151364  int iEq = -1;
151365  int iGe = -1;
151366  int iLe = -1;
151367  int iLangid = -1;
151368  int iNext = 1;                  /* Next free argvIndex value */
151369
151370  UNUSED_PARAMETER(pVTab);
151371
151372  /* This vtab delivers always results in "ORDER BY term ASC" order. */
151373  if( pInfo->nOrderBy==1
151374   && pInfo->aOrderBy[0].iColumn==0
151375   && pInfo->aOrderBy[0].desc==0
151376  ){
151377    pInfo->orderByConsumed = 1;
151378  }
151379
151380  /* Search for equality and range constraints on the "term" column.
151381  ** And equality constraints on the hidden "languageid" column. */
151382  for(i=0; i<pInfo->nConstraint; i++){
151383    if( pInfo->aConstraint[i].usable ){
151384      int op = pInfo->aConstraint[i].op;
151385      int iCol = pInfo->aConstraint[i].iColumn;
151386
151387      if( iCol==0 ){
151388        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
151389        if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
151390        if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
151391        if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
151392        if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
151393      }
151394      if( iCol==4 ){
151395        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
151396      }
151397    }
151398  }
151399
151400  if( iEq>=0 ){
151401    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
151402    pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
151403    pInfo->estimatedCost = 5;
151404  }else{
151405    pInfo->idxNum = 0;
151406    pInfo->estimatedCost = 20000;
151407    if( iGe>=0 ){
151408      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
151409      pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
151410      pInfo->estimatedCost /= 2;
151411    }
151412    if( iLe>=0 ){
151413      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
151414      pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
151415      pInfo->estimatedCost /= 2;
151416    }
151417  }
151418  if( iLangid>=0 ){
151419    pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
151420    pInfo->estimatedCost--;
151421  }
151422
151423  return SQLITE_OK;
151424}
151425
151426/*
151427** xOpen - Open a cursor.
151428*/
151429static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
151430  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
151431
151432  UNUSED_PARAMETER(pVTab);
151433
151434  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
151435  if( !pCsr ) return SQLITE_NOMEM;
151436  memset(pCsr, 0, sizeof(Fts3auxCursor));
151437
151438  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
151439  return SQLITE_OK;
151440}
151441
151442/*
151443** xClose - Close a cursor.
151444*/
151445static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
151446  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
151447  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
151448
151449  sqlite3Fts3SegmentsClose(pFts3);
151450  sqlite3Fts3SegReaderFinish(&pCsr->csr);
151451  sqlite3_free((void *)pCsr->filter.zTerm);
151452  sqlite3_free(pCsr->zStop);
151453  sqlite3_free(pCsr->aStat);
151454  sqlite3_free(pCsr);
151455  return SQLITE_OK;
151456}
151457
151458static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
151459  if( nSize>pCsr->nStat ){
151460    struct Fts3auxColstats *aNew;
151461    aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
151462        sizeof(struct Fts3auxColstats) * nSize
151463    );
151464    if( aNew==0 ) return SQLITE_NOMEM;
151465    memset(&aNew[pCsr->nStat], 0,
151466        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
151467    );
151468    pCsr->aStat = aNew;
151469    pCsr->nStat = nSize;
151470  }
151471  return SQLITE_OK;
151472}
151473
151474/*
151475** xNext - Advance the cursor to the next row, if any.
151476*/
151477static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
151478  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
151479  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
151480  int rc;
151481
151482  /* Increment our pretend rowid value. */
151483  pCsr->iRowid++;
151484
151485  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
151486    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
151487  }
151488
151489  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
151490  if( rc==SQLITE_ROW ){
151491    int i = 0;
151492    int nDoclist = pCsr->csr.nDoclist;
151493    char *aDoclist = pCsr->csr.aDoclist;
151494    int iCol;
151495
151496    int eState = 0;
151497
151498    if( pCsr->zStop ){
151499      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
151500      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
151501      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
151502        pCsr->isEof = 1;
151503        return SQLITE_OK;
151504      }
151505    }
151506
151507    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
151508    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
151509    iCol = 0;
151510
151511    while( i<nDoclist ){
151512      sqlite3_int64 v = 0;
151513
151514      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
151515      switch( eState ){
151516        /* State 0. In this state the integer just read was a docid. */
151517        case 0:
151518          pCsr->aStat[0].nDoc++;
151519          eState = 1;
151520          iCol = 0;
151521          break;
151522
151523        /* State 1. In this state we are expecting either a 1, indicating
151524        ** that the following integer will be a column number, or the
151525        ** start of a position list for column 0.
151526        **
151527        ** The only difference between state 1 and state 2 is that if the
151528        ** integer encountered in state 1 is not 0 or 1, then we need to
151529        ** increment the column 0 "nDoc" count for this term.
151530        */
151531        case 1:
151532          assert( iCol==0 );
151533          if( v>1 ){
151534            pCsr->aStat[1].nDoc++;
151535          }
151536          eState = 2;
151537          /* fall through */
151538
151539        case 2:
151540          if( v==0 ){       /* 0x00. Next integer will be a docid. */
151541            eState = 0;
151542          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
151543            eState = 3;
151544          }else{            /* 2 or greater. A position. */
151545            pCsr->aStat[iCol+1].nOcc++;
151546            pCsr->aStat[0].nOcc++;
151547          }
151548          break;
151549
151550        /* State 3. The integer just read is a column number. */
151551        default: assert( eState==3 );
151552          iCol = (int)v;
151553          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
151554          pCsr->aStat[iCol+1].nDoc++;
151555          eState = 2;
151556          break;
151557      }
151558    }
151559
151560    pCsr->iCol = 0;
151561    rc = SQLITE_OK;
151562  }else{
151563    pCsr->isEof = 1;
151564  }
151565  return rc;
151566}
151567
151568/*
151569** xFilter - Initialize a cursor to point at the start of its data.
151570*/
151571static int fts3auxFilterMethod(
151572  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
151573  int idxNum,                     /* Strategy index */
151574  const char *idxStr,             /* Unused */
151575  int nVal,                       /* Number of elements in apVal */
151576  sqlite3_value **apVal           /* Arguments for the indexing scheme */
151577){
151578  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
151579  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
151580  int rc;
151581  int isScan = 0;
151582  int iLangVal = 0;               /* Language id to query */
151583
151584  int iEq = -1;                   /* Index of term=? value in apVal */
151585  int iGe = -1;                   /* Index of term>=? value in apVal */
151586  int iLe = -1;                   /* Index of term<=? value in apVal */
151587  int iLangid = -1;               /* Index of languageid=? value in apVal */
151588  int iNext = 0;
151589
151590  UNUSED_PARAMETER(nVal);
151591  UNUSED_PARAMETER(idxStr);
151592
151593  assert( idxStr==0 );
151594  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
151595       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
151596       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
151597  );
151598
151599  if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
151600    iEq = iNext++;
151601  }else{
151602    isScan = 1;
151603    if( idxNum & FTS4AUX_GE_CONSTRAINT ){
151604      iGe = iNext++;
151605    }
151606    if( idxNum & FTS4AUX_LE_CONSTRAINT ){
151607      iLe = iNext++;
151608    }
151609  }
151610  if( iNext<nVal ){
151611    iLangid = iNext++;
151612  }
151613
151614  /* In case this cursor is being reused, close and zero it. */
151615  testcase(pCsr->filter.zTerm);
151616  sqlite3Fts3SegReaderFinish(&pCsr->csr);
151617  sqlite3_free((void *)pCsr->filter.zTerm);
151618  sqlite3_free(pCsr->aStat);
151619  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
151620
151621  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
151622  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
151623
151624  if( iEq>=0 || iGe>=0 ){
151625    const unsigned char *zStr = sqlite3_value_text(apVal[0]);
151626    assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
151627    if( zStr ){
151628      pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
151629      pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
151630      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
151631    }
151632  }
151633
151634  if( iLe>=0 ){
151635    pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
151636    pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
151637    if( pCsr->zStop==0 ) return SQLITE_NOMEM;
151638  }
151639
151640  if( iLangid>=0 ){
151641    iLangVal = sqlite3_value_int(apVal[iLangid]);
151642
151643    /* If the user specified a negative value for the languageid, use zero
151644    ** instead. This works, as the "languageid=?" constraint will also
151645    ** be tested by the VDBE layer. The test will always be false (since
151646    ** this module will not return a row with a negative languageid), and
151647    ** so the overall query will return zero rows.  */
151648    if( iLangVal<0 ) iLangVal = 0;
151649  }
151650  pCsr->iLangid = iLangVal;
151651
151652  rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
151653      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
151654  );
151655  if( rc==SQLITE_OK ){
151656    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
151657  }
151658
151659  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
151660  return rc;
151661}
151662
151663/*
151664** xEof - Return true if the cursor is at EOF, or false otherwise.
151665*/
151666static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
151667  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
151668  return pCsr->isEof;
151669}
151670
151671/*
151672** xColumn - Return a column value.
151673*/
151674static int fts3auxColumnMethod(
151675  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
151676  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
151677  int iCol                        /* Index of column to read value from */
151678){
151679  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
151680
151681  assert( p->isEof==0 );
151682  switch( iCol ){
151683    case 0: /* term */
151684      sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
151685      break;
151686
151687    case 1: /* col */
151688      if( p->iCol ){
151689        sqlite3_result_int(pCtx, p->iCol-1);
151690      }else{
151691        sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
151692      }
151693      break;
151694
151695    case 2: /* documents */
151696      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
151697      break;
151698
151699    case 3: /* occurrences */
151700      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
151701      break;
151702
151703    default: /* languageid */
151704      assert( iCol==4 );
151705      sqlite3_result_int(pCtx, p->iLangid);
151706      break;
151707  }
151708
151709  return SQLITE_OK;
151710}
151711
151712/*
151713** xRowid - Return the current rowid for the cursor.
151714*/
151715static int fts3auxRowidMethod(
151716  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
151717  sqlite_int64 *pRowid            /* OUT: Rowid value */
151718){
151719  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
151720  *pRowid = pCsr->iRowid;
151721  return SQLITE_OK;
151722}
151723
151724/*
151725** Register the fts3aux module with database connection db. Return SQLITE_OK
151726** if successful or an error code if sqlite3_create_module() fails.
151727*/
151728SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
151729  static const sqlite3_module fts3aux_module = {
151730     0,                           /* iVersion      */
151731     fts3auxConnectMethod,        /* xCreate       */
151732     fts3auxConnectMethod,        /* xConnect      */
151733     fts3auxBestIndexMethod,      /* xBestIndex    */
151734     fts3auxDisconnectMethod,     /* xDisconnect   */
151735     fts3auxDisconnectMethod,     /* xDestroy      */
151736     fts3auxOpenMethod,           /* xOpen         */
151737     fts3auxCloseMethod,          /* xClose        */
151738     fts3auxFilterMethod,         /* xFilter       */
151739     fts3auxNextMethod,           /* xNext         */
151740     fts3auxEofMethod,            /* xEof          */
151741     fts3auxColumnMethod,         /* xColumn       */
151742     fts3auxRowidMethod,          /* xRowid        */
151743     0,                           /* xUpdate       */
151744     0,                           /* xBegin        */
151745     0,                           /* xSync         */
151746     0,                           /* xCommit       */
151747     0,                           /* xRollback     */
151748     0,                           /* xFindFunction */
151749     0,                           /* xRename       */
151750     0,                           /* xSavepoint    */
151751     0,                           /* xRelease      */
151752     0                            /* xRollbackTo   */
151753  };
151754  int rc;                         /* Return code */
151755
151756  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
151757  return rc;
151758}
151759
151760#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151761
151762/************** End of fts3_aux.c ********************************************/
151763/************** Begin file fts3_expr.c ***************************************/
151764/*
151765** 2008 Nov 28
151766**
151767** The author disclaims copyright to this source code.  In place of
151768** a legal notice, here is a blessing:
151769**
151770**    May you do good and not evil.
151771**    May you find forgiveness for yourself and forgive others.
151772**    May you share freely, never taking more than you give.
151773**
151774******************************************************************************
151775**
151776** This module contains code that implements a parser for fts3 query strings
151777** (the right-hand argument to the MATCH operator). Because the supported
151778** syntax is relatively simple, the whole tokenizer/parser system is
151779** hand-coded.
151780*/
151781/* #include "fts3Int.h" */
151782#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151783
151784/*
151785** By default, this module parses the legacy syntax that has been
151786** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
151787** is defined, then it uses the new syntax. The differences between
151788** the new and the old syntaxes are:
151789**
151790**  a) The new syntax supports parenthesis. The old does not.
151791**
151792**  b) The new syntax supports the AND and NOT operators. The old does not.
151793**
151794**  c) The old syntax supports the "-" token qualifier. This is not
151795**     supported by the new syntax (it is replaced by the NOT operator).
151796**
151797**  d) When using the old syntax, the OR operator has a greater precedence
151798**     than an implicit AND. When using the new, both implicity and explicit
151799**     AND operators have a higher precedence than OR.
151800**
151801** If compiled with SQLITE_TEST defined, then this module exports the
151802** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
151803** to zero causes the module to use the old syntax. If it is set to
151804** non-zero the new syntax is activated. This is so both syntaxes can
151805** be tested using a single build of testfixture.
151806**
151807** The following describes the syntax supported by the fts3 MATCH
151808** operator in a similar format to that used by the lemon parser
151809** generator. This module does not use actually lemon, it uses a
151810** custom parser.
151811**
151812**   query ::= andexpr (OR andexpr)*.
151813**
151814**   andexpr ::= notexpr (AND? notexpr)*.
151815**
151816**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
151817**   notexpr ::= LP query RP.
151818**
151819**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
151820**
151821**   distance_opt ::= .
151822**   distance_opt ::= / INTEGER.
151823**
151824**   phrase ::= TOKEN.
151825**   phrase ::= COLUMN:TOKEN.
151826**   phrase ::= "TOKEN TOKEN TOKEN...".
151827*/
151828
151829#ifdef SQLITE_TEST
151830SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
151831#else
151832# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
151833#  define sqlite3_fts3_enable_parentheses 1
151834# else
151835#  define sqlite3_fts3_enable_parentheses 0
151836# endif
151837#endif
151838
151839/*
151840** Default span for NEAR operators.
151841*/
151842#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
151843
151844/* #include <string.h> */
151845/* #include <assert.h> */
151846
151847/*
151848** isNot:
151849**   This variable is used by function getNextNode(). When getNextNode() is
151850**   called, it sets ParseContext.isNot to true if the 'next node' is a
151851**   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
151852**   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
151853**   zero.
151854*/
151855typedef struct ParseContext ParseContext;
151856struct ParseContext {
151857  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
151858  int iLangid;                        /* Language id used with tokenizer */
151859  const char **azCol;                 /* Array of column names for fts3 table */
151860  int bFts4;                          /* True to allow FTS4-only syntax */
151861  int nCol;                           /* Number of entries in azCol[] */
151862  int iDefaultCol;                    /* Default column to query */
151863  int isNot;                          /* True if getNextNode() sees a unary - */
151864  sqlite3_context *pCtx;              /* Write error message here */
151865  int nNest;                          /* Number of nested brackets */
151866};
151867
151868/*
151869** This function is equivalent to the standard isspace() function.
151870**
151871** The standard isspace() can be awkward to use safely, because although it
151872** is defined to accept an argument of type int, its behavior when passed
151873** an integer that falls outside of the range of the unsigned char type
151874** is undefined (and sometimes, "undefined" means segfault). This wrapper
151875** is defined to accept an argument of type char, and always returns 0 for
151876** any values that fall outside of the range of the unsigned char type (i.e.
151877** negative values).
151878*/
151879static int fts3isspace(char c){
151880  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
151881}
151882
151883/*
151884** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
151885** zero the memory before returning a pointer to it. If unsuccessful,
151886** return NULL.
151887*/
151888static void *fts3MallocZero(int nByte){
151889  void *pRet = sqlite3_malloc(nByte);
151890  if( pRet ) memset(pRet, 0, nByte);
151891  return pRet;
151892}
151893
151894SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
151895  sqlite3_tokenizer *pTokenizer,
151896  int iLangid,
151897  const char *z,
151898  int n,
151899  sqlite3_tokenizer_cursor **ppCsr
151900){
151901  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
151902  sqlite3_tokenizer_cursor *pCsr = 0;
151903  int rc;
151904
151905  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
151906  assert( rc==SQLITE_OK || pCsr==0 );
151907  if( rc==SQLITE_OK ){
151908    pCsr->pTokenizer = pTokenizer;
151909    if( pModule->iVersion>=1 ){
151910      rc = pModule->xLanguageid(pCsr, iLangid);
151911      if( rc!=SQLITE_OK ){
151912        pModule->xClose(pCsr);
151913        pCsr = 0;
151914      }
151915    }
151916  }
151917  *ppCsr = pCsr;
151918  return rc;
151919}
151920
151921/*
151922** Function getNextNode(), which is called by fts3ExprParse(), may itself
151923** call fts3ExprParse(). So this forward declaration is required.
151924*/
151925static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
151926
151927/*
151928** Extract the next token from buffer z (length n) using the tokenizer
151929** and other information (column names etc.) in pParse. Create an Fts3Expr
151930** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
151931** single token and set *ppExpr to point to it. If the end of the buffer is
151932** reached before a token is found, set *ppExpr to zero. It is the
151933** responsibility of the caller to eventually deallocate the allocated
151934** Fts3Expr structure (if any) by passing it to sqlite3_free().
151935**
151936** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
151937** fails.
151938*/
151939static int getNextToken(
151940  ParseContext *pParse,                   /* fts3 query parse context */
151941  int iCol,                               /* Value for Fts3Phrase.iColumn */
151942  const char *z, int n,                   /* Input string */
151943  Fts3Expr **ppExpr,                      /* OUT: expression */
151944  int *pnConsumed                         /* OUT: Number of bytes consumed */
151945){
151946  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
151947  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
151948  int rc;
151949  sqlite3_tokenizer_cursor *pCursor;
151950  Fts3Expr *pRet = 0;
151951  int i = 0;
151952
151953  /* Set variable i to the maximum number of bytes of input to tokenize. */
151954  for(i=0; i<n; i++){
151955    if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
151956    if( z[i]=='"' ) break;
151957  }
151958
151959  *pnConsumed = i;
151960  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
151961  if( rc==SQLITE_OK ){
151962    const char *zToken;
151963    int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
151964    int nByte;                               /* total space to allocate */
151965
151966    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
151967    if( rc==SQLITE_OK ){
151968      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
151969      pRet = (Fts3Expr *)fts3MallocZero(nByte);
151970      if( !pRet ){
151971        rc = SQLITE_NOMEM;
151972      }else{
151973        pRet->eType = FTSQUERY_PHRASE;
151974        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
151975        pRet->pPhrase->nToken = 1;
151976        pRet->pPhrase->iColumn = iCol;
151977        pRet->pPhrase->aToken[0].n = nToken;
151978        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
151979        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
151980
151981        if( iEnd<n && z[iEnd]=='*' ){
151982          pRet->pPhrase->aToken[0].isPrefix = 1;
151983          iEnd++;
151984        }
151985
151986        while( 1 ){
151987          if( !sqlite3_fts3_enable_parentheses
151988           && iStart>0 && z[iStart-1]=='-'
151989          ){
151990            pParse->isNot = 1;
151991            iStart--;
151992          }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
151993            pRet->pPhrase->aToken[0].bFirst = 1;
151994            iStart--;
151995          }else{
151996            break;
151997          }
151998        }
151999
152000      }
152001      *pnConsumed = iEnd;
152002    }else if( i && rc==SQLITE_DONE ){
152003      rc = SQLITE_OK;
152004    }
152005
152006    pModule->xClose(pCursor);
152007  }
152008
152009  *ppExpr = pRet;
152010  return rc;
152011}
152012
152013
152014/*
152015** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
152016** then free the old allocation.
152017*/
152018static void *fts3ReallocOrFree(void *pOrig, int nNew){
152019  void *pRet = sqlite3_realloc(pOrig, nNew);
152020  if( !pRet ){
152021    sqlite3_free(pOrig);
152022  }
152023  return pRet;
152024}
152025
152026/*
152027** Buffer zInput, length nInput, contains the contents of a quoted string
152028** that appeared as part of an fts3 query expression. Neither quote character
152029** is included in the buffer. This function attempts to tokenize the entire
152030** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
152031** containing the results.
152032**
152033** If successful, SQLITE_OK is returned and *ppExpr set to point at the
152034** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
152035** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
152036** to 0.
152037*/
152038static int getNextString(
152039  ParseContext *pParse,                   /* fts3 query parse context */
152040  const char *zInput, int nInput,         /* Input string */
152041  Fts3Expr **ppExpr                       /* OUT: expression */
152042){
152043  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
152044  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
152045  int rc;
152046  Fts3Expr *p = 0;
152047  sqlite3_tokenizer_cursor *pCursor = 0;
152048  char *zTemp = 0;
152049  int nTemp = 0;
152050
152051  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
152052  int nToken = 0;
152053
152054  /* The final Fts3Expr data structure, including the Fts3Phrase,
152055  ** Fts3PhraseToken structures token buffers are all stored as a single
152056  ** allocation so that the expression can be freed with a single call to
152057  ** sqlite3_free(). Setting this up requires a two pass approach.
152058  **
152059  ** The first pass, in the block below, uses a tokenizer cursor to iterate
152060  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
152061  ** to assemble data in two dynamic buffers:
152062  **
152063  **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
152064  **             structure, followed by the array of Fts3PhraseToken
152065  **             structures. This pass only populates the Fts3PhraseToken array.
152066  **
152067  **   Buffer zTemp: Contains copies of all tokens.
152068  **
152069  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
152070  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
152071  ** structures.
152072  */
152073  rc = sqlite3Fts3OpenTokenizer(
152074      pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
152075  if( rc==SQLITE_OK ){
152076    int ii;
152077    for(ii=0; rc==SQLITE_OK; ii++){
152078      const char *zByte;
152079      int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
152080      rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
152081      if( rc==SQLITE_OK ){
152082        Fts3PhraseToken *pToken;
152083
152084        p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
152085        if( !p ) goto no_mem;
152086
152087        zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
152088        if( !zTemp ) goto no_mem;
152089
152090        assert( nToken==ii );
152091        pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
152092        memset(pToken, 0, sizeof(Fts3PhraseToken));
152093
152094        memcpy(&zTemp[nTemp], zByte, nByte);
152095        nTemp += nByte;
152096
152097        pToken->n = nByte;
152098        pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
152099        pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
152100        nToken = ii+1;
152101      }
152102    }
152103
152104    pModule->xClose(pCursor);
152105    pCursor = 0;
152106  }
152107
152108  if( rc==SQLITE_DONE ){
152109    int jj;
152110    char *zBuf = 0;
152111
152112    p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
152113    if( !p ) goto no_mem;
152114    memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
152115    p->eType = FTSQUERY_PHRASE;
152116    p->pPhrase = (Fts3Phrase *)&p[1];
152117    p->pPhrase->iColumn = pParse->iDefaultCol;
152118    p->pPhrase->nToken = nToken;
152119
152120    zBuf = (char *)&p->pPhrase->aToken[nToken];
152121    if( zTemp ){
152122      memcpy(zBuf, zTemp, nTemp);
152123      sqlite3_free(zTemp);
152124    }else{
152125      assert( nTemp==0 );
152126    }
152127
152128    for(jj=0; jj<p->pPhrase->nToken; jj++){
152129      p->pPhrase->aToken[jj].z = zBuf;
152130      zBuf += p->pPhrase->aToken[jj].n;
152131    }
152132    rc = SQLITE_OK;
152133  }
152134
152135  *ppExpr = p;
152136  return rc;
152137no_mem:
152138
152139  if( pCursor ){
152140    pModule->xClose(pCursor);
152141  }
152142  sqlite3_free(zTemp);
152143  sqlite3_free(p);
152144  *ppExpr = 0;
152145  return SQLITE_NOMEM;
152146}
152147
152148/*
152149** The output variable *ppExpr is populated with an allocated Fts3Expr
152150** structure, or set to 0 if the end of the input buffer is reached.
152151**
152152** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
152153** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
152154** If SQLITE_ERROR is returned, pContext is populated with an error message.
152155*/
152156static int getNextNode(
152157  ParseContext *pParse,                   /* fts3 query parse context */
152158  const char *z, int n,                   /* Input string */
152159  Fts3Expr **ppExpr,                      /* OUT: expression */
152160  int *pnConsumed                         /* OUT: Number of bytes consumed */
152161){
152162  static const struct Fts3Keyword {
152163    char *z;                              /* Keyword text */
152164    unsigned char n;                      /* Length of the keyword */
152165    unsigned char parenOnly;              /* Only valid in paren mode */
152166    unsigned char eType;                  /* Keyword code */
152167  } aKeyword[] = {
152168    { "OR" ,  2, 0, FTSQUERY_OR   },
152169    { "AND",  3, 1, FTSQUERY_AND  },
152170    { "NOT",  3, 1, FTSQUERY_NOT  },
152171    { "NEAR", 4, 0, FTSQUERY_NEAR }
152172  };
152173  int ii;
152174  int iCol;
152175  int iColLen;
152176  int rc;
152177  Fts3Expr *pRet = 0;
152178
152179  const char *zInput = z;
152180  int nInput = n;
152181
152182  pParse->isNot = 0;
152183
152184  /* Skip over any whitespace before checking for a keyword, an open or
152185  ** close bracket, or a quoted string.
152186  */
152187  while( nInput>0 && fts3isspace(*zInput) ){
152188    nInput--;
152189    zInput++;
152190  }
152191  if( nInput==0 ){
152192    return SQLITE_DONE;
152193  }
152194
152195  /* See if we are dealing with a keyword. */
152196  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
152197    const struct Fts3Keyword *pKey = &aKeyword[ii];
152198
152199    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
152200      continue;
152201    }
152202
152203    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
152204      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
152205      int nKey = pKey->n;
152206      char cNext;
152207
152208      /* If this is a "NEAR" keyword, check for an explicit nearness. */
152209      if( pKey->eType==FTSQUERY_NEAR ){
152210        assert( nKey==4 );
152211        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
152212          nNear = 0;
152213          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
152214            nNear = nNear * 10 + (zInput[nKey] - '0');
152215          }
152216        }
152217      }
152218
152219      /* At this point this is probably a keyword. But for that to be true,
152220      ** the next byte must contain either whitespace, an open or close
152221      ** parenthesis, a quote character, or EOF.
152222      */
152223      cNext = zInput[nKey];
152224      if( fts3isspace(cNext)
152225       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
152226      ){
152227        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
152228        if( !pRet ){
152229          return SQLITE_NOMEM;
152230        }
152231        pRet->eType = pKey->eType;
152232        pRet->nNear = nNear;
152233        *ppExpr = pRet;
152234        *pnConsumed = (int)((zInput - z) + nKey);
152235        return SQLITE_OK;
152236      }
152237
152238      /* Turns out that wasn't a keyword after all. This happens if the
152239      ** user has supplied a token such as "ORacle". Continue.
152240      */
152241    }
152242  }
152243
152244  /* See if we are dealing with a quoted phrase. If this is the case, then
152245  ** search for the closing quote and pass the whole string to getNextString()
152246  ** for processing. This is easy to do, as fts3 has no syntax for escaping
152247  ** a quote character embedded in a string.
152248  */
152249  if( *zInput=='"' ){
152250    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
152251    *pnConsumed = (int)((zInput - z) + ii + 1);
152252    if( ii==nInput ){
152253      return SQLITE_ERROR;
152254    }
152255    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
152256  }
152257
152258  if( sqlite3_fts3_enable_parentheses ){
152259    if( *zInput=='(' ){
152260      int nConsumed = 0;
152261      pParse->nNest++;
152262      rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
152263      if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
152264      *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
152265      return rc;
152266    }else if( *zInput==')' ){
152267      pParse->nNest--;
152268      *pnConsumed = (int)((zInput - z) + 1);
152269      *ppExpr = 0;
152270      return SQLITE_DONE;
152271    }
152272  }
152273
152274  /* If control flows to this point, this must be a regular token, or
152275  ** the end of the input. Read a regular token using the sqlite3_tokenizer
152276  ** interface. Before doing so, figure out if there is an explicit
152277  ** column specifier for the token.
152278  **
152279  ** TODO: Strangely, it is not possible to associate a column specifier
152280  ** with a quoted phrase, only with a single token. Not sure if this was
152281  ** an implementation artifact or an intentional decision when fts3 was
152282  ** first implemented. Whichever it was, this module duplicates the
152283  ** limitation.
152284  */
152285  iCol = pParse->iDefaultCol;
152286  iColLen = 0;
152287  for(ii=0; ii<pParse->nCol; ii++){
152288    const char *zStr = pParse->azCol[ii];
152289    int nStr = (int)strlen(zStr);
152290    if( nInput>nStr && zInput[nStr]==':'
152291     && sqlite3_strnicmp(zStr, zInput, nStr)==0
152292    ){
152293      iCol = ii;
152294      iColLen = (int)((zInput - z) + nStr + 1);
152295      break;
152296    }
152297  }
152298  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
152299  *pnConsumed += iColLen;
152300  return rc;
152301}
152302
152303/*
152304** The argument is an Fts3Expr structure for a binary operator (any type
152305** except an FTSQUERY_PHRASE). Return an integer value representing the
152306** precedence of the operator. Lower values have a higher precedence (i.e.
152307** group more tightly). For example, in the C language, the == operator
152308** groups more tightly than ||, and would therefore have a higher precedence.
152309**
152310** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
152311** is defined), the order of the operators in precedence from highest to
152312** lowest is:
152313**
152314**   NEAR
152315**   NOT
152316**   AND (including implicit ANDs)
152317**   OR
152318**
152319** Note that when using the old query syntax, the OR operator has a higher
152320** precedence than the AND operator.
152321*/
152322static int opPrecedence(Fts3Expr *p){
152323  assert( p->eType!=FTSQUERY_PHRASE );
152324  if( sqlite3_fts3_enable_parentheses ){
152325    return p->eType;
152326  }else if( p->eType==FTSQUERY_NEAR ){
152327    return 1;
152328  }else if( p->eType==FTSQUERY_OR ){
152329    return 2;
152330  }
152331  assert( p->eType==FTSQUERY_AND );
152332  return 3;
152333}
152334
152335/*
152336** Argument ppHead contains a pointer to the current head of a query
152337** expression tree being parsed. pPrev is the expression node most recently
152338** inserted into the tree. This function adds pNew, which is always a binary
152339** operator node, into the expression tree based on the relative precedence
152340** of pNew and the existing nodes of the tree. This may result in the head
152341** of the tree changing, in which case *ppHead is set to the new root node.
152342*/
152343static void insertBinaryOperator(
152344  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
152345  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
152346  Fts3Expr *pNew           /* New binary node to insert into expression tree */
152347){
152348  Fts3Expr *pSplit = pPrev;
152349  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
152350    pSplit = pSplit->pParent;
152351  }
152352
152353  if( pSplit->pParent ){
152354    assert( pSplit->pParent->pRight==pSplit );
152355    pSplit->pParent->pRight = pNew;
152356    pNew->pParent = pSplit->pParent;
152357  }else{
152358    *ppHead = pNew;
152359  }
152360  pNew->pLeft = pSplit;
152361  pSplit->pParent = pNew;
152362}
152363
152364/*
152365** Parse the fts3 query expression found in buffer z, length n. This function
152366** returns either when the end of the buffer is reached or an unmatched
152367** closing bracket - ')' - is encountered.
152368**
152369** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
152370** parsed form of the expression and *pnConsumed is set to the number of
152371** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
152372** (out of memory error) or SQLITE_ERROR (parse error) is returned.
152373*/
152374static int fts3ExprParse(
152375  ParseContext *pParse,                   /* fts3 query parse context */
152376  const char *z, int n,                   /* Text of MATCH query */
152377  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
152378  int *pnConsumed                         /* OUT: Number of bytes consumed */
152379){
152380  Fts3Expr *pRet = 0;
152381  Fts3Expr *pPrev = 0;
152382  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
152383  int nIn = n;
152384  const char *zIn = z;
152385  int rc = SQLITE_OK;
152386  int isRequirePhrase = 1;
152387
152388  while( rc==SQLITE_OK ){
152389    Fts3Expr *p = 0;
152390    int nByte = 0;
152391
152392    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
152393    assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
152394    if( rc==SQLITE_OK ){
152395      if( p ){
152396        int isPhrase;
152397
152398        if( !sqlite3_fts3_enable_parentheses
152399            && p->eType==FTSQUERY_PHRASE && pParse->isNot
152400        ){
152401          /* Create an implicit NOT operator. */
152402          Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
152403          if( !pNot ){
152404            sqlite3Fts3ExprFree(p);
152405            rc = SQLITE_NOMEM;
152406            goto exprparse_out;
152407          }
152408          pNot->eType = FTSQUERY_NOT;
152409          pNot->pRight = p;
152410          p->pParent = pNot;
152411          if( pNotBranch ){
152412            pNot->pLeft = pNotBranch;
152413            pNotBranch->pParent = pNot;
152414          }
152415          pNotBranch = pNot;
152416          p = pPrev;
152417        }else{
152418          int eType = p->eType;
152419          isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
152420
152421          /* The isRequirePhrase variable is set to true if a phrase or
152422          ** an expression contained in parenthesis is required. If a
152423          ** binary operator (AND, OR, NOT or NEAR) is encounted when
152424          ** isRequirePhrase is set, this is a syntax error.
152425          */
152426          if( !isPhrase && isRequirePhrase ){
152427            sqlite3Fts3ExprFree(p);
152428            rc = SQLITE_ERROR;
152429            goto exprparse_out;
152430          }
152431
152432          if( isPhrase && !isRequirePhrase ){
152433            /* Insert an implicit AND operator. */
152434            Fts3Expr *pAnd;
152435            assert( pRet && pPrev );
152436            pAnd = fts3MallocZero(sizeof(Fts3Expr));
152437            if( !pAnd ){
152438              sqlite3Fts3ExprFree(p);
152439              rc = SQLITE_NOMEM;
152440              goto exprparse_out;
152441            }
152442            pAnd->eType = FTSQUERY_AND;
152443            insertBinaryOperator(&pRet, pPrev, pAnd);
152444            pPrev = pAnd;
152445          }
152446
152447          /* This test catches attempts to make either operand of a NEAR
152448           ** operator something other than a phrase. For example, either of
152449           ** the following:
152450           **
152451           **    (bracketed expression) NEAR phrase
152452           **    phrase NEAR (bracketed expression)
152453           **
152454           ** Return an error in either case.
152455           */
152456          if( pPrev && (
152457            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
152458         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
152459          )){
152460            sqlite3Fts3ExprFree(p);
152461            rc = SQLITE_ERROR;
152462            goto exprparse_out;
152463          }
152464
152465          if( isPhrase ){
152466            if( pRet ){
152467              assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
152468              pPrev->pRight = p;
152469              p->pParent = pPrev;
152470            }else{
152471              pRet = p;
152472            }
152473          }else{
152474            insertBinaryOperator(&pRet, pPrev, p);
152475          }
152476          isRequirePhrase = !isPhrase;
152477        }
152478        pPrev = p;
152479      }
152480      assert( nByte>0 );
152481    }
152482    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
152483    nIn -= nByte;
152484    zIn += nByte;
152485  }
152486
152487  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
152488    rc = SQLITE_ERROR;
152489  }
152490
152491  if( rc==SQLITE_DONE ){
152492    rc = SQLITE_OK;
152493    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
152494      if( !pRet ){
152495        rc = SQLITE_ERROR;
152496      }else{
152497        Fts3Expr *pIter = pNotBranch;
152498        while( pIter->pLeft ){
152499          pIter = pIter->pLeft;
152500        }
152501        pIter->pLeft = pRet;
152502        pRet->pParent = pIter;
152503        pRet = pNotBranch;
152504      }
152505    }
152506  }
152507  *pnConsumed = n - nIn;
152508
152509exprparse_out:
152510  if( rc!=SQLITE_OK ){
152511    sqlite3Fts3ExprFree(pRet);
152512    sqlite3Fts3ExprFree(pNotBranch);
152513    pRet = 0;
152514  }
152515  *ppExpr = pRet;
152516  return rc;
152517}
152518
152519/*
152520** Return SQLITE_ERROR if the maximum depth of the expression tree passed
152521** as the only argument is more than nMaxDepth.
152522*/
152523static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
152524  int rc = SQLITE_OK;
152525  if( p ){
152526    if( nMaxDepth<0 ){
152527      rc = SQLITE_TOOBIG;
152528    }else{
152529      rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
152530      if( rc==SQLITE_OK ){
152531        rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
152532      }
152533    }
152534  }
152535  return rc;
152536}
152537
152538/*
152539** This function attempts to transform the expression tree at (*pp) to
152540** an equivalent but more balanced form. The tree is modified in place.
152541** If successful, SQLITE_OK is returned and (*pp) set to point to the
152542** new root expression node.
152543**
152544** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
152545**
152546** Otherwise, if an error occurs, an SQLite error code is returned and
152547** expression (*pp) freed.
152548*/
152549static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
152550  int rc = SQLITE_OK;             /* Return code */
152551  Fts3Expr *pRoot = *pp;          /* Initial root node */
152552  Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
152553  int eType = pRoot->eType;       /* Type of node in this tree */
152554
152555  if( nMaxDepth==0 ){
152556    rc = SQLITE_ERROR;
152557  }
152558
152559  if( rc==SQLITE_OK ){
152560    if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
152561      Fts3Expr **apLeaf;
152562      apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
152563      if( 0==apLeaf ){
152564        rc = SQLITE_NOMEM;
152565      }else{
152566        memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
152567      }
152568
152569      if( rc==SQLITE_OK ){
152570        int i;
152571        Fts3Expr *p;
152572
152573        /* Set $p to point to the left-most leaf in the tree of eType nodes. */
152574        for(p=pRoot; p->eType==eType; p=p->pLeft){
152575          assert( p->pParent==0 || p->pParent->pLeft==p );
152576          assert( p->pLeft && p->pRight );
152577        }
152578
152579        /* This loop runs once for each leaf in the tree of eType nodes. */
152580        while( 1 ){
152581          int iLvl;
152582          Fts3Expr *pParent = p->pParent;     /* Current parent of p */
152583
152584          assert( pParent==0 || pParent->pLeft==p );
152585          p->pParent = 0;
152586          if( pParent ){
152587            pParent->pLeft = 0;
152588          }else{
152589            pRoot = 0;
152590          }
152591          rc = fts3ExprBalance(&p, nMaxDepth-1);
152592          if( rc!=SQLITE_OK ) break;
152593
152594          for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
152595            if( apLeaf[iLvl]==0 ){
152596              apLeaf[iLvl] = p;
152597              p = 0;
152598            }else{
152599              assert( pFree );
152600              pFree->pLeft = apLeaf[iLvl];
152601              pFree->pRight = p;
152602              pFree->pLeft->pParent = pFree;
152603              pFree->pRight->pParent = pFree;
152604
152605              p = pFree;
152606              pFree = pFree->pParent;
152607              p->pParent = 0;
152608              apLeaf[iLvl] = 0;
152609            }
152610          }
152611          if( p ){
152612            sqlite3Fts3ExprFree(p);
152613            rc = SQLITE_TOOBIG;
152614            break;
152615          }
152616
152617          /* If that was the last leaf node, break out of the loop */
152618          if( pParent==0 ) break;
152619
152620          /* Set $p to point to the next leaf in the tree of eType nodes */
152621          for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
152622
152623          /* Remove pParent from the original tree. */
152624          assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
152625          pParent->pRight->pParent = pParent->pParent;
152626          if( pParent->pParent ){
152627            pParent->pParent->pLeft = pParent->pRight;
152628          }else{
152629            assert( pParent==pRoot );
152630            pRoot = pParent->pRight;
152631          }
152632
152633          /* Link pParent into the free node list. It will be used as an
152634          ** internal node of the new tree.  */
152635          pParent->pParent = pFree;
152636          pFree = pParent;
152637        }
152638
152639        if( rc==SQLITE_OK ){
152640          p = 0;
152641          for(i=0; i<nMaxDepth; i++){
152642            if( apLeaf[i] ){
152643              if( p==0 ){
152644                p = apLeaf[i];
152645                p->pParent = 0;
152646              }else{
152647                assert( pFree!=0 );
152648                pFree->pRight = p;
152649                pFree->pLeft = apLeaf[i];
152650                pFree->pLeft->pParent = pFree;
152651                pFree->pRight->pParent = pFree;
152652
152653                p = pFree;
152654                pFree = pFree->pParent;
152655                p->pParent = 0;
152656              }
152657            }
152658          }
152659          pRoot = p;
152660        }else{
152661          /* An error occurred. Delete the contents of the apLeaf[] array
152662          ** and pFree list. Everything else is cleaned up by the call to
152663          ** sqlite3Fts3ExprFree(pRoot) below.  */
152664          Fts3Expr *pDel;
152665          for(i=0; i<nMaxDepth; i++){
152666            sqlite3Fts3ExprFree(apLeaf[i]);
152667          }
152668          while( (pDel=pFree)!=0 ){
152669            pFree = pDel->pParent;
152670            sqlite3_free(pDel);
152671          }
152672        }
152673
152674        assert( pFree==0 );
152675        sqlite3_free( apLeaf );
152676      }
152677    }else if( eType==FTSQUERY_NOT ){
152678      Fts3Expr *pLeft = pRoot->pLeft;
152679      Fts3Expr *pRight = pRoot->pRight;
152680
152681      pRoot->pLeft = 0;
152682      pRoot->pRight = 0;
152683      pLeft->pParent = 0;
152684      pRight->pParent = 0;
152685
152686      rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
152687      if( rc==SQLITE_OK ){
152688        rc = fts3ExprBalance(&pRight, nMaxDepth-1);
152689      }
152690
152691      if( rc!=SQLITE_OK ){
152692        sqlite3Fts3ExprFree(pRight);
152693        sqlite3Fts3ExprFree(pLeft);
152694      }else{
152695        assert( pLeft && pRight );
152696        pRoot->pLeft = pLeft;
152697        pLeft->pParent = pRoot;
152698        pRoot->pRight = pRight;
152699        pRight->pParent = pRoot;
152700      }
152701    }
152702  }
152703
152704  if( rc!=SQLITE_OK ){
152705    sqlite3Fts3ExprFree(pRoot);
152706    pRoot = 0;
152707  }
152708  *pp = pRoot;
152709  return rc;
152710}
152711
152712/*
152713** This function is similar to sqlite3Fts3ExprParse(), with the following
152714** differences:
152715**
152716**   1. It does not do expression rebalancing.
152717**   2. It does not check that the expression does not exceed the
152718**      maximum allowable depth.
152719**   3. Even if it fails, *ppExpr may still be set to point to an
152720**      expression tree. It should be deleted using sqlite3Fts3ExprFree()
152721**      in this case.
152722*/
152723static int fts3ExprParseUnbalanced(
152724  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
152725  int iLangid,                        /* Language id for tokenizer */
152726  char **azCol,                       /* Array of column names for fts3 table */
152727  int bFts4,                          /* True to allow FTS4-only syntax */
152728  int nCol,                           /* Number of entries in azCol[] */
152729  int iDefaultCol,                    /* Default column to query */
152730  const char *z, int n,               /* Text of MATCH query */
152731  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
152732){
152733  int nParsed;
152734  int rc;
152735  ParseContext sParse;
152736
152737  memset(&sParse, 0, sizeof(ParseContext));
152738  sParse.pTokenizer = pTokenizer;
152739  sParse.iLangid = iLangid;
152740  sParse.azCol = (const char **)azCol;
152741  sParse.nCol = nCol;
152742  sParse.iDefaultCol = iDefaultCol;
152743  sParse.bFts4 = bFts4;
152744  if( z==0 ){
152745    *ppExpr = 0;
152746    return SQLITE_OK;
152747  }
152748  if( n<0 ){
152749    n = (int)strlen(z);
152750  }
152751  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
152752  assert( rc==SQLITE_OK || *ppExpr==0 );
152753
152754  /* Check for mismatched parenthesis */
152755  if( rc==SQLITE_OK && sParse.nNest ){
152756    rc = SQLITE_ERROR;
152757  }
152758
152759  return rc;
152760}
152761
152762/*
152763** Parameters z and n contain a pointer to and length of a buffer containing
152764** an fts3 query expression, respectively. This function attempts to parse the
152765** query expression and create a tree of Fts3Expr structures representing the
152766** parsed expression. If successful, *ppExpr is set to point to the head
152767** of the parsed expression tree and SQLITE_OK is returned. If an error
152768** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
152769** error) is returned and *ppExpr is set to 0.
152770**
152771** If parameter n is a negative number, then z is assumed to point to a
152772** nul-terminated string and the length is determined using strlen().
152773**
152774** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
152775** use to normalize query tokens while parsing the expression. The azCol[]
152776** array, which is assumed to contain nCol entries, should contain the names
152777** of each column in the target fts3 table, in order from left to right.
152778** Column names must be nul-terminated strings.
152779**
152780** The iDefaultCol parameter should be passed the index of the table column
152781** that appears on the left-hand-side of the MATCH operator (the default
152782** column to match against for tokens for which a column name is not explicitly
152783** specified as part of the query string), or -1 if tokens may by default
152784** match any table column.
152785*/
152786SQLITE_PRIVATE int sqlite3Fts3ExprParse(
152787  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
152788  int iLangid,                        /* Language id for tokenizer */
152789  char **azCol,                       /* Array of column names for fts3 table */
152790  int bFts4,                          /* True to allow FTS4-only syntax */
152791  int nCol,                           /* Number of entries in azCol[] */
152792  int iDefaultCol,                    /* Default column to query */
152793  const char *z, int n,               /* Text of MATCH query */
152794  Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
152795  char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
152796){
152797  int rc = fts3ExprParseUnbalanced(
152798      pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
152799  );
152800
152801  /* Rebalance the expression. And check that its depth does not exceed
152802  ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
152803  if( rc==SQLITE_OK && *ppExpr ){
152804    rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
152805    if( rc==SQLITE_OK ){
152806      rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
152807    }
152808  }
152809
152810  if( rc!=SQLITE_OK ){
152811    sqlite3Fts3ExprFree(*ppExpr);
152812    *ppExpr = 0;
152813    if( rc==SQLITE_TOOBIG ){
152814      sqlite3Fts3ErrMsg(pzErr,
152815          "FTS expression tree is too large (maximum depth %d)",
152816          SQLITE_FTS3_MAX_EXPR_DEPTH
152817      );
152818      rc = SQLITE_ERROR;
152819    }else if( rc==SQLITE_ERROR ){
152820      sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
152821    }
152822  }
152823
152824  return rc;
152825}
152826
152827/*
152828** Free a single node of an expression tree.
152829*/
152830static void fts3FreeExprNode(Fts3Expr *p){
152831  assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
152832  sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
152833  sqlite3_free(p->aMI);
152834  sqlite3_free(p);
152835}
152836
152837/*
152838** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
152839**
152840** This function would be simpler if it recursively called itself. But
152841** that would mean passing a sufficiently large expression to ExprParse()
152842** could cause a stack overflow.
152843*/
152844SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
152845  Fts3Expr *p;
152846  assert( pDel==0 || pDel->pParent==0 );
152847  for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
152848    assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
152849  }
152850  while( p ){
152851    Fts3Expr *pParent = p->pParent;
152852    fts3FreeExprNode(p);
152853    if( pParent && p==pParent->pLeft && pParent->pRight ){
152854      p = pParent->pRight;
152855      while( p && (p->pLeft || p->pRight) ){
152856        assert( p==p->pParent->pRight || p==p->pParent->pLeft );
152857        p = (p->pLeft ? p->pLeft : p->pRight);
152858      }
152859    }else{
152860      p = pParent;
152861    }
152862  }
152863}
152864
152865/****************************************************************************
152866*****************************************************************************
152867** Everything after this point is just test code.
152868*/
152869
152870#ifdef SQLITE_TEST
152871
152872/* #include <stdio.h> */
152873
152874/*
152875** Function to query the hash-table of tokenizers (see README.tokenizers).
152876*/
152877static int queryTestTokenizer(
152878  sqlite3 *db,
152879  const char *zName,
152880  const sqlite3_tokenizer_module **pp
152881){
152882  int rc;
152883  sqlite3_stmt *pStmt;
152884  const char zSql[] = "SELECT fts3_tokenizer(?)";
152885
152886  *pp = 0;
152887  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
152888  if( rc!=SQLITE_OK ){
152889    return rc;
152890  }
152891
152892  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
152893  if( SQLITE_ROW==sqlite3_step(pStmt) ){
152894    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
152895      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
152896    }
152897  }
152898
152899  return sqlite3_finalize(pStmt);
152900}
152901
152902/*
152903** Return a pointer to a buffer containing a text representation of the
152904** expression passed as the first argument. The buffer is obtained from
152905** sqlite3_malloc(). It is the responsibility of the caller to use
152906** sqlite3_free() to release the memory. If an OOM condition is encountered,
152907** NULL is returned.
152908**
152909** If the second argument is not NULL, then its contents are prepended to
152910** the returned expression text and then freed using sqlite3_free().
152911*/
152912static char *exprToString(Fts3Expr *pExpr, char *zBuf){
152913  if( pExpr==0 ){
152914    return sqlite3_mprintf("");
152915  }
152916  switch( pExpr->eType ){
152917    case FTSQUERY_PHRASE: {
152918      Fts3Phrase *pPhrase = pExpr->pPhrase;
152919      int i;
152920      zBuf = sqlite3_mprintf(
152921          "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
152922      for(i=0; zBuf && i<pPhrase->nToken; i++){
152923        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
152924            pPhrase->aToken[i].n, pPhrase->aToken[i].z,
152925            (pPhrase->aToken[i].isPrefix?"+":"")
152926        );
152927      }
152928      return zBuf;
152929    }
152930
152931    case FTSQUERY_NEAR:
152932      zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
152933      break;
152934    case FTSQUERY_NOT:
152935      zBuf = sqlite3_mprintf("%zNOT ", zBuf);
152936      break;
152937    case FTSQUERY_AND:
152938      zBuf = sqlite3_mprintf("%zAND ", zBuf);
152939      break;
152940    case FTSQUERY_OR:
152941      zBuf = sqlite3_mprintf("%zOR ", zBuf);
152942      break;
152943  }
152944
152945  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
152946  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
152947  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
152948
152949  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
152950  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
152951
152952  return zBuf;
152953}
152954
152955/*
152956** This is the implementation of a scalar SQL function used to test the
152957** expression parser. It should be called as follows:
152958**
152959**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
152960**
152961** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
152962** to parse the query expression (see README.tokenizers). The second argument
152963** is the query expression to parse. Each subsequent argument is the name
152964** of a column of the fts3 table that the query expression may refer to.
152965** For example:
152966**
152967**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
152968*/
152969static void fts3ExprTest(
152970  sqlite3_context *context,
152971  int argc,
152972  sqlite3_value **argv
152973){
152974  sqlite3_tokenizer_module const *pModule = 0;
152975  sqlite3_tokenizer *pTokenizer = 0;
152976  int rc;
152977  char **azCol = 0;
152978  const char *zExpr;
152979  int nExpr;
152980  int nCol;
152981  int ii;
152982  Fts3Expr *pExpr;
152983  char *zBuf = 0;
152984  sqlite3 *db = sqlite3_context_db_handle(context);
152985
152986  if( argc<3 ){
152987    sqlite3_result_error(context,
152988        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
152989    );
152990    return;
152991  }
152992
152993  rc = queryTestTokenizer(db,
152994                          (const char *)sqlite3_value_text(argv[0]), &pModule);
152995  if( rc==SQLITE_NOMEM ){
152996    sqlite3_result_error_nomem(context);
152997    goto exprtest_out;
152998  }else if( !pModule ){
152999    sqlite3_result_error(context, "No such tokenizer module", -1);
153000    goto exprtest_out;
153001  }
153002
153003  rc = pModule->xCreate(0, 0, &pTokenizer);
153004  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
153005  if( rc==SQLITE_NOMEM ){
153006    sqlite3_result_error_nomem(context);
153007    goto exprtest_out;
153008  }
153009  pTokenizer->pModule = pModule;
153010
153011  zExpr = (const char *)sqlite3_value_text(argv[1]);
153012  nExpr = sqlite3_value_bytes(argv[1]);
153013  nCol = argc-2;
153014  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
153015  if( !azCol ){
153016    sqlite3_result_error_nomem(context);
153017    goto exprtest_out;
153018  }
153019  for(ii=0; ii<nCol; ii++){
153020    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
153021  }
153022
153023  if( sqlite3_user_data(context) ){
153024    char *zDummy = 0;
153025    rc = sqlite3Fts3ExprParse(
153026        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
153027    );
153028    assert( rc==SQLITE_OK || pExpr==0 );
153029    sqlite3_free(zDummy);
153030  }else{
153031    rc = fts3ExprParseUnbalanced(
153032        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
153033    );
153034  }
153035
153036  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
153037    sqlite3Fts3ExprFree(pExpr);
153038    sqlite3_result_error(context, "Error parsing expression", -1);
153039  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
153040    sqlite3_result_error_nomem(context);
153041  }else{
153042    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
153043    sqlite3_free(zBuf);
153044  }
153045
153046  sqlite3Fts3ExprFree(pExpr);
153047
153048exprtest_out:
153049  if( pModule && pTokenizer ){
153050    rc = pModule->xDestroy(pTokenizer);
153051  }
153052  sqlite3_free(azCol);
153053}
153054
153055/*
153056** Register the query expression parser test function fts3_exprtest()
153057** with database connection db.
153058*/
153059SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
153060  int rc = sqlite3_create_function(
153061      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
153062  );
153063  if( rc==SQLITE_OK ){
153064    rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
153065        -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
153066    );
153067  }
153068  return rc;
153069}
153070
153071#endif
153072#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
153073
153074/************** End of fts3_expr.c *******************************************/
153075/************** Begin file fts3_hash.c ***************************************/
153076/*
153077** 2001 September 22
153078**
153079** The author disclaims copyright to this source code.  In place of
153080** a legal notice, here is a blessing:
153081**
153082**    May you do good and not evil.
153083**    May you find forgiveness for yourself and forgive others.
153084**    May you share freely, never taking more than you give.
153085**
153086*************************************************************************
153087** This is the implementation of generic hash-tables used in SQLite.
153088** We've modified it slightly to serve as a standalone hash table
153089** implementation for the full-text indexing module.
153090*/
153091
153092/*
153093** The code in this file is only compiled if:
153094**
153095**     * The FTS3 module is being built as an extension
153096**       (in which case SQLITE_CORE is not defined), or
153097**
153098**     * The FTS3 module is being built into the core of
153099**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
153100*/
153101/* #include "fts3Int.h" */
153102#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
153103
153104/* #include <assert.h> */
153105/* #include <stdlib.h> */
153106/* #include <string.h> */
153107
153108/* #include "fts3_hash.h" */
153109
153110/*
153111** Malloc and Free functions
153112*/
153113static void *fts3HashMalloc(int n){
153114  void *p = sqlite3_malloc(n);
153115  if( p ){
153116    memset(p, 0, n);
153117  }
153118  return p;
153119}
153120static void fts3HashFree(void *p){
153121  sqlite3_free(p);
153122}
153123
153124/* Turn bulk memory into a hash table object by initializing the
153125** fields of the Hash structure.
153126**
153127** "pNew" is a pointer to the hash table that is to be initialized.
153128** keyClass is one of the constants
153129** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
153130** determines what kind of key the hash table will use.  "copyKey" is
153131** true if the hash table should make its own private copy of keys and
153132** false if it should just use the supplied pointer.
153133*/
153134SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
153135  assert( pNew!=0 );
153136  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
153137  pNew->keyClass = keyClass;
153138  pNew->copyKey = copyKey;
153139  pNew->first = 0;
153140  pNew->count = 0;
153141  pNew->htsize = 0;
153142  pNew->ht = 0;
153143}
153144
153145/* Remove all entries from a hash table.  Reclaim all memory.
153146** Call this routine to delete a hash table or to reset a hash table
153147** to the empty state.
153148*/
153149SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
153150  Fts3HashElem *elem;         /* For looping over all elements of the table */
153151
153152  assert( pH!=0 );
153153  elem = pH->first;
153154  pH->first = 0;
153155  fts3HashFree(pH->ht);
153156  pH->ht = 0;
153157  pH->htsize = 0;
153158  while( elem ){
153159    Fts3HashElem *next_elem = elem->next;
153160    if( pH->copyKey && elem->pKey ){
153161      fts3HashFree(elem->pKey);
153162    }
153163    fts3HashFree(elem);
153164    elem = next_elem;
153165  }
153166  pH->count = 0;
153167}
153168
153169/*
153170** Hash and comparison functions when the mode is FTS3_HASH_STRING
153171*/
153172static int fts3StrHash(const void *pKey, int nKey){
153173  const char *z = (const char *)pKey;
153174  unsigned h = 0;
153175  if( nKey<=0 ) nKey = (int) strlen(z);
153176  while( nKey > 0  ){
153177    h = (h<<3) ^ h ^ *z++;
153178    nKey--;
153179  }
153180  return (int)(h & 0x7fffffff);
153181}
153182static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
153183  if( n1!=n2 ) return 1;
153184  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
153185}
153186
153187/*
153188** Hash and comparison functions when the mode is FTS3_HASH_BINARY
153189*/
153190static int fts3BinHash(const void *pKey, int nKey){
153191  int h = 0;
153192  const char *z = (const char *)pKey;
153193  while( nKey-- > 0 ){
153194    h = (h<<3) ^ h ^ *(z++);
153195  }
153196  return h & 0x7fffffff;
153197}
153198static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
153199  if( n1!=n2 ) return 1;
153200  return memcmp(pKey1,pKey2,n1);
153201}
153202
153203/*
153204** Return a pointer to the appropriate hash function given the key class.
153205**
153206** The C syntax in this function definition may be unfamilar to some
153207** programmers, so we provide the following additional explanation:
153208**
153209** The name of the function is "ftsHashFunction".  The function takes a
153210** single parameter "keyClass".  The return value of ftsHashFunction()
153211** is a pointer to another function.  Specifically, the return value
153212** of ftsHashFunction() is a pointer to a function that takes two parameters
153213** with types "const void*" and "int" and returns an "int".
153214*/
153215static int (*ftsHashFunction(int keyClass))(const void*,int){
153216  if( keyClass==FTS3_HASH_STRING ){
153217    return &fts3StrHash;
153218  }else{
153219    assert( keyClass==FTS3_HASH_BINARY );
153220    return &fts3BinHash;
153221  }
153222}
153223
153224/*
153225** Return a pointer to the appropriate hash function given the key class.
153226**
153227** For help in interpreted the obscure C code in the function definition,
153228** see the header comment on the previous function.
153229*/
153230static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
153231  if( keyClass==FTS3_HASH_STRING ){
153232    return &fts3StrCompare;
153233  }else{
153234    assert( keyClass==FTS3_HASH_BINARY );
153235    return &fts3BinCompare;
153236  }
153237}
153238
153239/* Link an element into the hash table
153240*/
153241static void fts3HashInsertElement(
153242  Fts3Hash *pH,            /* The complete hash table */
153243  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
153244  Fts3HashElem *pNew       /* The element to be inserted */
153245){
153246  Fts3HashElem *pHead;     /* First element already in pEntry */
153247  pHead = pEntry->chain;
153248  if( pHead ){
153249    pNew->next = pHead;
153250    pNew->prev = pHead->prev;
153251    if( pHead->prev ){ pHead->prev->next = pNew; }
153252    else             { pH->first = pNew; }
153253    pHead->prev = pNew;
153254  }else{
153255    pNew->next = pH->first;
153256    if( pH->first ){ pH->first->prev = pNew; }
153257    pNew->prev = 0;
153258    pH->first = pNew;
153259  }
153260  pEntry->count++;
153261  pEntry->chain = pNew;
153262}
153263
153264
153265/* Resize the hash table so that it cantains "new_size" buckets.
153266** "new_size" must be a power of 2.  The hash table might fail
153267** to resize if sqliteMalloc() fails.
153268**
153269** Return non-zero if a memory allocation error occurs.
153270*/
153271static int fts3Rehash(Fts3Hash *pH, int new_size){
153272  struct _fts3ht *new_ht;          /* The new hash table */
153273  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
153274  int (*xHash)(const void*,int);   /* The hash function */
153275
153276  assert( (new_size & (new_size-1))==0 );
153277  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
153278  if( new_ht==0 ) return 1;
153279  fts3HashFree(pH->ht);
153280  pH->ht = new_ht;
153281  pH->htsize = new_size;
153282  xHash = ftsHashFunction(pH->keyClass);
153283  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
153284    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
153285    next_elem = elem->next;
153286    fts3HashInsertElement(pH, &new_ht[h], elem);
153287  }
153288  return 0;
153289}
153290
153291/* This function (for internal use only) locates an element in an
153292** hash table that matches the given key.  The hash for this key has
153293** already been computed and is passed as the 4th parameter.
153294*/
153295static Fts3HashElem *fts3FindElementByHash(
153296  const Fts3Hash *pH, /* The pH to be searched */
153297  const void *pKey,   /* The key we are searching for */
153298  int nKey,
153299  int h               /* The hash for this key. */
153300){
153301  Fts3HashElem *elem;            /* Used to loop thru the element list */
153302  int count;                     /* Number of elements left to test */
153303  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
153304
153305  if( pH->ht ){
153306    struct _fts3ht *pEntry = &pH->ht[h];
153307    elem = pEntry->chain;
153308    count = pEntry->count;
153309    xCompare = ftsCompareFunction(pH->keyClass);
153310    while( count-- && elem ){
153311      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
153312        return elem;
153313      }
153314      elem = elem->next;
153315    }
153316  }
153317  return 0;
153318}
153319
153320/* Remove a single entry from the hash table given a pointer to that
153321** element and a hash on the element's key.
153322*/
153323static void fts3RemoveElementByHash(
153324  Fts3Hash *pH,         /* The pH containing "elem" */
153325  Fts3HashElem* elem,   /* The element to be removed from the pH */
153326  int h                 /* Hash value for the element */
153327){
153328  struct _fts3ht *pEntry;
153329  if( elem->prev ){
153330    elem->prev->next = elem->next;
153331  }else{
153332    pH->first = elem->next;
153333  }
153334  if( elem->next ){
153335    elem->next->prev = elem->prev;
153336  }
153337  pEntry = &pH->ht[h];
153338  if( pEntry->chain==elem ){
153339    pEntry->chain = elem->next;
153340  }
153341  pEntry->count--;
153342  if( pEntry->count<=0 ){
153343    pEntry->chain = 0;
153344  }
153345  if( pH->copyKey && elem->pKey ){
153346    fts3HashFree(elem->pKey);
153347  }
153348  fts3HashFree( elem );
153349  pH->count--;
153350  if( pH->count<=0 ){
153351    assert( pH->first==0 );
153352    assert( pH->count==0 );
153353    fts3HashClear(pH);
153354  }
153355}
153356
153357SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
153358  const Fts3Hash *pH,
153359  const void *pKey,
153360  int nKey
153361){
153362  int h;                          /* A hash on key */
153363  int (*xHash)(const void*,int);  /* The hash function */
153364
153365  if( pH==0 || pH->ht==0 ) return 0;
153366  xHash = ftsHashFunction(pH->keyClass);
153367  assert( xHash!=0 );
153368  h = (*xHash)(pKey,nKey);
153369  assert( (pH->htsize & (pH->htsize-1))==0 );
153370  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
153371}
153372
153373/*
153374** Attempt to locate an element of the hash table pH with a key
153375** that matches pKey,nKey.  Return the data for this element if it is
153376** found, or NULL if there is no match.
153377*/
153378SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
153379  Fts3HashElem *pElem;            /* The element that matches key (if any) */
153380
153381  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
153382  return pElem ? pElem->data : 0;
153383}
153384
153385/* Insert an element into the hash table pH.  The key is pKey,nKey
153386** and the data is "data".
153387**
153388** If no element exists with a matching key, then a new
153389** element is created.  A copy of the key is made if the copyKey
153390** flag is set.  NULL is returned.
153391**
153392** If another element already exists with the same key, then the
153393** new data replaces the old data and the old data is returned.
153394** The key is not copied in this instance.  If a malloc fails, then
153395** the new data is returned and the hash table is unchanged.
153396**
153397** If the "data" parameter to this function is NULL, then the
153398** element corresponding to "key" is removed from the hash table.
153399*/
153400SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
153401  Fts3Hash *pH,        /* The hash table to insert into */
153402  const void *pKey,    /* The key */
153403  int nKey,            /* Number of bytes in the key */
153404  void *data           /* The data */
153405){
153406  int hraw;                 /* Raw hash value of the key */
153407  int h;                    /* the hash of the key modulo hash table size */
153408  Fts3HashElem *elem;       /* Used to loop thru the element list */
153409  Fts3HashElem *new_elem;   /* New element added to the pH */
153410  int (*xHash)(const void*,int);  /* The hash function */
153411
153412  assert( pH!=0 );
153413  xHash = ftsHashFunction(pH->keyClass);
153414  assert( xHash!=0 );
153415  hraw = (*xHash)(pKey, nKey);
153416  assert( (pH->htsize & (pH->htsize-1))==0 );
153417  h = hraw & (pH->htsize-1);
153418  elem = fts3FindElementByHash(pH,pKey,nKey,h);
153419  if( elem ){
153420    void *old_data = elem->data;
153421    if( data==0 ){
153422      fts3RemoveElementByHash(pH,elem,h);
153423    }else{
153424      elem->data = data;
153425    }
153426    return old_data;
153427  }
153428  if( data==0 ) return 0;
153429  if( (pH->htsize==0 && fts3Rehash(pH,8))
153430   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
153431  ){
153432    pH->count = 0;
153433    return data;
153434  }
153435  assert( pH->htsize>0 );
153436  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
153437  if( new_elem==0 ) return data;
153438  if( pH->copyKey && pKey!=0 ){
153439    new_elem->pKey = fts3HashMalloc( nKey );
153440    if( new_elem->pKey==0 ){
153441      fts3HashFree(new_elem);
153442      return data;
153443    }
153444    memcpy((void*)new_elem->pKey, pKey, nKey);
153445  }else{
153446    new_elem->pKey = (void*)pKey;
153447  }
153448  new_elem->nKey = nKey;
153449  pH->count++;
153450  assert( pH->htsize>0 );
153451  assert( (pH->htsize & (pH->htsize-1))==0 );
153452  h = hraw & (pH->htsize-1);
153453  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
153454  new_elem->data = data;
153455  return 0;
153456}
153457
153458#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
153459
153460/************** End of fts3_hash.c *******************************************/
153461/************** Begin file fts3_porter.c *************************************/
153462/*
153463** 2006 September 30
153464**
153465** The author disclaims copyright to this source code.  In place of
153466** a legal notice, here is a blessing:
153467**
153468**    May you do good and not evil.
153469**    May you find forgiveness for yourself and forgive others.
153470**    May you share freely, never taking more than you give.
153471**
153472*************************************************************************
153473** Implementation of the full-text-search tokenizer that implements
153474** a Porter stemmer.
153475*/
153476
153477/*
153478** The code in this file is only compiled if:
153479**
153480**     * The FTS3 module is being built as an extension
153481**       (in which case SQLITE_CORE is not defined), or
153482**
153483**     * The FTS3 module is being built into the core of
153484**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
153485*/
153486/* #include "fts3Int.h" */
153487#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
153488
153489/* #include <assert.h> */
153490/* #include <stdlib.h> */
153491/* #include <stdio.h> */
153492/* #include <string.h> */
153493
153494/* #include "fts3_tokenizer.h" */
153495
153496/*
153497** Class derived from sqlite3_tokenizer
153498*/
153499typedef struct porter_tokenizer {
153500  sqlite3_tokenizer base;      /* Base class */
153501} porter_tokenizer;
153502
153503/*
153504** Class derived from sqlite3_tokenizer_cursor
153505*/
153506typedef struct porter_tokenizer_cursor {
153507  sqlite3_tokenizer_cursor base;
153508  const char *zInput;          /* input we are tokenizing */
153509  int nInput;                  /* size of the input */
153510  int iOffset;                 /* current position in zInput */
153511  int iToken;                  /* index of next token to be returned */
153512  char *zToken;                /* storage for current token */
153513  int nAllocated;              /* space allocated to zToken buffer */
153514} porter_tokenizer_cursor;
153515
153516
153517/*
153518** Create a new tokenizer instance.
153519*/
153520static int porterCreate(
153521  int argc, const char * const *argv,
153522  sqlite3_tokenizer **ppTokenizer
153523){
153524  porter_tokenizer *t;
153525
153526  UNUSED_PARAMETER(argc);
153527  UNUSED_PARAMETER(argv);
153528
153529  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
153530  if( t==NULL ) return SQLITE_NOMEM;
153531  memset(t, 0, sizeof(*t));
153532  *ppTokenizer = &t->base;
153533  return SQLITE_OK;
153534}
153535
153536/*
153537** Destroy a tokenizer
153538*/
153539static int porterDestroy(sqlite3_tokenizer *pTokenizer){
153540  sqlite3_free(pTokenizer);
153541  return SQLITE_OK;
153542}
153543
153544/*
153545** Prepare to begin tokenizing a particular string.  The input
153546** string to be tokenized is zInput[0..nInput-1].  A cursor
153547** used to incrementally tokenize this string is returned in
153548** *ppCursor.
153549*/
153550static int porterOpen(
153551  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
153552  const char *zInput, int nInput,        /* String to be tokenized */
153553  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
153554){
153555  porter_tokenizer_cursor *c;
153556
153557  UNUSED_PARAMETER(pTokenizer);
153558
153559  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
153560  if( c==NULL ) return SQLITE_NOMEM;
153561
153562  c->zInput = zInput;
153563  if( zInput==0 ){
153564    c->nInput = 0;
153565  }else if( nInput<0 ){
153566    c->nInput = (int)strlen(zInput);
153567  }else{
153568    c->nInput = nInput;
153569  }
153570  c->iOffset = 0;                 /* start tokenizing at the beginning */
153571  c->iToken = 0;
153572  c->zToken = NULL;               /* no space allocated, yet. */
153573  c->nAllocated = 0;
153574
153575  *ppCursor = &c->base;
153576  return SQLITE_OK;
153577}
153578
153579/*
153580** Close a tokenization cursor previously opened by a call to
153581** porterOpen() above.
153582*/
153583static int porterClose(sqlite3_tokenizer_cursor *pCursor){
153584  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
153585  sqlite3_free(c->zToken);
153586  sqlite3_free(c);
153587  return SQLITE_OK;
153588}
153589/*
153590** Vowel or consonant
153591*/
153592static const char cType[] = {
153593   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
153594   1, 1, 1, 2, 1
153595};
153596
153597/*
153598** isConsonant() and isVowel() determine if their first character in
153599** the string they point to is a consonant or a vowel, according
153600** to Porter ruls.
153601**
153602** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
153603** 'Y' is a consonant unless it follows another consonant,
153604** in which case it is a vowel.
153605**
153606** In these routine, the letters are in reverse order.  So the 'y' rule
153607** is that 'y' is a consonant unless it is followed by another
153608** consonent.
153609*/
153610static int isVowel(const char*);
153611static int isConsonant(const char *z){
153612  int j;
153613  char x = *z;
153614  if( x==0 ) return 0;
153615  assert( x>='a' && x<='z' );
153616  j = cType[x-'a'];
153617  if( j<2 ) return j;
153618  return z[1]==0 || isVowel(z + 1);
153619}
153620static int isVowel(const char *z){
153621  int j;
153622  char x = *z;
153623  if( x==0 ) return 0;
153624  assert( x>='a' && x<='z' );
153625  j = cType[x-'a'];
153626  if( j<2 ) return 1-j;
153627  return isConsonant(z + 1);
153628}
153629
153630/*
153631** Let any sequence of one or more vowels be represented by V and let
153632** C be sequence of one or more consonants.  Then every word can be
153633** represented as:
153634**
153635**           [C] (VC){m} [V]
153636**
153637** In prose:  A word is an optional consonant followed by zero or
153638** vowel-consonant pairs followed by an optional vowel.  "m" is the
153639** number of vowel consonant pairs.  This routine computes the value
153640** of m for the first i bytes of a word.
153641**
153642** Return true if the m-value for z is 1 or more.  In other words,
153643** return true if z contains at least one vowel that is followed
153644** by a consonant.
153645**
153646** In this routine z[] is in reverse order.  So we are really looking
153647** for an instance of a consonant followed by a vowel.
153648*/
153649static int m_gt_0(const char *z){
153650  while( isVowel(z) ){ z++; }
153651  if( *z==0 ) return 0;
153652  while( isConsonant(z) ){ z++; }
153653  return *z!=0;
153654}
153655
153656/* Like mgt0 above except we are looking for a value of m which is
153657** exactly 1
153658*/
153659static int m_eq_1(const char *z){
153660  while( isVowel(z) ){ z++; }
153661  if( *z==0 ) return 0;
153662  while( isConsonant(z) ){ z++; }
153663  if( *z==0 ) return 0;
153664  while( isVowel(z) ){ z++; }
153665  if( *z==0 ) return 1;
153666  while( isConsonant(z) ){ z++; }
153667  return *z==0;
153668}
153669
153670/* Like mgt0 above except we are looking for a value of m>1 instead
153671** or m>0
153672*/
153673static int m_gt_1(const char *z){
153674  while( isVowel(z) ){ z++; }
153675  if( *z==0 ) return 0;
153676  while( isConsonant(z) ){ z++; }
153677  if( *z==0 ) return 0;
153678  while( isVowel(z) ){ z++; }
153679  if( *z==0 ) return 0;
153680  while( isConsonant(z) ){ z++; }
153681  return *z!=0;
153682}
153683
153684/*
153685** Return TRUE if there is a vowel anywhere within z[0..n-1]
153686*/
153687static int hasVowel(const char *z){
153688  while( isConsonant(z) ){ z++; }
153689  return *z!=0;
153690}
153691
153692/*
153693** Return TRUE if the word ends in a double consonant.
153694**
153695** The text is reversed here. So we are really looking at
153696** the first two characters of z[].
153697*/
153698static int doubleConsonant(const char *z){
153699  return isConsonant(z) && z[0]==z[1];
153700}
153701
153702/*
153703** Return TRUE if the word ends with three letters which
153704** are consonant-vowel-consonent and where the final consonant
153705** is not 'w', 'x', or 'y'.
153706**
153707** The word is reversed here.  So we are really checking the
153708** first three letters and the first one cannot be in [wxy].
153709*/
153710static int star_oh(const char *z){
153711  return
153712    isConsonant(z) &&
153713    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
153714    isVowel(z+1) &&
153715    isConsonant(z+2);
153716}
153717
153718/*
153719** If the word ends with zFrom and xCond() is true for the stem
153720** of the word that preceeds the zFrom ending, then change the
153721** ending to zTo.
153722**
153723** The input word *pz and zFrom are both in reverse order.  zTo
153724** is in normal order.
153725**
153726** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
153727** match.  Not that TRUE is returned even if xCond() fails and
153728** no substitution occurs.
153729*/
153730static int stem(
153731  char **pz,             /* The word being stemmed (Reversed) */
153732  const char *zFrom,     /* If the ending matches this... (Reversed) */
153733  const char *zTo,       /* ... change the ending to this (not reversed) */
153734  int (*xCond)(const char*)   /* Condition that must be true */
153735){
153736  char *z = *pz;
153737  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
153738  if( *zFrom!=0 ) return 0;
153739  if( xCond && !xCond(z) ) return 1;
153740  while( *zTo ){
153741    *(--z) = *(zTo++);
153742  }
153743  *pz = z;
153744  return 1;
153745}
153746
153747/*
153748** This is the fallback stemmer used when the porter stemmer is
153749** inappropriate.  The input word is copied into the output with
153750** US-ASCII case folding.  If the input word is too long (more
153751** than 20 bytes if it contains no digits or more than 6 bytes if
153752** it contains digits) then word is truncated to 20 or 6 bytes
153753** by taking 10 or 3 bytes from the beginning and end.
153754*/
153755static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
153756  int i, mx, j;
153757  int hasDigit = 0;
153758  for(i=0; i<nIn; i++){
153759    char c = zIn[i];
153760    if( c>='A' && c<='Z' ){
153761      zOut[i] = c - 'A' + 'a';
153762    }else{
153763      if( c>='0' && c<='9' ) hasDigit = 1;
153764      zOut[i] = c;
153765    }
153766  }
153767  mx = hasDigit ? 3 : 10;
153768  if( nIn>mx*2 ){
153769    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
153770      zOut[j] = zOut[i];
153771    }
153772    i = j;
153773  }
153774  zOut[i] = 0;
153775  *pnOut = i;
153776}
153777
153778
153779/*
153780** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
153781** zOut is at least big enough to hold nIn bytes.  Write the actual
153782** size of the output word (exclusive of the '\0' terminator) into *pnOut.
153783**
153784** Any upper-case characters in the US-ASCII character set ([A-Z])
153785** are converted to lower case.  Upper-case UTF characters are
153786** unchanged.
153787**
153788** Words that are longer than about 20 bytes are stemmed by retaining
153789** a few bytes from the beginning and the end of the word.  If the
153790** word contains digits, 3 bytes are taken from the beginning and
153791** 3 bytes from the end.  For long words without digits, 10 bytes
153792** are taken from each end.  US-ASCII case folding still applies.
153793**
153794** If the input word contains not digits but does characters not
153795** in [a-zA-Z] then no stemming is attempted and this routine just
153796** copies the input into the input into the output with US-ASCII
153797** case folding.
153798**
153799** Stemming never increases the length of the word.  So there is
153800** no chance of overflowing the zOut buffer.
153801*/
153802static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
153803  int i, j;
153804  char zReverse[28];
153805  char *z, *z2;
153806  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
153807    /* The word is too big or too small for the porter stemmer.
153808    ** Fallback to the copy stemmer */
153809    copy_stemmer(zIn, nIn, zOut, pnOut);
153810    return;
153811  }
153812  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
153813    char c = zIn[i];
153814    if( c>='A' && c<='Z' ){
153815      zReverse[j] = c + 'a' - 'A';
153816    }else if( c>='a' && c<='z' ){
153817      zReverse[j] = c;
153818    }else{
153819      /* The use of a character not in [a-zA-Z] means that we fallback
153820      ** to the copy stemmer */
153821      copy_stemmer(zIn, nIn, zOut, pnOut);
153822      return;
153823    }
153824  }
153825  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
153826  z = &zReverse[j+1];
153827
153828
153829  /* Step 1a */
153830  if( z[0]=='s' ){
153831    if(
153832     !stem(&z, "sess", "ss", 0) &&
153833     !stem(&z, "sei", "i", 0)  &&
153834     !stem(&z, "ss", "ss", 0)
153835    ){
153836      z++;
153837    }
153838  }
153839
153840  /* Step 1b */
153841  z2 = z;
153842  if( stem(&z, "dee", "ee", m_gt_0) ){
153843    /* Do nothing.  The work was all in the test */
153844  }else if(
153845     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
153846      && z!=z2
153847  ){
153848     if( stem(&z, "ta", "ate", 0) ||
153849         stem(&z, "lb", "ble", 0) ||
153850         stem(&z, "zi", "ize", 0) ){
153851       /* Do nothing.  The work was all in the test */
153852     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
153853       z++;
153854     }else if( m_eq_1(z) && star_oh(z) ){
153855       *(--z) = 'e';
153856     }
153857  }
153858
153859  /* Step 1c */
153860  if( z[0]=='y' && hasVowel(z+1) ){
153861    z[0] = 'i';
153862  }
153863
153864  /* Step 2 */
153865  switch( z[1] ){
153866   case 'a':
153867     if( !stem(&z, "lanoita", "ate", m_gt_0) ){
153868       stem(&z, "lanoit", "tion", m_gt_0);
153869     }
153870     break;
153871   case 'c':
153872     if( !stem(&z, "icne", "ence", m_gt_0) ){
153873       stem(&z, "icna", "ance", m_gt_0);
153874     }
153875     break;
153876   case 'e':
153877     stem(&z, "rezi", "ize", m_gt_0);
153878     break;
153879   case 'g':
153880     stem(&z, "igol", "log", m_gt_0);
153881     break;
153882   case 'l':
153883     if( !stem(&z, "ilb", "ble", m_gt_0)
153884      && !stem(&z, "illa", "al", m_gt_0)
153885      && !stem(&z, "iltne", "ent", m_gt_0)
153886      && !stem(&z, "ile", "e", m_gt_0)
153887     ){
153888       stem(&z, "ilsuo", "ous", m_gt_0);
153889     }
153890     break;
153891   case 'o':
153892     if( !stem(&z, "noitazi", "ize", m_gt_0)
153893      && !stem(&z, "noita", "ate", m_gt_0)
153894     ){
153895       stem(&z, "rota", "ate", m_gt_0);
153896     }
153897     break;
153898   case 's':
153899     if( !stem(&z, "msila", "al", m_gt_0)
153900      && !stem(&z, "ssenevi", "ive", m_gt_0)
153901      && !stem(&z, "ssenluf", "ful", m_gt_0)
153902     ){
153903       stem(&z, "ssensuo", "ous", m_gt_0);
153904     }
153905     break;
153906   case 't':
153907     if( !stem(&z, "itila", "al", m_gt_0)
153908      && !stem(&z, "itivi", "ive", m_gt_0)
153909     ){
153910       stem(&z, "itilib", "ble", m_gt_0);
153911     }
153912     break;
153913  }
153914
153915  /* Step 3 */
153916  switch( z[0] ){
153917   case 'e':
153918     if( !stem(&z, "etaci", "ic", m_gt_0)
153919      && !stem(&z, "evita", "", m_gt_0)
153920     ){
153921       stem(&z, "ezila", "al", m_gt_0);
153922     }
153923     break;
153924   case 'i':
153925     stem(&z, "itici", "ic", m_gt_0);
153926     break;
153927   case 'l':
153928     if( !stem(&z, "laci", "ic", m_gt_0) ){
153929       stem(&z, "luf", "", m_gt_0);
153930     }
153931     break;
153932   case 's':
153933     stem(&z, "ssen", "", m_gt_0);
153934     break;
153935  }
153936
153937  /* Step 4 */
153938  switch( z[1] ){
153939   case 'a':
153940     if( z[0]=='l' && m_gt_1(z+2) ){
153941       z += 2;
153942     }
153943     break;
153944   case 'c':
153945     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
153946       z += 4;
153947     }
153948     break;
153949   case 'e':
153950     if( z[0]=='r' && m_gt_1(z+2) ){
153951       z += 2;
153952     }
153953     break;
153954   case 'i':
153955     if( z[0]=='c' && m_gt_1(z+2) ){
153956       z += 2;
153957     }
153958     break;
153959   case 'l':
153960     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
153961       z += 4;
153962     }
153963     break;
153964   case 'n':
153965     if( z[0]=='t' ){
153966       if( z[2]=='a' ){
153967         if( m_gt_1(z+3) ){
153968           z += 3;
153969         }
153970       }else if( z[2]=='e' ){
153971         if( !stem(&z, "tneme", "", m_gt_1)
153972          && !stem(&z, "tnem", "", m_gt_1)
153973         ){
153974           stem(&z, "tne", "", m_gt_1);
153975         }
153976       }
153977     }
153978     break;
153979   case 'o':
153980     if( z[0]=='u' ){
153981       if( m_gt_1(z+2) ){
153982         z += 2;
153983       }
153984     }else if( z[3]=='s' || z[3]=='t' ){
153985       stem(&z, "noi", "", m_gt_1);
153986     }
153987     break;
153988   case 's':
153989     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
153990       z += 3;
153991     }
153992     break;
153993   case 't':
153994     if( !stem(&z, "eta", "", m_gt_1) ){
153995       stem(&z, "iti", "", m_gt_1);
153996     }
153997     break;
153998   case 'u':
153999     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
154000       z += 3;
154001     }
154002     break;
154003   case 'v':
154004   case 'z':
154005     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
154006       z += 3;
154007     }
154008     break;
154009  }
154010
154011  /* Step 5a */
154012  if( z[0]=='e' ){
154013    if( m_gt_1(z+1) ){
154014      z++;
154015    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
154016      z++;
154017    }
154018  }
154019
154020  /* Step 5b */
154021  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
154022    z++;
154023  }
154024
154025  /* z[] is now the stemmed word in reverse order.  Flip it back
154026  ** around into forward order and return.
154027  */
154028  *pnOut = i = (int)strlen(z);
154029  zOut[i] = 0;
154030  while( *z ){
154031    zOut[--i] = *(z++);
154032  }
154033}
154034
154035/*
154036** Characters that can be part of a token.  We assume any character
154037** whose value is greater than 0x80 (any UTF character) can be
154038** part of a token.  In other words, delimiters all must have
154039** values of 0x7f or lower.
154040*/
154041static const char porterIdChar[] = {
154042/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
154043    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
154044    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
154045    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
154046    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
154047    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
154048};
154049#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
154050
154051/*
154052** Extract the next token from a tokenization cursor.  The cursor must
154053** have been opened by a prior call to porterOpen().
154054*/
154055static int porterNext(
154056  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
154057  const char **pzToken,               /* OUT: *pzToken is the token text */
154058  int *pnBytes,                       /* OUT: Number of bytes in token */
154059  int *piStartOffset,                 /* OUT: Starting offset of token */
154060  int *piEndOffset,                   /* OUT: Ending offset of token */
154061  int *piPosition                     /* OUT: Position integer of token */
154062){
154063  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
154064  const char *z = c->zInput;
154065
154066  while( c->iOffset<c->nInput ){
154067    int iStartOffset, ch;
154068
154069    /* Scan past delimiter characters */
154070    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
154071      c->iOffset++;
154072    }
154073
154074    /* Count non-delimiter characters. */
154075    iStartOffset = c->iOffset;
154076    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
154077      c->iOffset++;
154078    }
154079
154080    if( c->iOffset>iStartOffset ){
154081      int n = c->iOffset-iStartOffset;
154082      if( n>c->nAllocated ){
154083        char *pNew;
154084        c->nAllocated = n+20;
154085        pNew = sqlite3_realloc(c->zToken, c->nAllocated);
154086        if( !pNew ) return SQLITE_NOMEM;
154087        c->zToken = pNew;
154088      }
154089      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
154090      *pzToken = c->zToken;
154091      *piStartOffset = iStartOffset;
154092      *piEndOffset = c->iOffset;
154093      *piPosition = c->iToken++;
154094      return SQLITE_OK;
154095    }
154096  }
154097  return SQLITE_DONE;
154098}
154099
154100/*
154101** The set of routines that implement the porter-stemmer tokenizer
154102*/
154103static const sqlite3_tokenizer_module porterTokenizerModule = {
154104  0,
154105  porterCreate,
154106  porterDestroy,
154107  porterOpen,
154108  porterClose,
154109  porterNext,
154110  0
154111};
154112
154113/*
154114** Allocate a new porter tokenizer.  Return a pointer to the new
154115** tokenizer in *ppModule
154116*/
154117SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
154118  sqlite3_tokenizer_module const**ppModule
154119){
154120  *ppModule = &porterTokenizerModule;
154121}
154122
154123#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
154124
154125/************** End of fts3_porter.c *****************************************/
154126/************** Begin file fts3_tokenizer.c **********************************/
154127/*
154128** 2007 June 22
154129**
154130** The author disclaims copyright to this source code.  In place of
154131** a legal notice, here is a blessing:
154132**
154133**    May you do good and not evil.
154134**    May you find forgiveness for yourself and forgive others.
154135**    May you share freely, never taking more than you give.
154136**
154137******************************************************************************
154138**
154139** This is part of an SQLite module implementing full-text search.
154140** This particular file implements the generic tokenizer interface.
154141*/
154142
154143/*
154144** The code in this file is only compiled if:
154145**
154146**     * The FTS3 module is being built as an extension
154147**       (in which case SQLITE_CORE is not defined), or
154148**
154149**     * The FTS3 module is being built into the core of
154150**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
154151*/
154152/* #include "fts3Int.h" */
154153#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
154154
154155/* #include <assert.h> */
154156/* #include <string.h> */
154157
154158/*
154159** Return true if the two-argument version of fts3_tokenizer()
154160** has been activated via a prior call to sqlite3_db_config(db,
154161** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
154162*/
154163static int fts3TokenizerEnabled(sqlite3_context *context){
154164  sqlite3 *db = sqlite3_context_db_handle(context);
154165  int isEnabled = 0;
154166  sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
154167  return isEnabled;
154168}
154169
154170/*
154171** Implementation of the SQL scalar function for accessing the underlying
154172** hash table. This function may be called as follows:
154173**
154174**   SELECT <function-name>(<key-name>);
154175**   SELECT <function-name>(<key-name>, <pointer>);
154176**
154177** where <function-name> is the name passed as the second argument
154178** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
154179**
154180** If the <pointer> argument is specified, it must be a blob value
154181** containing a pointer to be stored as the hash data corresponding
154182** to the string <key-name>. If <pointer> is not specified, then
154183** the string <key-name> must already exist in the has table. Otherwise,
154184** an error is returned.
154185**
154186** Whether or not the <pointer> argument is specified, the value returned
154187** is a blob containing the pointer stored as the hash data corresponding
154188** to string <key-name> (after the hash-table is updated, if applicable).
154189*/
154190static void fts3TokenizerFunc(
154191  sqlite3_context *context,
154192  int argc,
154193  sqlite3_value **argv
154194){
154195  Fts3Hash *pHash;
154196  void *pPtr = 0;
154197  const unsigned char *zName;
154198  int nName;
154199
154200  assert( argc==1 || argc==2 );
154201
154202  pHash = (Fts3Hash *)sqlite3_user_data(context);
154203
154204  zName = sqlite3_value_text(argv[0]);
154205  nName = sqlite3_value_bytes(argv[0])+1;
154206
154207  if( argc==2 ){
154208    if( fts3TokenizerEnabled(context) ){
154209      void *pOld;
154210      int n = sqlite3_value_bytes(argv[1]);
154211      if( zName==0 || n!=sizeof(pPtr) ){
154212        sqlite3_result_error(context, "argument type mismatch", -1);
154213        return;
154214      }
154215      pPtr = *(void **)sqlite3_value_blob(argv[1]);
154216      pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
154217      if( pOld==pPtr ){
154218        sqlite3_result_error(context, "out of memory", -1);
154219      }
154220    }else{
154221      sqlite3_result_error(context, "fts3tokenize disabled", -1);
154222      return;
154223    }
154224  }else{
154225    if( zName ){
154226      pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
154227    }
154228    if( !pPtr ){
154229      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
154230      sqlite3_result_error(context, zErr, -1);
154231      sqlite3_free(zErr);
154232      return;
154233    }
154234  }
154235  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
154236}
154237
154238SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
154239  static const char isFtsIdChar[] = {
154240      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
154241      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
154242      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
154243      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
154244      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
154245      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
154246      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
154247      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
154248  };
154249  return (c&0x80 || isFtsIdChar[(int)(c)]);
154250}
154251
154252SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
154253  const char *z1;
154254  const char *z2 = 0;
154255
154256  /* Find the start of the next token. */
154257  z1 = zStr;
154258  while( z2==0 ){
154259    char c = *z1;
154260    switch( c ){
154261      case '\0': return 0;        /* No more tokens here */
154262      case '\'':
154263      case '"':
154264      case '`': {
154265        z2 = z1;
154266        while( *++z2 && (*z2!=c || *++z2==c) );
154267        break;
154268      }
154269      case '[':
154270        z2 = &z1[1];
154271        while( *z2 && z2[0]!=']' ) z2++;
154272        if( *z2 ) z2++;
154273        break;
154274
154275      default:
154276        if( sqlite3Fts3IsIdChar(*z1) ){
154277          z2 = &z1[1];
154278          while( sqlite3Fts3IsIdChar(*z2) ) z2++;
154279        }else{
154280          z1++;
154281        }
154282    }
154283  }
154284
154285  *pn = (int)(z2-z1);
154286  return z1;
154287}
154288
154289SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
154290  Fts3Hash *pHash,                /* Tokenizer hash table */
154291  const char *zArg,               /* Tokenizer name */
154292  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
154293  char **pzErr                    /* OUT: Set to malloced error message */
154294){
154295  int rc;
154296  char *z = (char *)zArg;
154297  int n = 0;
154298  char *zCopy;
154299  char *zEnd;                     /* Pointer to nul-term of zCopy */
154300  sqlite3_tokenizer_module *m;
154301
154302  zCopy = sqlite3_mprintf("%s", zArg);
154303  if( !zCopy ) return SQLITE_NOMEM;
154304  zEnd = &zCopy[strlen(zCopy)];
154305
154306  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
154307  if( z==0 ){
154308    assert( n==0 );
154309    z = zCopy;
154310  }
154311  z[n] = '\0';
154312  sqlite3Fts3Dequote(z);
154313
154314  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
154315  if( !m ){
154316    sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
154317    rc = SQLITE_ERROR;
154318  }else{
154319    char const **aArg = 0;
154320    int iArg = 0;
154321    z = &z[n+1];
154322    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
154323      int nNew = sizeof(char *)*(iArg+1);
154324      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
154325      if( !aNew ){
154326        sqlite3_free(zCopy);
154327        sqlite3_free((void *)aArg);
154328        return SQLITE_NOMEM;
154329      }
154330      aArg = aNew;
154331      aArg[iArg++] = z;
154332      z[n] = '\0';
154333      sqlite3Fts3Dequote(z);
154334      z = &z[n+1];
154335    }
154336    rc = m->xCreate(iArg, aArg, ppTok);
154337    assert( rc!=SQLITE_OK || *ppTok );
154338    if( rc!=SQLITE_OK ){
154339      sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
154340    }else{
154341      (*ppTok)->pModule = m;
154342    }
154343    sqlite3_free((void *)aArg);
154344  }
154345
154346  sqlite3_free(zCopy);
154347  return rc;
154348}
154349
154350
154351#ifdef SQLITE_TEST
154352
154353#if defined(INCLUDE_SQLITE_TCL_H)
154354#  include "sqlite_tcl.h"
154355#else
154356#  include "tcl.h"
154357#endif
154358/* #include <string.h> */
154359
154360/*
154361** Implementation of a special SQL scalar function for testing tokenizers
154362** designed to be used in concert with the Tcl testing framework. This
154363** function must be called with two or more arguments:
154364**
154365**   SELECT <function-name>(<key-name>, ..., <input-string>);
154366**
154367** where <function-name> is the name passed as the second argument
154368** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
154369** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
154370**
154371** The return value is a string that may be interpreted as a Tcl
154372** list. For each token in the <input-string>, three elements are
154373** added to the returned list. The first is the token position, the
154374** second is the token text (folded, stemmed, etc.) and the third is the
154375** substring of <input-string> associated with the token. For example,
154376** using the built-in "simple" tokenizer:
154377**
154378**   SELECT fts_tokenizer_test('simple', 'I don't see how');
154379**
154380** will return the string:
154381**
154382**   "{0 i I 1 dont don't 2 see see 3 how how}"
154383**
154384*/
154385static void testFunc(
154386  sqlite3_context *context,
154387  int argc,
154388  sqlite3_value **argv
154389){
154390  Fts3Hash *pHash;
154391  sqlite3_tokenizer_module *p;
154392  sqlite3_tokenizer *pTokenizer = 0;
154393  sqlite3_tokenizer_cursor *pCsr = 0;
154394
154395  const char *zErr = 0;
154396
154397  const char *zName;
154398  int nName;
154399  const char *zInput;
154400  int nInput;
154401
154402  const char *azArg[64];
154403
154404  const char *zToken;
154405  int nToken = 0;
154406  int iStart = 0;
154407  int iEnd = 0;
154408  int iPos = 0;
154409  int i;
154410
154411  Tcl_Obj *pRet;
154412
154413  if( argc<2 ){
154414    sqlite3_result_error(context, "insufficient arguments", -1);
154415    return;
154416  }
154417
154418  nName = sqlite3_value_bytes(argv[0]);
154419  zName = (const char *)sqlite3_value_text(argv[0]);
154420  nInput = sqlite3_value_bytes(argv[argc-1]);
154421  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
154422
154423  pHash = (Fts3Hash *)sqlite3_user_data(context);
154424  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
154425
154426  if( !p ){
154427    char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
154428    sqlite3_result_error(context, zErr2, -1);
154429    sqlite3_free(zErr2);
154430    return;
154431  }
154432
154433  pRet = Tcl_NewObj();
154434  Tcl_IncrRefCount(pRet);
154435
154436  for(i=1; i<argc-1; i++){
154437    azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
154438  }
154439
154440  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
154441    zErr = "error in xCreate()";
154442    goto finish;
154443  }
154444  pTokenizer->pModule = p;
154445  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
154446    zErr = "error in xOpen()";
154447    goto finish;
154448  }
154449
154450  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
154451    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
154452    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
154453    zToken = &zInput[iStart];
154454    nToken = iEnd-iStart;
154455    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
154456  }
154457
154458  if( SQLITE_OK!=p->xClose(pCsr) ){
154459    zErr = "error in xClose()";
154460    goto finish;
154461  }
154462  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
154463    zErr = "error in xDestroy()";
154464    goto finish;
154465  }
154466
154467finish:
154468  if( zErr ){
154469    sqlite3_result_error(context, zErr, -1);
154470  }else{
154471    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
154472  }
154473  Tcl_DecrRefCount(pRet);
154474}
154475
154476static
154477int registerTokenizer(
154478  sqlite3 *db,
154479  char *zName,
154480  const sqlite3_tokenizer_module *p
154481){
154482  int rc;
154483  sqlite3_stmt *pStmt;
154484  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
154485
154486  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
154487  if( rc!=SQLITE_OK ){
154488    return rc;
154489  }
154490
154491  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
154492  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
154493  sqlite3_step(pStmt);
154494
154495  return sqlite3_finalize(pStmt);
154496}
154497
154498
154499static
154500int queryTokenizer(
154501  sqlite3 *db,
154502  char *zName,
154503  const sqlite3_tokenizer_module **pp
154504){
154505  int rc;
154506  sqlite3_stmt *pStmt;
154507  const char zSql[] = "SELECT fts3_tokenizer(?)";
154508
154509  *pp = 0;
154510  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
154511  if( rc!=SQLITE_OK ){
154512    return rc;
154513  }
154514
154515  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
154516  if( SQLITE_ROW==sqlite3_step(pStmt) ){
154517    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
154518      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
154519    }
154520  }
154521
154522  return sqlite3_finalize(pStmt);
154523}
154524
154525SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
154526
154527/*
154528** Implementation of the scalar function fts3_tokenizer_internal_test().
154529** This function is used for testing only, it is not included in the
154530** build unless SQLITE_TEST is defined.
154531**
154532** The purpose of this is to test that the fts3_tokenizer() function
154533** can be used as designed by the C-code in the queryTokenizer and
154534** registerTokenizer() functions above. These two functions are repeated
154535** in the README.tokenizer file as an example, so it is important to
154536** test them.
154537**
154538** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
154539** function with no arguments. An assert() will fail if a problem is
154540** detected. i.e.:
154541**
154542**     SELECT fts3_tokenizer_internal_test();
154543**
154544*/
154545static void intTestFunc(
154546  sqlite3_context *context,
154547  int argc,
154548  sqlite3_value **argv
154549){
154550  int rc;
154551  const sqlite3_tokenizer_module *p1;
154552  const sqlite3_tokenizer_module *p2;
154553  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
154554
154555  UNUSED_PARAMETER(argc);
154556  UNUSED_PARAMETER(argv);
154557
154558  /* Test the query function */
154559  sqlite3Fts3SimpleTokenizerModule(&p1);
154560  rc = queryTokenizer(db, "simple", &p2);
154561  assert( rc==SQLITE_OK );
154562  assert( p1==p2 );
154563  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
154564  assert( rc==SQLITE_ERROR );
154565  assert( p2==0 );
154566  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
154567
154568  /* Test the storage function */
154569  if( fts3TokenizerEnabled(context) ){
154570    rc = registerTokenizer(db, "nosuchtokenizer", p1);
154571    assert( rc==SQLITE_OK );
154572    rc = queryTokenizer(db, "nosuchtokenizer", &p2);
154573    assert( rc==SQLITE_OK );
154574    assert( p2==p1 );
154575  }
154576
154577  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
154578}
154579
154580#endif
154581
154582/*
154583** Set up SQL objects in database db used to access the contents of
154584** the hash table pointed to by argument pHash. The hash table must
154585** been initialized to use string keys, and to take a private copy
154586** of the key when a value is inserted. i.e. by a call similar to:
154587**
154588**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
154589**
154590** This function adds a scalar function (see header comment above
154591** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
154592** defined at compilation time, a temporary virtual table (see header
154593** comment above struct HashTableVtab) to the database schema. Both
154594** provide read/write access to the contents of *pHash.
154595**
154596** The third argument to this function, zName, is used as the name
154597** of both the scalar and, if created, the virtual table.
154598*/
154599SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
154600  sqlite3 *db,
154601  Fts3Hash *pHash,
154602  const char *zName
154603){
154604  int rc = SQLITE_OK;
154605  void *p = (void *)pHash;
154606  const int any = SQLITE_ANY;
154607
154608#ifdef SQLITE_TEST
154609  char *zTest = 0;
154610  char *zTest2 = 0;
154611  void *pdb = (void *)db;
154612  zTest = sqlite3_mprintf("%s_test", zName);
154613  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
154614  if( !zTest || !zTest2 ){
154615    rc = SQLITE_NOMEM;
154616  }
154617#endif
154618
154619  if( SQLITE_OK==rc ){
154620    rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
154621  }
154622  if( SQLITE_OK==rc ){
154623    rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
154624  }
154625#ifdef SQLITE_TEST
154626  if( SQLITE_OK==rc ){
154627    rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
154628  }
154629  if( SQLITE_OK==rc ){
154630    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
154631  }
154632#endif
154633
154634#ifdef SQLITE_TEST
154635  sqlite3_free(zTest);
154636  sqlite3_free(zTest2);
154637#endif
154638
154639  return rc;
154640}
154641
154642#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
154643
154644/************** End of fts3_tokenizer.c **************************************/
154645/************** Begin file fts3_tokenizer1.c *********************************/
154646/*
154647** 2006 Oct 10
154648**
154649** The author disclaims copyright to this source code.  In place of
154650** a legal notice, here is a blessing:
154651**
154652**    May you do good and not evil.
154653**    May you find forgiveness for yourself and forgive others.
154654**    May you share freely, never taking more than you give.
154655**
154656******************************************************************************
154657**
154658** Implementation of the "simple" full-text-search tokenizer.
154659*/
154660
154661/*
154662** The code in this file is only compiled if:
154663**
154664**     * The FTS3 module is being built as an extension
154665**       (in which case SQLITE_CORE is not defined), or
154666**
154667**     * The FTS3 module is being built into the core of
154668**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
154669*/
154670/* #include "fts3Int.h" */
154671#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
154672
154673/* #include <assert.h> */
154674/* #include <stdlib.h> */
154675/* #include <stdio.h> */
154676/* #include <string.h> */
154677
154678/* #include "fts3_tokenizer.h" */
154679
154680typedef struct simple_tokenizer {
154681  sqlite3_tokenizer base;
154682  char delim[128];             /* flag ASCII delimiters */
154683} simple_tokenizer;
154684
154685typedef struct simple_tokenizer_cursor {
154686  sqlite3_tokenizer_cursor base;
154687  const char *pInput;          /* input we are tokenizing */
154688  int nBytes;                  /* size of the input */
154689  int iOffset;                 /* current position in pInput */
154690  int iToken;                  /* index of next token to be returned */
154691  char *pToken;                /* storage for current token */
154692  int nTokenAllocated;         /* space allocated to zToken buffer */
154693} simple_tokenizer_cursor;
154694
154695
154696static int simpleDelim(simple_tokenizer *t, unsigned char c){
154697  return c<0x80 && t->delim[c];
154698}
154699static int fts3_isalnum(int x){
154700  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
154701}
154702
154703/*
154704** Create a new tokenizer instance.
154705*/
154706static int simpleCreate(
154707  int argc, const char * const *argv,
154708  sqlite3_tokenizer **ppTokenizer
154709){
154710  simple_tokenizer *t;
154711
154712  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
154713  if( t==NULL ) return SQLITE_NOMEM;
154714  memset(t, 0, sizeof(*t));
154715
154716  /* TODO(shess) Delimiters need to remain the same from run to run,
154717  ** else we need to reindex.  One solution would be a meta-table to
154718  ** track such information in the database, then we'd only want this
154719  ** information on the initial create.
154720  */
154721  if( argc>1 ){
154722    int i, n = (int)strlen(argv[1]);
154723    for(i=0; i<n; i++){
154724      unsigned char ch = argv[1][i];
154725      /* We explicitly don't support UTF-8 delimiters for now. */
154726      if( ch>=0x80 ){
154727        sqlite3_free(t);
154728        return SQLITE_ERROR;
154729      }
154730      t->delim[ch] = 1;
154731    }
154732  } else {
154733    /* Mark non-alphanumeric ASCII characters as delimiters */
154734    int i;
154735    for(i=1; i<0x80; i++){
154736      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
154737    }
154738  }
154739
154740  *ppTokenizer = &t->base;
154741  return SQLITE_OK;
154742}
154743
154744/*
154745** Destroy a tokenizer
154746*/
154747static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
154748  sqlite3_free(pTokenizer);
154749  return SQLITE_OK;
154750}
154751
154752/*
154753** Prepare to begin tokenizing a particular string.  The input
154754** string to be tokenized is pInput[0..nBytes-1].  A cursor
154755** used to incrementally tokenize this string is returned in
154756** *ppCursor.
154757*/
154758static int simpleOpen(
154759  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
154760  const char *pInput, int nBytes,        /* String to be tokenized */
154761  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
154762){
154763  simple_tokenizer_cursor *c;
154764
154765  UNUSED_PARAMETER(pTokenizer);
154766
154767  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
154768  if( c==NULL ) return SQLITE_NOMEM;
154769
154770  c->pInput = pInput;
154771  if( pInput==0 ){
154772    c->nBytes = 0;
154773  }else if( nBytes<0 ){
154774    c->nBytes = (int)strlen(pInput);
154775  }else{
154776    c->nBytes = nBytes;
154777  }
154778  c->iOffset = 0;                 /* start tokenizing at the beginning */
154779  c->iToken = 0;
154780  c->pToken = NULL;               /* no space allocated, yet. */
154781  c->nTokenAllocated = 0;
154782
154783  *ppCursor = &c->base;
154784  return SQLITE_OK;
154785}
154786
154787/*
154788** Close a tokenization cursor previously opened by a call to
154789** simpleOpen() above.
154790*/
154791static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
154792  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
154793  sqlite3_free(c->pToken);
154794  sqlite3_free(c);
154795  return SQLITE_OK;
154796}
154797
154798/*
154799** Extract the next token from a tokenization cursor.  The cursor must
154800** have been opened by a prior call to simpleOpen().
154801*/
154802static int simpleNext(
154803  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
154804  const char **ppToken,               /* OUT: *ppToken is the token text */
154805  int *pnBytes,                       /* OUT: Number of bytes in token */
154806  int *piStartOffset,                 /* OUT: Starting offset of token */
154807  int *piEndOffset,                   /* OUT: Ending offset of token */
154808  int *piPosition                     /* OUT: Position integer of token */
154809){
154810  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
154811  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
154812  unsigned char *p = (unsigned char *)c->pInput;
154813
154814  while( c->iOffset<c->nBytes ){
154815    int iStartOffset;
154816
154817    /* Scan past delimiter characters */
154818    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
154819      c->iOffset++;
154820    }
154821
154822    /* Count non-delimiter characters. */
154823    iStartOffset = c->iOffset;
154824    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
154825      c->iOffset++;
154826    }
154827
154828    if( c->iOffset>iStartOffset ){
154829      int i, n = c->iOffset-iStartOffset;
154830      if( n>c->nTokenAllocated ){
154831        char *pNew;
154832        c->nTokenAllocated = n+20;
154833        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
154834        if( !pNew ) return SQLITE_NOMEM;
154835        c->pToken = pNew;
154836      }
154837      for(i=0; i<n; i++){
154838        /* TODO(shess) This needs expansion to handle UTF-8
154839        ** case-insensitivity.
154840        */
154841        unsigned char ch = p[iStartOffset+i];
154842        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
154843      }
154844      *ppToken = c->pToken;
154845      *pnBytes = n;
154846      *piStartOffset = iStartOffset;
154847      *piEndOffset = c->iOffset;
154848      *piPosition = c->iToken++;
154849
154850      return SQLITE_OK;
154851    }
154852  }
154853  return SQLITE_DONE;
154854}
154855
154856/*
154857** The set of routines that implement the simple tokenizer
154858*/
154859static const sqlite3_tokenizer_module simpleTokenizerModule = {
154860  0,
154861  simpleCreate,
154862  simpleDestroy,
154863  simpleOpen,
154864  simpleClose,
154865  simpleNext,
154866  0,
154867};
154868
154869/*
154870** Allocate a new simple tokenizer.  Return a pointer to the new
154871** tokenizer in *ppModule
154872*/
154873SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
154874  sqlite3_tokenizer_module const**ppModule
154875){
154876  *ppModule = &simpleTokenizerModule;
154877}
154878
154879#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
154880
154881/************** End of fts3_tokenizer1.c *************************************/
154882/************** Begin file fts3_tokenize_vtab.c ******************************/
154883/*
154884** 2013 Apr 22
154885**
154886** The author disclaims copyright to this source code.  In place of
154887** a legal notice, here is a blessing:
154888**
154889**    May you do good and not evil.
154890**    May you find forgiveness for yourself and forgive others.
154891**    May you share freely, never taking more than you give.
154892**
154893******************************************************************************
154894**
154895** This file contains code for the "fts3tokenize" virtual table module.
154896** An fts3tokenize virtual table is created as follows:
154897**
154898**   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
154899**       <tokenizer-name>, <arg-1>, ...
154900**   );
154901**
154902** The table created has the following schema:
154903**
154904**   CREATE TABLE <tbl>(input, token, start, end, position)
154905**
154906** When queried, the query must include a WHERE clause of type:
154907**
154908**   input = <string>
154909**
154910** The virtual table module tokenizes this <string>, using the FTS3
154911** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
154912** statement and returns one row for each token in the result. With
154913** fields set as follows:
154914**
154915**   input:   Always set to a copy of <string>
154916**   token:   A token from the input.
154917**   start:   Byte offset of the token within the input <string>.
154918**   end:     Byte offset of the byte immediately following the end of the
154919**            token within the input string.
154920**   pos:     Token offset of token within input.
154921**
154922*/
154923/* #include "fts3Int.h" */
154924#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
154925
154926/* #include <string.h> */
154927/* #include <assert.h> */
154928
154929typedef struct Fts3tokTable Fts3tokTable;
154930typedef struct Fts3tokCursor Fts3tokCursor;
154931
154932/*
154933** Virtual table structure.
154934*/
154935struct Fts3tokTable {
154936  sqlite3_vtab base;              /* Base class used by SQLite core */
154937  const sqlite3_tokenizer_module *pMod;
154938  sqlite3_tokenizer *pTok;
154939};
154940
154941/*
154942** Virtual table cursor structure.
154943*/
154944struct Fts3tokCursor {
154945  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
154946  char *zInput;                   /* Input string */
154947  sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
154948  int iRowid;                     /* Current 'rowid' value */
154949  const char *zToken;             /* Current 'token' value */
154950  int nToken;                     /* Size of zToken in bytes */
154951  int iStart;                     /* Current 'start' value */
154952  int iEnd;                       /* Current 'end' value */
154953  int iPos;                       /* Current 'pos' value */
154954};
154955
154956/*
154957** Query FTS for the tokenizer implementation named zName.
154958*/
154959static int fts3tokQueryTokenizer(
154960  Fts3Hash *pHash,
154961  const char *zName,
154962  const sqlite3_tokenizer_module **pp,
154963  char **pzErr
154964){
154965  sqlite3_tokenizer_module *p;
154966  int nName = (int)strlen(zName);
154967
154968  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
154969  if( !p ){
154970    sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
154971    return SQLITE_ERROR;
154972  }
154973
154974  *pp = p;
154975  return SQLITE_OK;
154976}
154977
154978/*
154979** The second argument, argv[], is an array of pointers to nul-terminated
154980** strings. This function makes a copy of the array and strings into a
154981** single block of memory. It then dequotes any of the strings that appear
154982** to be quoted.
154983**
154984** If successful, output parameter *pazDequote is set to point at the
154985** array of dequoted strings and SQLITE_OK is returned. The caller is
154986** responsible for eventually calling sqlite3_free() to free the array
154987** in this case. Or, if an error occurs, an SQLite error code is returned.
154988** The final value of *pazDequote is undefined in this case.
154989*/
154990static int fts3tokDequoteArray(
154991  int argc,                       /* Number of elements in argv[] */
154992  const char * const *argv,       /* Input array */
154993  char ***pazDequote              /* Output array */
154994){
154995  int rc = SQLITE_OK;             /* Return code */
154996  if( argc==0 ){
154997    *pazDequote = 0;
154998  }else{
154999    int i;
155000    int nByte = 0;
155001    char **azDequote;
155002
155003    for(i=0; i<argc; i++){
155004      nByte += (int)(strlen(argv[i]) + 1);
155005    }
155006
155007    *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
155008    if( azDequote==0 ){
155009      rc = SQLITE_NOMEM;
155010    }else{
155011      char *pSpace = (char *)&azDequote[argc];
155012      for(i=0; i<argc; i++){
155013        int n = (int)strlen(argv[i]);
155014        azDequote[i] = pSpace;
155015        memcpy(pSpace, argv[i], n+1);
155016        sqlite3Fts3Dequote(pSpace);
155017        pSpace += (n+1);
155018      }
155019    }
155020  }
155021
155022  return rc;
155023}
155024
155025/*
155026** Schema of the tokenizer table.
155027*/
155028#define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
155029
155030/*
155031** This function does all the work for both the xConnect and xCreate methods.
155032** These tables have no persistent representation of their own, so xConnect
155033** and xCreate are identical operations.
155034**
155035**   argv[0]: module name
155036**   argv[1]: database name
155037**   argv[2]: table name
155038**   argv[3]: first argument (tokenizer name)
155039*/
155040static int fts3tokConnectMethod(
155041  sqlite3 *db,                    /* Database connection */
155042  void *pHash,                    /* Hash table of tokenizers */
155043  int argc,                       /* Number of elements in argv array */
155044  const char * const *argv,       /* xCreate/xConnect argument array */
155045  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
155046  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
155047){
155048  Fts3tokTable *pTab = 0;
155049  const sqlite3_tokenizer_module *pMod = 0;
155050  sqlite3_tokenizer *pTok = 0;
155051  int rc;
155052  char **azDequote = 0;
155053  int nDequote;
155054
155055  rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
155056  if( rc!=SQLITE_OK ) return rc;
155057
155058  nDequote = argc-3;
155059  rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
155060
155061  if( rc==SQLITE_OK ){
155062    const char *zModule;
155063    if( nDequote<1 ){
155064      zModule = "simple";
155065    }else{
155066      zModule = azDequote[0];
155067    }
155068    rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
155069  }
155070
155071  assert( (rc==SQLITE_OK)==(pMod!=0) );
155072  if( rc==SQLITE_OK ){
155073    const char * const *azArg = (const char * const *)&azDequote[1];
155074    rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
155075  }
155076
155077  if( rc==SQLITE_OK ){
155078    pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
155079    if( pTab==0 ){
155080      rc = SQLITE_NOMEM;
155081    }
155082  }
155083
155084  if( rc==SQLITE_OK ){
155085    memset(pTab, 0, sizeof(Fts3tokTable));
155086    pTab->pMod = pMod;
155087    pTab->pTok = pTok;
155088    *ppVtab = &pTab->base;
155089  }else{
155090    if( pTok ){
155091      pMod->xDestroy(pTok);
155092    }
155093  }
155094
155095  sqlite3_free(azDequote);
155096  return rc;
155097}
155098
155099/*
155100** This function does the work for both the xDisconnect and xDestroy methods.
155101** These tables have no persistent representation of their own, so xDisconnect
155102** and xDestroy are identical operations.
155103*/
155104static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
155105  Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
155106
155107  pTab->pMod->xDestroy(pTab->pTok);
155108  sqlite3_free(pTab);
155109  return SQLITE_OK;
155110}
155111
155112/*
155113** xBestIndex - Analyze a WHERE and ORDER BY clause.
155114*/
155115static int fts3tokBestIndexMethod(
155116  sqlite3_vtab *pVTab,
155117  sqlite3_index_info *pInfo
155118){
155119  int i;
155120  UNUSED_PARAMETER(pVTab);
155121
155122  for(i=0; i<pInfo->nConstraint; i++){
155123    if( pInfo->aConstraint[i].usable
155124     && pInfo->aConstraint[i].iColumn==0
155125     && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
155126    ){
155127      pInfo->idxNum = 1;
155128      pInfo->aConstraintUsage[i].argvIndex = 1;
155129      pInfo->aConstraintUsage[i].omit = 1;
155130      pInfo->estimatedCost = 1;
155131      return SQLITE_OK;
155132    }
155133  }
155134
155135  pInfo->idxNum = 0;
155136  assert( pInfo->estimatedCost>1000000.0 );
155137
155138  return SQLITE_OK;
155139}
155140
155141/*
155142** xOpen - Open a cursor.
155143*/
155144static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
155145  Fts3tokCursor *pCsr;
155146  UNUSED_PARAMETER(pVTab);
155147
155148  pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
155149  if( pCsr==0 ){
155150    return SQLITE_NOMEM;
155151  }
155152  memset(pCsr, 0, sizeof(Fts3tokCursor));
155153
155154  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
155155  return SQLITE_OK;
155156}
155157
155158/*
155159** Reset the tokenizer cursor passed as the only argument. As if it had
155160** just been returned by fts3tokOpenMethod().
155161*/
155162static void fts3tokResetCursor(Fts3tokCursor *pCsr){
155163  if( pCsr->pCsr ){
155164    Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
155165    pTab->pMod->xClose(pCsr->pCsr);
155166    pCsr->pCsr = 0;
155167  }
155168  sqlite3_free(pCsr->zInput);
155169  pCsr->zInput = 0;
155170  pCsr->zToken = 0;
155171  pCsr->nToken = 0;
155172  pCsr->iStart = 0;
155173  pCsr->iEnd = 0;
155174  pCsr->iPos = 0;
155175  pCsr->iRowid = 0;
155176}
155177
155178/*
155179** xClose - Close a cursor.
155180*/
155181static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
155182  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
155183
155184  fts3tokResetCursor(pCsr);
155185  sqlite3_free(pCsr);
155186  return SQLITE_OK;
155187}
155188
155189/*
155190** xNext - Advance the cursor to the next row, if any.
155191*/
155192static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
155193  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
155194  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
155195  int rc;                         /* Return code */
155196
155197  pCsr->iRowid++;
155198  rc = pTab->pMod->xNext(pCsr->pCsr,
155199      &pCsr->zToken, &pCsr->nToken,
155200      &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
155201  );
155202
155203  if( rc!=SQLITE_OK ){
155204    fts3tokResetCursor(pCsr);
155205    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
155206  }
155207
155208  return rc;
155209}
155210
155211/*
155212** xFilter - Initialize a cursor to point at the start of its data.
155213*/
155214static int fts3tokFilterMethod(
155215  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
155216  int idxNum,                     /* Strategy index */
155217  const char *idxStr,             /* Unused */
155218  int nVal,                       /* Number of elements in apVal */
155219  sqlite3_value **apVal           /* Arguments for the indexing scheme */
155220){
155221  int rc = SQLITE_ERROR;
155222  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
155223  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
155224  UNUSED_PARAMETER(idxStr);
155225  UNUSED_PARAMETER(nVal);
155226
155227  fts3tokResetCursor(pCsr);
155228  if( idxNum==1 ){
155229    const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
155230    int nByte = sqlite3_value_bytes(apVal[0]);
155231    pCsr->zInput = sqlite3_malloc(nByte+1);
155232    if( pCsr->zInput==0 ){
155233      rc = SQLITE_NOMEM;
155234    }else{
155235      memcpy(pCsr->zInput, zByte, nByte);
155236      pCsr->zInput[nByte] = 0;
155237      rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
155238      if( rc==SQLITE_OK ){
155239        pCsr->pCsr->pTokenizer = pTab->pTok;
155240      }
155241    }
155242  }
155243
155244  if( rc!=SQLITE_OK ) return rc;
155245  return fts3tokNextMethod(pCursor);
155246}
155247
155248/*
155249** xEof - Return true if the cursor is at EOF, or false otherwise.
155250*/
155251static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
155252  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
155253  return (pCsr->zToken==0);
155254}
155255
155256/*
155257** xColumn - Return a column value.
155258*/
155259static int fts3tokColumnMethod(
155260  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
155261  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
155262  int iCol                        /* Index of column to read value from */
155263){
155264  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
155265
155266  /* CREATE TABLE x(input, token, start, end, position) */
155267  switch( iCol ){
155268    case 0:
155269      sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
155270      break;
155271    case 1:
155272      sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
155273      break;
155274    case 2:
155275      sqlite3_result_int(pCtx, pCsr->iStart);
155276      break;
155277    case 3:
155278      sqlite3_result_int(pCtx, pCsr->iEnd);
155279      break;
155280    default:
155281      assert( iCol==4 );
155282      sqlite3_result_int(pCtx, pCsr->iPos);
155283      break;
155284  }
155285  return SQLITE_OK;
155286}
155287
155288/*
155289** xRowid - Return the current rowid for the cursor.
155290*/
155291static int fts3tokRowidMethod(
155292  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
155293  sqlite_int64 *pRowid            /* OUT: Rowid value */
155294){
155295  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
155296  *pRowid = (sqlite3_int64)pCsr->iRowid;
155297  return SQLITE_OK;
155298}
155299
155300/*
155301** Register the fts3tok module with database connection db. Return SQLITE_OK
155302** if successful or an error code if sqlite3_create_module() fails.
155303*/
155304SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
155305  static const sqlite3_module fts3tok_module = {
155306     0,                           /* iVersion      */
155307     fts3tokConnectMethod,        /* xCreate       */
155308     fts3tokConnectMethod,        /* xConnect      */
155309     fts3tokBestIndexMethod,      /* xBestIndex    */
155310     fts3tokDisconnectMethod,     /* xDisconnect   */
155311     fts3tokDisconnectMethod,     /* xDestroy      */
155312     fts3tokOpenMethod,           /* xOpen         */
155313     fts3tokCloseMethod,          /* xClose        */
155314     fts3tokFilterMethod,         /* xFilter       */
155315     fts3tokNextMethod,           /* xNext         */
155316     fts3tokEofMethod,            /* xEof          */
155317     fts3tokColumnMethod,         /* xColumn       */
155318     fts3tokRowidMethod,          /* xRowid        */
155319     0,                           /* xUpdate       */
155320     0,                           /* xBegin        */
155321     0,                           /* xSync         */
155322     0,                           /* xCommit       */
155323     0,                           /* xRollback     */
155324     0,                           /* xFindFunction */
155325     0,                           /* xRename       */
155326     0,                           /* xSavepoint    */
155327     0,                           /* xRelease      */
155328     0                            /* xRollbackTo   */
155329  };
155330  int rc;                         /* Return code */
155331
155332  rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
155333  return rc;
155334}
155335
155336#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
155337
155338/************** End of fts3_tokenize_vtab.c **********************************/
155339/************** Begin file fts3_write.c **************************************/
155340/*
155341** 2009 Oct 23
155342**
155343** The author disclaims copyright to this source code.  In place of
155344** a legal notice, here is a blessing:
155345**
155346**    May you do good and not evil.
155347**    May you find forgiveness for yourself and forgive others.
155348**    May you share freely, never taking more than you give.
155349**
155350******************************************************************************
155351**
155352** This file is part of the SQLite FTS3 extension module. Specifically,
155353** this file contains code to insert, update and delete rows from FTS3
155354** tables. It also contains code to merge FTS3 b-tree segments. Some
155355** of the sub-routines used to merge segments are also used by the query
155356** code in fts3.c.
155357*/
155358
155359/* #include "fts3Int.h" */
155360#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
155361
155362/* #include <string.h> */
155363/* #include <assert.h> */
155364/* #include <stdlib.h> */
155365
155366
155367#define FTS_MAX_APPENDABLE_HEIGHT 16
155368
155369/*
155370** When full-text index nodes are loaded from disk, the buffer that they
155371** are loaded into has the following number of bytes of padding at the end
155372** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
155373** of 920 bytes is allocated for it.
155374**
155375** This means that if we have a pointer into a buffer containing node data,
155376** it is always safe to read up to two varints from it without risking an
155377** overread, even if the node data is corrupted.
155378*/
155379#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
155380
155381/*
155382** Under certain circumstances, b-tree nodes (doclists) can be loaded into
155383** memory incrementally instead of all at once. This can be a big performance
155384** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
155385** method before retrieving all query results (as may happen, for example,
155386** if a query has a LIMIT clause).
155387**
155388** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
155389** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
155390** The code is written so that the hard lower-limit for each of these values
155391** is 1. Clearly such small values would be inefficient, but can be useful
155392** for testing purposes.
155393**
155394** If this module is built with SQLITE_TEST defined, these constants may
155395** be overridden at runtime for testing purposes. File fts3_test.c contains
155396** a Tcl interface to read and write the values.
155397*/
155398#ifdef SQLITE_TEST
155399int test_fts3_node_chunksize = (4*1024);
155400int test_fts3_node_chunk_threshold = (4*1024)*4;
155401# define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
155402# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
155403#else
155404# define FTS3_NODE_CHUNKSIZE (4*1024)
155405# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
155406#endif
155407
155408/*
155409** The two values that may be meaningfully bound to the :1 parameter in
155410** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
155411*/
155412#define FTS_STAT_DOCTOTAL      0
155413#define FTS_STAT_INCRMERGEHINT 1
155414#define FTS_STAT_AUTOINCRMERGE 2
155415
155416/*
155417** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
155418** and incremental merge operation that takes place. This is used for
155419** debugging FTS only, it should not usually be turned on in production
155420** systems.
155421*/
155422#ifdef FTS3_LOG_MERGES
155423static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
155424  sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
155425}
155426#else
155427#define fts3LogMerge(x, y)
155428#endif
155429
155430
155431typedef struct PendingList PendingList;
155432typedef struct SegmentNode SegmentNode;
155433typedef struct SegmentWriter SegmentWriter;
155434
155435/*
155436** An instance of the following data structure is used to build doclists
155437** incrementally. See function fts3PendingListAppend() for details.
155438*/
155439struct PendingList {
155440  int nData;
155441  char *aData;
155442  int nSpace;
155443  sqlite3_int64 iLastDocid;
155444  sqlite3_int64 iLastCol;
155445  sqlite3_int64 iLastPos;
155446};
155447
155448
155449/*
155450** Each cursor has a (possibly empty) linked list of the following objects.
155451*/
155452struct Fts3DeferredToken {
155453  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
155454  int iCol;                       /* Column token must occur in */
155455  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
155456  PendingList *pList;             /* Doclist is assembled here */
155457};
155458
155459/*
155460** An instance of this structure is used to iterate through the terms on
155461** a contiguous set of segment b-tree leaf nodes. Although the details of
155462** this structure are only manipulated by code in this file, opaque handles
155463** of type Fts3SegReader* are also used by code in fts3.c to iterate through
155464** terms when querying the full-text index. See functions:
155465**
155466**   sqlite3Fts3SegReaderNew()
155467**   sqlite3Fts3SegReaderFree()
155468**   sqlite3Fts3SegReaderIterate()
155469**
155470** Methods used to manipulate Fts3SegReader structures:
155471**
155472**   fts3SegReaderNext()
155473**   fts3SegReaderFirstDocid()
155474**   fts3SegReaderNextDocid()
155475*/
155476struct Fts3SegReader {
155477  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
155478  u8 bLookup;                     /* True for a lookup only */
155479  u8 rootOnly;                    /* True for a root-only reader */
155480
155481  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
155482  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
155483  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
155484  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
155485
155486  char *aNode;                    /* Pointer to node data (or NULL) */
155487  int nNode;                      /* Size of buffer at aNode (or 0) */
155488  int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
155489  sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
155490
155491  Fts3HashElem **ppNextElem;
155492
155493  /* Variables set by fts3SegReaderNext(). These may be read directly
155494  ** by the caller. They are valid from the time SegmentReaderNew() returns
155495  ** until SegmentReaderNext() returns something other than SQLITE_OK
155496  ** (i.e. SQLITE_DONE).
155497  */
155498  int nTerm;                      /* Number of bytes in current term */
155499  char *zTerm;                    /* Pointer to current term */
155500  int nTermAlloc;                 /* Allocated size of zTerm buffer */
155501  char *aDoclist;                 /* Pointer to doclist of current entry */
155502  int nDoclist;                   /* Size of doclist in current entry */
155503
155504  /* The following variables are used by fts3SegReaderNextDocid() to iterate
155505  ** through the current doclist (aDoclist/nDoclist).
155506  */
155507  char *pOffsetList;
155508  int nOffsetList;                /* For descending pending seg-readers only */
155509  sqlite3_int64 iDocid;
155510};
155511
155512#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
155513#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
155514
155515/*
155516** An instance of this structure is used to create a segment b-tree in the
155517** database. The internal details of this type are only accessed by the
155518** following functions:
155519**
155520**   fts3SegWriterAdd()
155521**   fts3SegWriterFlush()
155522**   fts3SegWriterFree()
155523*/
155524struct SegmentWriter {
155525  SegmentNode *pTree;             /* Pointer to interior tree structure */
155526  sqlite3_int64 iFirst;           /* First slot in %_segments written */
155527  sqlite3_int64 iFree;            /* Next free slot in %_segments */
155528  char *zTerm;                    /* Pointer to previous term buffer */
155529  int nTerm;                      /* Number of bytes in zTerm */
155530  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
155531  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
155532  int nSize;                      /* Size of allocation at aData */
155533  int nData;                      /* Bytes of data in aData */
155534  char *aData;                    /* Pointer to block from malloc() */
155535  i64 nLeafData;                  /* Number of bytes of leaf data written */
155536};
155537
155538/*
155539** Type SegmentNode is used by the following three functions to create
155540** the interior part of the segment b+-tree structures (everything except
155541** the leaf nodes). These functions and type are only ever used by code
155542** within the fts3SegWriterXXX() family of functions described above.
155543**
155544**   fts3NodeAddTerm()
155545**   fts3NodeWrite()
155546**   fts3NodeFree()
155547**
155548** When a b+tree is written to the database (either as a result of a merge
155549** or the pending-terms table being flushed), leaves are written into the
155550** database file as soon as they are completely populated. The interior of
155551** the tree is assembled in memory and written out only once all leaves have
155552** been populated and stored. This is Ok, as the b+-tree fanout is usually
155553** very large, meaning that the interior of the tree consumes relatively
155554** little memory.
155555*/
155556struct SegmentNode {
155557  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
155558  SegmentNode *pRight;            /* Pointer to right-sibling */
155559  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
155560  int nEntry;                     /* Number of terms written to node so far */
155561  char *zTerm;                    /* Pointer to previous term buffer */
155562  int nTerm;                      /* Number of bytes in zTerm */
155563  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
155564  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
155565  int nData;                      /* Bytes of valid data so far */
155566  char *aData;                    /* Node data */
155567};
155568
155569/*
155570** Valid values for the second argument to fts3SqlStmt().
155571*/
155572#define SQL_DELETE_CONTENT             0
155573#define SQL_IS_EMPTY                   1
155574#define SQL_DELETE_ALL_CONTENT         2
155575#define SQL_DELETE_ALL_SEGMENTS        3
155576#define SQL_DELETE_ALL_SEGDIR          4
155577#define SQL_DELETE_ALL_DOCSIZE         5
155578#define SQL_DELETE_ALL_STAT            6
155579#define SQL_SELECT_CONTENT_BY_ROWID    7
155580#define SQL_NEXT_SEGMENT_INDEX         8
155581#define SQL_INSERT_SEGMENTS            9
155582#define SQL_NEXT_SEGMENTS_ID          10
155583#define SQL_INSERT_SEGDIR             11
155584#define SQL_SELECT_LEVEL              12
155585#define SQL_SELECT_LEVEL_RANGE        13
155586#define SQL_SELECT_LEVEL_COUNT        14
155587#define SQL_SELECT_SEGDIR_MAX_LEVEL   15
155588#define SQL_DELETE_SEGDIR_LEVEL       16
155589#define SQL_DELETE_SEGMENTS_RANGE     17
155590#define SQL_CONTENT_INSERT            18
155591#define SQL_DELETE_DOCSIZE            19
155592#define SQL_REPLACE_DOCSIZE           20
155593#define SQL_SELECT_DOCSIZE            21
155594#define SQL_SELECT_STAT               22
155595#define SQL_REPLACE_STAT              23
155596
155597#define SQL_SELECT_ALL_PREFIX_LEVEL   24
155598#define SQL_DELETE_ALL_TERMS_SEGDIR   25
155599#define SQL_DELETE_SEGDIR_RANGE       26
155600#define SQL_SELECT_ALL_LANGID         27
155601#define SQL_FIND_MERGE_LEVEL          28
155602#define SQL_MAX_LEAF_NODE_ESTIMATE    29
155603#define SQL_DELETE_SEGDIR_ENTRY       30
155604#define SQL_SHIFT_SEGDIR_ENTRY        31
155605#define SQL_SELECT_SEGDIR             32
155606#define SQL_CHOMP_SEGDIR              33
155607#define SQL_SEGMENT_IS_APPENDABLE     34
155608#define SQL_SELECT_INDEXES            35
155609#define SQL_SELECT_MXLEVEL            36
155610
155611#define SQL_SELECT_LEVEL_RANGE2       37
155612#define SQL_UPDATE_LEVEL_IDX          38
155613#define SQL_UPDATE_LEVEL              39
155614
155615/*
155616** This function is used to obtain an SQLite prepared statement handle
155617** for the statement identified by the second argument. If successful,
155618** *pp is set to the requested statement handle and SQLITE_OK returned.
155619** Otherwise, an SQLite error code is returned and *pp is set to 0.
155620**
155621** If argument apVal is not NULL, then it must point to an array with
155622** at least as many entries as the requested statement has bound
155623** parameters. The values are bound to the statements parameters before
155624** returning.
155625*/
155626static int fts3SqlStmt(
155627  Fts3Table *p,                   /* Virtual table handle */
155628  int eStmt,                      /* One of the SQL_XXX constants above */
155629  sqlite3_stmt **pp,              /* OUT: Statement handle */
155630  sqlite3_value **apVal           /* Values to bind to statement */
155631){
155632  const char *azSql[] = {
155633/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
155634/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
155635/* 2  */  "DELETE FROM %Q.'%q_content'",
155636/* 3  */  "DELETE FROM %Q.'%q_segments'",
155637/* 4  */  "DELETE FROM %Q.'%q_segdir'",
155638/* 5  */  "DELETE FROM %Q.'%q_docsize'",
155639/* 6  */  "DELETE FROM %Q.'%q_stat'",
155640/* 7  */  "SELECT %s WHERE rowid=?",
155641/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
155642/* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
155643/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
155644/* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
155645
155646          /* Return segments in order from oldest to newest.*/
155647/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
155648            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
155649/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
155650            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
155651            "ORDER BY level DESC, idx ASC",
155652
155653/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
155654/* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
155655
155656/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
155657/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
155658/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
155659/* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
155660/* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
155661/* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
155662/* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
155663/* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
155664/* 24 */  "",
155665/* 25 */  "",
155666
155667/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
155668/* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
155669
155670/* This statement is used to determine which level to read the input from
155671** when performing an incremental merge. It returns the absolute level number
155672** of the oldest level in the db that contains at least ? segments. Or,
155673** if no level in the FTS index contains more than ? segments, the statement
155674** returns zero rows.  */
155675/* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
155676         "  GROUP BY level HAVING cnt>=?"
155677         "  ORDER BY (level %% 1024) ASC LIMIT 1",
155678
155679/* Estimate the upper limit on the number of leaf nodes in a new segment
155680** created by merging the oldest :2 segments from absolute level :1. See
155681** function sqlite3Fts3Incrmerge() for details.  */
155682/* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
155683         "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
155684
155685/* SQL_DELETE_SEGDIR_ENTRY
155686**   Delete the %_segdir entry on absolute level :1 with index :2.  */
155687/* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
155688
155689/* SQL_SHIFT_SEGDIR_ENTRY
155690**   Modify the idx value for the segment with idx=:3 on absolute level :2
155691**   to :1.  */
155692/* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
155693
155694/* SQL_SELECT_SEGDIR
155695**   Read a single entry from the %_segdir table. The entry from absolute
155696**   level :1 with index value :2.  */
155697/* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
155698            "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
155699
155700/* SQL_CHOMP_SEGDIR
155701**   Update the start_block (:1) and root (:2) fields of the %_segdir
155702**   entry located on absolute level :3 with index :4.  */
155703/* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
155704            "WHERE level = ? AND idx = ?",
155705
155706/* SQL_SEGMENT_IS_APPENDABLE
155707**   Return a single row if the segment with end_block=? is appendable. Or
155708**   no rows otherwise.  */
155709/* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
155710
155711/* SQL_SELECT_INDEXES
155712**   Return the list of valid segment indexes for absolute level ?  */
155713/* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
155714
155715/* SQL_SELECT_MXLEVEL
155716**   Return the largest relative level in the FTS index or indexes.  */
155717/* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
155718
155719          /* Return segments in order from oldest to newest.*/
155720/* 37 */  "SELECT level, idx, end_block "
155721            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
155722            "ORDER BY level DESC, idx ASC",
155723
155724          /* Update statements used while promoting segments */
155725/* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
155726            "WHERE level=? AND idx=?",
155727/* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
155728
155729  };
155730  int rc = SQLITE_OK;
155731  sqlite3_stmt *pStmt;
155732
155733  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
155734  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
155735
155736  pStmt = p->aStmt[eStmt];
155737  if( !pStmt ){
155738    char *zSql;
155739    if( eStmt==SQL_CONTENT_INSERT ){
155740      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
155741    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
155742      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
155743    }else{
155744      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
155745    }
155746    if( !zSql ){
155747      rc = SQLITE_NOMEM;
155748    }else{
155749      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
155750      sqlite3_free(zSql);
155751      assert( rc==SQLITE_OK || pStmt==0 );
155752      p->aStmt[eStmt] = pStmt;
155753    }
155754  }
155755  if( apVal ){
155756    int i;
155757    int nParam = sqlite3_bind_parameter_count(pStmt);
155758    for(i=0; rc==SQLITE_OK && i<nParam; i++){
155759      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
155760    }
155761  }
155762  *pp = pStmt;
155763  return rc;
155764}
155765
155766
155767static int fts3SelectDocsize(
155768  Fts3Table *pTab,                /* FTS3 table handle */
155769  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
155770  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
155771){
155772  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
155773  int rc;                         /* Return code */
155774
155775  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
155776  if( rc==SQLITE_OK ){
155777    sqlite3_bind_int64(pStmt, 1, iDocid);
155778    rc = sqlite3_step(pStmt);
155779    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
155780      rc = sqlite3_reset(pStmt);
155781      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
155782      pStmt = 0;
155783    }else{
155784      rc = SQLITE_OK;
155785    }
155786  }
155787
155788  *ppStmt = pStmt;
155789  return rc;
155790}
155791
155792SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
155793  Fts3Table *pTab,                /* Fts3 table handle */
155794  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
155795){
155796  sqlite3_stmt *pStmt = 0;
155797  int rc;
155798  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
155799  if( rc==SQLITE_OK ){
155800    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
155801    if( sqlite3_step(pStmt)!=SQLITE_ROW
155802     || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
155803    ){
155804      rc = sqlite3_reset(pStmt);
155805      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
155806      pStmt = 0;
155807    }
155808  }
155809  *ppStmt = pStmt;
155810  return rc;
155811}
155812
155813SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
155814  Fts3Table *pTab,                /* Fts3 table handle */
155815  sqlite3_int64 iDocid,           /* Docid to read size data for */
155816  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
155817){
155818  return fts3SelectDocsize(pTab, iDocid, ppStmt);
155819}
155820
155821/*
155822** Similar to fts3SqlStmt(). Except, after binding the parameters in
155823** array apVal[] to the SQL statement identified by eStmt, the statement
155824** is executed.
155825**
155826** Returns SQLITE_OK if the statement is successfully executed, or an
155827** SQLite error code otherwise.
155828*/
155829static void fts3SqlExec(
155830  int *pRC,                /* Result code */
155831  Fts3Table *p,            /* The FTS3 table */
155832  int eStmt,               /* Index of statement to evaluate */
155833  sqlite3_value **apVal    /* Parameters to bind */
155834){
155835  sqlite3_stmt *pStmt;
155836  int rc;
155837  if( *pRC ) return;
155838  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
155839  if( rc==SQLITE_OK ){
155840    sqlite3_step(pStmt);
155841    rc = sqlite3_reset(pStmt);
155842  }
155843  *pRC = rc;
155844}
155845
155846
155847/*
155848** This function ensures that the caller has obtained an exclusive
155849** shared-cache table-lock on the %_segdir table. This is required before
155850** writing data to the fts3 table. If this lock is not acquired first, then
155851** the caller may end up attempting to take this lock as part of committing
155852** a transaction, causing SQLite to return SQLITE_LOCKED or
155853** LOCKED_SHAREDCACHEto a COMMIT command.
155854**
155855** It is best to avoid this because if FTS3 returns any error when
155856** committing a transaction, the whole transaction will be rolled back.
155857** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
155858** It can still happen if the user locks the underlying tables directly
155859** instead of accessing them via FTS.
155860*/
155861static int fts3Writelock(Fts3Table *p){
155862  int rc = SQLITE_OK;
155863
155864  if( p->nPendingData==0 ){
155865    sqlite3_stmt *pStmt;
155866    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
155867    if( rc==SQLITE_OK ){
155868      sqlite3_bind_null(pStmt, 1);
155869      sqlite3_step(pStmt);
155870      rc = sqlite3_reset(pStmt);
155871    }
155872  }
155873
155874  return rc;
155875}
155876
155877/*
155878** FTS maintains a separate indexes for each language-id (a 32-bit integer).
155879** Within each language id, a separate index is maintained to store the
155880** document terms, and each configured prefix size (configured the FTS
155881** "prefix=" option). And each index consists of multiple levels ("relative
155882** levels").
155883**
155884** All three of these values (the language id, the specific index and the
155885** level within the index) are encoded in 64-bit integer values stored
155886** in the %_segdir table on disk. This function is used to convert three
155887** separate component values into the single 64-bit integer value that
155888** can be used to query the %_segdir table.
155889**
155890** Specifically, each language-id/index combination is allocated 1024
155891** 64-bit integer level values ("absolute levels"). The main terms index
155892** for language-id 0 is allocate values 0-1023. The first prefix index
155893** (if any) for language-id 0 is allocated values 1024-2047. And so on.
155894** Language 1 indexes are allocated immediately following language 0.
155895**
155896** So, for a system with nPrefix prefix indexes configured, the block of
155897** absolute levels that corresponds to language-id iLangid and index
155898** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
155899*/
155900static sqlite3_int64 getAbsoluteLevel(
155901  Fts3Table *p,                   /* FTS3 table handle */
155902  int iLangid,                    /* Language id */
155903  int iIndex,                     /* Index in p->aIndex[] */
155904  int iLevel                      /* Level of segments */
155905){
155906  sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
155907  assert( iLangid>=0 );
155908  assert( p->nIndex>0 );
155909  assert( iIndex>=0 && iIndex<p->nIndex );
155910
155911  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
155912  return iBase + iLevel;
155913}
155914
155915/*
155916** Set *ppStmt to a statement handle that may be used to iterate through
155917** all rows in the %_segdir table, from oldest to newest. If successful,
155918** return SQLITE_OK. If an error occurs while preparing the statement,
155919** return an SQLite error code.
155920**
155921** There is only ever one instance of this SQL statement compiled for
155922** each FTS3 table.
155923**
155924** The statement returns the following columns from the %_segdir table:
155925**
155926**   0: idx
155927**   1: start_block
155928**   2: leaves_end_block
155929**   3: end_block
155930**   4: root
155931*/
155932SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
155933  Fts3Table *p,                   /* FTS3 table */
155934  int iLangid,                    /* Language being queried */
155935  int iIndex,                     /* Index for p->aIndex[] */
155936  int iLevel,                     /* Level to select (relative level) */
155937  sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
155938){
155939  int rc;
155940  sqlite3_stmt *pStmt = 0;
155941
155942  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
155943  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
155944  assert( iIndex>=0 && iIndex<p->nIndex );
155945
155946  if( iLevel<0 ){
155947    /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
155948    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
155949    if( rc==SQLITE_OK ){
155950      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
155951      sqlite3_bind_int64(pStmt, 2,
155952          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
155953      );
155954    }
155955  }else{
155956    /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
155957    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
155958    if( rc==SQLITE_OK ){
155959      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
155960    }
155961  }
155962  *ppStmt = pStmt;
155963  return rc;
155964}
155965
155966
155967/*
155968** Append a single varint to a PendingList buffer. SQLITE_OK is returned
155969** if successful, or an SQLite error code otherwise.
155970**
155971** This function also serves to allocate the PendingList structure itself.
155972** For example, to create a new PendingList structure containing two
155973** varints:
155974**
155975**   PendingList *p = 0;
155976**   fts3PendingListAppendVarint(&p, 1);
155977**   fts3PendingListAppendVarint(&p, 2);
155978*/
155979static int fts3PendingListAppendVarint(
155980  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
155981  sqlite3_int64 i                 /* Value to append to data */
155982){
155983  PendingList *p = *pp;
155984
155985  /* Allocate or grow the PendingList as required. */
155986  if( !p ){
155987    p = sqlite3_malloc(sizeof(*p) + 100);
155988    if( !p ){
155989      return SQLITE_NOMEM;
155990    }
155991    p->nSpace = 100;
155992    p->aData = (char *)&p[1];
155993    p->nData = 0;
155994  }
155995  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
155996    int nNew = p->nSpace * 2;
155997    p = sqlite3_realloc(p, sizeof(*p) + nNew);
155998    if( !p ){
155999      sqlite3_free(*pp);
156000      *pp = 0;
156001      return SQLITE_NOMEM;
156002    }
156003    p->nSpace = nNew;
156004    p->aData = (char *)&p[1];
156005  }
156006
156007  /* Append the new serialized varint to the end of the list. */
156008  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
156009  p->aData[p->nData] = '\0';
156010  *pp = p;
156011  return SQLITE_OK;
156012}
156013
156014/*
156015** Add a docid/column/position entry to a PendingList structure. Non-zero
156016** is returned if the structure is sqlite3_realloced as part of adding
156017** the entry. Otherwise, zero.
156018**
156019** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
156020** Zero is always returned in this case. Otherwise, if no OOM error occurs,
156021** it is set to SQLITE_OK.
156022*/
156023static int fts3PendingListAppend(
156024  PendingList **pp,               /* IN/OUT: PendingList structure */
156025  sqlite3_int64 iDocid,           /* Docid for entry to add */
156026  sqlite3_int64 iCol,             /* Column for entry to add */
156027  sqlite3_int64 iPos,             /* Position of term for entry to add */
156028  int *pRc                        /* OUT: Return code */
156029){
156030  PendingList *p = *pp;
156031  int rc = SQLITE_OK;
156032
156033  assert( !p || p->iLastDocid<=iDocid );
156034
156035  if( !p || p->iLastDocid!=iDocid ){
156036    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
156037    if( p ){
156038      assert( p->nData<p->nSpace );
156039      assert( p->aData[p->nData]==0 );
156040      p->nData++;
156041    }
156042    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
156043      goto pendinglistappend_out;
156044    }
156045    p->iLastCol = -1;
156046    p->iLastPos = 0;
156047    p->iLastDocid = iDocid;
156048  }
156049  if( iCol>0 && p->iLastCol!=iCol ){
156050    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
156051     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
156052    ){
156053      goto pendinglistappend_out;
156054    }
156055    p->iLastCol = iCol;
156056    p->iLastPos = 0;
156057  }
156058  if( iCol>=0 ){
156059    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
156060    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
156061    if( rc==SQLITE_OK ){
156062      p->iLastPos = iPos;
156063    }
156064  }
156065
156066 pendinglistappend_out:
156067  *pRc = rc;
156068  if( p!=*pp ){
156069    *pp = p;
156070    return 1;
156071  }
156072  return 0;
156073}
156074
156075/*
156076** Free a PendingList object allocated by fts3PendingListAppend().
156077*/
156078static void fts3PendingListDelete(PendingList *pList){
156079  sqlite3_free(pList);
156080}
156081
156082/*
156083** Add an entry to one of the pending-terms hash tables.
156084*/
156085static int fts3PendingTermsAddOne(
156086  Fts3Table *p,
156087  int iCol,
156088  int iPos,
156089  Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
156090  const char *zToken,
156091  int nToken
156092){
156093  PendingList *pList;
156094  int rc = SQLITE_OK;
156095
156096  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
156097  if( pList ){
156098    p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
156099  }
156100  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
156101    if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
156102      /* Malloc failed while inserting the new entry. This can only
156103      ** happen if there was no previous entry for this token.
156104      */
156105      assert( 0==fts3HashFind(pHash, zToken, nToken) );
156106      sqlite3_free(pList);
156107      rc = SQLITE_NOMEM;
156108    }
156109  }
156110  if( rc==SQLITE_OK ){
156111    p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
156112  }
156113  return rc;
156114}
156115
156116/*
156117** Tokenize the nul-terminated string zText and add all tokens to the
156118** pending-terms hash-table. The docid used is that currently stored in
156119** p->iPrevDocid, and the column is specified by argument iCol.
156120**
156121** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
156122*/
156123static int fts3PendingTermsAdd(
156124  Fts3Table *p,                   /* Table into which text will be inserted */
156125  int iLangid,                    /* Language id to use */
156126  const char *zText,              /* Text of document to be inserted */
156127  int iCol,                       /* Column into which text is being inserted */
156128  u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
156129){
156130  int rc;
156131  int iStart = 0;
156132  int iEnd = 0;
156133  int iPos = 0;
156134  int nWord = 0;
156135
156136  char const *zToken;
156137  int nToken = 0;
156138
156139  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
156140  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
156141  sqlite3_tokenizer_cursor *pCsr;
156142  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
156143      const char**,int*,int*,int*,int*);
156144
156145  assert( pTokenizer && pModule );
156146
156147  /* If the user has inserted a NULL value, this function may be called with
156148  ** zText==0. In this case, add zero token entries to the hash table and
156149  ** return early. */
156150  if( zText==0 ){
156151    *pnWord = 0;
156152    return SQLITE_OK;
156153  }
156154
156155  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
156156  if( rc!=SQLITE_OK ){
156157    return rc;
156158  }
156159
156160  xNext = pModule->xNext;
156161  while( SQLITE_OK==rc
156162      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
156163  ){
156164    int i;
156165    if( iPos>=nWord ) nWord = iPos+1;
156166
156167    /* Positions cannot be negative; we use -1 as a terminator internally.
156168    ** Tokens must have a non-zero length.
156169    */
156170    if( iPos<0 || !zToken || nToken<=0 ){
156171      rc = SQLITE_ERROR;
156172      break;
156173    }
156174
156175    /* Add the term to the terms index */
156176    rc = fts3PendingTermsAddOne(
156177        p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
156178    );
156179
156180    /* Add the term to each of the prefix indexes that it is not too
156181    ** short for. */
156182    for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
156183      struct Fts3Index *pIndex = &p->aIndex[i];
156184      if( nToken<pIndex->nPrefix ) continue;
156185      rc = fts3PendingTermsAddOne(
156186          p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
156187      );
156188    }
156189  }
156190
156191  pModule->xClose(pCsr);
156192  *pnWord += nWord;
156193  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
156194}
156195
156196/*
156197** Calling this function indicates that subsequent calls to
156198** fts3PendingTermsAdd() are to add term/position-list pairs for the
156199** contents of the document with docid iDocid.
156200*/
156201static int fts3PendingTermsDocid(
156202  Fts3Table *p,                   /* Full-text table handle */
156203  int bDelete,                    /* True if this op is a delete */
156204  int iLangid,                    /* Language id of row being written */
156205  sqlite_int64 iDocid             /* Docid of row being written */
156206){
156207  assert( iLangid>=0 );
156208  assert( bDelete==1 || bDelete==0 );
156209
156210  /* TODO(shess) Explore whether partially flushing the buffer on
156211  ** forced-flush would provide better performance.  I suspect that if
156212  ** we ordered the doclists by size and flushed the largest until the
156213  ** buffer was half empty, that would let the less frequent terms
156214  ** generate longer doclists.
156215  */
156216  if( iDocid<p->iPrevDocid
156217   || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
156218   || p->iPrevLangid!=iLangid
156219   || p->nPendingData>p->nMaxPendingData
156220  ){
156221    int rc = sqlite3Fts3PendingTermsFlush(p);
156222    if( rc!=SQLITE_OK ) return rc;
156223  }
156224  p->iPrevDocid = iDocid;
156225  p->iPrevLangid = iLangid;
156226  p->bPrevDelete = bDelete;
156227  return SQLITE_OK;
156228}
156229
156230/*
156231** Discard the contents of the pending-terms hash tables.
156232*/
156233SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
156234  int i;
156235  for(i=0; i<p->nIndex; i++){
156236    Fts3HashElem *pElem;
156237    Fts3Hash *pHash = &p->aIndex[i].hPending;
156238    for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
156239      PendingList *pList = (PendingList *)fts3HashData(pElem);
156240      fts3PendingListDelete(pList);
156241    }
156242    fts3HashClear(pHash);
156243  }
156244  p->nPendingData = 0;
156245}
156246
156247/*
156248** This function is called by the xUpdate() method as part of an INSERT
156249** operation. It adds entries for each term in the new record to the
156250** pendingTerms hash table.
156251**
156252** Argument apVal is the same as the similarly named argument passed to
156253** fts3InsertData(). Parameter iDocid is the docid of the new row.
156254*/
156255static int fts3InsertTerms(
156256  Fts3Table *p,
156257  int iLangid,
156258  sqlite3_value **apVal,
156259  u32 *aSz
156260){
156261  int i;                          /* Iterator variable */
156262  for(i=2; i<p->nColumn+2; i++){
156263    int iCol = i-2;
156264    if( p->abNotindexed[iCol]==0 ){
156265      const char *zText = (const char *)sqlite3_value_text(apVal[i]);
156266      int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
156267      if( rc!=SQLITE_OK ){
156268        return rc;
156269      }
156270      aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
156271    }
156272  }
156273  return SQLITE_OK;
156274}
156275
156276/*
156277** This function is called by the xUpdate() method for an INSERT operation.
156278** The apVal parameter is passed a copy of the apVal argument passed by
156279** SQLite to the xUpdate() method. i.e:
156280**
156281**   apVal[0]                Not used for INSERT.
156282**   apVal[1]                rowid
156283**   apVal[2]                Left-most user-defined column
156284**   ...
156285**   apVal[p->nColumn+1]     Right-most user-defined column
156286**   apVal[p->nColumn+2]     Hidden column with same name as table
156287**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
156288**   apVal[p->nColumn+4]     Hidden languageid column
156289*/
156290static int fts3InsertData(
156291  Fts3Table *p,                   /* Full-text table */
156292  sqlite3_value **apVal,          /* Array of values to insert */
156293  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
156294){
156295  int rc;                         /* Return code */
156296  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
156297
156298  if( p->zContentTbl ){
156299    sqlite3_value *pRowid = apVal[p->nColumn+3];
156300    if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
156301      pRowid = apVal[1];
156302    }
156303    if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
156304      return SQLITE_CONSTRAINT;
156305    }
156306    *piDocid = sqlite3_value_int64(pRowid);
156307    return SQLITE_OK;
156308  }
156309
156310  /* Locate the statement handle used to insert data into the %_content
156311  ** table. The SQL for this statement is:
156312  **
156313  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
156314  **
156315  ** The statement features N '?' variables, where N is the number of user
156316  ** defined columns in the FTS3 table, plus one for the docid field.
156317  */
156318  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
156319  if( rc==SQLITE_OK && p->zLanguageid ){
156320    rc = sqlite3_bind_int(
156321        pContentInsert, p->nColumn+2,
156322        sqlite3_value_int(apVal[p->nColumn+4])
156323    );
156324  }
156325  if( rc!=SQLITE_OK ) return rc;
156326
156327  /* There is a quirk here. The users INSERT statement may have specified
156328  ** a value for the "rowid" field, for the "docid" field, or for both.
156329  ** Which is a problem, since "rowid" and "docid" are aliases for the
156330  ** same value. For example:
156331  **
156332  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
156333  **
156334  ** In FTS3, this is an error. It is an error to specify non-NULL values
156335  ** for both docid and some other rowid alias.
156336  */
156337  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
156338    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
156339     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
156340    ){
156341      /* A rowid/docid conflict. */
156342      return SQLITE_ERROR;
156343    }
156344    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
156345    if( rc!=SQLITE_OK ) return rc;
156346  }
156347
156348  /* Execute the statement to insert the record. Set *piDocid to the
156349  ** new docid value.
156350  */
156351  sqlite3_step(pContentInsert);
156352  rc = sqlite3_reset(pContentInsert);
156353
156354  *piDocid = sqlite3_last_insert_rowid(p->db);
156355  return rc;
156356}
156357
156358
156359
156360/*
156361** Remove all data from the FTS3 table. Clear the hash table containing
156362** pending terms.
156363*/
156364static int fts3DeleteAll(Fts3Table *p, int bContent){
156365  int rc = SQLITE_OK;             /* Return code */
156366
156367  /* Discard the contents of the pending-terms hash table. */
156368  sqlite3Fts3PendingTermsClear(p);
156369
156370  /* Delete everything from the shadow tables. Except, leave %_content as
156371  ** is if bContent is false.  */
156372  assert( p->zContentTbl==0 || bContent==0 );
156373  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
156374  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
156375  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
156376  if( p->bHasDocsize ){
156377    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
156378  }
156379  if( p->bHasStat ){
156380    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
156381  }
156382  return rc;
156383}
156384
156385/*
156386**
156387*/
156388static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
156389  int iLangid = 0;
156390  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
156391  return iLangid;
156392}
156393
156394/*
156395** The first element in the apVal[] array is assumed to contain the docid
156396** (an integer) of a row about to be deleted. Remove all terms from the
156397** full-text index.
156398*/
156399static void fts3DeleteTerms(
156400  int *pRC,               /* Result code */
156401  Fts3Table *p,           /* The FTS table to delete from */
156402  sqlite3_value *pRowid,  /* The docid to be deleted */
156403  u32 *aSz,               /* Sizes of deleted document written here */
156404  int *pbFound            /* OUT: Set to true if row really does exist */
156405){
156406  int rc;
156407  sqlite3_stmt *pSelect;
156408
156409  assert( *pbFound==0 );
156410  if( *pRC ) return;
156411  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
156412  if( rc==SQLITE_OK ){
156413    if( SQLITE_ROW==sqlite3_step(pSelect) ){
156414      int i;
156415      int iLangid = langidFromSelect(p, pSelect);
156416      i64 iDocid = sqlite3_column_int64(pSelect, 0);
156417      rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
156418      for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
156419        int iCol = i-1;
156420        if( p->abNotindexed[iCol]==0 ){
156421          const char *zText = (const char *)sqlite3_column_text(pSelect, i);
156422          rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
156423          aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
156424        }
156425      }
156426      if( rc!=SQLITE_OK ){
156427        sqlite3_reset(pSelect);
156428        *pRC = rc;
156429        return;
156430      }
156431      *pbFound = 1;
156432    }
156433    rc = sqlite3_reset(pSelect);
156434  }else{
156435    sqlite3_reset(pSelect);
156436  }
156437  *pRC = rc;
156438}
156439
156440/*
156441** Forward declaration to account for the circular dependency between
156442** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
156443*/
156444static int fts3SegmentMerge(Fts3Table *, int, int, int);
156445
156446/*
156447** This function allocates a new level iLevel index in the segdir table.
156448** Usually, indexes are allocated within a level sequentially starting
156449** with 0, so the allocated index is one greater than the value returned
156450** by:
156451**
156452**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
156453**
156454** However, if there are already FTS3_MERGE_COUNT indexes at the requested
156455** level, they are merged into a single level (iLevel+1) segment and the
156456** allocated index is 0.
156457**
156458** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
156459** returned. Otherwise, an SQLite error code is returned.
156460*/
156461static int fts3AllocateSegdirIdx(
156462  Fts3Table *p,
156463  int iLangid,                    /* Language id */
156464  int iIndex,                     /* Index for p->aIndex */
156465  int iLevel,
156466  int *piIdx
156467){
156468  int rc;                         /* Return Code */
156469  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
156470  int iNext = 0;                  /* Result of query pNextIdx */
156471
156472  assert( iLangid>=0 );
156473  assert( p->nIndex>=1 );
156474
156475  /* Set variable iNext to the next available segdir index at level iLevel. */
156476  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
156477  if( rc==SQLITE_OK ){
156478    sqlite3_bind_int64(
156479        pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
156480    );
156481    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
156482      iNext = sqlite3_column_int(pNextIdx, 0);
156483    }
156484    rc = sqlite3_reset(pNextIdx);
156485  }
156486
156487  if( rc==SQLITE_OK ){
156488    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
156489    ** full, merge all segments in level iLevel into a single iLevel+1
156490    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
156491    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
156492    */
156493    if( iNext>=FTS3_MERGE_COUNT ){
156494      fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
156495      rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
156496      *piIdx = 0;
156497    }else{
156498      *piIdx = iNext;
156499    }
156500  }
156501
156502  return rc;
156503}
156504
156505/*
156506** The %_segments table is declared as follows:
156507**
156508**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
156509**
156510** This function reads data from a single row of the %_segments table. The
156511** specific row is identified by the iBlockid parameter. If paBlob is not
156512** NULL, then a buffer is allocated using sqlite3_malloc() and populated
156513** with the contents of the blob stored in the "block" column of the
156514** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
156515** to the size of the blob in bytes before returning.
156516**
156517** If an error occurs, or the table does not contain the specified row,
156518** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
156519** paBlob is non-NULL, then it is the responsibility of the caller to
156520** eventually free the returned buffer.
156521**
156522** This function may leave an open sqlite3_blob* handle in the
156523** Fts3Table.pSegments variable. This handle is reused by subsequent calls
156524** to this function. The handle may be closed by calling the
156525** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
156526** performance improvement, but the blob handle should always be closed
156527** before control is returned to the user (to prevent a lock being held
156528** on the database file for longer than necessary). Thus, any virtual table
156529** method (xFilter etc.) that may directly or indirectly call this function
156530** must call sqlite3Fts3SegmentsClose() before returning.
156531*/
156532SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
156533  Fts3Table *p,                   /* FTS3 table handle */
156534  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
156535  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
156536  int *pnBlob,                    /* OUT: Size of blob data */
156537  int *pnLoad                     /* OUT: Bytes actually loaded */
156538){
156539  int rc;                         /* Return code */
156540
156541  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
156542  assert( pnBlob );
156543
156544  if( p->pSegments ){
156545    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
156546  }else{
156547    if( 0==p->zSegmentsTbl ){
156548      p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
156549      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
156550    }
156551    rc = sqlite3_blob_open(
156552       p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
156553    );
156554  }
156555
156556  if( rc==SQLITE_OK ){
156557    int nByte = sqlite3_blob_bytes(p->pSegments);
156558    *pnBlob = nByte;
156559    if( paBlob ){
156560      char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
156561      if( !aByte ){
156562        rc = SQLITE_NOMEM;
156563      }else{
156564        if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
156565          nByte = FTS3_NODE_CHUNKSIZE;
156566          *pnLoad = nByte;
156567        }
156568        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
156569        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
156570        if( rc!=SQLITE_OK ){
156571          sqlite3_free(aByte);
156572          aByte = 0;
156573        }
156574      }
156575      *paBlob = aByte;
156576    }
156577  }
156578
156579  return rc;
156580}
156581
156582/*
156583** Close the blob handle at p->pSegments, if it is open. See comments above
156584** the sqlite3Fts3ReadBlock() function for details.
156585*/
156586SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
156587  sqlite3_blob_close(p->pSegments);
156588  p->pSegments = 0;
156589}
156590
156591static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
156592  int nRead;                      /* Number of bytes to read */
156593  int rc;                         /* Return code */
156594
156595  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
156596  rc = sqlite3_blob_read(
156597      pReader->pBlob,
156598      &pReader->aNode[pReader->nPopulate],
156599      nRead,
156600      pReader->nPopulate
156601  );
156602
156603  if( rc==SQLITE_OK ){
156604    pReader->nPopulate += nRead;
156605    memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
156606    if( pReader->nPopulate==pReader->nNode ){
156607      sqlite3_blob_close(pReader->pBlob);
156608      pReader->pBlob = 0;
156609      pReader->nPopulate = 0;
156610    }
156611  }
156612  return rc;
156613}
156614
156615static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
156616  int rc = SQLITE_OK;
156617  assert( !pReader->pBlob
156618       || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
156619  );
156620  while( pReader->pBlob && rc==SQLITE_OK
156621     &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
156622  ){
156623    rc = fts3SegReaderIncrRead(pReader);
156624  }
156625  return rc;
156626}
156627
156628/*
156629** Set an Fts3SegReader cursor to point at EOF.
156630*/
156631static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
156632  if( !fts3SegReaderIsRootOnly(pSeg) ){
156633    sqlite3_free(pSeg->aNode);
156634    sqlite3_blob_close(pSeg->pBlob);
156635    pSeg->pBlob = 0;
156636  }
156637  pSeg->aNode = 0;
156638}
156639
156640/*
156641** Move the iterator passed as the first argument to the next term in the
156642** segment. If successful, SQLITE_OK is returned. If there is no next term,
156643** SQLITE_DONE. Otherwise, an SQLite error code.
156644*/
156645static int fts3SegReaderNext(
156646  Fts3Table *p,
156647  Fts3SegReader *pReader,
156648  int bIncr
156649){
156650  int rc;                         /* Return code of various sub-routines */
156651  char *pNext;                    /* Cursor variable */
156652  int nPrefix;                    /* Number of bytes in term prefix */
156653  int nSuffix;                    /* Number of bytes in term suffix */
156654
156655  if( !pReader->aDoclist ){
156656    pNext = pReader->aNode;
156657  }else{
156658    pNext = &pReader->aDoclist[pReader->nDoclist];
156659  }
156660
156661  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
156662
156663    if( fts3SegReaderIsPending(pReader) ){
156664      Fts3HashElem *pElem = *(pReader->ppNextElem);
156665      sqlite3_free(pReader->aNode);
156666      pReader->aNode = 0;
156667      if( pElem ){
156668        char *aCopy;
156669        PendingList *pList = (PendingList *)fts3HashData(pElem);
156670        int nCopy = pList->nData+1;
156671        pReader->zTerm = (char *)fts3HashKey(pElem);
156672        pReader->nTerm = fts3HashKeysize(pElem);
156673        aCopy = (char*)sqlite3_malloc(nCopy);
156674        if( !aCopy ) return SQLITE_NOMEM;
156675        memcpy(aCopy, pList->aData, nCopy);
156676        pReader->nNode = pReader->nDoclist = nCopy;
156677        pReader->aNode = pReader->aDoclist = aCopy;
156678        pReader->ppNextElem++;
156679        assert( pReader->aNode );
156680      }
156681      return SQLITE_OK;
156682    }
156683
156684    fts3SegReaderSetEof(pReader);
156685
156686    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
156687    ** blocks have already been traversed.  */
156688    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
156689    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
156690      return SQLITE_OK;
156691    }
156692
156693    rc = sqlite3Fts3ReadBlock(
156694        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
156695        (bIncr ? &pReader->nPopulate : 0)
156696    );
156697    if( rc!=SQLITE_OK ) return rc;
156698    assert( pReader->pBlob==0 );
156699    if( bIncr && pReader->nPopulate<pReader->nNode ){
156700      pReader->pBlob = p->pSegments;
156701      p->pSegments = 0;
156702    }
156703    pNext = pReader->aNode;
156704  }
156705
156706  assert( !fts3SegReaderIsPending(pReader) );
156707
156708  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
156709  if( rc!=SQLITE_OK ) return rc;
156710
156711  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
156712  ** safe (no risk of overread) even if the node data is corrupted. */
156713  pNext += fts3GetVarint32(pNext, &nPrefix);
156714  pNext += fts3GetVarint32(pNext, &nSuffix);
156715  if( nPrefix<0 || nSuffix<=0
156716   || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
156717  ){
156718    return FTS_CORRUPT_VTAB;
156719  }
156720
156721  if( nPrefix+nSuffix>pReader->nTermAlloc ){
156722    int nNew = (nPrefix+nSuffix)*2;
156723    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
156724    if( !zNew ){
156725      return SQLITE_NOMEM;
156726    }
156727    pReader->zTerm = zNew;
156728    pReader->nTermAlloc = nNew;
156729  }
156730
156731  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
156732  if( rc!=SQLITE_OK ) return rc;
156733
156734  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
156735  pReader->nTerm = nPrefix+nSuffix;
156736  pNext += nSuffix;
156737  pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
156738  pReader->aDoclist = pNext;
156739  pReader->pOffsetList = 0;
156740
156741  /* Check that the doclist does not appear to extend past the end of the
156742  ** b-tree node. And that the final byte of the doclist is 0x00. If either
156743  ** of these statements is untrue, then the data structure is corrupt.
156744  */
156745  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
156746   || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
156747  ){
156748    return FTS_CORRUPT_VTAB;
156749  }
156750  return SQLITE_OK;
156751}
156752
156753/*
156754** Set the SegReader to point to the first docid in the doclist associated
156755** with the current term.
156756*/
156757static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
156758  int rc = SQLITE_OK;
156759  assert( pReader->aDoclist );
156760  assert( !pReader->pOffsetList );
156761  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
156762    u8 bEof = 0;
156763    pReader->iDocid = 0;
156764    pReader->nOffsetList = 0;
156765    sqlite3Fts3DoclistPrev(0,
156766        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
156767        &pReader->iDocid, &pReader->nOffsetList, &bEof
156768    );
156769  }else{
156770    rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
156771    if( rc==SQLITE_OK ){
156772      int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
156773      pReader->pOffsetList = &pReader->aDoclist[n];
156774    }
156775  }
156776  return rc;
156777}
156778
156779/*
156780** Advance the SegReader to point to the next docid in the doclist
156781** associated with the current term.
156782**
156783** If arguments ppOffsetList and pnOffsetList are not NULL, then
156784** *ppOffsetList is set to point to the first column-offset list
156785** in the doclist entry (i.e. immediately past the docid varint).
156786** *pnOffsetList is set to the length of the set of column-offset
156787** lists, not including the nul-terminator byte. For example:
156788*/
156789static int fts3SegReaderNextDocid(
156790  Fts3Table *pTab,
156791  Fts3SegReader *pReader,         /* Reader to advance to next docid */
156792  char **ppOffsetList,            /* OUT: Pointer to current position-list */
156793  int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
156794){
156795  int rc = SQLITE_OK;
156796  char *p = pReader->pOffsetList;
156797  char c = 0;
156798
156799  assert( p );
156800
156801  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
156802    /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
156803    ** Pending-terms doclists are always built up in ascending order, so
156804    ** we have to iterate through them backwards here. */
156805    u8 bEof = 0;
156806    if( ppOffsetList ){
156807      *ppOffsetList = pReader->pOffsetList;
156808      *pnOffsetList = pReader->nOffsetList - 1;
156809    }
156810    sqlite3Fts3DoclistPrev(0,
156811        pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
156812        &pReader->nOffsetList, &bEof
156813    );
156814    if( bEof ){
156815      pReader->pOffsetList = 0;
156816    }else{
156817      pReader->pOffsetList = p;
156818    }
156819  }else{
156820    char *pEnd = &pReader->aDoclist[pReader->nDoclist];
156821
156822    /* Pointer p currently points at the first byte of an offset list. The
156823    ** following block advances it to point one byte past the end of
156824    ** the same offset list. */
156825    while( 1 ){
156826
156827      /* The following line of code (and the "p++" below the while() loop) is
156828      ** normally all that is required to move pointer p to the desired
156829      ** position. The exception is if this node is being loaded from disk
156830      ** incrementally and pointer "p" now points to the first byte past
156831      ** the populated part of pReader->aNode[].
156832      */
156833      while( *p | c ) c = *p++ & 0x80;
156834      assert( *p==0 );
156835
156836      if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
156837      rc = fts3SegReaderIncrRead(pReader);
156838      if( rc!=SQLITE_OK ) return rc;
156839    }
156840    p++;
156841
156842    /* If required, populate the output variables with a pointer to and the
156843    ** size of the previous offset-list.
156844    */
156845    if( ppOffsetList ){
156846      *ppOffsetList = pReader->pOffsetList;
156847      *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
156848    }
156849
156850    /* List may have been edited in place by fts3EvalNearTrim() */
156851    while( p<pEnd && *p==0 ) p++;
156852
156853    /* If there are no more entries in the doclist, set pOffsetList to
156854    ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
156855    ** Fts3SegReader.pOffsetList to point to the next offset list before
156856    ** returning.
156857    */
156858    if( p>=pEnd ){
156859      pReader->pOffsetList = 0;
156860    }else{
156861      rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
156862      if( rc==SQLITE_OK ){
156863        sqlite3_int64 iDelta;
156864        pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
156865        if( pTab->bDescIdx ){
156866          pReader->iDocid -= iDelta;
156867        }else{
156868          pReader->iDocid += iDelta;
156869        }
156870      }
156871    }
156872  }
156873
156874  return SQLITE_OK;
156875}
156876
156877
156878SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
156879  Fts3Cursor *pCsr,
156880  Fts3MultiSegReader *pMsr,
156881  int *pnOvfl
156882){
156883  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
156884  int nOvfl = 0;
156885  int ii;
156886  int rc = SQLITE_OK;
156887  int pgsz = p->nPgsz;
156888
156889  assert( p->bFts4 );
156890  assert( pgsz>0 );
156891
156892  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
156893    Fts3SegReader *pReader = pMsr->apSegment[ii];
156894    if( !fts3SegReaderIsPending(pReader)
156895     && !fts3SegReaderIsRootOnly(pReader)
156896    ){
156897      sqlite3_int64 jj;
156898      for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
156899        int nBlob;
156900        rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
156901        if( rc!=SQLITE_OK ) break;
156902        if( (nBlob+35)>pgsz ){
156903          nOvfl += (nBlob + 34)/pgsz;
156904        }
156905      }
156906    }
156907  }
156908  *pnOvfl = nOvfl;
156909  return rc;
156910}
156911
156912/*
156913** Free all allocations associated with the iterator passed as the
156914** second argument.
156915*/
156916SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
156917  if( pReader ){
156918    if( !fts3SegReaderIsPending(pReader) ){
156919      sqlite3_free(pReader->zTerm);
156920    }
156921    if( !fts3SegReaderIsRootOnly(pReader) ){
156922      sqlite3_free(pReader->aNode);
156923    }
156924    sqlite3_blob_close(pReader->pBlob);
156925  }
156926  sqlite3_free(pReader);
156927}
156928
156929/*
156930** Allocate a new SegReader object.
156931*/
156932SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
156933  int iAge,                       /* Segment "age". */
156934  int bLookup,                    /* True for a lookup only */
156935  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
156936  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
156937  sqlite3_int64 iEndBlock,        /* Final block of segment */
156938  const char *zRoot,              /* Buffer containing root node */
156939  int nRoot,                      /* Size of buffer containing root node */
156940  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
156941){
156942  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
156943  int nExtra = 0;                 /* Bytes to allocate segment root node */
156944
156945  assert( iStartLeaf<=iEndLeaf );
156946  if( iStartLeaf==0 ){
156947    nExtra = nRoot + FTS3_NODE_PADDING;
156948  }
156949
156950  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
156951  if( !pReader ){
156952    return SQLITE_NOMEM;
156953  }
156954  memset(pReader, 0, sizeof(Fts3SegReader));
156955  pReader->iIdx = iAge;
156956  pReader->bLookup = bLookup!=0;
156957  pReader->iStartBlock = iStartLeaf;
156958  pReader->iLeafEndBlock = iEndLeaf;
156959  pReader->iEndBlock = iEndBlock;
156960
156961  if( nExtra ){
156962    /* The entire segment is stored in the root node. */
156963    pReader->aNode = (char *)&pReader[1];
156964    pReader->rootOnly = 1;
156965    pReader->nNode = nRoot;
156966    memcpy(pReader->aNode, zRoot, nRoot);
156967    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
156968  }else{
156969    pReader->iCurrentBlock = iStartLeaf-1;
156970  }
156971  *ppReader = pReader;
156972  return SQLITE_OK;
156973}
156974
156975/*
156976** This is a comparison function used as a qsort() callback when sorting
156977** an array of pending terms by term. This occurs as part of flushing
156978** the contents of the pending-terms hash table to the database.
156979*/
156980static int SQLITE_CDECL fts3CompareElemByTerm(
156981  const void *lhs,
156982  const void *rhs
156983){
156984  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
156985  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
156986  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
156987  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
156988
156989  int n = (n1<n2 ? n1 : n2);
156990  int c = memcmp(z1, z2, n);
156991  if( c==0 ){
156992    c = n1 - n2;
156993  }
156994  return c;
156995}
156996
156997/*
156998** This function is used to allocate an Fts3SegReader that iterates through
156999** a subset of the terms stored in the Fts3Table.pendingTerms array.
157000**
157001** If the isPrefixIter parameter is zero, then the returned SegReader iterates
157002** through each term in the pending-terms table. Or, if isPrefixIter is
157003** non-zero, it iterates through each term and its prefixes. For example, if
157004** the pending terms hash table contains the terms "sqlite", "mysql" and
157005** "firebird", then the iterator visits the following 'terms' (in the order
157006** shown):
157007**
157008**   f fi fir fire fireb firebi firebir firebird
157009**   m my mys mysq mysql
157010**   s sq sql sqli sqlit sqlite
157011**
157012** Whereas if isPrefixIter is zero, the terms visited are:
157013**
157014**   firebird mysql sqlite
157015*/
157016SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
157017  Fts3Table *p,                   /* Virtual table handle */
157018  int iIndex,                     /* Index for p->aIndex */
157019  const char *zTerm,              /* Term to search for */
157020  int nTerm,                      /* Size of buffer zTerm */
157021  int bPrefix,                    /* True for a prefix iterator */
157022  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
157023){
157024  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
157025  Fts3HashElem *pE;               /* Iterator variable */
157026  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
157027  int nElem = 0;                  /* Size of array at aElem */
157028  int rc = SQLITE_OK;             /* Return Code */
157029  Fts3Hash *pHash;
157030
157031  pHash = &p->aIndex[iIndex].hPending;
157032  if( bPrefix ){
157033    int nAlloc = 0;               /* Size of allocated array at aElem */
157034
157035    for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
157036      char *zKey = (char *)fts3HashKey(pE);
157037      int nKey = fts3HashKeysize(pE);
157038      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
157039        if( nElem==nAlloc ){
157040          Fts3HashElem **aElem2;
157041          nAlloc += 16;
157042          aElem2 = (Fts3HashElem **)sqlite3_realloc(
157043              aElem, nAlloc*sizeof(Fts3HashElem *)
157044          );
157045          if( !aElem2 ){
157046            rc = SQLITE_NOMEM;
157047            nElem = 0;
157048            break;
157049          }
157050          aElem = aElem2;
157051        }
157052
157053        aElem[nElem++] = pE;
157054      }
157055    }
157056
157057    /* If more than one term matches the prefix, sort the Fts3HashElem
157058    ** objects in term order using qsort(). This uses the same comparison
157059    ** callback as is used when flushing terms to disk.
157060    */
157061    if( nElem>1 ){
157062      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
157063    }
157064
157065  }else{
157066    /* The query is a simple term lookup that matches at most one term in
157067    ** the index. All that is required is a straight hash-lookup.
157068    **
157069    ** Because the stack address of pE may be accessed via the aElem pointer
157070    ** below, the "Fts3HashElem *pE" must be declared so that it is valid
157071    ** within this entire function, not just this "else{...}" block.
157072    */
157073    pE = fts3HashFindElem(pHash, zTerm, nTerm);
157074    if( pE ){
157075      aElem = &pE;
157076      nElem = 1;
157077    }
157078  }
157079
157080  if( nElem>0 ){
157081    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
157082    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
157083    if( !pReader ){
157084      rc = SQLITE_NOMEM;
157085    }else{
157086      memset(pReader, 0, nByte);
157087      pReader->iIdx = 0x7FFFFFFF;
157088      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
157089      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
157090    }
157091  }
157092
157093  if( bPrefix ){
157094    sqlite3_free(aElem);
157095  }
157096  *ppReader = pReader;
157097  return rc;
157098}
157099
157100/*
157101** Compare the entries pointed to by two Fts3SegReader structures.
157102** Comparison is as follows:
157103**
157104**   1) EOF is greater than not EOF.
157105**
157106**   2) The current terms (if any) are compared using memcmp(). If one
157107**      term is a prefix of another, the longer term is considered the
157108**      larger.
157109**
157110**   3) By segment age. An older segment is considered larger.
157111*/
157112static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
157113  int rc;
157114  if( pLhs->aNode && pRhs->aNode ){
157115    int rc2 = pLhs->nTerm - pRhs->nTerm;
157116    if( rc2<0 ){
157117      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
157118    }else{
157119      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
157120    }
157121    if( rc==0 ){
157122      rc = rc2;
157123    }
157124  }else{
157125    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
157126  }
157127  if( rc==0 ){
157128    rc = pRhs->iIdx - pLhs->iIdx;
157129  }
157130  assert( rc!=0 );
157131  return rc;
157132}
157133
157134/*
157135** A different comparison function for SegReader structures. In this
157136** version, it is assumed that each SegReader points to an entry in
157137** a doclist for identical terms. Comparison is made as follows:
157138**
157139**   1) EOF (end of doclist in this case) is greater than not EOF.
157140**
157141**   2) By current docid.
157142**
157143**   3) By segment age. An older segment is considered larger.
157144*/
157145static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
157146  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
157147  if( rc==0 ){
157148    if( pLhs->iDocid==pRhs->iDocid ){
157149      rc = pRhs->iIdx - pLhs->iIdx;
157150    }else{
157151      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
157152    }
157153  }
157154  assert( pLhs->aNode && pRhs->aNode );
157155  return rc;
157156}
157157static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
157158  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
157159  if( rc==0 ){
157160    if( pLhs->iDocid==pRhs->iDocid ){
157161      rc = pRhs->iIdx - pLhs->iIdx;
157162    }else{
157163      rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
157164    }
157165  }
157166  assert( pLhs->aNode && pRhs->aNode );
157167  return rc;
157168}
157169
157170/*
157171** Compare the term that the Fts3SegReader object passed as the first argument
157172** points to with the term specified by arguments zTerm and nTerm.
157173**
157174** If the pSeg iterator is already at EOF, return 0. Otherwise, return
157175** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
157176** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
157177*/
157178static int fts3SegReaderTermCmp(
157179  Fts3SegReader *pSeg,            /* Segment reader object */
157180  const char *zTerm,              /* Term to compare to */
157181  int nTerm                       /* Size of term zTerm in bytes */
157182){
157183  int res = 0;
157184  if( pSeg->aNode ){
157185    if( pSeg->nTerm>nTerm ){
157186      res = memcmp(pSeg->zTerm, zTerm, nTerm);
157187    }else{
157188      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
157189    }
157190    if( res==0 ){
157191      res = pSeg->nTerm-nTerm;
157192    }
157193  }
157194  return res;
157195}
157196
157197/*
157198** Argument apSegment is an array of nSegment elements. It is known that
157199** the final (nSegment-nSuspect) members are already in sorted order
157200** (according to the comparison function provided). This function shuffles
157201** the array around until all entries are in sorted order.
157202*/
157203static void fts3SegReaderSort(
157204  Fts3SegReader **apSegment,                     /* Array to sort entries of */
157205  int nSegment,                                  /* Size of apSegment array */
157206  int nSuspect,                                  /* Unsorted entry count */
157207  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
157208){
157209  int i;                          /* Iterator variable */
157210
157211  assert( nSuspect<=nSegment );
157212
157213  if( nSuspect==nSegment ) nSuspect--;
157214  for(i=nSuspect-1; i>=0; i--){
157215    int j;
157216    for(j=i; j<(nSegment-1); j++){
157217      Fts3SegReader *pTmp;
157218      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
157219      pTmp = apSegment[j+1];
157220      apSegment[j+1] = apSegment[j];
157221      apSegment[j] = pTmp;
157222    }
157223  }
157224
157225#ifndef NDEBUG
157226  /* Check that the list really is sorted now. */
157227  for(i=0; i<(nSuspect-1); i++){
157228    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
157229  }
157230#endif
157231}
157232
157233/*
157234** Insert a record into the %_segments table.
157235*/
157236static int fts3WriteSegment(
157237  Fts3Table *p,                   /* Virtual table handle */
157238  sqlite3_int64 iBlock,           /* Block id for new block */
157239  char *z,                        /* Pointer to buffer containing block data */
157240  int n                           /* Size of buffer z in bytes */
157241){
157242  sqlite3_stmt *pStmt;
157243  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
157244  if( rc==SQLITE_OK ){
157245    sqlite3_bind_int64(pStmt, 1, iBlock);
157246    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
157247    sqlite3_step(pStmt);
157248    rc = sqlite3_reset(pStmt);
157249  }
157250  return rc;
157251}
157252
157253/*
157254** Find the largest relative level number in the table. If successful, set
157255** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
157256** set *pnMax to zero and return an SQLite error code.
157257*/
157258SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
157259  int rc;
157260  int mxLevel = 0;
157261  sqlite3_stmt *pStmt = 0;
157262
157263  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
157264  if( rc==SQLITE_OK ){
157265    if( SQLITE_ROW==sqlite3_step(pStmt) ){
157266      mxLevel = sqlite3_column_int(pStmt, 0);
157267    }
157268    rc = sqlite3_reset(pStmt);
157269  }
157270  *pnMax = mxLevel;
157271  return rc;
157272}
157273
157274/*
157275** Insert a record into the %_segdir table.
157276*/
157277static int fts3WriteSegdir(
157278  Fts3Table *p,                   /* Virtual table handle */
157279  sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
157280  int iIdx,                       /* Value for "idx" field */
157281  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
157282  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
157283  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
157284  sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
157285  char *zRoot,                    /* Blob value for "root" field */
157286  int nRoot                       /* Number of bytes in buffer zRoot */
157287){
157288  sqlite3_stmt *pStmt;
157289  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
157290  if( rc==SQLITE_OK ){
157291    sqlite3_bind_int64(pStmt, 1, iLevel);
157292    sqlite3_bind_int(pStmt, 2, iIdx);
157293    sqlite3_bind_int64(pStmt, 3, iStartBlock);
157294    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
157295    if( nLeafData==0 ){
157296      sqlite3_bind_int64(pStmt, 5, iEndBlock);
157297    }else{
157298      char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
157299      if( !zEnd ) return SQLITE_NOMEM;
157300      sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
157301    }
157302    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
157303    sqlite3_step(pStmt);
157304    rc = sqlite3_reset(pStmt);
157305  }
157306  return rc;
157307}
157308
157309/*
157310** Return the size of the common prefix (if any) shared by zPrev and
157311** zNext, in bytes. For example,
157312**
157313**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
157314**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
157315**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
157316*/
157317static int fts3PrefixCompress(
157318  const char *zPrev,              /* Buffer containing previous term */
157319  int nPrev,                      /* Size of buffer zPrev in bytes */
157320  const char *zNext,              /* Buffer containing next term */
157321  int nNext                       /* Size of buffer zNext in bytes */
157322){
157323  int n;
157324  UNUSED_PARAMETER(nNext);
157325  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
157326  return n;
157327}
157328
157329/*
157330** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
157331** (according to memcmp) than the previous term.
157332*/
157333static int fts3NodeAddTerm(
157334  Fts3Table *p,                   /* Virtual table handle */
157335  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
157336  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
157337  const char *zTerm,              /* Pointer to buffer containing term */
157338  int nTerm                       /* Size of term in bytes */
157339){
157340  SegmentNode *pTree = *ppTree;
157341  int rc;
157342  SegmentNode *pNew;
157343
157344  /* First try to append the term to the current node. Return early if
157345  ** this is possible.
157346  */
157347  if( pTree ){
157348    int nData = pTree->nData;     /* Current size of node in bytes */
157349    int nReq = nData;             /* Required space after adding zTerm */
157350    int nPrefix;                  /* Number of bytes of prefix compression */
157351    int nSuffix;                  /* Suffix length */
157352
157353    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
157354    nSuffix = nTerm-nPrefix;
157355
157356    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
157357    if( nReq<=p->nNodeSize || !pTree->zTerm ){
157358
157359      if( nReq>p->nNodeSize ){
157360        /* An unusual case: this is the first term to be added to the node
157361        ** and the static node buffer (p->nNodeSize bytes) is not large
157362        ** enough. Use a separately malloced buffer instead This wastes
157363        ** p->nNodeSize bytes, but since this scenario only comes about when
157364        ** the database contain two terms that share a prefix of almost 2KB,
157365        ** this is not expected to be a serious problem.
157366        */
157367        assert( pTree->aData==(char *)&pTree[1] );
157368        pTree->aData = (char *)sqlite3_malloc(nReq);
157369        if( !pTree->aData ){
157370          return SQLITE_NOMEM;
157371        }
157372      }
157373
157374      if( pTree->zTerm ){
157375        /* There is no prefix-length field for first term in a node */
157376        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
157377      }
157378
157379      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
157380      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
157381      pTree->nData = nData + nSuffix;
157382      pTree->nEntry++;
157383
157384      if( isCopyTerm ){
157385        if( pTree->nMalloc<nTerm ){
157386          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
157387          if( !zNew ){
157388            return SQLITE_NOMEM;
157389          }
157390          pTree->nMalloc = nTerm*2;
157391          pTree->zMalloc = zNew;
157392        }
157393        pTree->zTerm = pTree->zMalloc;
157394        memcpy(pTree->zTerm, zTerm, nTerm);
157395        pTree->nTerm = nTerm;
157396      }else{
157397        pTree->zTerm = (char *)zTerm;
157398        pTree->nTerm = nTerm;
157399      }
157400      return SQLITE_OK;
157401    }
157402  }
157403
157404  /* If control flows to here, it was not possible to append zTerm to the
157405  ** current node. Create a new node (a right-sibling of the current node).
157406  ** If this is the first node in the tree, the term is added to it.
157407  **
157408  ** Otherwise, the term is not added to the new node, it is left empty for
157409  ** now. Instead, the term is inserted into the parent of pTree. If pTree
157410  ** has no parent, one is created here.
157411  */
157412  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
157413  if( !pNew ){
157414    return SQLITE_NOMEM;
157415  }
157416  memset(pNew, 0, sizeof(SegmentNode));
157417  pNew->nData = 1 + FTS3_VARINT_MAX;
157418  pNew->aData = (char *)&pNew[1];
157419
157420  if( pTree ){
157421    SegmentNode *pParent = pTree->pParent;
157422    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
157423    if( pTree->pParent==0 ){
157424      pTree->pParent = pParent;
157425    }
157426    pTree->pRight = pNew;
157427    pNew->pLeftmost = pTree->pLeftmost;
157428    pNew->pParent = pParent;
157429    pNew->zMalloc = pTree->zMalloc;
157430    pNew->nMalloc = pTree->nMalloc;
157431    pTree->zMalloc = 0;
157432  }else{
157433    pNew->pLeftmost = pNew;
157434    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
157435  }
157436
157437  *ppTree = pNew;
157438  return rc;
157439}
157440
157441/*
157442** Helper function for fts3NodeWrite().
157443*/
157444static int fts3TreeFinishNode(
157445  SegmentNode *pTree,
157446  int iHeight,
157447  sqlite3_int64 iLeftChild
157448){
157449  int nStart;
157450  assert( iHeight>=1 && iHeight<128 );
157451  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
157452  pTree->aData[nStart] = (char)iHeight;
157453  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
157454  return nStart;
157455}
157456
157457/*
157458** Write the buffer for the segment node pTree and all of its peers to the
157459** database. Then call this function recursively to write the parent of
157460** pTree and its peers to the database.
157461**
157462** Except, if pTree is a root node, do not write it to the database. Instead,
157463** set output variables *paRoot and *pnRoot to contain the root node.
157464**
157465** If successful, SQLITE_OK is returned and output variable *piLast is
157466** set to the largest blockid written to the database (or zero if no
157467** blocks were written to the db). Otherwise, an SQLite error code is
157468** returned.
157469*/
157470static int fts3NodeWrite(
157471  Fts3Table *p,                   /* Virtual table handle */
157472  SegmentNode *pTree,             /* SegmentNode handle */
157473  int iHeight,                    /* Height of this node in tree */
157474  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
157475  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
157476  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
157477  char **paRoot,                  /* OUT: Data for root node */
157478  int *pnRoot                     /* OUT: Size of root node in bytes */
157479){
157480  int rc = SQLITE_OK;
157481
157482  if( !pTree->pParent ){
157483    /* Root node of the tree. */
157484    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
157485    *piLast = iFree-1;
157486    *pnRoot = pTree->nData - nStart;
157487    *paRoot = &pTree->aData[nStart];
157488  }else{
157489    SegmentNode *pIter;
157490    sqlite3_int64 iNextFree = iFree;
157491    sqlite3_int64 iNextLeaf = iLeaf;
157492    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
157493      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
157494      int nWrite = pIter->nData - nStart;
157495
157496      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
157497      iNextFree++;
157498      iNextLeaf += (pIter->nEntry+1);
157499    }
157500    if( rc==SQLITE_OK ){
157501      assert( iNextLeaf==iFree );
157502      rc = fts3NodeWrite(
157503          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
157504      );
157505    }
157506  }
157507
157508  return rc;
157509}
157510
157511/*
157512** Free all memory allocations associated with the tree pTree.
157513*/
157514static void fts3NodeFree(SegmentNode *pTree){
157515  if( pTree ){
157516    SegmentNode *p = pTree->pLeftmost;
157517    fts3NodeFree(p->pParent);
157518    while( p ){
157519      SegmentNode *pRight = p->pRight;
157520      if( p->aData!=(char *)&p[1] ){
157521        sqlite3_free(p->aData);
157522      }
157523      assert( pRight==0 || p->zMalloc==0 );
157524      sqlite3_free(p->zMalloc);
157525      sqlite3_free(p);
157526      p = pRight;
157527    }
157528  }
157529}
157530
157531/*
157532** Add a term to the segment being constructed by the SegmentWriter object
157533** *ppWriter. When adding the first term to a segment, *ppWriter should
157534** be passed NULL. This function will allocate a new SegmentWriter object
157535** and return it via the input/output variable *ppWriter in this case.
157536**
157537** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
157538*/
157539static int fts3SegWriterAdd(
157540  Fts3Table *p,                   /* Virtual table handle */
157541  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
157542  int isCopyTerm,                 /* True if buffer zTerm must be copied */
157543  const char *zTerm,              /* Pointer to buffer containing term */
157544  int nTerm,                      /* Size of term in bytes */
157545  const char *aDoclist,           /* Pointer to buffer containing doclist */
157546  int nDoclist                    /* Size of doclist in bytes */
157547){
157548  int nPrefix;                    /* Size of term prefix in bytes */
157549  int nSuffix;                    /* Size of term suffix in bytes */
157550  int nReq;                       /* Number of bytes required on leaf page */
157551  int nData;
157552  SegmentWriter *pWriter = *ppWriter;
157553
157554  if( !pWriter ){
157555    int rc;
157556    sqlite3_stmt *pStmt;
157557
157558    /* Allocate the SegmentWriter structure */
157559    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
157560    if( !pWriter ) return SQLITE_NOMEM;
157561    memset(pWriter, 0, sizeof(SegmentWriter));
157562    *ppWriter = pWriter;
157563
157564    /* Allocate a buffer in which to accumulate data */
157565    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
157566    if( !pWriter->aData ) return SQLITE_NOMEM;
157567    pWriter->nSize = p->nNodeSize;
157568
157569    /* Find the next free blockid in the %_segments table */
157570    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
157571    if( rc!=SQLITE_OK ) return rc;
157572    if( SQLITE_ROW==sqlite3_step(pStmt) ){
157573      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
157574      pWriter->iFirst = pWriter->iFree;
157575    }
157576    rc = sqlite3_reset(pStmt);
157577    if( rc!=SQLITE_OK ) return rc;
157578  }
157579  nData = pWriter->nData;
157580
157581  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
157582  nSuffix = nTerm-nPrefix;
157583
157584  /* Figure out how many bytes are required by this new entry */
157585  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
157586    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
157587    nSuffix +                               /* Term suffix */
157588    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
157589    nDoclist;                               /* Doclist data */
157590
157591  if( nData>0 && nData+nReq>p->nNodeSize ){
157592    int rc;
157593
157594    /* The current leaf node is full. Write it out to the database. */
157595    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
157596    if( rc!=SQLITE_OK ) return rc;
157597    p->nLeafAdd++;
157598
157599    /* Add the current term to the interior node tree. The term added to
157600    ** the interior tree must:
157601    **
157602    **   a) be greater than the largest term on the leaf node just written
157603    **      to the database (still available in pWriter->zTerm), and
157604    **
157605    **   b) be less than or equal to the term about to be added to the new
157606    **      leaf node (zTerm/nTerm).
157607    **
157608    ** In other words, it must be the prefix of zTerm 1 byte longer than
157609    ** the common prefix (if any) of zTerm and pWriter->zTerm.
157610    */
157611    assert( nPrefix<nTerm );
157612    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
157613    if( rc!=SQLITE_OK ) return rc;
157614
157615    nData = 0;
157616    pWriter->nTerm = 0;
157617
157618    nPrefix = 0;
157619    nSuffix = nTerm;
157620    nReq = 1 +                              /* varint containing prefix size */
157621      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
157622      nTerm +                               /* Term suffix */
157623      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
157624      nDoclist;                             /* Doclist data */
157625  }
157626
157627  /* Increase the total number of bytes written to account for the new entry. */
157628  pWriter->nLeafData += nReq;
157629
157630  /* If the buffer currently allocated is too small for this entry, realloc
157631  ** the buffer to make it large enough.
157632  */
157633  if( nReq>pWriter->nSize ){
157634    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
157635    if( !aNew ) return SQLITE_NOMEM;
157636    pWriter->aData = aNew;
157637    pWriter->nSize = nReq;
157638  }
157639  assert( nData+nReq<=pWriter->nSize );
157640
157641  /* Append the prefix-compressed term and doclist to the buffer. */
157642  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
157643  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
157644  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
157645  nData += nSuffix;
157646  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
157647  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
157648  pWriter->nData = nData + nDoclist;
157649
157650  /* Save the current term so that it can be used to prefix-compress the next.
157651  ** If the isCopyTerm parameter is true, then the buffer pointed to by
157652  ** zTerm is transient, so take a copy of the term data. Otherwise, just
157653  ** store a copy of the pointer.
157654  */
157655  if( isCopyTerm ){
157656    if( nTerm>pWriter->nMalloc ){
157657      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
157658      if( !zNew ){
157659        return SQLITE_NOMEM;
157660      }
157661      pWriter->nMalloc = nTerm*2;
157662      pWriter->zMalloc = zNew;
157663      pWriter->zTerm = zNew;
157664    }
157665    assert( pWriter->zTerm==pWriter->zMalloc );
157666    memcpy(pWriter->zTerm, zTerm, nTerm);
157667  }else{
157668    pWriter->zTerm = (char *)zTerm;
157669  }
157670  pWriter->nTerm = nTerm;
157671
157672  return SQLITE_OK;
157673}
157674
157675/*
157676** Flush all data associated with the SegmentWriter object pWriter to the
157677** database. This function must be called after all terms have been added
157678** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
157679** returned. Otherwise, an SQLite error code.
157680*/
157681static int fts3SegWriterFlush(
157682  Fts3Table *p,                   /* Virtual table handle */
157683  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
157684  sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
157685  int iIdx                        /* Value for 'idx' column of %_segdir */
157686){
157687  int rc;                         /* Return code */
157688  if( pWriter->pTree ){
157689    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
157690    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
157691    char *zRoot = NULL;           /* Pointer to buffer containing root node */
157692    int nRoot = 0;                /* Size of buffer zRoot */
157693
157694    iLastLeaf = pWriter->iFree;
157695    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
157696    if( rc==SQLITE_OK ){
157697      rc = fts3NodeWrite(p, pWriter->pTree, 1,
157698          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
157699    }
157700    if( rc==SQLITE_OK ){
157701      rc = fts3WriteSegdir(p, iLevel, iIdx,
157702          pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
157703    }
157704  }else{
157705    /* The entire tree fits on the root node. Write it to the segdir table. */
157706    rc = fts3WriteSegdir(p, iLevel, iIdx,
157707        0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
157708  }
157709  p->nLeafAdd++;
157710  return rc;
157711}
157712
157713/*
157714** Release all memory held by the SegmentWriter object passed as the
157715** first argument.
157716*/
157717static void fts3SegWriterFree(SegmentWriter *pWriter){
157718  if( pWriter ){
157719    sqlite3_free(pWriter->aData);
157720    sqlite3_free(pWriter->zMalloc);
157721    fts3NodeFree(pWriter->pTree);
157722    sqlite3_free(pWriter);
157723  }
157724}
157725
157726/*
157727** The first value in the apVal[] array is assumed to contain an integer.
157728** This function tests if there exist any documents with docid values that
157729** are different from that integer. i.e. if deleting the document with docid
157730** pRowid would mean the FTS3 table were empty.
157731**
157732** If successful, *pisEmpty is set to true if the table is empty except for
157733** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
157734** error occurs, an SQLite error code is returned.
157735*/
157736static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
157737  sqlite3_stmt *pStmt;
157738  int rc;
157739  if( p->zContentTbl ){
157740    /* If using the content=xxx option, assume the table is never empty */
157741    *pisEmpty = 0;
157742    rc = SQLITE_OK;
157743  }else{
157744    rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
157745    if( rc==SQLITE_OK ){
157746      if( SQLITE_ROW==sqlite3_step(pStmt) ){
157747        *pisEmpty = sqlite3_column_int(pStmt, 0);
157748      }
157749      rc = sqlite3_reset(pStmt);
157750    }
157751  }
157752  return rc;
157753}
157754
157755/*
157756** Set *pnMax to the largest segment level in the database for the index
157757** iIndex.
157758**
157759** Segment levels are stored in the 'level' column of the %_segdir table.
157760**
157761** Return SQLITE_OK if successful, or an SQLite error code if not.
157762*/
157763static int fts3SegmentMaxLevel(
157764  Fts3Table *p,
157765  int iLangid,
157766  int iIndex,
157767  sqlite3_int64 *pnMax
157768){
157769  sqlite3_stmt *pStmt;
157770  int rc;
157771  assert( iIndex>=0 && iIndex<p->nIndex );
157772
157773  /* Set pStmt to the compiled version of:
157774  **
157775  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
157776  **
157777  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
157778  */
157779  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
157780  if( rc!=SQLITE_OK ) return rc;
157781  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
157782  sqlite3_bind_int64(pStmt, 2,
157783      getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
157784  );
157785  if( SQLITE_ROW==sqlite3_step(pStmt) ){
157786    *pnMax = sqlite3_column_int64(pStmt, 0);
157787  }
157788  return sqlite3_reset(pStmt);
157789}
157790
157791/*
157792** iAbsLevel is an absolute level that may be assumed to exist within
157793** the database. This function checks if it is the largest level number
157794** within its index. Assuming no error occurs, *pbMax is set to 1 if
157795** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
157796** is returned. If an error occurs, an error code is returned and the
157797** final value of *pbMax is undefined.
157798*/
157799static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
157800
157801  /* Set pStmt to the compiled version of:
157802  **
157803  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
157804  **
157805  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
157806  */
157807  sqlite3_stmt *pStmt;
157808  int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
157809  if( rc!=SQLITE_OK ) return rc;
157810  sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
157811  sqlite3_bind_int64(pStmt, 2,
157812      ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
157813  );
157814
157815  *pbMax = 0;
157816  if( SQLITE_ROW==sqlite3_step(pStmt) ){
157817    *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
157818  }
157819  return sqlite3_reset(pStmt);
157820}
157821
157822/*
157823** Delete all entries in the %_segments table associated with the segment
157824** opened with seg-reader pSeg. This function does not affect the contents
157825** of the %_segdir table.
157826*/
157827static int fts3DeleteSegment(
157828  Fts3Table *p,                   /* FTS table handle */
157829  Fts3SegReader *pSeg             /* Segment to delete */
157830){
157831  int rc = SQLITE_OK;             /* Return code */
157832  if( pSeg->iStartBlock ){
157833    sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
157834    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
157835    if( rc==SQLITE_OK ){
157836      sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
157837      sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
157838      sqlite3_step(pDelete);
157839      rc = sqlite3_reset(pDelete);
157840    }
157841  }
157842  return rc;
157843}
157844
157845/*
157846** This function is used after merging multiple segments into a single large
157847** segment to delete the old, now redundant, segment b-trees. Specifically,
157848** it:
157849**
157850**   1) Deletes all %_segments entries for the segments associated with
157851**      each of the SegReader objects in the array passed as the third
157852**      argument, and
157853**
157854**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
157855**      entries regardless of level if (iLevel<0).
157856**
157857** SQLITE_OK is returned if successful, otherwise an SQLite error code.
157858*/
157859static int fts3DeleteSegdir(
157860  Fts3Table *p,                   /* Virtual table handle */
157861  int iLangid,                    /* Language id */
157862  int iIndex,                     /* Index for p->aIndex */
157863  int iLevel,                     /* Level of %_segdir entries to delete */
157864  Fts3SegReader **apSegment,      /* Array of SegReader objects */
157865  int nReader                     /* Size of array apSegment */
157866){
157867  int rc = SQLITE_OK;             /* Return Code */
157868  int i;                          /* Iterator variable */
157869  sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
157870
157871  for(i=0; rc==SQLITE_OK && i<nReader; i++){
157872    rc = fts3DeleteSegment(p, apSegment[i]);
157873  }
157874  if( rc!=SQLITE_OK ){
157875    return rc;
157876  }
157877
157878  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
157879  if( iLevel==FTS3_SEGCURSOR_ALL ){
157880    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
157881    if( rc==SQLITE_OK ){
157882      sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
157883      sqlite3_bind_int64(pDelete, 2,
157884          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
157885      );
157886    }
157887  }else{
157888    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
157889    if( rc==SQLITE_OK ){
157890      sqlite3_bind_int64(
157891          pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
157892      );
157893    }
157894  }
157895
157896  if( rc==SQLITE_OK ){
157897    sqlite3_step(pDelete);
157898    rc = sqlite3_reset(pDelete);
157899  }
157900
157901  return rc;
157902}
157903
157904/*
157905** When this function is called, buffer *ppList (size *pnList bytes) contains
157906** a position list that may (or may not) feature multiple columns. This
157907** function adjusts the pointer *ppList and the length *pnList so that they
157908** identify the subset of the position list that corresponds to column iCol.
157909**
157910** If there are no entries in the input position list for column iCol, then
157911** *pnList is set to zero before returning.
157912**
157913** If parameter bZero is non-zero, then any part of the input list following
157914** the end of the output list is zeroed before returning.
157915*/
157916static void fts3ColumnFilter(
157917  int iCol,                       /* Column to filter on */
157918  int bZero,                      /* Zero out anything following *ppList */
157919  char **ppList,                  /* IN/OUT: Pointer to position list */
157920  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
157921){
157922  char *pList = *ppList;
157923  int nList = *pnList;
157924  char *pEnd = &pList[nList];
157925  int iCurrent = 0;
157926  char *p = pList;
157927
157928  assert( iCol>=0 );
157929  while( 1 ){
157930    char c = 0;
157931    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
157932
157933    if( iCol==iCurrent ){
157934      nList = (int)(p - pList);
157935      break;
157936    }
157937
157938    nList -= (int)(p - pList);
157939    pList = p;
157940    if( nList==0 ){
157941      break;
157942    }
157943    p = &pList[1];
157944    p += fts3GetVarint32(p, &iCurrent);
157945  }
157946
157947  if( bZero && &pList[nList]!=pEnd ){
157948    memset(&pList[nList], 0, pEnd - &pList[nList]);
157949  }
157950  *ppList = pList;
157951  *pnList = nList;
157952}
157953
157954/*
157955** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
157956** existing data). Grow the buffer if required.
157957**
157958** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
157959** trying to resize the buffer, return SQLITE_NOMEM.
157960*/
157961static int fts3MsrBufferData(
157962  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
157963  char *pList,
157964  int nList
157965){
157966  if( nList>pMsr->nBuffer ){
157967    char *pNew;
157968    pMsr->nBuffer = nList*2;
157969    pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
157970    if( !pNew ) return SQLITE_NOMEM;
157971    pMsr->aBuffer = pNew;
157972  }
157973
157974  memcpy(pMsr->aBuffer, pList, nList);
157975  return SQLITE_OK;
157976}
157977
157978SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
157979  Fts3Table *p,                   /* Virtual table handle */
157980  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
157981  sqlite3_int64 *piDocid,         /* OUT: Docid value */
157982  char **paPoslist,               /* OUT: Pointer to position list */
157983  int *pnPoslist                  /* OUT: Size of position list in bytes */
157984){
157985  int nMerge = pMsr->nAdvance;
157986  Fts3SegReader **apSegment = pMsr->apSegment;
157987  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
157988    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
157989  );
157990
157991  if( nMerge==0 ){
157992    *paPoslist = 0;
157993    return SQLITE_OK;
157994  }
157995
157996  while( 1 ){
157997    Fts3SegReader *pSeg;
157998    pSeg = pMsr->apSegment[0];
157999
158000    if( pSeg->pOffsetList==0 ){
158001      *paPoslist = 0;
158002      break;
158003    }else{
158004      int rc;
158005      char *pList;
158006      int nList;
158007      int j;
158008      sqlite3_int64 iDocid = apSegment[0]->iDocid;
158009
158010      rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
158011      j = 1;
158012      while( rc==SQLITE_OK
158013        && j<nMerge
158014        && apSegment[j]->pOffsetList
158015        && apSegment[j]->iDocid==iDocid
158016      ){
158017        rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
158018        j++;
158019      }
158020      if( rc!=SQLITE_OK ) return rc;
158021      fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
158022
158023      if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
158024        rc = fts3MsrBufferData(pMsr, pList, nList+1);
158025        if( rc!=SQLITE_OK ) return rc;
158026        assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
158027        pList = pMsr->aBuffer;
158028      }
158029
158030      if( pMsr->iColFilter>=0 ){
158031        fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
158032      }
158033
158034      if( nList>0 ){
158035        *paPoslist = pList;
158036        *piDocid = iDocid;
158037        *pnPoslist = nList;
158038        break;
158039      }
158040    }
158041  }
158042
158043  return SQLITE_OK;
158044}
158045
158046static int fts3SegReaderStart(
158047  Fts3Table *p,                   /* Virtual table handle */
158048  Fts3MultiSegReader *pCsr,       /* Cursor object */
158049  const char *zTerm,              /* Term searched for (or NULL) */
158050  int nTerm                       /* Length of zTerm in bytes */
158051){
158052  int i;
158053  int nSeg = pCsr->nSegment;
158054
158055  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
158056  ** for, then advance each segment iterator until it points to a term of
158057  ** equal or greater value than the specified term. This prevents many
158058  ** unnecessary merge/sort operations for the case where single segment
158059  ** b-tree leaf nodes contain more than one term.
158060  */
158061  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
158062    int res = 0;
158063    Fts3SegReader *pSeg = pCsr->apSegment[i];
158064    do {
158065      int rc = fts3SegReaderNext(p, pSeg, 0);
158066      if( rc!=SQLITE_OK ) return rc;
158067    }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
158068
158069    if( pSeg->bLookup && res!=0 ){
158070      fts3SegReaderSetEof(pSeg);
158071    }
158072  }
158073  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
158074
158075  return SQLITE_OK;
158076}
158077
158078SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
158079  Fts3Table *p,                   /* Virtual table handle */
158080  Fts3MultiSegReader *pCsr,       /* Cursor object */
158081  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
158082){
158083  pCsr->pFilter = pFilter;
158084  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
158085}
158086
158087SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
158088  Fts3Table *p,                   /* Virtual table handle */
158089  Fts3MultiSegReader *pCsr,       /* Cursor object */
158090  int iCol,                       /* Column to match on. */
158091  const char *zTerm,              /* Term to iterate through a doclist for */
158092  int nTerm                       /* Number of bytes in zTerm */
158093){
158094  int i;
158095  int rc;
158096  int nSegment = pCsr->nSegment;
158097  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
158098    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
158099  );
158100
158101  assert( pCsr->pFilter==0 );
158102  assert( zTerm && nTerm>0 );
158103
158104  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
158105  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
158106  if( rc!=SQLITE_OK ) return rc;
158107
158108  /* Determine how many of the segments actually point to zTerm/nTerm. */
158109  for(i=0; i<nSegment; i++){
158110    Fts3SegReader *pSeg = pCsr->apSegment[i];
158111    if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
158112      break;
158113    }
158114  }
158115  pCsr->nAdvance = i;
158116
158117  /* Advance each of the segments to point to the first docid. */
158118  for(i=0; i<pCsr->nAdvance; i++){
158119    rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
158120    if( rc!=SQLITE_OK ) return rc;
158121  }
158122  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
158123
158124  assert( iCol<0 || iCol<p->nColumn );
158125  pCsr->iColFilter = iCol;
158126
158127  return SQLITE_OK;
158128}
158129
158130/*
158131** This function is called on a MultiSegReader that has been started using
158132** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
158133** have been made. Calling this function puts the MultiSegReader in such
158134** a state that if the next two calls are:
158135**
158136**   sqlite3Fts3SegReaderStart()
158137**   sqlite3Fts3SegReaderStep()
158138**
158139** then the entire doclist for the term is available in
158140** MultiSegReader.aDoclist/nDoclist.
158141*/
158142SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
158143  int i;                          /* Used to iterate through segment-readers */
158144
158145  assert( pCsr->zTerm==0 );
158146  assert( pCsr->nTerm==0 );
158147  assert( pCsr->aDoclist==0 );
158148  assert( pCsr->nDoclist==0 );
158149
158150  pCsr->nAdvance = 0;
158151  pCsr->bRestart = 1;
158152  for(i=0; i<pCsr->nSegment; i++){
158153    pCsr->apSegment[i]->pOffsetList = 0;
158154    pCsr->apSegment[i]->nOffsetList = 0;
158155    pCsr->apSegment[i]->iDocid = 0;
158156  }
158157
158158  return SQLITE_OK;
158159}
158160
158161
158162SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
158163  Fts3Table *p,                   /* Virtual table handle */
158164  Fts3MultiSegReader *pCsr        /* Cursor object */
158165){
158166  int rc = SQLITE_OK;
158167
158168  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
158169  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
158170  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
158171  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
158172  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
158173  int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
158174
158175  Fts3SegReader **apSegment = pCsr->apSegment;
158176  int nSegment = pCsr->nSegment;
158177  Fts3SegFilter *pFilter = pCsr->pFilter;
158178  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
158179    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
158180  );
158181
158182  if( pCsr->nSegment==0 ) return SQLITE_OK;
158183
158184  do {
158185    int nMerge;
158186    int i;
158187
158188    /* Advance the first pCsr->nAdvance entries in the apSegment[] array
158189    ** forward. Then sort the list in order of current term again.
158190    */
158191    for(i=0; i<pCsr->nAdvance; i++){
158192      Fts3SegReader *pSeg = apSegment[i];
158193      if( pSeg->bLookup ){
158194        fts3SegReaderSetEof(pSeg);
158195      }else{
158196        rc = fts3SegReaderNext(p, pSeg, 0);
158197      }
158198      if( rc!=SQLITE_OK ) return rc;
158199    }
158200    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
158201    pCsr->nAdvance = 0;
158202
158203    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
158204    assert( rc==SQLITE_OK );
158205    if( apSegment[0]->aNode==0 ) break;
158206
158207    pCsr->nTerm = apSegment[0]->nTerm;
158208    pCsr->zTerm = apSegment[0]->zTerm;
158209
158210    /* If this is a prefix-search, and if the term that apSegment[0] points
158211    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
158212    ** required callbacks have been made. In this case exit early.
158213    **
158214    ** Similarly, if this is a search for an exact match, and the first term
158215    ** of segment apSegment[0] is not a match, exit early.
158216    */
158217    if( pFilter->zTerm && !isScan ){
158218      if( pCsr->nTerm<pFilter->nTerm
158219       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
158220       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
158221      ){
158222        break;
158223      }
158224    }
158225
158226    nMerge = 1;
158227    while( nMerge<nSegment
158228        && apSegment[nMerge]->aNode
158229        && apSegment[nMerge]->nTerm==pCsr->nTerm
158230        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
158231    ){
158232      nMerge++;
158233    }
158234
158235    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
158236    if( nMerge==1
158237     && !isIgnoreEmpty
158238     && !isFirst
158239     && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
158240    ){
158241      pCsr->nDoclist = apSegment[0]->nDoclist;
158242      if( fts3SegReaderIsPending(apSegment[0]) ){
158243        rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
158244        pCsr->aDoclist = pCsr->aBuffer;
158245      }else{
158246        pCsr->aDoclist = apSegment[0]->aDoclist;
158247      }
158248      if( rc==SQLITE_OK ) rc = SQLITE_ROW;
158249    }else{
158250      int nDoclist = 0;           /* Size of doclist */
158251      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
158252
158253      /* The current term of the first nMerge entries in the array
158254      ** of Fts3SegReader objects is the same. The doclists must be merged
158255      ** and a single term returned with the merged doclist.
158256      */
158257      for(i=0; i<nMerge; i++){
158258        fts3SegReaderFirstDocid(p, apSegment[i]);
158259      }
158260      fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
158261      while( apSegment[0]->pOffsetList ){
158262        int j;                    /* Number of segments that share a docid */
158263        char *pList = 0;
158264        int nList = 0;
158265        int nByte;
158266        sqlite3_int64 iDocid = apSegment[0]->iDocid;
158267        fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
158268        j = 1;
158269        while( j<nMerge
158270            && apSegment[j]->pOffsetList
158271            && apSegment[j]->iDocid==iDocid
158272        ){
158273          fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
158274          j++;
158275        }
158276
158277        if( isColFilter ){
158278          fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
158279        }
158280
158281        if( !isIgnoreEmpty || nList>0 ){
158282
158283          /* Calculate the 'docid' delta value to write into the merged
158284          ** doclist. */
158285          sqlite3_int64 iDelta;
158286          if( p->bDescIdx && nDoclist>0 ){
158287            iDelta = iPrev - iDocid;
158288          }else{
158289            iDelta = iDocid - iPrev;
158290          }
158291          assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
158292          assert( nDoclist>0 || iDelta==iDocid );
158293
158294          nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
158295          if( nDoclist+nByte>pCsr->nBuffer ){
158296            char *aNew;
158297            pCsr->nBuffer = (nDoclist+nByte)*2;
158298            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
158299            if( !aNew ){
158300              return SQLITE_NOMEM;
158301            }
158302            pCsr->aBuffer = aNew;
158303          }
158304
158305          if( isFirst ){
158306            char *a = &pCsr->aBuffer[nDoclist];
158307            int nWrite;
158308
158309            nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
158310            if( nWrite ){
158311              iPrev = iDocid;
158312              nDoclist += nWrite;
158313            }
158314          }else{
158315            nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
158316            iPrev = iDocid;
158317            if( isRequirePos ){
158318              memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
158319              nDoclist += nList;
158320              pCsr->aBuffer[nDoclist++] = '\0';
158321            }
158322          }
158323        }
158324
158325        fts3SegReaderSort(apSegment, nMerge, j, xCmp);
158326      }
158327      if( nDoclist>0 ){
158328        pCsr->aDoclist = pCsr->aBuffer;
158329        pCsr->nDoclist = nDoclist;
158330        rc = SQLITE_ROW;
158331      }
158332    }
158333    pCsr->nAdvance = nMerge;
158334  }while( rc==SQLITE_OK );
158335
158336  return rc;
158337}
158338
158339
158340SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
158341  Fts3MultiSegReader *pCsr       /* Cursor object */
158342){
158343  if( pCsr ){
158344    int i;
158345    for(i=0; i<pCsr->nSegment; i++){
158346      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
158347    }
158348    sqlite3_free(pCsr->apSegment);
158349    sqlite3_free(pCsr->aBuffer);
158350
158351    pCsr->nSegment = 0;
158352    pCsr->apSegment = 0;
158353    pCsr->aBuffer = 0;
158354  }
158355}
158356
158357/*
158358** Decode the "end_block" field, selected by column iCol of the SELECT
158359** statement passed as the first argument.
158360**
158361** The "end_block" field may contain either an integer, or a text field
158362** containing the text representation of two non-negative integers separated
158363** by one or more space (0x20) characters. In the first case, set *piEndBlock
158364** to the integer value and *pnByte to zero before returning. In the second,
158365** set *piEndBlock to the first value and *pnByte to the second.
158366*/
158367static void fts3ReadEndBlockField(
158368  sqlite3_stmt *pStmt,
158369  int iCol,
158370  i64 *piEndBlock,
158371  i64 *pnByte
158372){
158373  const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
158374  if( zText ){
158375    int i;
158376    int iMul = 1;
158377    i64 iVal = 0;
158378    for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
158379      iVal = iVal*10 + (zText[i] - '0');
158380    }
158381    *piEndBlock = iVal;
158382    while( zText[i]==' ' ) i++;
158383    iVal = 0;
158384    if( zText[i]=='-' ){
158385      i++;
158386      iMul = -1;
158387    }
158388    for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
158389      iVal = iVal*10 + (zText[i] - '0');
158390    }
158391    *pnByte = (iVal * (i64)iMul);
158392  }
158393}
158394
158395
158396/*
158397** A segment of size nByte bytes has just been written to absolute level
158398** iAbsLevel. Promote any segments that should be promoted as a result.
158399*/
158400static int fts3PromoteSegments(
158401  Fts3Table *p,                   /* FTS table handle */
158402  sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
158403  sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
158404){
158405  int rc = SQLITE_OK;
158406  sqlite3_stmt *pRange;
158407
158408  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
158409
158410  if( rc==SQLITE_OK ){
158411    int bOk = 0;
158412    i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
158413    i64 nLimit = (nByte*3)/2;
158414
158415    /* Loop through all entries in the %_segdir table corresponding to
158416    ** segments in this index on levels greater than iAbsLevel. If there is
158417    ** at least one such segment, and it is possible to determine that all
158418    ** such segments are smaller than nLimit bytes in size, they will be
158419    ** promoted to level iAbsLevel.  */
158420    sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
158421    sqlite3_bind_int64(pRange, 2, iLast);
158422    while( SQLITE_ROW==sqlite3_step(pRange) ){
158423      i64 nSize = 0, dummy;
158424      fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
158425      if( nSize<=0 || nSize>nLimit ){
158426        /* If nSize==0, then the %_segdir.end_block field does not not
158427        ** contain a size value. This happens if it was written by an
158428        ** old version of FTS. In this case it is not possible to determine
158429        ** the size of the segment, and so segment promotion does not
158430        ** take place.  */
158431        bOk = 0;
158432        break;
158433      }
158434      bOk = 1;
158435    }
158436    rc = sqlite3_reset(pRange);
158437
158438    if( bOk ){
158439      int iIdx = 0;
158440      sqlite3_stmt *pUpdate1 = 0;
158441      sqlite3_stmt *pUpdate2 = 0;
158442
158443      if( rc==SQLITE_OK ){
158444        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
158445      }
158446      if( rc==SQLITE_OK ){
158447        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
158448      }
158449
158450      if( rc==SQLITE_OK ){
158451
158452        /* Loop through all %_segdir entries for segments in this index with
158453        ** levels equal to or greater than iAbsLevel. As each entry is visited,
158454        ** updated it to set (level = -1) and (idx = N), where N is 0 for the
158455        ** oldest segment in the range, 1 for the next oldest, and so on.
158456        **
158457        ** In other words, move all segments being promoted to level -1,
158458        ** setting the "idx" fields as appropriate to keep them in the same
158459        ** order. The contents of level -1 (which is never used, except
158460        ** transiently here), will be moved back to level iAbsLevel below.  */
158461        sqlite3_bind_int64(pRange, 1, iAbsLevel);
158462        while( SQLITE_ROW==sqlite3_step(pRange) ){
158463          sqlite3_bind_int(pUpdate1, 1, iIdx++);
158464          sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
158465          sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
158466          sqlite3_step(pUpdate1);
158467          rc = sqlite3_reset(pUpdate1);
158468          if( rc!=SQLITE_OK ){
158469            sqlite3_reset(pRange);
158470            break;
158471          }
158472        }
158473      }
158474      if( rc==SQLITE_OK ){
158475        rc = sqlite3_reset(pRange);
158476      }
158477
158478      /* Move level -1 to level iAbsLevel */
158479      if( rc==SQLITE_OK ){
158480        sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
158481        sqlite3_step(pUpdate2);
158482        rc = sqlite3_reset(pUpdate2);
158483      }
158484    }
158485  }
158486
158487
158488  return rc;
158489}
158490
158491/*
158492** Merge all level iLevel segments in the database into a single
158493** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
158494** single segment with a level equal to the numerically largest level
158495** currently present in the database.
158496**
158497** If this function is called with iLevel<0, but there is only one
158498** segment in the database, SQLITE_DONE is returned immediately.
158499** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
158500** an SQLite error code is returned.
158501*/
158502static int fts3SegmentMerge(
158503  Fts3Table *p,
158504  int iLangid,                    /* Language id to merge */
158505  int iIndex,                     /* Index in p->aIndex[] to merge */
158506  int iLevel                      /* Level to merge */
158507){
158508  int rc;                         /* Return code */
158509  int iIdx = 0;                   /* Index of new segment */
158510  sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
158511  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
158512  Fts3SegFilter filter;           /* Segment term filter condition */
158513  Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
158514  int bIgnoreEmpty = 0;           /* True to ignore empty segments */
158515  i64 iMaxLevel = 0;              /* Max level number for this index/langid */
158516
158517  assert( iLevel==FTS3_SEGCURSOR_ALL
158518       || iLevel==FTS3_SEGCURSOR_PENDING
158519       || iLevel>=0
158520  );
158521  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
158522  assert( iIndex>=0 && iIndex<p->nIndex );
158523
158524  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
158525  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
158526
158527  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
158528    rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
158529    if( rc!=SQLITE_OK ) goto finished;
158530  }
158531
158532  if( iLevel==FTS3_SEGCURSOR_ALL ){
158533    /* This call is to merge all segments in the database to a single
158534    ** segment. The level of the new segment is equal to the numerically
158535    ** greatest segment level currently present in the database for this
158536    ** index. The idx of the new segment is always 0.  */
158537    if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
158538      rc = SQLITE_DONE;
158539      goto finished;
158540    }
158541    iNewLevel = iMaxLevel;
158542    bIgnoreEmpty = 1;
158543
158544  }else{
158545    /* This call is to merge all segments at level iLevel. find the next
158546    ** available segment index at level iLevel+1. The call to
158547    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
158548    ** a single iLevel+2 segment if necessary.  */
158549    assert( FTS3_SEGCURSOR_PENDING==-1 );
158550    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
158551    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
158552    bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
158553  }
158554  if( rc!=SQLITE_OK ) goto finished;
158555
158556  assert( csr.nSegment>0 );
158557  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
158558  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
158559
158560  memset(&filter, 0, sizeof(Fts3SegFilter));
158561  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
158562  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
158563
158564  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
158565  while( SQLITE_OK==rc ){
158566    rc = sqlite3Fts3SegReaderStep(p, &csr);
158567    if( rc!=SQLITE_ROW ) break;
158568    rc = fts3SegWriterAdd(p, &pWriter, 1,
158569        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
158570  }
158571  if( rc!=SQLITE_OK ) goto finished;
158572  assert( pWriter || bIgnoreEmpty );
158573
158574  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
158575    rc = fts3DeleteSegdir(
158576        p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
158577    );
158578    if( rc!=SQLITE_OK ) goto finished;
158579  }
158580  if( pWriter ){
158581    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
158582    if( rc==SQLITE_OK ){
158583      if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
158584        rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
158585      }
158586    }
158587  }
158588
158589 finished:
158590  fts3SegWriterFree(pWriter);
158591  sqlite3Fts3SegReaderFinish(&csr);
158592  return rc;
158593}
158594
158595
158596/*
158597** Flush the contents of pendingTerms to level 0 segments.
158598*/
158599SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
158600  int rc = SQLITE_OK;
158601  int i;
158602
158603  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
158604    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
158605    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
158606  }
158607  sqlite3Fts3PendingTermsClear(p);
158608
158609  /* Determine the auto-incr-merge setting if unknown.  If enabled,
158610  ** estimate the number of leaf blocks of content to be written
158611  */
158612  if( rc==SQLITE_OK && p->bHasStat
158613   && p->nAutoincrmerge==0xff && p->nLeafAdd>0
158614  ){
158615    sqlite3_stmt *pStmt = 0;
158616    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
158617    if( rc==SQLITE_OK ){
158618      sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
158619      rc = sqlite3_step(pStmt);
158620      if( rc==SQLITE_ROW ){
158621        p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
158622        if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
158623      }else if( rc==SQLITE_DONE ){
158624        p->nAutoincrmerge = 0;
158625      }
158626      rc = sqlite3_reset(pStmt);
158627    }
158628  }
158629  return rc;
158630}
158631
158632/*
158633** Encode N integers as varints into a blob.
158634*/
158635static void fts3EncodeIntArray(
158636  int N,             /* The number of integers to encode */
158637  u32 *a,            /* The integer values */
158638  char *zBuf,        /* Write the BLOB here */
158639  int *pNBuf         /* Write number of bytes if zBuf[] used here */
158640){
158641  int i, j;
158642  for(i=j=0; i<N; i++){
158643    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
158644  }
158645  *pNBuf = j;
158646}
158647
158648/*
158649** Decode a blob of varints into N integers
158650*/
158651static void fts3DecodeIntArray(
158652  int N,             /* The number of integers to decode */
158653  u32 *a,            /* Write the integer values */
158654  const char *zBuf,  /* The BLOB containing the varints */
158655  int nBuf           /* size of the BLOB */
158656){
158657  int i, j;
158658  UNUSED_PARAMETER(nBuf);
158659  for(i=j=0; i<N; i++){
158660    sqlite3_int64 x;
158661    j += sqlite3Fts3GetVarint(&zBuf[j], &x);
158662    assert(j<=nBuf);
158663    a[i] = (u32)(x & 0xffffffff);
158664  }
158665}
158666
158667/*
158668** Insert the sizes (in tokens) for each column of the document
158669** with docid equal to p->iPrevDocid.  The sizes are encoded as
158670** a blob of varints.
158671*/
158672static void fts3InsertDocsize(
158673  int *pRC,                       /* Result code */
158674  Fts3Table *p,                   /* Table into which to insert */
158675  u32 *aSz                        /* Sizes of each column, in tokens */
158676){
158677  char *pBlob;             /* The BLOB encoding of the document size */
158678  int nBlob;               /* Number of bytes in the BLOB */
158679  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
158680  int rc;                  /* Result code from subfunctions */
158681
158682  if( *pRC ) return;
158683  pBlob = sqlite3_malloc( 10*p->nColumn );
158684  if( pBlob==0 ){
158685    *pRC = SQLITE_NOMEM;
158686    return;
158687  }
158688  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
158689  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
158690  if( rc ){
158691    sqlite3_free(pBlob);
158692    *pRC = rc;
158693    return;
158694  }
158695  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
158696  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
158697  sqlite3_step(pStmt);
158698  *pRC = sqlite3_reset(pStmt);
158699}
158700
158701/*
158702** Record 0 of the %_stat table contains a blob consisting of N varints,
158703** where N is the number of user defined columns in the fts3 table plus
158704** two. If nCol is the number of user defined columns, then values of the
158705** varints are set as follows:
158706**
158707**   Varint 0:       Total number of rows in the table.
158708**
158709**   Varint 1..nCol: For each column, the total number of tokens stored in
158710**                   the column for all rows of the table.
158711**
158712**   Varint 1+nCol:  The total size, in bytes, of all text values in all
158713**                   columns of all rows of the table.
158714**
158715*/
158716static void fts3UpdateDocTotals(
158717  int *pRC,                       /* The result code */
158718  Fts3Table *p,                   /* Table being updated */
158719  u32 *aSzIns,                    /* Size increases */
158720  u32 *aSzDel,                    /* Size decreases */
158721  int nChng                       /* Change in the number of documents */
158722){
158723  char *pBlob;             /* Storage for BLOB written into %_stat */
158724  int nBlob;               /* Size of BLOB written into %_stat */
158725  u32 *a;                  /* Array of integers that becomes the BLOB */
158726  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
158727  int i;                   /* Loop counter */
158728  int rc;                  /* Result code from subfunctions */
158729
158730  const int nStat = p->nColumn+2;
158731
158732  if( *pRC ) return;
158733  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
158734  if( a==0 ){
158735    *pRC = SQLITE_NOMEM;
158736    return;
158737  }
158738  pBlob = (char*)&a[nStat];
158739  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
158740  if( rc ){
158741    sqlite3_free(a);
158742    *pRC = rc;
158743    return;
158744  }
158745  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
158746  if( sqlite3_step(pStmt)==SQLITE_ROW ){
158747    fts3DecodeIntArray(nStat, a,
158748         sqlite3_column_blob(pStmt, 0),
158749         sqlite3_column_bytes(pStmt, 0));
158750  }else{
158751    memset(a, 0, sizeof(u32)*(nStat) );
158752  }
158753  rc = sqlite3_reset(pStmt);
158754  if( rc!=SQLITE_OK ){
158755    sqlite3_free(a);
158756    *pRC = rc;
158757    return;
158758  }
158759  if( nChng<0 && a[0]<(u32)(-nChng) ){
158760    a[0] = 0;
158761  }else{
158762    a[0] += nChng;
158763  }
158764  for(i=0; i<p->nColumn+1; i++){
158765    u32 x = a[i+1];
158766    if( x+aSzIns[i] < aSzDel[i] ){
158767      x = 0;
158768    }else{
158769      x = x + aSzIns[i] - aSzDel[i];
158770    }
158771    a[i+1] = x;
158772  }
158773  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
158774  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
158775  if( rc ){
158776    sqlite3_free(a);
158777    *pRC = rc;
158778    return;
158779  }
158780  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
158781  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
158782  sqlite3_step(pStmt);
158783  *pRC = sqlite3_reset(pStmt);
158784  sqlite3_free(a);
158785}
158786
158787/*
158788** Merge the entire database so that there is one segment for each
158789** iIndex/iLangid combination.
158790*/
158791static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
158792  int bSeenDone = 0;
158793  int rc;
158794  sqlite3_stmt *pAllLangid = 0;
158795
158796  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
158797  if( rc==SQLITE_OK ){
158798    int rc2;
158799    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
158800    sqlite3_bind_int(pAllLangid, 2, p->nIndex);
158801    while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
158802      int i;
158803      int iLangid = sqlite3_column_int(pAllLangid, 0);
158804      for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
158805        rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
158806        if( rc==SQLITE_DONE ){
158807          bSeenDone = 1;
158808          rc = SQLITE_OK;
158809        }
158810      }
158811    }
158812    rc2 = sqlite3_reset(pAllLangid);
158813    if( rc==SQLITE_OK ) rc = rc2;
158814  }
158815
158816  sqlite3Fts3SegmentsClose(p);
158817  sqlite3Fts3PendingTermsClear(p);
158818
158819  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
158820}
158821
158822/*
158823** This function is called when the user executes the following statement:
158824**
158825**     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
158826**
158827** The entire FTS index is discarded and rebuilt. If the table is one
158828** created using the content=xxx option, then the new index is based on
158829** the current contents of the xxx table. Otherwise, it is rebuilt based
158830** on the contents of the %_content table.
158831*/
158832static int fts3DoRebuild(Fts3Table *p){
158833  int rc;                         /* Return Code */
158834
158835  rc = fts3DeleteAll(p, 0);
158836  if( rc==SQLITE_OK ){
158837    u32 *aSz = 0;
158838    u32 *aSzIns = 0;
158839    u32 *aSzDel = 0;
158840    sqlite3_stmt *pStmt = 0;
158841    int nEntry = 0;
158842
158843    /* Compose and prepare an SQL statement to loop through the content table */
158844    char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
158845    if( !zSql ){
158846      rc = SQLITE_NOMEM;
158847    }else{
158848      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
158849      sqlite3_free(zSql);
158850    }
158851
158852    if( rc==SQLITE_OK ){
158853      int nByte = sizeof(u32) * (p->nColumn+1)*3;
158854      aSz = (u32 *)sqlite3_malloc(nByte);
158855      if( aSz==0 ){
158856        rc = SQLITE_NOMEM;
158857      }else{
158858        memset(aSz, 0, nByte);
158859        aSzIns = &aSz[p->nColumn+1];
158860        aSzDel = &aSzIns[p->nColumn+1];
158861      }
158862    }
158863
158864    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
158865      int iCol;
158866      int iLangid = langidFromSelect(p, pStmt);
158867      rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
158868      memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
158869      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
158870        if( p->abNotindexed[iCol]==0 ){
158871          const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
158872          rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
158873          aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
158874        }
158875      }
158876      if( p->bHasDocsize ){
158877        fts3InsertDocsize(&rc, p, aSz);
158878      }
158879      if( rc!=SQLITE_OK ){
158880        sqlite3_finalize(pStmt);
158881        pStmt = 0;
158882      }else{
158883        nEntry++;
158884        for(iCol=0; iCol<=p->nColumn; iCol++){
158885          aSzIns[iCol] += aSz[iCol];
158886        }
158887      }
158888    }
158889    if( p->bFts4 ){
158890      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
158891    }
158892    sqlite3_free(aSz);
158893
158894    if( pStmt ){
158895      int rc2 = sqlite3_finalize(pStmt);
158896      if( rc==SQLITE_OK ){
158897        rc = rc2;
158898      }
158899    }
158900  }
158901
158902  return rc;
158903}
158904
158905
158906/*
158907** This function opens a cursor used to read the input data for an
158908** incremental merge operation. Specifically, it opens a cursor to scan
158909** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
158910** level iAbsLevel.
158911*/
158912static int fts3IncrmergeCsr(
158913  Fts3Table *p,                   /* FTS3 table handle */
158914  sqlite3_int64 iAbsLevel,        /* Absolute level to open */
158915  int nSeg,                       /* Number of segments to merge */
158916  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
158917){
158918  int rc;                         /* Return Code */
158919  sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
158920  int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
158921
158922  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
158923  memset(pCsr, 0, sizeof(*pCsr));
158924  nByte = sizeof(Fts3SegReader *) * nSeg;
158925  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
158926
158927  if( pCsr->apSegment==0 ){
158928    rc = SQLITE_NOMEM;
158929  }else{
158930    memset(pCsr->apSegment, 0, nByte);
158931    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
158932  }
158933  if( rc==SQLITE_OK ){
158934    int i;
158935    int rc2;
158936    sqlite3_bind_int64(pStmt, 1, iAbsLevel);
158937    assert( pCsr->nSegment==0 );
158938    for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
158939      rc = sqlite3Fts3SegReaderNew(i, 0,
158940          sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
158941          sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
158942          sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
158943          sqlite3_column_blob(pStmt, 4),         /* segdir.root */
158944          sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
158945          &pCsr->apSegment[i]
158946      );
158947      pCsr->nSegment++;
158948    }
158949    rc2 = sqlite3_reset(pStmt);
158950    if( rc==SQLITE_OK ) rc = rc2;
158951  }
158952
158953  return rc;
158954}
158955
158956typedef struct IncrmergeWriter IncrmergeWriter;
158957typedef struct NodeWriter NodeWriter;
158958typedef struct Blob Blob;
158959typedef struct NodeReader NodeReader;
158960
158961/*
158962** An instance of the following structure is used as a dynamic buffer
158963** to build up nodes or other blobs of data in.
158964**
158965** The function blobGrowBuffer() is used to extend the allocation.
158966*/
158967struct Blob {
158968  char *a;                        /* Pointer to allocation */
158969  int n;                          /* Number of valid bytes of data in a[] */
158970  int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
158971};
158972
158973/*
158974** This structure is used to build up buffers containing segment b-tree
158975** nodes (blocks).
158976*/
158977struct NodeWriter {
158978  sqlite3_int64 iBlock;           /* Current block id */
158979  Blob key;                       /* Last key written to the current block */
158980  Blob block;                     /* Current block image */
158981};
158982
158983/*
158984** An object of this type contains the state required to create or append
158985** to an appendable b-tree segment.
158986*/
158987struct IncrmergeWriter {
158988  int nLeafEst;                   /* Space allocated for leaf blocks */
158989  int nWork;                      /* Number of leaf pages flushed */
158990  sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
158991  int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
158992  sqlite3_int64 iStart;           /* Block number of first allocated block */
158993  sqlite3_int64 iEnd;             /* Block number of last allocated block */
158994  sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
158995  u8 bNoLeafData;                 /* If true, store 0 for segment size */
158996  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
158997};
158998
158999/*
159000** An object of the following type is used to read data from a single
159001** FTS segment node. See the following functions:
159002**
159003**     nodeReaderInit()
159004**     nodeReaderNext()
159005**     nodeReaderRelease()
159006*/
159007struct NodeReader {
159008  const char *aNode;
159009  int nNode;
159010  int iOff;                       /* Current offset within aNode[] */
159011
159012  /* Output variables. Containing the current node entry. */
159013  sqlite3_int64 iChild;           /* Pointer to child node */
159014  Blob term;                      /* Current term */
159015  const char *aDoclist;           /* Pointer to doclist */
159016  int nDoclist;                   /* Size of doclist in bytes */
159017};
159018
159019/*
159020** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
159021** Otherwise, if the allocation at pBlob->a is not already at least nMin
159022** bytes in size, extend (realloc) it to be so.
159023**
159024** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
159025** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
159026** to reflect the new size of the pBlob->a[] buffer.
159027*/
159028static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
159029  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
159030    int nAlloc = nMin;
159031    char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
159032    if( a ){
159033      pBlob->nAlloc = nAlloc;
159034      pBlob->a = a;
159035    }else{
159036      *pRc = SQLITE_NOMEM;
159037    }
159038  }
159039}
159040
159041/*
159042** Attempt to advance the node-reader object passed as the first argument to
159043** the next entry on the node.
159044**
159045** Return an error code if an error occurs (SQLITE_NOMEM is possible).
159046** Otherwise return SQLITE_OK. If there is no next entry on the node
159047** (e.g. because the current entry is the last) set NodeReader->aNode to
159048** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
159049** variables for the new entry.
159050*/
159051static int nodeReaderNext(NodeReader *p){
159052  int bFirst = (p->term.n==0);    /* True for first term on the node */
159053  int nPrefix = 0;                /* Bytes to copy from previous term */
159054  int nSuffix = 0;                /* Bytes to append to the prefix */
159055  int rc = SQLITE_OK;             /* Return code */
159056
159057  assert( p->aNode );
159058  if( p->iChild && bFirst==0 ) p->iChild++;
159059  if( p->iOff>=p->nNode ){
159060    /* EOF */
159061    p->aNode = 0;
159062  }else{
159063    if( bFirst==0 ){
159064      p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
159065    }
159066    p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
159067
159068    blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
159069    if( rc==SQLITE_OK ){
159070      memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
159071      p->term.n = nPrefix+nSuffix;
159072      p->iOff += nSuffix;
159073      if( p->iChild==0 ){
159074        p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
159075        p->aDoclist = &p->aNode[p->iOff];
159076        p->iOff += p->nDoclist;
159077      }
159078    }
159079  }
159080
159081  assert( p->iOff<=p->nNode );
159082
159083  return rc;
159084}
159085
159086/*
159087** Release all dynamic resources held by node-reader object *p.
159088*/
159089static void nodeReaderRelease(NodeReader *p){
159090  sqlite3_free(p->term.a);
159091}
159092
159093/*
159094** Initialize a node-reader object to read the node in buffer aNode/nNode.
159095**
159096** If successful, SQLITE_OK is returned and the NodeReader object set to
159097** point to the first entry on the node (if any). Otherwise, an SQLite
159098** error code is returned.
159099*/
159100static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
159101  memset(p, 0, sizeof(NodeReader));
159102  p->aNode = aNode;
159103  p->nNode = nNode;
159104
159105  /* Figure out if this is a leaf or an internal node. */
159106  if( p->aNode[0] ){
159107    /* An internal node. */
159108    p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
159109  }else{
159110    p->iOff = 1;
159111  }
159112
159113  return nodeReaderNext(p);
159114}
159115
159116/*
159117** This function is called while writing an FTS segment each time a leaf o
159118** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
159119** to be greater than the largest key on the node just written, but smaller
159120** than or equal to the first key that will be written to the next leaf
159121** node.
159122**
159123** The block id of the leaf node just written to disk may be found in
159124** (pWriter->aNodeWriter[0].iBlock) when this function is called.
159125*/
159126static int fts3IncrmergePush(
159127  Fts3Table *p,                   /* Fts3 table handle */
159128  IncrmergeWriter *pWriter,       /* Writer object */
159129  const char *zTerm,              /* Term to write to internal node */
159130  int nTerm                       /* Bytes at zTerm */
159131){
159132  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
159133  int iLayer;
159134
159135  assert( nTerm>0 );
159136  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
159137    sqlite3_int64 iNextPtr = 0;
159138    NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
159139    int rc = SQLITE_OK;
159140    int nPrefix;
159141    int nSuffix;
159142    int nSpace;
159143
159144    /* Figure out how much space the key will consume if it is written to
159145    ** the current node of layer iLayer. Due to the prefix compression,
159146    ** the space required changes depending on which node the key is to
159147    ** be added to.  */
159148    nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
159149    nSuffix = nTerm - nPrefix;
159150    nSpace  = sqlite3Fts3VarintLen(nPrefix);
159151    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
159152
159153    if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
159154      /* If the current node of layer iLayer contains zero keys, or if adding
159155      ** the key to it will not cause it to grow to larger than nNodeSize
159156      ** bytes in size, write the key here.  */
159157
159158      Blob *pBlk = &pNode->block;
159159      if( pBlk->n==0 ){
159160        blobGrowBuffer(pBlk, p->nNodeSize, &rc);
159161        if( rc==SQLITE_OK ){
159162          pBlk->a[0] = (char)iLayer;
159163          pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
159164        }
159165      }
159166      blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
159167      blobGrowBuffer(&pNode->key, nTerm, &rc);
159168
159169      if( rc==SQLITE_OK ){
159170        if( pNode->key.n ){
159171          pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
159172        }
159173        pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
159174        memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
159175        pBlk->n += nSuffix;
159176
159177        memcpy(pNode->key.a, zTerm, nTerm);
159178        pNode->key.n = nTerm;
159179      }
159180    }else{
159181      /* Otherwise, flush the current node of layer iLayer to disk.
159182      ** Then allocate a new, empty sibling node. The key will be written
159183      ** into the parent of this node. */
159184      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
159185
159186      assert( pNode->block.nAlloc>=p->nNodeSize );
159187      pNode->block.a[0] = (char)iLayer;
159188      pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
159189
159190      iNextPtr = pNode->iBlock;
159191      pNode->iBlock++;
159192      pNode->key.n = 0;
159193    }
159194
159195    if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
159196    iPtr = iNextPtr;
159197  }
159198
159199  assert( 0 );
159200  return 0;
159201}
159202
159203/*
159204** Append a term and (optionally) doclist to the FTS segment node currently
159205** stored in blob *pNode. The node need not contain any terms, but the
159206** header must be written before this function is called.
159207**
159208** A node header is a single 0x00 byte for a leaf node, or a height varint
159209** followed by the left-hand-child varint for an internal node.
159210**
159211** The term to be appended is passed via arguments zTerm/nTerm. For a
159212** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
159213** node, both aDoclist and nDoclist must be passed 0.
159214**
159215** If the size of the value in blob pPrev is zero, then this is the first
159216** term written to the node. Otherwise, pPrev contains a copy of the
159217** previous term. Before this function returns, it is updated to contain a
159218** copy of zTerm/nTerm.
159219**
159220** It is assumed that the buffer associated with pNode is already large
159221** enough to accommodate the new entry. The buffer associated with pPrev
159222** is extended by this function if requrired.
159223**
159224** If an error (i.e. OOM condition) occurs, an SQLite error code is
159225** returned. Otherwise, SQLITE_OK.
159226*/
159227static int fts3AppendToNode(
159228  Blob *pNode,                    /* Current node image to append to */
159229  Blob *pPrev,                    /* Buffer containing previous term written */
159230  const char *zTerm,              /* New term to write */
159231  int nTerm,                      /* Size of zTerm in bytes */
159232  const char *aDoclist,           /* Doclist (or NULL) to write */
159233  int nDoclist                    /* Size of aDoclist in bytes */
159234){
159235  int rc = SQLITE_OK;             /* Return code */
159236  int bFirst = (pPrev->n==0);     /* True if this is the first term written */
159237  int nPrefix;                    /* Size of term prefix in bytes */
159238  int nSuffix;                    /* Size of term suffix in bytes */
159239
159240  /* Node must have already been started. There must be a doclist for a
159241  ** leaf node, and there must not be a doclist for an internal node.  */
159242  assert( pNode->n>0 );
159243  assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
159244
159245  blobGrowBuffer(pPrev, nTerm, &rc);
159246  if( rc!=SQLITE_OK ) return rc;
159247
159248  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
159249  nSuffix = nTerm - nPrefix;
159250  memcpy(pPrev->a, zTerm, nTerm);
159251  pPrev->n = nTerm;
159252
159253  if( bFirst==0 ){
159254    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
159255  }
159256  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
159257  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
159258  pNode->n += nSuffix;
159259
159260  if( aDoclist ){
159261    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
159262    memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
159263    pNode->n += nDoclist;
159264  }
159265
159266  assert( pNode->n<=pNode->nAlloc );
159267
159268  return SQLITE_OK;
159269}
159270
159271/*
159272** Append the current term and doclist pointed to by cursor pCsr to the
159273** appendable b-tree segment opened for writing by pWriter.
159274**
159275** Return SQLITE_OK if successful, or an SQLite error code otherwise.
159276*/
159277static int fts3IncrmergeAppend(
159278  Fts3Table *p,                   /* Fts3 table handle */
159279  IncrmergeWriter *pWriter,       /* Writer object */
159280  Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
159281){
159282  const char *zTerm = pCsr->zTerm;
159283  int nTerm = pCsr->nTerm;
159284  const char *aDoclist = pCsr->aDoclist;
159285  int nDoclist = pCsr->nDoclist;
159286  int rc = SQLITE_OK;           /* Return code */
159287  int nSpace;                   /* Total space in bytes required on leaf */
159288  int nPrefix;                  /* Size of prefix shared with previous term */
159289  int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
159290  NodeWriter *pLeaf;            /* Object used to write leaf nodes */
159291
159292  pLeaf = &pWriter->aNodeWriter[0];
159293  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
159294  nSuffix = nTerm - nPrefix;
159295
159296  nSpace  = sqlite3Fts3VarintLen(nPrefix);
159297  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
159298  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
159299
159300  /* If the current block is not empty, and if adding this term/doclist
159301  ** to the current block would make it larger than Fts3Table.nNodeSize
159302  ** bytes, write this block out to the database. */
159303  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
159304    rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
159305    pWriter->nWork++;
159306
159307    /* Add the current term to the parent node. The term added to the
159308    ** parent must:
159309    **
159310    **   a) be greater than the largest term on the leaf node just written
159311    **      to the database (still available in pLeaf->key), and
159312    **
159313    **   b) be less than or equal to the term about to be added to the new
159314    **      leaf node (zTerm/nTerm).
159315    **
159316    ** In other words, it must be the prefix of zTerm 1 byte longer than
159317    ** the common prefix (if any) of zTerm and pWriter->zTerm.
159318    */
159319    if( rc==SQLITE_OK ){
159320      rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
159321    }
159322
159323    /* Advance to the next output block */
159324    pLeaf->iBlock++;
159325    pLeaf->key.n = 0;
159326    pLeaf->block.n = 0;
159327
159328    nSuffix = nTerm;
159329    nSpace  = 1;
159330    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
159331    nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
159332  }
159333
159334  pWriter->nLeafData += nSpace;
159335  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
159336  if( rc==SQLITE_OK ){
159337    if( pLeaf->block.n==0 ){
159338      pLeaf->block.n = 1;
159339      pLeaf->block.a[0] = '\0';
159340    }
159341    rc = fts3AppendToNode(
159342        &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
159343    );
159344  }
159345
159346  return rc;
159347}
159348
159349/*
159350** This function is called to release all dynamic resources held by the
159351** merge-writer object pWriter, and if no error has occurred, to flush
159352** all outstanding node buffers held by pWriter to disk.
159353**
159354** If *pRc is not SQLITE_OK when this function is called, then no attempt
159355** is made to write any data to disk. Instead, this function serves only
159356** to release outstanding resources.
159357**
159358** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
159359** flushing buffers to disk, *pRc is set to an SQLite error code before
159360** returning.
159361*/
159362static void fts3IncrmergeRelease(
159363  Fts3Table *p,                   /* FTS3 table handle */
159364  IncrmergeWriter *pWriter,       /* Merge-writer object */
159365  int *pRc                        /* IN/OUT: Error code */
159366){
159367  int i;                          /* Used to iterate through non-root layers */
159368  int iRoot;                      /* Index of root in pWriter->aNodeWriter */
159369  NodeWriter *pRoot;              /* NodeWriter for root node */
159370  int rc = *pRc;                  /* Error code */
159371
159372  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
159373  ** root node. If the segment fits entirely on a single leaf node, iRoot
159374  ** will be set to 0. If the root node is the parent of the leaves, iRoot
159375  ** will be 1. And so on.  */
159376  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
159377    NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
159378    if( pNode->block.n>0 ) break;
159379    assert( *pRc || pNode->block.nAlloc==0 );
159380    assert( *pRc || pNode->key.nAlloc==0 );
159381    sqlite3_free(pNode->block.a);
159382    sqlite3_free(pNode->key.a);
159383  }
159384
159385  /* Empty output segment. This is a no-op. */
159386  if( iRoot<0 ) return;
159387
159388  /* The entire output segment fits on a single node. Normally, this means
159389  ** the node would be stored as a blob in the "root" column of the %_segdir
159390  ** table. However, this is not permitted in this case. The problem is that
159391  ** space has already been reserved in the %_segments table, and so the
159392  ** start_block and end_block fields of the %_segdir table must be populated.
159393  ** And, by design or by accident, released versions of FTS cannot handle
159394  ** segments that fit entirely on the root node with start_block!=0.
159395  **
159396  ** Instead, create a synthetic root node that contains nothing but a
159397  ** pointer to the single content node. So that the segment consists of a
159398  ** single leaf and a single interior (root) node.
159399  **
159400  ** Todo: Better might be to defer allocating space in the %_segments
159401  ** table until we are sure it is needed.
159402  */
159403  if( iRoot==0 ){
159404    Blob *pBlock = &pWriter->aNodeWriter[1].block;
159405    blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
159406    if( rc==SQLITE_OK ){
159407      pBlock->a[0] = 0x01;
159408      pBlock->n = 1 + sqlite3Fts3PutVarint(
159409          &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
159410      );
159411    }
159412    iRoot = 1;
159413  }
159414  pRoot = &pWriter->aNodeWriter[iRoot];
159415
159416  /* Flush all currently outstanding nodes to disk. */
159417  for(i=0; i<iRoot; i++){
159418    NodeWriter *pNode = &pWriter->aNodeWriter[i];
159419    if( pNode->block.n>0 && rc==SQLITE_OK ){
159420      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
159421    }
159422    sqlite3_free(pNode->block.a);
159423    sqlite3_free(pNode->key.a);
159424  }
159425
159426  /* Write the %_segdir record. */
159427  if( rc==SQLITE_OK ){
159428    rc = fts3WriteSegdir(p,
159429        pWriter->iAbsLevel+1,               /* level */
159430        pWriter->iIdx,                      /* idx */
159431        pWriter->iStart,                    /* start_block */
159432        pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
159433        pWriter->iEnd,                      /* end_block */
159434        (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
159435        pRoot->block.a, pRoot->block.n      /* root */
159436    );
159437  }
159438  sqlite3_free(pRoot->block.a);
159439  sqlite3_free(pRoot->key.a);
159440
159441  *pRc = rc;
159442}
159443
159444/*
159445** Compare the term in buffer zLhs (size in bytes nLhs) with that in
159446** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
159447** the other, it is considered to be smaller than the other.
159448**
159449** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
159450** if it is greater.
159451*/
159452static int fts3TermCmp(
159453  const char *zLhs, int nLhs,     /* LHS of comparison */
159454  const char *zRhs, int nRhs      /* RHS of comparison */
159455){
159456  int nCmp = MIN(nLhs, nRhs);
159457  int res;
159458
159459  res = memcmp(zLhs, zRhs, nCmp);
159460  if( res==0 ) res = nLhs - nRhs;
159461
159462  return res;
159463}
159464
159465
159466/*
159467** Query to see if the entry in the %_segments table with blockid iEnd is
159468** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
159469** returning. Otherwise, set *pbRes to 0.
159470**
159471** Or, if an error occurs while querying the database, return an SQLite
159472** error code. The final value of *pbRes is undefined in this case.
159473**
159474** This is used to test if a segment is an "appendable" segment. If it
159475** is, then a NULL entry has been inserted into the %_segments table
159476** with blockid %_segdir.end_block.
159477*/
159478static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
159479  int bRes = 0;                   /* Result to set *pbRes to */
159480  sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
159481  int rc;                         /* Return code */
159482
159483  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
159484  if( rc==SQLITE_OK ){
159485    sqlite3_bind_int64(pCheck, 1, iEnd);
159486    if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
159487    rc = sqlite3_reset(pCheck);
159488  }
159489
159490  *pbRes = bRes;
159491  return rc;
159492}
159493
159494/*
159495** This function is called when initializing an incremental-merge operation.
159496** It checks if the existing segment with index value iIdx at absolute level
159497** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
159498** merge-writer object *pWriter is initialized to write to it.
159499**
159500** An existing segment can be appended to by an incremental merge if:
159501**
159502**   * It was initially created as an appendable segment (with all required
159503**     space pre-allocated), and
159504**
159505**   * The first key read from the input (arguments zKey and nKey) is
159506**     greater than the largest key currently stored in the potential
159507**     output segment.
159508*/
159509static int fts3IncrmergeLoad(
159510  Fts3Table *p,                   /* Fts3 table handle */
159511  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
159512  int iIdx,                       /* Index of candidate output segment */
159513  const char *zKey,               /* First key to write */
159514  int nKey,                       /* Number of bytes in nKey */
159515  IncrmergeWriter *pWriter        /* Populate this object */
159516){
159517  int rc;                         /* Return code */
159518  sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
159519
159520  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
159521  if( rc==SQLITE_OK ){
159522    sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
159523    sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
159524    sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
159525    const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
159526    int nRoot = 0;                /* Size of aRoot[] in bytes */
159527    int rc2;                      /* Return code from sqlite3_reset() */
159528    int bAppendable = 0;          /* Set to true if segment is appendable */
159529
159530    /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
159531    sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
159532    sqlite3_bind_int(pSelect, 2, iIdx);
159533    if( sqlite3_step(pSelect)==SQLITE_ROW ){
159534      iStart = sqlite3_column_int64(pSelect, 1);
159535      iLeafEnd = sqlite3_column_int64(pSelect, 2);
159536      fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
159537      if( pWriter->nLeafData<0 ){
159538        pWriter->nLeafData = pWriter->nLeafData * -1;
159539      }
159540      pWriter->bNoLeafData = (pWriter->nLeafData==0);
159541      nRoot = sqlite3_column_bytes(pSelect, 4);
159542      aRoot = sqlite3_column_blob(pSelect, 4);
159543    }else{
159544      return sqlite3_reset(pSelect);
159545    }
159546
159547    /* Check for the zero-length marker in the %_segments table */
159548    rc = fts3IsAppendable(p, iEnd, &bAppendable);
159549
159550    /* Check that zKey/nKey is larger than the largest key the candidate */
159551    if( rc==SQLITE_OK && bAppendable ){
159552      char *aLeaf = 0;
159553      int nLeaf = 0;
159554
159555      rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
159556      if( rc==SQLITE_OK ){
159557        NodeReader reader;
159558        for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
159559            rc==SQLITE_OK && reader.aNode;
159560            rc = nodeReaderNext(&reader)
159561        ){
159562          assert( reader.aNode );
159563        }
159564        if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
159565          bAppendable = 0;
159566        }
159567        nodeReaderRelease(&reader);
159568      }
159569      sqlite3_free(aLeaf);
159570    }
159571
159572    if( rc==SQLITE_OK && bAppendable ){
159573      /* It is possible to append to this segment. Set up the IncrmergeWriter
159574      ** object to do so.  */
159575      int i;
159576      int nHeight = (int)aRoot[0];
159577      NodeWriter *pNode;
159578
159579      pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
159580      pWriter->iStart = iStart;
159581      pWriter->iEnd = iEnd;
159582      pWriter->iAbsLevel = iAbsLevel;
159583      pWriter->iIdx = iIdx;
159584
159585      for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
159586        pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
159587      }
159588
159589      pNode = &pWriter->aNodeWriter[nHeight];
159590      pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
159591      blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
159592      if( rc==SQLITE_OK ){
159593        memcpy(pNode->block.a, aRoot, nRoot);
159594        pNode->block.n = nRoot;
159595      }
159596
159597      for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
159598        NodeReader reader;
159599        pNode = &pWriter->aNodeWriter[i];
159600
159601        rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
159602        while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
159603        blobGrowBuffer(&pNode->key, reader.term.n, &rc);
159604        if( rc==SQLITE_OK ){
159605          memcpy(pNode->key.a, reader.term.a, reader.term.n);
159606          pNode->key.n = reader.term.n;
159607          if( i>0 ){
159608            char *aBlock = 0;
159609            int nBlock = 0;
159610            pNode = &pWriter->aNodeWriter[i-1];
159611            pNode->iBlock = reader.iChild;
159612            rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
159613            blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
159614            if( rc==SQLITE_OK ){
159615              memcpy(pNode->block.a, aBlock, nBlock);
159616              pNode->block.n = nBlock;
159617            }
159618            sqlite3_free(aBlock);
159619          }
159620        }
159621        nodeReaderRelease(&reader);
159622      }
159623    }
159624
159625    rc2 = sqlite3_reset(pSelect);
159626    if( rc==SQLITE_OK ) rc = rc2;
159627  }
159628
159629  return rc;
159630}
159631
159632/*
159633** Determine the largest segment index value that exists within absolute
159634** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
159635** one before returning SQLITE_OK. Or, if there are no segments at all
159636** within level iAbsLevel, set *piIdx to zero.
159637**
159638** If an error occurs, return an SQLite error code. The final value of
159639** *piIdx is undefined in this case.
159640*/
159641static int fts3IncrmergeOutputIdx(
159642  Fts3Table *p,                   /* FTS Table handle */
159643  sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
159644  int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
159645){
159646  int rc;
159647  sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
159648
159649  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
159650  if( rc==SQLITE_OK ){
159651    sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
159652    sqlite3_step(pOutputIdx);
159653    *piIdx = sqlite3_column_int(pOutputIdx, 0);
159654    rc = sqlite3_reset(pOutputIdx);
159655  }
159656
159657  return rc;
159658}
159659
159660/*
159661** Allocate an appendable output segment on absolute level iAbsLevel+1
159662** with idx value iIdx.
159663**
159664** In the %_segdir table, a segment is defined by the values in three
159665** columns:
159666**
159667**     start_block
159668**     leaves_end_block
159669**     end_block
159670**
159671** When an appendable segment is allocated, it is estimated that the
159672** maximum number of leaf blocks that may be required is the sum of the
159673** number of leaf blocks consumed by the input segments, plus the number
159674** of input segments, multiplied by two. This value is stored in stack
159675** variable nLeafEst.
159676**
159677** A total of 16*nLeafEst blocks are allocated when an appendable segment
159678** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
159679** array of leaf nodes starts at the first block allocated. The array
159680** of interior nodes that are parents of the leaf nodes start at block
159681** (start_block + (1 + end_block - start_block) / 16). And so on.
159682**
159683** In the actual code below, the value "16" is replaced with the
159684** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
159685*/
159686static int fts3IncrmergeWriter(
159687  Fts3Table *p,                   /* Fts3 table handle */
159688  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
159689  int iIdx,                       /* Index of new output segment */
159690  Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
159691  IncrmergeWriter *pWriter        /* Populate this object */
159692){
159693  int rc;                         /* Return Code */
159694  int i;                          /* Iterator variable */
159695  int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
159696  sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
159697  sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
159698
159699  /* Calculate nLeafEst. */
159700  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
159701  if( rc==SQLITE_OK ){
159702    sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
159703    sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
159704    if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
159705      nLeafEst = sqlite3_column_int(pLeafEst, 0);
159706    }
159707    rc = sqlite3_reset(pLeafEst);
159708  }
159709  if( rc!=SQLITE_OK ) return rc;
159710
159711  /* Calculate the first block to use in the output segment */
159712  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
159713  if( rc==SQLITE_OK ){
159714    if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
159715      pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
159716      pWriter->iEnd = pWriter->iStart - 1;
159717      pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
159718    }
159719    rc = sqlite3_reset(pFirstBlock);
159720  }
159721  if( rc!=SQLITE_OK ) return rc;
159722
159723  /* Insert the marker in the %_segments table to make sure nobody tries
159724  ** to steal the space just allocated. This is also used to identify
159725  ** appendable segments.  */
159726  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
159727  if( rc!=SQLITE_OK ) return rc;
159728
159729  pWriter->iAbsLevel = iAbsLevel;
159730  pWriter->nLeafEst = nLeafEst;
159731  pWriter->iIdx = iIdx;
159732
159733  /* Set up the array of NodeWriter objects */
159734  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
159735    pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
159736  }
159737  return SQLITE_OK;
159738}
159739
159740/*
159741** Remove an entry from the %_segdir table. This involves running the
159742** following two statements:
159743**
159744**   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
159745**   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
159746**
159747** The DELETE statement removes the specific %_segdir level. The UPDATE
159748** statement ensures that the remaining segments have contiguously allocated
159749** idx values.
159750*/
159751static int fts3RemoveSegdirEntry(
159752  Fts3Table *p,                   /* FTS3 table handle */
159753  sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
159754  int iIdx                        /* Index of %_segdir entry to delete */
159755){
159756  int rc;                         /* Return code */
159757  sqlite3_stmt *pDelete = 0;      /* DELETE statement */
159758
159759  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
159760  if( rc==SQLITE_OK ){
159761    sqlite3_bind_int64(pDelete, 1, iAbsLevel);
159762    sqlite3_bind_int(pDelete, 2, iIdx);
159763    sqlite3_step(pDelete);
159764    rc = sqlite3_reset(pDelete);
159765  }
159766
159767  return rc;
159768}
159769
159770/*
159771** One or more segments have just been removed from absolute level iAbsLevel.
159772** Update the 'idx' values of the remaining segments in the level so that
159773** the idx values are a contiguous sequence starting from 0.
159774*/
159775static int fts3RepackSegdirLevel(
159776  Fts3Table *p,                   /* FTS3 table handle */
159777  sqlite3_int64 iAbsLevel         /* Absolute level to repack */
159778){
159779  int rc;                         /* Return code */
159780  int *aIdx = 0;                  /* Array of remaining idx values */
159781  int nIdx = 0;                   /* Valid entries in aIdx[] */
159782  int nAlloc = 0;                 /* Allocated size of aIdx[] */
159783  int i;                          /* Iterator variable */
159784  sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
159785  sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
159786
159787  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
159788  if( rc==SQLITE_OK ){
159789    int rc2;
159790    sqlite3_bind_int64(pSelect, 1, iAbsLevel);
159791    while( SQLITE_ROW==sqlite3_step(pSelect) ){
159792      if( nIdx>=nAlloc ){
159793        int *aNew;
159794        nAlloc += 16;
159795        aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
159796        if( !aNew ){
159797          rc = SQLITE_NOMEM;
159798          break;
159799        }
159800        aIdx = aNew;
159801      }
159802      aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
159803    }
159804    rc2 = sqlite3_reset(pSelect);
159805    if( rc==SQLITE_OK ) rc = rc2;
159806  }
159807
159808  if( rc==SQLITE_OK ){
159809    rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
159810  }
159811  if( rc==SQLITE_OK ){
159812    sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
159813  }
159814
159815  assert( p->bIgnoreSavepoint==0 );
159816  p->bIgnoreSavepoint = 1;
159817  for(i=0; rc==SQLITE_OK && i<nIdx; i++){
159818    if( aIdx[i]!=i ){
159819      sqlite3_bind_int(pUpdate, 3, aIdx[i]);
159820      sqlite3_bind_int(pUpdate, 1, i);
159821      sqlite3_step(pUpdate);
159822      rc = sqlite3_reset(pUpdate);
159823    }
159824  }
159825  p->bIgnoreSavepoint = 0;
159826
159827  sqlite3_free(aIdx);
159828  return rc;
159829}
159830
159831static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
159832  pNode->a[0] = (char)iHeight;
159833  if( iChild ){
159834    assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
159835    pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
159836  }else{
159837    assert( pNode->nAlloc>=1 );
159838    pNode->n = 1;
159839  }
159840}
159841
159842/*
159843** The first two arguments are a pointer to and the size of a segment b-tree
159844** node. The node may be a leaf or an internal node.
159845**
159846** This function creates a new node image in blob object *pNew by copying
159847** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
159848** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
159849*/
159850static int fts3TruncateNode(
159851  const char *aNode,              /* Current node image */
159852  int nNode,                      /* Size of aNode in bytes */
159853  Blob *pNew,                     /* OUT: Write new node image here */
159854  const char *zTerm,              /* Omit all terms smaller than this */
159855  int nTerm,                      /* Size of zTerm in bytes */
159856  sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
159857){
159858  NodeReader reader;              /* Reader object */
159859  Blob prev = {0, 0, 0};          /* Previous term written to new node */
159860  int rc = SQLITE_OK;             /* Return code */
159861  int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
159862
159863  /* Allocate required output space */
159864  blobGrowBuffer(pNew, nNode, &rc);
159865  if( rc!=SQLITE_OK ) return rc;
159866  pNew->n = 0;
159867
159868  /* Populate new node buffer */
159869  for(rc = nodeReaderInit(&reader, aNode, nNode);
159870      rc==SQLITE_OK && reader.aNode;
159871      rc = nodeReaderNext(&reader)
159872  ){
159873    if( pNew->n==0 ){
159874      int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
159875      if( res<0 || (bLeaf==0 && res==0) ) continue;
159876      fts3StartNode(pNew, (int)aNode[0], reader.iChild);
159877      *piBlock = reader.iChild;
159878    }
159879    rc = fts3AppendToNode(
159880        pNew, &prev, reader.term.a, reader.term.n,
159881        reader.aDoclist, reader.nDoclist
159882    );
159883    if( rc!=SQLITE_OK ) break;
159884  }
159885  if( pNew->n==0 ){
159886    fts3StartNode(pNew, (int)aNode[0], reader.iChild);
159887    *piBlock = reader.iChild;
159888  }
159889  assert( pNew->n<=pNew->nAlloc );
159890
159891  nodeReaderRelease(&reader);
159892  sqlite3_free(prev.a);
159893  return rc;
159894}
159895
159896/*
159897** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
159898** level iAbsLevel. This may involve deleting entries from the %_segments
159899** table, and modifying existing entries in both the %_segments and %_segdir
159900** tables.
159901**
159902** SQLITE_OK is returned if the segment is updated successfully. Or an
159903** SQLite error code otherwise.
159904*/
159905static int fts3TruncateSegment(
159906  Fts3Table *p,                   /* FTS3 table handle */
159907  sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
159908  int iIdx,                       /* Index within level of segment to modify */
159909  const char *zTerm,              /* Remove terms smaller than this */
159910  int nTerm                      /* Number of bytes in buffer zTerm */
159911){
159912  int rc = SQLITE_OK;             /* Return code */
159913  Blob root = {0,0,0};            /* New root page image */
159914  Blob block = {0,0,0};           /* Buffer used for any other block */
159915  sqlite3_int64 iBlock = 0;       /* Block id */
159916  sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
159917  sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
159918  sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
159919
159920  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
159921  if( rc==SQLITE_OK ){
159922    int rc2;                      /* sqlite3_reset() return code */
159923    sqlite3_bind_int64(pFetch, 1, iAbsLevel);
159924    sqlite3_bind_int(pFetch, 2, iIdx);
159925    if( SQLITE_ROW==sqlite3_step(pFetch) ){
159926      const char *aRoot = sqlite3_column_blob(pFetch, 4);
159927      int nRoot = sqlite3_column_bytes(pFetch, 4);
159928      iOldStart = sqlite3_column_int64(pFetch, 1);
159929      rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
159930    }
159931    rc2 = sqlite3_reset(pFetch);
159932    if( rc==SQLITE_OK ) rc = rc2;
159933  }
159934
159935  while( rc==SQLITE_OK && iBlock ){
159936    char *aBlock = 0;
159937    int nBlock = 0;
159938    iNewStart = iBlock;
159939
159940    rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
159941    if( rc==SQLITE_OK ){
159942      rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
159943    }
159944    if( rc==SQLITE_OK ){
159945      rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
159946    }
159947    sqlite3_free(aBlock);
159948  }
159949
159950  /* Variable iNewStart now contains the first valid leaf node. */
159951  if( rc==SQLITE_OK && iNewStart ){
159952    sqlite3_stmt *pDel = 0;
159953    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
159954    if( rc==SQLITE_OK ){
159955      sqlite3_bind_int64(pDel, 1, iOldStart);
159956      sqlite3_bind_int64(pDel, 2, iNewStart-1);
159957      sqlite3_step(pDel);
159958      rc = sqlite3_reset(pDel);
159959    }
159960  }
159961
159962  if( rc==SQLITE_OK ){
159963    sqlite3_stmt *pChomp = 0;
159964    rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
159965    if( rc==SQLITE_OK ){
159966      sqlite3_bind_int64(pChomp, 1, iNewStart);
159967      sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
159968      sqlite3_bind_int64(pChomp, 3, iAbsLevel);
159969      sqlite3_bind_int(pChomp, 4, iIdx);
159970      sqlite3_step(pChomp);
159971      rc = sqlite3_reset(pChomp);
159972    }
159973  }
159974
159975  sqlite3_free(root.a);
159976  sqlite3_free(block.a);
159977  return rc;
159978}
159979
159980/*
159981** This function is called after an incrmental-merge operation has run to
159982** merge (or partially merge) two or more segments from absolute level
159983** iAbsLevel.
159984**
159985** Each input segment is either removed from the db completely (if all of
159986** its data was copied to the output segment by the incrmerge operation)
159987** or modified in place so that it no longer contains those entries that
159988** have been duplicated in the output segment.
159989*/
159990static int fts3IncrmergeChomp(
159991  Fts3Table *p,                   /* FTS table handle */
159992  sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
159993  Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
159994  int *pnRem                      /* Number of segments not deleted */
159995){
159996  int i;
159997  int nRem = 0;
159998  int rc = SQLITE_OK;
159999
160000  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
160001    Fts3SegReader *pSeg = 0;
160002    int j;
160003
160004    /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
160005    ** somewhere in the pCsr->apSegment[] array.  */
160006    for(j=0; ALWAYS(j<pCsr->nSegment); j++){
160007      pSeg = pCsr->apSegment[j];
160008      if( pSeg->iIdx==i ) break;
160009    }
160010    assert( j<pCsr->nSegment && pSeg->iIdx==i );
160011
160012    if( pSeg->aNode==0 ){
160013      /* Seg-reader is at EOF. Remove the entire input segment. */
160014      rc = fts3DeleteSegment(p, pSeg);
160015      if( rc==SQLITE_OK ){
160016        rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
160017      }
160018      *pnRem = 0;
160019    }else{
160020      /* The incremental merge did not copy all the data from this
160021      ** segment to the upper level. The segment is modified in place
160022      ** so that it contains no keys smaller than zTerm/nTerm. */
160023      const char *zTerm = pSeg->zTerm;
160024      int nTerm = pSeg->nTerm;
160025      rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
160026      nRem++;
160027    }
160028  }
160029
160030  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
160031    rc = fts3RepackSegdirLevel(p, iAbsLevel);
160032  }
160033
160034  *pnRem = nRem;
160035  return rc;
160036}
160037
160038/*
160039** Store an incr-merge hint in the database.
160040*/
160041static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
160042  sqlite3_stmt *pReplace = 0;
160043  int rc;                         /* Return code */
160044
160045  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
160046  if( rc==SQLITE_OK ){
160047    sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
160048    sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
160049    sqlite3_step(pReplace);
160050    rc = sqlite3_reset(pReplace);
160051  }
160052
160053  return rc;
160054}
160055
160056/*
160057** Load an incr-merge hint from the database. The incr-merge hint, if one
160058** exists, is stored in the rowid==1 row of the %_stat table.
160059**
160060** If successful, populate blob *pHint with the value read from the %_stat
160061** table and return SQLITE_OK. Otherwise, if an error occurs, return an
160062** SQLite error code.
160063*/
160064static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
160065  sqlite3_stmt *pSelect = 0;
160066  int rc;
160067
160068  pHint->n = 0;
160069  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
160070  if( rc==SQLITE_OK ){
160071    int rc2;
160072    sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
160073    if( SQLITE_ROW==sqlite3_step(pSelect) ){
160074      const char *aHint = sqlite3_column_blob(pSelect, 0);
160075      int nHint = sqlite3_column_bytes(pSelect, 0);
160076      if( aHint ){
160077        blobGrowBuffer(pHint, nHint, &rc);
160078        if( rc==SQLITE_OK ){
160079          memcpy(pHint->a, aHint, nHint);
160080          pHint->n = nHint;
160081        }
160082      }
160083    }
160084    rc2 = sqlite3_reset(pSelect);
160085    if( rc==SQLITE_OK ) rc = rc2;
160086  }
160087
160088  return rc;
160089}
160090
160091/*
160092** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
160093** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
160094** consists of two varints, the absolute level number of the input segments
160095** and the number of input segments.
160096**
160097** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
160098** set *pRc to an SQLite error code before returning.
160099*/
160100static void fts3IncrmergeHintPush(
160101  Blob *pHint,                    /* Hint blob to append to */
160102  i64 iAbsLevel,                  /* First varint to store in hint */
160103  int nInput,                     /* Second varint to store in hint */
160104  int *pRc                        /* IN/OUT: Error code */
160105){
160106  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
160107  if( *pRc==SQLITE_OK ){
160108    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
160109    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
160110  }
160111}
160112
160113/*
160114** Read the last entry (most recently pushed) from the hint blob *pHint
160115** and then remove the entry. Write the two values read to *piAbsLevel and
160116** *pnInput before returning.
160117**
160118** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
160119** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
160120*/
160121static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
160122  const int nHint = pHint->n;
160123  int i;
160124
160125  i = pHint->n-2;
160126  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
160127  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
160128
160129  pHint->n = i;
160130  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
160131  i += fts3GetVarint32(&pHint->a[i], pnInput);
160132  if( i!=nHint ) return FTS_CORRUPT_VTAB;
160133
160134  return SQLITE_OK;
160135}
160136
160137
160138/*
160139** Attempt an incremental merge that writes nMerge leaf blocks.
160140**
160141** Incremental merges happen nMin segments at a time. The segments
160142** to be merged are the nMin oldest segments (the ones with the smallest
160143** values for the _segdir.idx field) in the highest level that contains
160144** at least nMin segments. Multiple merges might occur in an attempt to
160145** write the quota of nMerge leaf blocks.
160146*/
160147SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
160148  int rc;                         /* Return code */
160149  int nRem = nMerge;              /* Number of leaf pages yet to  be written */
160150  Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
160151  Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
160152  IncrmergeWriter *pWriter;       /* Writer object */
160153  int nSeg = 0;                   /* Number of input segments */
160154  sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
160155  Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
160156  int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
160157
160158  /* Allocate space for the cursor, filter and writer objects */
160159  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
160160  pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
160161  if( !pWriter ) return SQLITE_NOMEM;
160162  pFilter = (Fts3SegFilter *)&pWriter[1];
160163  pCsr = (Fts3MultiSegReader *)&pFilter[1];
160164
160165  rc = fts3IncrmergeHintLoad(p, &hint);
160166  while( rc==SQLITE_OK && nRem>0 ){
160167    const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
160168    sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
160169    int bUseHint = 0;             /* True if attempting to append */
160170    int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
160171
160172    /* Search the %_segdir table for the absolute level with the smallest
160173    ** relative level number that contains at least nMin segments, if any.
160174    ** If one is found, set iAbsLevel to the absolute level number and
160175    ** nSeg to nMin. If no level with at least nMin segments can be found,
160176    ** set nSeg to -1.
160177    */
160178    rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
160179    sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
160180    if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
160181      iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
160182      nSeg = sqlite3_column_int(pFindLevel, 1);
160183      assert( nSeg>=2 );
160184    }else{
160185      nSeg = -1;
160186    }
160187    rc = sqlite3_reset(pFindLevel);
160188
160189    /* If the hint read from the %_stat table is not empty, check if the
160190    ** last entry in it specifies a relative level smaller than or equal
160191    ** to the level identified by the block above (if any). If so, this
160192    ** iteration of the loop will work on merging at the hinted level.
160193    */
160194    if( rc==SQLITE_OK && hint.n ){
160195      int nHint = hint.n;
160196      sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
160197      int nHintSeg = 0;                     /* Hint number of segments */
160198
160199      rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
160200      if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
160201        iAbsLevel = iHintAbsLevel;
160202        nSeg = nHintSeg;
160203        bUseHint = 1;
160204        bDirtyHint = 1;
160205      }else{
160206        /* This undoes the effect of the HintPop() above - so that no entry
160207        ** is removed from the hint blob.  */
160208        hint.n = nHint;
160209      }
160210    }
160211
160212    /* If nSeg is less that zero, then there is no level with at least
160213    ** nMin segments and no hint in the %_stat table. No work to do.
160214    ** Exit early in this case.  */
160215    if( nSeg<0 ) break;
160216
160217    /* Open a cursor to iterate through the contents of the oldest nSeg
160218    ** indexes of absolute level iAbsLevel. If this cursor is opened using
160219    ** the 'hint' parameters, it is possible that there are less than nSeg
160220    ** segments available in level iAbsLevel. In this case, no work is
160221    ** done on iAbsLevel - fall through to the next iteration of the loop
160222    ** to start work on some other level.  */
160223    memset(pWriter, 0, nAlloc);
160224    pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
160225
160226    if( rc==SQLITE_OK ){
160227      rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
160228      assert( bUseHint==1 || bUseHint==0 );
160229      if( iIdx==0 || (bUseHint && iIdx==1) ){
160230        int bIgnore = 0;
160231        rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
160232        if( bIgnore ){
160233          pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
160234        }
160235      }
160236    }
160237
160238    if( rc==SQLITE_OK ){
160239      rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
160240    }
160241    if( SQLITE_OK==rc && pCsr->nSegment==nSeg
160242     && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
160243     && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
160244    ){
160245      if( bUseHint && iIdx>0 ){
160246        const char *zKey = pCsr->zTerm;
160247        int nKey = pCsr->nTerm;
160248        rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
160249      }else{
160250        rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
160251      }
160252
160253      if( rc==SQLITE_OK && pWriter->nLeafEst ){
160254        fts3LogMerge(nSeg, iAbsLevel);
160255        do {
160256          rc = fts3IncrmergeAppend(p, pWriter, pCsr);
160257          if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
160258          if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
160259        }while( rc==SQLITE_ROW );
160260
160261        /* Update or delete the input segments */
160262        if( rc==SQLITE_OK ){
160263          nRem -= (1 + pWriter->nWork);
160264          rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
160265          if( nSeg!=0 ){
160266            bDirtyHint = 1;
160267            fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
160268          }
160269        }
160270      }
160271
160272      if( nSeg!=0 ){
160273        pWriter->nLeafData = pWriter->nLeafData * -1;
160274      }
160275      fts3IncrmergeRelease(p, pWriter, &rc);
160276      if( nSeg==0 && pWriter->bNoLeafData==0 ){
160277        fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
160278      }
160279    }
160280
160281    sqlite3Fts3SegReaderFinish(pCsr);
160282  }
160283
160284  /* Write the hint values into the %_stat table for the next incr-merger */
160285  if( bDirtyHint && rc==SQLITE_OK ){
160286    rc = fts3IncrmergeHintStore(p, &hint);
160287  }
160288
160289  sqlite3_free(pWriter);
160290  sqlite3_free(hint.a);
160291  return rc;
160292}
160293
160294/*
160295** Convert the text beginning at *pz into an integer and return
160296** its value.  Advance *pz to point to the first character past
160297** the integer.
160298**
160299** This function used for parameters to merge= and incrmerge=
160300** commands.
160301*/
160302static int fts3Getint(const char **pz){
160303  const char *z = *pz;
160304  int i = 0;
160305  while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
160306  *pz = z;
160307  return i;
160308}
160309
160310/*
160311** Process statements of the form:
160312**
160313**    INSERT INTO table(table) VALUES('merge=A,B');
160314**
160315** A and B are integers that decode to be the number of leaf pages
160316** written for the merge, and the minimum number of segments on a level
160317** before it will be selected for a merge, respectively.
160318*/
160319static int fts3DoIncrmerge(
160320  Fts3Table *p,                   /* FTS3 table handle */
160321  const char *zParam              /* Nul-terminated string containing "A,B" */
160322){
160323  int rc;
160324  int nMin = (FTS3_MERGE_COUNT / 2);
160325  int nMerge = 0;
160326  const char *z = zParam;
160327
160328  /* Read the first integer value */
160329  nMerge = fts3Getint(&z);
160330
160331  /* If the first integer value is followed by a ',',  read the second
160332  ** integer value. */
160333  if( z[0]==',' && z[1]!='\0' ){
160334    z++;
160335    nMin = fts3Getint(&z);
160336  }
160337
160338  if( z[0]!='\0' || nMin<2 ){
160339    rc = SQLITE_ERROR;
160340  }else{
160341    rc = SQLITE_OK;
160342    if( !p->bHasStat ){
160343      assert( p->bFts4==0 );
160344      sqlite3Fts3CreateStatTable(&rc, p);
160345    }
160346    if( rc==SQLITE_OK ){
160347      rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
160348    }
160349    sqlite3Fts3SegmentsClose(p);
160350  }
160351  return rc;
160352}
160353
160354/*
160355** Process statements of the form:
160356**
160357**    INSERT INTO table(table) VALUES('automerge=X');
160358**
160359** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
160360** turn it on.  The setting is persistent.
160361*/
160362static int fts3DoAutoincrmerge(
160363  Fts3Table *p,                   /* FTS3 table handle */
160364  const char *zParam              /* Nul-terminated string containing boolean */
160365){
160366  int rc = SQLITE_OK;
160367  sqlite3_stmt *pStmt = 0;
160368  p->nAutoincrmerge = fts3Getint(&zParam);
160369  if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
160370    p->nAutoincrmerge = 8;
160371  }
160372  if( !p->bHasStat ){
160373    assert( p->bFts4==0 );
160374    sqlite3Fts3CreateStatTable(&rc, p);
160375    if( rc ) return rc;
160376  }
160377  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
160378  if( rc ) return rc;
160379  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
160380  sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
160381  sqlite3_step(pStmt);
160382  rc = sqlite3_reset(pStmt);
160383  return rc;
160384}
160385
160386/*
160387** Return a 64-bit checksum for the FTS index entry specified by the
160388** arguments to this function.
160389*/
160390static u64 fts3ChecksumEntry(
160391  const char *zTerm,              /* Pointer to buffer containing term */
160392  int nTerm,                      /* Size of zTerm in bytes */
160393  int iLangid,                    /* Language id for current row */
160394  int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
160395  i64 iDocid,                     /* Docid for current row. */
160396  int iCol,                       /* Column number */
160397  int iPos                        /* Position */
160398){
160399  int i;
160400  u64 ret = (u64)iDocid;
160401
160402  ret += (ret<<3) + iLangid;
160403  ret += (ret<<3) + iIndex;
160404  ret += (ret<<3) + iCol;
160405  ret += (ret<<3) + iPos;
160406  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
160407
160408  return ret;
160409}
160410
160411/*
160412** Return a checksum of all entries in the FTS index that correspond to
160413** language id iLangid. The checksum is calculated by XORing the checksums
160414** of each individual entry (see fts3ChecksumEntry()) together.
160415**
160416** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
160417** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
160418** return value is undefined in this case.
160419*/
160420static u64 fts3ChecksumIndex(
160421  Fts3Table *p,                   /* FTS3 table handle */
160422  int iLangid,                    /* Language id to return cksum for */
160423  int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
160424  int *pRc                        /* OUT: Return code */
160425){
160426  Fts3SegFilter filter;
160427  Fts3MultiSegReader csr;
160428  int rc;
160429  u64 cksum = 0;
160430
160431  assert( *pRc==SQLITE_OK );
160432
160433  memset(&filter, 0, sizeof(filter));
160434  memset(&csr, 0, sizeof(csr));
160435  filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
160436  filter.flags |= FTS3_SEGMENT_SCAN;
160437
160438  rc = sqlite3Fts3SegReaderCursor(
160439      p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
160440  );
160441  if( rc==SQLITE_OK ){
160442    rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
160443  }
160444
160445  if( rc==SQLITE_OK ){
160446    while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
160447      char *pCsr = csr.aDoclist;
160448      char *pEnd = &pCsr[csr.nDoclist];
160449
160450      i64 iDocid = 0;
160451      i64 iCol = 0;
160452      i64 iPos = 0;
160453
160454      pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
160455      while( pCsr<pEnd ){
160456        i64 iVal = 0;
160457        pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
160458        if( pCsr<pEnd ){
160459          if( iVal==0 || iVal==1 ){
160460            iCol = 0;
160461            iPos = 0;
160462            if( iVal ){
160463              pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
160464            }else{
160465              pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
160466              iDocid += iVal;
160467            }
160468          }else{
160469            iPos += (iVal - 2);
160470            cksum = cksum ^ fts3ChecksumEntry(
160471                csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
160472                (int)iCol, (int)iPos
160473            );
160474          }
160475        }
160476      }
160477    }
160478  }
160479  sqlite3Fts3SegReaderFinish(&csr);
160480
160481  *pRc = rc;
160482  return cksum;
160483}
160484
160485/*
160486** Check if the contents of the FTS index match the current contents of the
160487** content table. If no error occurs and the contents do match, set *pbOk
160488** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
160489** to false before returning.
160490**
160491** If an error occurs (e.g. an OOM or IO error), return an SQLite error
160492** code. The final value of *pbOk is undefined in this case.
160493*/
160494static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
160495  int rc = SQLITE_OK;             /* Return code */
160496  u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
160497  u64 cksum2 = 0;                 /* Checksum based on %_content contents */
160498  sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
160499
160500  /* This block calculates the checksum according to the FTS index. */
160501  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
160502  if( rc==SQLITE_OK ){
160503    int rc2;
160504    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
160505    sqlite3_bind_int(pAllLangid, 2, p->nIndex);
160506    while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
160507      int iLangid = sqlite3_column_int(pAllLangid, 0);
160508      int i;
160509      for(i=0; i<p->nIndex; i++){
160510        cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
160511      }
160512    }
160513    rc2 = sqlite3_reset(pAllLangid);
160514    if( rc==SQLITE_OK ) rc = rc2;
160515  }
160516
160517  /* This block calculates the checksum according to the %_content table */
160518  if( rc==SQLITE_OK ){
160519    sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
160520    sqlite3_stmt *pStmt = 0;
160521    char *zSql;
160522
160523    zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
160524    if( !zSql ){
160525      rc = SQLITE_NOMEM;
160526    }else{
160527      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
160528      sqlite3_free(zSql);
160529    }
160530
160531    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
160532      i64 iDocid = sqlite3_column_int64(pStmt, 0);
160533      int iLang = langidFromSelect(p, pStmt);
160534      int iCol;
160535
160536      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
160537        if( p->abNotindexed[iCol]==0 ){
160538          const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
160539          int nText = sqlite3_column_bytes(pStmt, iCol+1);
160540          sqlite3_tokenizer_cursor *pT = 0;
160541
160542          rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
160543          while( rc==SQLITE_OK ){
160544            char const *zToken;       /* Buffer containing token */
160545            int nToken = 0;           /* Number of bytes in token */
160546            int iDum1 = 0, iDum2 = 0; /* Dummy variables */
160547            int iPos = 0;             /* Position of token in zText */
160548
160549            rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
160550            if( rc==SQLITE_OK ){
160551              int i;
160552              cksum2 = cksum2 ^ fts3ChecksumEntry(
160553                  zToken, nToken, iLang, 0, iDocid, iCol, iPos
160554              );
160555              for(i=1; i<p->nIndex; i++){
160556                if( p->aIndex[i].nPrefix<=nToken ){
160557                  cksum2 = cksum2 ^ fts3ChecksumEntry(
160558                      zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
160559                  );
160560                }
160561              }
160562            }
160563          }
160564          if( pT ) pModule->xClose(pT);
160565          if( rc==SQLITE_DONE ) rc = SQLITE_OK;
160566        }
160567      }
160568    }
160569
160570    sqlite3_finalize(pStmt);
160571  }
160572
160573  *pbOk = (cksum1==cksum2);
160574  return rc;
160575}
160576
160577/*
160578** Run the integrity-check. If no error occurs and the current contents of
160579** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
160580** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
160581**
160582** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
160583** error code.
160584**
160585** The integrity-check works as follows. For each token and indexed token
160586** prefix in the document set, a 64-bit checksum is calculated (by code
160587** in fts3ChecksumEntry()) based on the following:
160588**
160589**     + The index number (0 for the main index, 1 for the first prefix
160590**       index etc.),
160591**     + The token (or token prefix) text itself,
160592**     + The language-id of the row it appears in,
160593**     + The docid of the row it appears in,
160594**     + The column it appears in, and
160595**     + The tokens position within that column.
160596**
160597** The checksums for all entries in the index are XORed together to create
160598** a single checksum for the entire index.
160599**
160600** The integrity-check code calculates the same checksum in two ways:
160601**
160602**     1. By scanning the contents of the FTS index, and
160603**     2. By scanning and tokenizing the content table.
160604**
160605** If the two checksums are identical, the integrity-check is deemed to have
160606** passed.
160607*/
160608static int fts3DoIntegrityCheck(
160609  Fts3Table *p                    /* FTS3 table handle */
160610){
160611  int rc;
160612  int bOk = 0;
160613  rc = fts3IntegrityCheck(p, &bOk);
160614  if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
160615  return rc;
160616}
160617
160618/*
160619** Handle a 'special' INSERT of the form:
160620**
160621**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
160622**
160623** Argument pVal contains the result of <expr>. Currently the only
160624** meaningful value to insert is the text 'optimize'.
160625*/
160626static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
160627  int rc;                         /* Return Code */
160628  const char *zVal = (const char *)sqlite3_value_text(pVal);
160629  int nVal = sqlite3_value_bytes(pVal);
160630
160631  if( !zVal ){
160632    return SQLITE_NOMEM;
160633  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
160634    rc = fts3DoOptimize(p, 0);
160635  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
160636    rc = fts3DoRebuild(p);
160637  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
160638    rc = fts3DoIntegrityCheck(p);
160639  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
160640    rc = fts3DoIncrmerge(p, &zVal[6]);
160641  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
160642    rc = fts3DoAutoincrmerge(p, &zVal[10]);
160643#ifdef SQLITE_TEST
160644  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
160645    p->nNodeSize = atoi(&zVal[9]);
160646    rc = SQLITE_OK;
160647  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
160648    p->nMaxPendingData = atoi(&zVal[11]);
160649    rc = SQLITE_OK;
160650  }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
160651    p->bNoIncrDoclist = atoi(&zVal[21]);
160652    rc = SQLITE_OK;
160653#endif
160654  }else{
160655    rc = SQLITE_ERROR;
160656  }
160657
160658  return rc;
160659}
160660
160661#ifndef SQLITE_DISABLE_FTS4_DEFERRED
160662/*
160663** Delete all cached deferred doclists. Deferred doclists are cached
160664** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
160665*/
160666SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
160667  Fts3DeferredToken *pDef;
160668  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
160669    fts3PendingListDelete(pDef->pList);
160670    pDef->pList = 0;
160671  }
160672}
160673
160674/*
160675** Free all entries in the pCsr->pDeffered list. Entries are added to
160676** this list using sqlite3Fts3DeferToken().
160677*/
160678SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
160679  Fts3DeferredToken *pDef;
160680  Fts3DeferredToken *pNext;
160681  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
160682    pNext = pDef->pNext;
160683    fts3PendingListDelete(pDef->pList);
160684    sqlite3_free(pDef);
160685  }
160686  pCsr->pDeferred = 0;
160687}
160688
160689/*
160690** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
160691** based on the row that pCsr currently points to.
160692**
160693** A deferred-doclist is like any other doclist with position information
160694** included, except that it only contains entries for a single row of the
160695** table, not for all rows.
160696*/
160697SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
160698  int rc = SQLITE_OK;             /* Return code */
160699  if( pCsr->pDeferred ){
160700    int i;                        /* Used to iterate through table columns */
160701    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
160702    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
160703
160704    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
160705    sqlite3_tokenizer *pT = p->pTokenizer;
160706    sqlite3_tokenizer_module const *pModule = pT->pModule;
160707
160708    assert( pCsr->isRequireSeek==0 );
160709    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
160710
160711    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
160712      if( p->abNotindexed[i]==0 ){
160713        const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
160714        sqlite3_tokenizer_cursor *pTC = 0;
160715
160716        rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
160717        while( rc==SQLITE_OK ){
160718          char const *zToken;       /* Buffer containing token */
160719          int nToken = 0;           /* Number of bytes in token */
160720          int iDum1 = 0, iDum2 = 0; /* Dummy variables */
160721          int iPos = 0;             /* Position of token in zText */
160722
160723          rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
160724          for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
160725            Fts3PhraseToken *pPT = pDef->pToken;
160726            if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
160727                && (pPT->bFirst==0 || iPos==0)
160728                && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
160729                && (0==memcmp(zToken, pPT->z, pPT->n))
160730              ){
160731              fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
160732            }
160733          }
160734        }
160735        if( pTC ) pModule->xClose(pTC);
160736        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
160737      }
160738    }
160739
160740    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
160741      if( pDef->pList ){
160742        rc = fts3PendingListAppendVarint(&pDef->pList, 0);
160743      }
160744    }
160745  }
160746
160747  return rc;
160748}
160749
160750SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
160751  Fts3DeferredToken *p,
160752  char **ppData,
160753  int *pnData
160754){
160755  char *pRet;
160756  int nSkip;
160757  sqlite3_int64 dummy;
160758
160759  *ppData = 0;
160760  *pnData = 0;
160761
160762  if( p->pList==0 ){
160763    return SQLITE_OK;
160764  }
160765
160766  pRet = (char *)sqlite3_malloc(p->pList->nData);
160767  if( !pRet ) return SQLITE_NOMEM;
160768
160769  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
160770  *pnData = p->pList->nData - nSkip;
160771  *ppData = pRet;
160772
160773  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
160774  return SQLITE_OK;
160775}
160776
160777/*
160778** Add an entry for token pToken to the pCsr->pDeferred list.
160779*/
160780SQLITE_PRIVATE int sqlite3Fts3DeferToken(
160781  Fts3Cursor *pCsr,               /* Fts3 table cursor */
160782  Fts3PhraseToken *pToken,        /* Token to defer */
160783  int iCol                        /* Column that token must appear in (or -1) */
160784){
160785  Fts3DeferredToken *pDeferred;
160786  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
160787  if( !pDeferred ){
160788    return SQLITE_NOMEM;
160789  }
160790  memset(pDeferred, 0, sizeof(*pDeferred));
160791  pDeferred->pToken = pToken;
160792  pDeferred->pNext = pCsr->pDeferred;
160793  pDeferred->iCol = iCol;
160794  pCsr->pDeferred = pDeferred;
160795
160796  assert( pToken->pDeferred==0 );
160797  pToken->pDeferred = pDeferred;
160798
160799  return SQLITE_OK;
160800}
160801#endif
160802
160803/*
160804** SQLite value pRowid contains the rowid of a row that may or may not be
160805** present in the FTS3 table. If it is, delete it and adjust the contents
160806** of subsiduary data structures accordingly.
160807*/
160808static int fts3DeleteByRowid(
160809  Fts3Table *p,
160810  sqlite3_value *pRowid,
160811  int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
160812  u32 *aSzDel
160813){
160814  int rc = SQLITE_OK;             /* Return code */
160815  int bFound = 0;                 /* True if *pRowid really is in the table */
160816
160817  fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
160818  if( bFound && rc==SQLITE_OK ){
160819    int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
160820    rc = fts3IsEmpty(p, pRowid, &isEmpty);
160821    if( rc==SQLITE_OK ){
160822      if( isEmpty ){
160823        /* Deleting this row means the whole table is empty. In this case
160824        ** delete the contents of all three tables and throw away any
160825        ** data in the pendingTerms hash table.  */
160826        rc = fts3DeleteAll(p, 1);
160827        *pnChng = 0;
160828        memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
160829      }else{
160830        *pnChng = *pnChng - 1;
160831        if( p->zContentTbl==0 ){
160832          fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
160833        }
160834        if( p->bHasDocsize ){
160835          fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
160836        }
160837      }
160838    }
160839  }
160840
160841  return rc;
160842}
160843
160844/*
160845** This function does the work for the xUpdate method of FTS3 virtual
160846** tables. The schema of the virtual table being:
160847**
160848**     CREATE TABLE <table name>(
160849**       <user columns>,
160850**       <table name> HIDDEN,
160851**       docid HIDDEN,
160852**       <langid> HIDDEN
160853**     );
160854**
160855**
160856*/
160857SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
160858  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
160859  int nArg,                       /* Size of argument array */
160860  sqlite3_value **apVal,          /* Array of arguments */
160861  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
160862){
160863  Fts3Table *p = (Fts3Table *)pVtab;
160864  int rc = SQLITE_OK;             /* Return Code */
160865  int isRemove = 0;               /* True for an UPDATE or DELETE */
160866  u32 *aSzIns = 0;                /* Sizes of inserted documents */
160867  u32 *aSzDel = 0;                /* Sizes of deleted documents */
160868  int nChng = 0;                  /* Net change in number of documents */
160869  int bInsertDone = 0;
160870
160871  /* At this point it must be known if the %_stat table exists or not.
160872  ** So bHasStat may not be 2.  */
160873  assert( p->bHasStat==0 || p->bHasStat==1 );
160874
160875  assert( p->pSegments==0 );
160876  assert(
160877      nArg==1                     /* DELETE operations */
160878   || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
160879  );
160880
160881  /* Check for a "special" INSERT operation. One of the form:
160882  **
160883  **   INSERT INTO xyz(xyz) VALUES('command');
160884  */
160885  if( nArg>1
160886   && sqlite3_value_type(apVal[0])==SQLITE_NULL
160887   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
160888  ){
160889    rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
160890    goto update_out;
160891  }
160892
160893  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
160894    rc = SQLITE_CONSTRAINT;
160895    goto update_out;
160896  }
160897
160898  /* Allocate space to hold the change in document sizes */
160899  aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
160900  if( aSzDel==0 ){
160901    rc = SQLITE_NOMEM;
160902    goto update_out;
160903  }
160904  aSzIns = &aSzDel[p->nColumn+1];
160905  memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
160906
160907  rc = fts3Writelock(p);
160908  if( rc!=SQLITE_OK ) goto update_out;
160909
160910  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
160911  ** value, then this operation requires constraint handling.
160912  **
160913  ** If the on-conflict mode is REPLACE, this means that the existing row
160914  ** should be deleted from the database before inserting the new row. Or,
160915  ** if the on-conflict mode is other than REPLACE, then this method must
160916  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
160917  ** modify the database file.
160918  */
160919  if( nArg>1 && p->zContentTbl==0 ){
160920    /* Find the value object that holds the new rowid value. */
160921    sqlite3_value *pNewRowid = apVal[3+p->nColumn];
160922    if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
160923      pNewRowid = apVal[1];
160924    }
160925
160926    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
160927        sqlite3_value_type(apVal[0])==SQLITE_NULL
160928     || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
160929    )){
160930      /* The new rowid is not NULL (in this case the rowid will be
160931      ** automatically assigned and there is no chance of a conflict), and
160932      ** the statement is either an INSERT or an UPDATE that modifies the
160933      ** rowid column. So if the conflict mode is REPLACE, then delete any
160934      ** existing row with rowid=pNewRowid.
160935      **
160936      ** Or, if the conflict mode is not REPLACE, insert the new record into
160937      ** the %_content table. If we hit the duplicate rowid constraint (or any
160938      ** other error) while doing so, return immediately.
160939      **
160940      ** This branch may also run if pNewRowid contains a value that cannot
160941      ** be losslessly converted to an integer. In this case, the eventual
160942      ** call to fts3InsertData() (either just below or further on in this
160943      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
160944      ** invoked, it will delete zero rows (since no row will have
160945      ** docid=$pNewRowid if $pNewRowid is not an integer value).
160946      */
160947      if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
160948        rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
160949      }else{
160950        rc = fts3InsertData(p, apVal, pRowid);
160951        bInsertDone = 1;
160952      }
160953    }
160954  }
160955  if( rc!=SQLITE_OK ){
160956    goto update_out;
160957  }
160958
160959  /* If this is a DELETE or UPDATE operation, remove the old record. */
160960  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
160961    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
160962    rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
160963    isRemove = 1;
160964  }
160965
160966  /* If this is an INSERT or UPDATE operation, insert the new record. */
160967  if( nArg>1 && rc==SQLITE_OK ){
160968    int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
160969    if( bInsertDone==0 ){
160970      rc = fts3InsertData(p, apVal, pRowid);
160971      if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
160972        rc = FTS_CORRUPT_VTAB;
160973      }
160974    }
160975    if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
160976      rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
160977    }
160978    if( rc==SQLITE_OK ){
160979      assert( p->iPrevDocid==*pRowid );
160980      rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
160981    }
160982    if( p->bHasDocsize ){
160983      fts3InsertDocsize(&rc, p, aSzIns);
160984    }
160985    nChng++;
160986  }
160987
160988  if( p->bFts4 ){
160989    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
160990  }
160991
160992 update_out:
160993  sqlite3_free(aSzDel);
160994  sqlite3Fts3SegmentsClose(p);
160995  return rc;
160996}
160997
160998/*
160999** Flush any data in the pending-terms hash table to disk. If successful,
161000** merge all segments in the database (including the new segment, if
161001** there was any data to flush) into a single segment.
161002*/
161003SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
161004  int rc;
161005  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
161006  if( rc==SQLITE_OK ){
161007    rc = fts3DoOptimize(p, 1);
161008    if( rc==SQLITE_OK || rc==SQLITE_DONE ){
161009      int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
161010      if( rc2!=SQLITE_OK ) rc = rc2;
161011    }else{
161012      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
161013      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
161014    }
161015  }
161016  sqlite3Fts3SegmentsClose(p);
161017  return rc;
161018}
161019
161020#endif
161021
161022/************** End of fts3_write.c ******************************************/
161023/************** Begin file fts3_snippet.c ************************************/
161024/*
161025** 2009 Oct 23
161026**
161027** The author disclaims copyright to this source code.  In place of
161028** a legal notice, here is a blessing:
161029**
161030**    May you do good and not evil.
161031**    May you find forgiveness for yourself and forgive others.
161032**    May you share freely, never taking more than you give.
161033**
161034******************************************************************************
161035*/
161036
161037/* #include "fts3Int.h" */
161038#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
161039
161040/* #include <string.h> */
161041/* #include <assert.h> */
161042
161043/*
161044** Characters that may appear in the second argument to matchinfo().
161045*/
161046#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
161047#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
161048#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
161049#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
161050#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
161051#define FTS3_MATCHINFO_LCS       's'        /* nCol values */
161052#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
161053#define FTS3_MATCHINFO_LHITS     'y'        /* nCol*nPhrase values */
161054#define FTS3_MATCHINFO_LHITS_BM  'b'        /* nCol*nPhrase values */
161055
161056/*
161057** The default value for the second argument to matchinfo().
161058*/
161059#define FTS3_MATCHINFO_DEFAULT   "pcx"
161060
161061
161062/*
161063** Used as an fts3ExprIterate() context when loading phrase doclists to
161064** Fts3Expr.aDoclist[]/nDoclist.
161065*/
161066typedef struct LoadDoclistCtx LoadDoclistCtx;
161067struct LoadDoclistCtx {
161068  Fts3Cursor *pCsr;               /* FTS3 Cursor */
161069  int nPhrase;                    /* Number of phrases seen so far */
161070  int nToken;                     /* Number of tokens seen so far */
161071};
161072
161073/*
161074** The following types are used as part of the implementation of the
161075** fts3BestSnippet() routine.
161076*/
161077typedef struct SnippetIter SnippetIter;
161078typedef struct SnippetPhrase SnippetPhrase;
161079typedef struct SnippetFragment SnippetFragment;
161080
161081struct SnippetIter {
161082  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
161083  int iCol;                       /* Extract snippet from this column */
161084  int nSnippet;                   /* Requested snippet length (in tokens) */
161085  int nPhrase;                    /* Number of phrases in query */
161086  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
161087  int iCurrent;                   /* First token of current snippet */
161088};
161089
161090struct SnippetPhrase {
161091  int nToken;                     /* Number of tokens in phrase */
161092  char *pList;                    /* Pointer to start of phrase position list */
161093  int iHead;                      /* Next value in position list */
161094  char *pHead;                    /* Position list data following iHead */
161095  int iTail;                      /* Next value in trailing position list */
161096  char *pTail;                    /* Position list data following iTail */
161097};
161098
161099struct SnippetFragment {
161100  int iCol;                       /* Column snippet is extracted from */
161101  int iPos;                       /* Index of first token in snippet */
161102  u64 covered;                    /* Mask of query phrases covered */
161103  u64 hlmask;                     /* Mask of snippet terms to highlight */
161104};
161105
161106/*
161107** This type is used as an fts3ExprIterate() context object while
161108** accumulating the data returned by the matchinfo() function.
161109*/
161110typedef struct MatchInfo MatchInfo;
161111struct MatchInfo {
161112  Fts3Cursor *pCursor;            /* FTS3 Cursor */
161113  int nCol;                       /* Number of columns in table */
161114  int nPhrase;                    /* Number of matchable phrases in query */
161115  sqlite3_int64 nDoc;             /* Number of docs in database */
161116  char flag;
161117  u32 *aMatchinfo;                /* Pre-allocated buffer */
161118};
161119
161120/*
161121** An instance of this structure is used to manage a pair of buffers, each
161122** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
161123** for details.
161124*/
161125struct MatchinfoBuffer {
161126  u8 aRef[3];
161127  int nElem;
161128  int bGlobal;                    /* Set if global data is loaded */
161129  char *zMatchinfo;
161130  u32 aMatchinfo[1];
161131};
161132
161133
161134/*
161135** The snippet() and offsets() functions both return text values. An instance
161136** of the following structure is used to accumulate those values while the
161137** functions are running. See fts3StringAppend() for details.
161138*/
161139typedef struct StrBuffer StrBuffer;
161140struct StrBuffer {
161141  char *z;                        /* Pointer to buffer containing string */
161142  int n;                          /* Length of z in bytes (excl. nul-term) */
161143  int nAlloc;                     /* Allocated size of buffer z in bytes */
161144};
161145
161146
161147/*************************************************************************
161148** Start of MatchinfoBuffer code.
161149*/
161150
161151/*
161152** Allocate a two-slot MatchinfoBuffer object.
161153*/
161154static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
161155  MatchinfoBuffer *pRet;
161156  int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
161157  int nStr = (int)strlen(zMatchinfo);
161158
161159  pRet = sqlite3_malloc(nByte + nStr+1);
161160  if( pRet ){
161161    memset(pRet, 0, nByte);
161162    pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
161163    pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
161164    pRet->nElem = nElem;
161165    pRet->zMatchinfo = ((char*)pRet) + nByte;
161166    memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
161167    pRet->aRef[0] = 1;
161168  }
161169
161170  return pRet;
161171}
161172
161173static void fts3MIBufferFree(void *p){
161174  MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
161175
161176  assert( (u32*)p==&pBuf->aMatchinfo[1]
161177       || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
161178  );
161179  if( (u32*)p==&pBuf->aMatchinfo[1] ){
161180    pBuf->aRef[1] = 0;
161181  }else{
161182    pBuf->aRef[2] = 0;
161183  }
161184
161185  if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
161186    sqlite3_free(pBuf);
161187  }
161188}
161189
161190static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
161191  void (*xRet)(void*) = 0;
161192  u32 *aOut = 0;
161193
161194  if( p->aRef[1]==0 ){
161195    p->aRef[1] = 1;
161196    aOut = &p->aMatchinfo[1];
161197    xRet = fts3MIBufferFree;
161198  }
161199  else if( p->aRef[2]==0 ){
161200    p->aRef[2] = 1;
161201    aOut = &p->aMatchinfo[p->nElem+2];
161202    xRet = fts3MIBufferFree;
161203  }else{
161204    aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
161205    if( aOut ){
161206      xRet = sqlite3_free;
161207      if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
161208    }
161209  }
161210
161211  *paOut = aOut;
161212  return xRet;
161213}
161214
161215static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
161216  p->bGlobal = 1;
161217  memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
161218}
161219
161220/*
161221** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
161222*/
161223SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
161224  if( p ){
161225    assert( p->aRef[0]==1 );
161226    p->aRef[0] = 0;
161227    if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
161228      sqlite3_free(p);
161229    }
161230  }
161231}
161232
161233/*
161234** End of MatchinfoBuffer code.
161235*************************************************************************/
161236
161237
161238/*
161239** This function is used to help iterate through a position-list. A position
161240** list is a list of unique integers, sorted from smallest to largest. Each
161241** element of the list is represented by an FTS3 varint that takes the value
161242** of the difference between the current element and the previous one plus
161243** two. For example, to store the position-list:
161244**
161245**     4 9 113
161246**
161247** the three varints:
161248**
161249**     6 7 106
161250**
161251** are encoded.
161252**
161253** When this function is called, *pp points to the start of an element of
161254** the list. *piPos contains the value of the previous entry in the list.
161255** After it returns, *piPos contains the value of the next element of the
161256** list and *pp is advanced to the following varint.
161257*/
161258static void fts3GetDeltaPosition(char **pp, int *piPos){
161259  int iVal;
161260  *pp += fts3GetVarint32(*pp, &iVal);
161261  *piPos += (iVal-2);
161262}
161263
161264/*
161265** Helper function for fts3ExprIterate() (see below).
161266*/
161267static int fts3ExprIterate2(
161268  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
161269  int *piPhrase,                  /* Pointer to phrase counter */
161270  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
161271  void *pCtx                      /* Second argument to pass to callback */
161272){
161273  int rc;                         /* Return code */
161274  int eType = pExpr->eType;     /* Type of expression node pExpr */
161275
161276  if( eType!=FTSQUERY_PHRASE ){
161277    assert( pExpr->pLeft && pExpr->pRight );
161278    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
161279    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
161280      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
161281    }
161282  }else{
161283    rc = x(pExpr, *piPhrase, pCtx);
161284    (*piPhrase)++;
161285  }
161286  return rc;
161287}
161288
161289/*
161290** Iterate through all phrase nodes in an FTS3 query, except those that
161291** are part of a sub-tree that is the right-hand-side of a NOT operator.
161292** For each phrase node found, the supplied callback function is invoked.
161293**
161294** If the callback function returns anything other than SQLITE_OK,
161295** the iteration is abandoned and the error code returned immediately.
161296** Otherwise, SQLITE_OK is returned after a callback has been made for
161297** all eligible phrase nodes.
161298*/
161299static int fts3ExprIterate(
161300  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
161301  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
161302  void *pCtx                      /* Second argument to pass to callback */
161303){
161304  int iPhrase = 0;                /* Variable used as the phrase counter */
161305  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
161306}
161307
161308
161309/*
161310** This is an fts3ExprIterate() callback used while loading the doclists
161311** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
161312** fts3ExprLoadDoclists().
161313*/
161314static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
161315  int rc = SQLITE_OK;
161316  Fts3Phrase *pPhrase = pExpr->pPhrase;
161317  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
161318
161319  UNUSED_PARAMETER(iPhrase);
161320
161321  p->nPhrase++;
161322  p->nToken += pPhrase->nToken;
161323
161324  return rc;
161325}
161326
161327/*
161328** Load the doclists for each phrase in the query associated with FTS3 cursor
161329** pCsr.
161330**
161331** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
161332** phrases in the expression (all phrases except those directly or
161333** indirectly descended from the right-hand-side of a NOT operator). If
161334** pnToken is not NULL, then it is set to the number of tokens in all
161335** matchable phrases of the expression.
161336*/
161337static int fts3ExprLoadDoclists(
161338  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
161339  int *pnPhrase,                  /* OUT: Number of phrases in query */
161340  int *pnToken                    /* OUT: Number of tokens in query */
161341){
161342  int rc;                         /* Return Code */
161343  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
161344  sCtx.pCsr = pCsr;
161345  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
161346  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
161347  if( pnToken ) *pnToken = sCtx.nToken;
161348  return rc;
161349}
161350
161351static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
161352  (*(int *)ctx)++;
161353  pExpr->iPhrase = iPhrase;
161354  return SQLITE_OK;
161355}
161356static int fts3ExprPhraseCount(Fts3Expr *pExpr){
161357  int nPhrase = 0;
161358  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
161359  return nPhrase;
161360}
161361
161362/*
161363** Advance the position list iterator specified by the first two
161364** arguments so that it points to the first element with a value greater
161365** than or equal to parameter iNext.
161366*/
161367static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
161368  char *pIter = *ppIter;
161369  if( pIter ){
161370    int iIter = *piIter;
161371
161372    while( iIter<iNext ){
161373      if( 0==(*pIter & 0xFE) ){
161374        iIter = -1;
161375        pIter = 0;
161376        break;
161377      }
161378      fts3GetDeltaPosition(&pIter, &iIter);
161379    }
161380
161381    *piIter = iIter;
161382    *ppIter = pIter;
161383  }
161384}
161385
161386/*
161387** Advance the snippet iterator to the next candidate snippet.
161388*/
161389static int fts3SnippetNextCandidate(SnippetIter *pIter){
161390  int i;                          /* Loop counter */
161391
161392  if( pIter->iCurrent<0 ){
161393    /* The SnippetIter object has just been initialized. The first snippet
161394    ** candidate always starts at offset 0 (even if this candidate has a
161395    ** score of 0.0).
161396    */
161397    pIter->iCurrent = 0;
161398
161399    /* Advance the 'head' iterator of each phrase to the first offset that
161400    ** is greater than or equal to (iNext+nSnippet).
161401    */
161402    for(i=0; i<pIter->nPhrase; i++){
161403      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
161404      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
161405    }
161406  }else{
161407    int iStart;
161408    int iEnd = 0x7FFFFFFF;
161409
161410    for(i=0; i<pIter->nPhrase; i++){
161411      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
161412      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
161413        iEnd = pPhrase->iHead;
161414      }
161415    }
161416    if( iEnd==0x7FFFFFFF ){
161417      return 1;
161418    }
161419
161420    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
161421    for(i=0; i<pIter->nPhrase; i++){
161422      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
161423      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
161424      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
161425    }
161426  }
161427
161428  return 0;
161429}
161430
161431/*
161432** Retrieve information about the current candidate snippet of snippet
161433** iterator pIter.
161434*/
161435static void fts3SnippetDetails(
161436  SnippetIter *pIter,             /* Snippet iterator */
161437  u64 mCovered,                   /* Bitmask of phrases already covered */
161438  int *piToken,                   /* OUT: First token of proposed snippet */
161439  int *piScore,                   /* OUT: "Score" for this snippet */
161440  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
161441  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
161442){
161443  int iStart = pIter->iCurrent;   /* First token of snippet */
161444  int iScore = 0;                 /* Score of this snippet */
161445  int i;                          /* Loop counter */
161446  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
161447  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
161448
161449  for(i=0; i<pIter->nPhrase; i++){
161450    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
161451    if( pPhrase->pTail ){
161452      char *pCsr = pPhrase->pTail;
161453      int iCsr = pPhrase->iTail;
161454
161455      while( iCsr<(iStart+pIter->nSnippet) ){
161456        int j;
161457        u64 mPhrase = (u64)1 << i;
161458        u64 mPos = (u64)1 << (iCsr - iStart);
161459        assert( iCsr>=iStart );
161460        if( (mCover|mCovered)&mPhrase ){
161461          iScore++;
161462        }else{
161463          iScore += 1000;
161464        }
161465        mCover |= mPhrase;
161466
161467        for(j=0; j<pPhrase->nToken; j++){
161468          mHighlight |= (mPos>>j);
161469        }
161470
161471        if( 0==(*pCsr & 0x0FE) ) break;
161472        fts3GetDeltaPosition(&pCsr, &iCsr);
161473      }
161474    }
161475  }
161476
161477  /* Set the output variables before returning. */
161478  *piToken = iStart;
161479  *piScore = iScore;
161480  *pmCover = mCover;
161481  *pmHighlight = mHighlight;
161482}
161483
161484/*
161485** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
161486** Each invocation populates an element of the SnippetIter.aPhrase[] array.
161487*/
161488static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
161489  SnippetIter *p = (SnippetIter *)ctx;
161490  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
161491  char *pCsr;
161492  int rc;
161493
161494  pPhrase->nToken = pExpr->pPhrase->nToken;
161495  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
161496  assert( rc==SQLITE_OK || pCsr==0 );
161497  if( pCsr ){
161498    int iFirst = 0;
161499    pPhrase->pList = pCsr;
161500    fts3GetDeltaPosition(&pCsr, &iFirst);
161501    assert( iFirst>=0 );
161502    pPhrase->pHead = pCsr;
161503    pPhrase->pTail = pCsr;
161504    pPhrase->iHead = iFirst;
161505    pPhrase->iTail = iFirst;
161506  }else{
161507    assert( rc!=SQLITE_OK || (
161508       pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
161509    ));
161510  }
161511
161512  return rc;
161513}
161514
161515/*
161516** Select the fragment of text consisting of nFragment contiguous tokens
161517** from column iCol that represent the "best" snippet. The best snippet
161518** is the snippet with the highest score, where scores are calculated
161519** by adding:
161520**
161521**   (a) +1 point for each occurrence of a matchable phrase in the snippet.
161522**
161523**   (b) +1000 points for the first occurrence of each matchable phrase in
161524**       the snippet for which the corresponding mCovered bit is not set.
161525**
161526** The selected snippet parameters are stored in structure *pFragment before
161527** returning. The score of the selected snippet is stored in *piScore
161528** before returning.
161529*/
161530static int fts3BestSnippet(
161531  int nSnippet,                   /* Desired snippet length */
161532  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
161533  int iCol,                       /* Index of column to create snippet from */
161534  u64 mCovered,                   /* Mask of phrases already covered */
161535  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
161536  SnippetFragment *pFragment,     /* OUT: Best snippet found */
161537  int *piScore                    /* OUT: Score of snippet pFragment */
161538){
161539  int rc;                         /* Return Code */
161540  int nList;                      /* Number of phrases in expression */
161541  SnippetIter sIter;              /* Iterates through snippet candidates */
161542  int nByte;                      /* Number of bytes of space to allocate */
161543  int iBestScore = -1;            /* Best snippet score found so far */
161544  int i;                          /* Loop counter */
161545
161546  memset(&sIter, 0, sizeof(sIter));
161547
161548  /* Iterate through the phrases in the expression to count them. The same
161549  ** callback makes sure the doclists are loaded for each phrase.
161550  */
161551  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
161552  if( rc!=SQLITE_OK ){
161553    return rc;
161554  }
161555
161556  /* Now that it is known how many phrases there are, allocate and zero
161557  ** the required space using malloc().
161558  */
161559  nByte = sizeof(SnippetPhrase) * nList;
161560  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
161561  if( !sIter.aPhrase ){
161562    return SQLITE_NOMEM;
161563  }
161564  memset(sIter.aPhrase, 0, nByte);
161565
161566  /* Initialize the contents of the SnippetIter object. Then iterate through
161567  ** the set of phrases in the expression to populate the aPhrase[] array.
161568  */
161569  sIter.pCsr = pCsr;
161570  sIter.iCol = iCol;
161571  sIter.nSnippet = nSnippet;
161572  sIter.nPhrase = nList;
161573  sIter.iCurrent = -1;
161574  rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
161575  if( rc==SQLITE_OK ){
161576
161577    /* Set the *pmSeen output variable. */
161578    for(i=0; i<nList; i++){
161579      if( sIter.aPhrase[i].pHead ){
161580        *pmSeen |= (u64)1 << i;
161581      }
161582    }
161583
161584    /* Loop through all candidate snippets. Store the best snippet in
161585     ** *pFragment. Store its associated 'score' in iBestScore.
161586     */
161587    pFragment->iCol = iCol;
161588    while( !fts3SnippetNextCandidate(&sIter) ){
161589      int iPos;
161590      int iScore;
161591      u64 mCover;
161592      u64 mHighlite;
161593      fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
161594      assert( iScore>=0 );
161595      if( iScore>iBestScore ){
161596        pFragment->iPos = iPos;
161597        pFragment->hlmask = mHighlite;
161598        pFragment->covered = mCover;
161599        iBestScore = iScore;
161600      }
161601    }
161602
161603    *piScore = iBestScore;
161604  }
161605  sqlite3_free(sIter.aPhrase);
161606  return rc;
161607}
161608
161609
161610/*
161611** Append a string to the string-buffer passed as the first argument.
161612**
161613** If nAppend is negative, then the length of the string zAppend is
161614** determined using strlen().
161615*/
161616static int fts3StringAppend(
161617  StrBuffer *pStr,                /* Buffer to append to */
161618  const char *zAppend,            /* Pointer to data to append to buffer */
161619  int nAppend                     /* Size of zAppend in bytes (or -1) */
161620){
161621  if( nAppend<0 ){
161622    nAppend = (int)strlen(zAppend);
161623  }
161624
161625  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
161626  ** to grow the buffer until so that it is big enough to accomadate the
161627  ** appended data.
161628  */
161629  if( pStr->n+nAppend+1>=pStr->nAlloc ){
161630    int nAlloc = pStr->nAlloc+nAppend+100;
161631    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
161632    if( !zNew ){
161633      return SQLITE_NOMEM;
161634    }
161635    pStr->z = zNew;
161636    pStr->nAlloc = nAlloc;
161637  }
161638  assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
161639
161640  /* Append the data to the string buffer. */
161641  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
161642  pStr->n += nAppend;
161643  pStr->z[pStr->n] = '\0';
161644
161645  return SQLITE_OK;
161646}
161647
161648/*
161649** The fts3BestSnippet() function often selects snippets that end with a
161650** query term. That is, the final term of the snippet is always a term
161651** that requires highlighting. For example, if 'X' is a highlighted term
161652** and '.' is a non-highlighted term, BestSnippet() may select:
161653**
161654**     ........X.....X
161655**
161656** This function "shifts" the beginning of the snippet forward in the
161657** document so that there are approximately the same number of
161658** non-highlighted terms to the right of the final highlighted term as there
161659** are to the left of the first highlighted term. For example, to this:
161660**
161661**     ....X.....X....
161662**
161663** This is done as part of extracting the snippet text, not when selecting
161664** the snippet. Snippet selection is done based on doclists only, so there
161665** is no way for fts3BestSnippet() to know whether or not the document
161666** actually contains terms that follow the final highlighted term.
161667*/
161668static int fts3SnippetShift(
161669  Fts3Table *pTab,                /* FTS3 table snippet comes from */
161670  int iLangid,                    /* Language id to use in tokenizing */
161671  int nSnippet,                   /* Number of tokens desired for snippet */
161672  const char *zDoc,               /* Document text to extract snippet from */
161673  int nDoc,                       /* Size of buffer zDoc in bytes */
161674  int *piPos,                     /* IN/OUT: First token of snippet */
161675  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
161676){
161677  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
161678
161679  if( hlmask ){
161680    int nLeft;                    /* Tokens to the left of first highlight */
161681    int nRight;                   /* Tokens to the right of last highlight */
161682    int nDesired;                 /* Ideal number of tokens to shift forward */
161683
161684    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
161685    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
161686    nDesired = (nLeft-nRight)/2;
161687
161688    /* Ideally, the start of the snippet should be pushed forward in the
161689    ** document nDesired tokens. This block checks if there are actually
161690    ** nDesired tokens to the right of the snippet. If so, *piPos and
161691    ** *pHlMask are updated to shift the snippet nDesired tokens to the
161692    ** right. Otherwise, the snippet is shifted by the number of tokens
161693    ** available.
161694    */
161695    if( nDesired>0 ){
161696      int nShift;                 /* Number of tokens to shift snippet by */
161697      int iCurrent = 0;           /* Token counter */
161698      int rc;                     /* Return Code */
161699      sqlite3_tokenizer_module *pMod;
161700      sqlite3_tokenizer_cursor *pC;
161701      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
161702
161703      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
161704      ** or more tokens in zDoc/nDoc.
161705      */
161706      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
161707      if( rc!=SQLITE_OK ){
161708        return rc;
161709      }
161710      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
161711        const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
161712        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
161713      }
161714      pMod->xClose(pC);
161715      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
161716
161717      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
161718      assert( nShift<=nDesired );
161719      if( nShift>0 ){
161720        *piPos += nShift;
161721        *pHlmask = hlmask >> nShift;
161722      }
161723    }
161724  }
161725  return SQLITE_OK;
161726}
161727
161728/*
161729** Extract the snippet text for fragment pFragment from cursor pCsr and
161730** append it to string buffer pOut.
161731*/
161732static int fts3SnippetText(
161733  Fts3Cursor *pCsr,               /* FTS3 Cursor */
161734  SnippetFragment *pFragment,     /* Snippet to extract */
161735  int iFragment,                  /* Fragment number */
161736  int isLast,                     /* True for final fragment in snippet */
161737  int nSnippet,                   /* Number of tokens in extracted snippet */
161738  const char *zOpen,              /* String inserted before highlighted term */
161739  const char *zClose,             /* String inserted after highlighted term */
161740  const char *zEllipsis,          /* String inserted between snippets */
161741  StrBuffer *pOut                 /* Write output here */
161742){
161743  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
161744  int rc;                         /* Return code */
161745  const char *zDoc;               /* Document text to extract snippet from */
161746  int nDoc;                       /* Size of zDoc in bytes */
161747  int iCurrent = 0;               /* Current token number of document */
161748  int iEnd = 0;                   /* Byte offset of end of current token */
161749  int isShiftDone = 0;            /* True after snippet is shifted */
161750  int iPos = pFragment->iPos;     /* First token of snippet */
161751  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
161752  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
161753  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
161754  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
161755
161756  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
161757  if( zDoc==0 ){
161758    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
161759      return SQLITE_NOMEM;
161760    }
161761    return SQLITE_OK;
161762  }
161763  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
161764
161765  /* Open a token cursor on the document. */
161766  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
161767  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
161768  if( rc!=SQLITE_OK ){
161769    return rc;
161770  }
161771
161772  while( rc==SQLITE_OK ){
161773    const char *ZDUMMY;           /* Dummy argument used with tokenizer */
161774    int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
161775    int iBegin = 0;               /* Offset in zDoc of start of token */
161776    int iFin = 0;                 /* Offset in zDoc of end of token */
161777    int isHighlight = 0;          /* True for highlighted terms */
161778
161779    /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
161780    ** in the FTS code the variable that the third argument to xNext points to
161781    ** is initialized to zero before the first (*but not necessarily
161782    ** subsequent*) call to xNext(). This is done for a particular application
161783    ** that needs to know whether or not the tokenizer is being used for
161784    ** snippet generation or for some other purpose.
161785    **
161786    ** Extreme care is required when writing code to depend on this
161787    ** initialization. It is not a documented part of the tokenizer interface.
161788    ** If a tokenizer is used directly by any code outside of FTS, this
161789    ** convention might not be respected.  */
161790    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
161791    if( rc!=SQLITE_OK ){
161792      if( rc==SQLITE_DONE ){
161793        /* Special case - the last token of the snippet is also the last token
161794        ** of the column. Append any punctuation that occurred between the end
161795        ** of the previous token and the end of the document to the output.
161796        ** Then break out of the loop. */
161797        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
161798      }
161799      break;
161800    }
161801    if( iCurrent<iPos ){ continue; }
161802
161803    if( !isShiftDone ){
161804      int n = nDoc - iBegin;
161805      rc = fts3SnippetShift(
161806          pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
161807      );
161808      isShiftDone = 1;
161809
161810      /* Now that the shift has been done, check if the initial "..." are
161811      ** required. They are required if (a) this is not the first fragment,
161812      ** or (b) this fragment does not begin at position 0 of its column.
161813      */
161814      if( rc==SQLITE_OK ){
161815        if( iPos>0 || iFragment>0 ){
161816          rc = fts3StringAppend(pOut, zEllipsis, -1);
161817        }else if( iBegin ){
161818          rc = fts3StringAppend(pOut, zDoc, iBegin);
161819        }
161820      }
161821      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
161822    }
161823
161824    if( iCurrent>=(iPos+nSnippet) ){
161825      if( isLast ){
161826        rc = fts3StringAppend(pOut, zEllipsis, -1);
161827      }
161828      break;
161829    }
161830
161831    /* Set isHighlight to true if this term should be highlighted. */
161832    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
161833
161834    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
161835    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
161836    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
161837    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
161838
161839    iEnd = iFin;
161840  }
161841
161842  pMod->xClose(pC);
161843  return rc;
161844}
161845
161846
161847/*
161848** This function is used to count the entries in a column-list (a
161849** delta-encoded list of term offsets within a single column of a single
161850** row). When this function is called, *ppCollist should point to the
161851** beginning of the first varint in the column-list (the varint that
161852** contains the position of the first matching term in the column data).
161853** Before returning, *ppCollist is set to point to the first byte after
161854** the last varint in the column-list (either the 0x00 signifying the end
161855** of the position-list, or the 0x01 that precedes the column number of
161856** the next column in the position-list).
161857**
161858** The number of elements in the column-list is returned.
161859*/
161860static int fts3ColumnlistCount(char **ppCollist){
161861  char *pEnd = *ppCollist;
161862  char c = 0;
161863  int nEntry = 0;
161864
161865  /* A column-list is terminated by either a 0x01 or 0x00. */
161866  while( 0xFE & (*pEnd | c) ){
161867    c = *pEnd++ & 0x80;
161868    if( !c ) nEntry++;
161869  }
161870
161871  *ppCollist = pEnd;
161872  return nEntry;
161873}
161874
161875/*
161876** This function gathers 'y' or 'b' data for a single phrase.
161877*/
161878static void fts3ExprLHits(
161879  Fts3Expr *pExpr,                /* Phrase expression node */
161880  MatchInfo *p                    /* Matchinfo context */
161881){
161882  Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
161883  int iStart;
161884  Fts3Phrase *pPhrase = pExpr->pPhrase;
161885  char *pIter = pPhrase->doclist.pList;
161886  int iCol = 0;
161887
161888  assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
161889  if( p->flag==FTS3_MATCHINFO_LHITS ){
161890    iStart = pExpr->iPhrase * p->nCol;
161891  }else{
161892    iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
161893  }
161894
161895  while( 1 ){
161896    int nHit = fts3ColumnlistCount(&pIter);
161897    if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
161898      if( p->flag==FTS3_MATCHINFO_LHITS ){
161899        p->aMatchinfo[iStart + iCol] = (u32)nHit;
161900      }else if( nHit ){
161901        p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
161902      }
161903    }
161904    assert( *pIter==0x00 || *pIter==0x01 );
161905    if( *pIter!=0x01 ) break;
161906    pIter++;
161907    pIter += fts3GetVarint32(pIter, &iCol);
161908  }
161909}
161910
161911/*
161912** Gather the results for matchinfo directives 'y' and 'b'.
161913*/
161914static void fts3ExprLHitGather(
161915  Fts3Expr *pExpr,
161916  MatchInfo *p
161917){
161918  assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
161919  if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
161920    if( pExpr->pLeft ){
161921      fts3ExprLHitGather(pExpr->pLeft, p);
161922      fts3ExprLHitGather(pExpr->pRight, p);
161923    }else{
161924      fts3ExprLHits(pExpr, p);
161925    }
161926  }
161927}
161928
161929/*
161930** fts3ExprIterate() callback used to collect the "global" matchinfo stats
161931** for a single query.
161932**
161933** fts3ExprIterate() callback to load the 'global' elements of a
161934** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
161935** of the matchinfo array that are constant for all rows returned by the
161936** current query.
161937**
161938** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
161939** function populates Matchinfo.aMatchinfo[] as follows:
161940**
161941**   for(iCol=0; iCol<nCol; iCol++){
161942**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
161943**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
161944**   }
161945**
161946** where X is the number of matches for phrase iPhrase is column iCol of all
161947** rows of the table. Y is the number of rows for which column iCol contains
161948** at least one instance of phrase iPhrase.
161949**
161950** If the phrase pExpr consists entirely of deferred tokens, then all X and
161951** Y values are set to nDoc, where nDoc is the number of documents in the
161952** file system. This is done because the full-text index doclist is required
161953** to calculate these values properly, and the full-text index doclist is
161954** not available for deferred tokens.
161955*/
161956static int fts3ExprGlobalHitsCb(
161957  Fts3Expr *pExpr,                /* Phrase expression node */
161958  int iPhrase,                    /* Phrase number (numbered from zero) */
161959  void *pCtx                      /* Pointer to MatchInfo structure */
161960){
161961  MatchInfo *p = (MatchInfo *)pCtx;
161962  return sqlite3Fts3EvalPhraseStats(
161963      p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
161964  );
161965}
161966
161967/*
161968** fts3ExprIterate() callback used to collect the "local" part of the
161969** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
161970** array that are different for each row returned by the query.
161971*/
161972static int fts3ExprLocalHitsCb(
161973  Fts3Expr *pExpr,                /* Phrase expression node */
161974  int iPhrase,                    /* Phrase number */
161975  void *pCtx                      /* Pointer to MatchInfo structure */
161976){
161977  int rc = SQLITE_OK;
161978  MatchInfo *p = (MatchInfo *)pCtx;
161979  int iStart = iPhrase * p->nCol * 3;
161980  int i;
161981
161982  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
161983    char *pCsr;
161984    rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
161985    if( pCsr ){
161986      p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
161987    }else{
161988      p->aMatchinfo[iStart+i*3] = 0;
161989    }
161990  }
161991
161992  return rc;
161993}
161994
161995static int fts3MatchinfoCheck(
161996  Fts3Table *pTab,
161997  char cArg,
161998  char **pzErr
161999){
162000  if( (cArg==FTS3_MATCHINFO_NPHRASE)
162001   || (cArg==FTS3_MATCHINFO_NCOL)
162002   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
162003   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
162004   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
162005   || (cArg==FTS3_MATCHINFO_LCS)
162006   || (cArg==FTS3_MATCHINFO_HITS)
162007   || (cArg==FTS3_MATCHINFO_LHITS)
162008   || (cArg==FTS3_MATCHINFO_LHITS_BM)
162009  ){
162010    return SQLITE_OK;
162011  }
162012  sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
162013  return SQLITE_ERROR;
162014}
162015
162016static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
162017  int nVal;                       /* Number of integers output by cArg */
162018
162019  switch( cArg ){
162020    case FTS3_MATCHINFO_NDOC:
162021    case FTS3_MATCHINFO_NPHRASE:
162022    case FTS3_MATCHINFO_NCOL:
162023      nVal = 1;
162024      break;
162025
162026    case FTS3_MATCHINFO_AVGLENGTH:
162027    case FTS3_MATCHINFO_LENGTH:
162028    case FTS3_MATCHINFO_LCS:
162029      nVal = pInfo->nCol;
162030      break;
162031
162032    case FTS3_MATCHINFO_LHITS:
162033      nVal = pInfo->nCol * pInfo->nPhrase;
162034      break;
162035
162036    case FTS3_MATCHINFO_LHITS_BM:
162037      nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
162038      break;
162039
162040    default:
162041      assert( cArg==FTS3_MATCHINFO_HITS );
162042      nVal = pInfo->nCol * pInfo->nPhrase * 3;
162043      break;
162044  }
162045
162046  return nVal;
162047}
162048
162049static int fts3MatchinfoSelectDoctotal(
162050  Fts3Table *pTab,
162051  sqlite3_stmt **ppStmt,
162052  sqlite3_int64 *pnDoc,
162053  const char **paLen
162054){
162055  sqlite3_stmt *pStmt;
162056  const char *a;
162057  sqlite3_int64 nDoc;
162058
162059  if( !*ppStmt ){
162060    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
162061    if( rc!=SQLITE_OK ) return rc;
162062  }
162063  pStmt = *ppStmt;
162064  assert( sqlite3_data_count(pStmt)==1 );
162065
162066  a = sqlite3_column_blob(pStmt, 0);
162067  a += sqlite3Fts3GetVarint(a, &nDoc);
162068  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
162069  *pnDoc = (u32)nDoc;
162070
162071  if( paLen ) *paLen = a;
162072  return SQLITE_OK;
162073}
162074
162075/*
162076** An instance of the following structure is used to store state while
162077** iterating through a multi-column position-list corresponding to the
162078** hits for a single phrase on a single row in order to calculate the
162079** values for a matchinfo() FTS3_MATCHINFO_LCS request.
162080*/
162081typedef struct LcsIterator LcsIterator;
162082struct LcsIterator {
162083  Fts3Expr *pExpr;                /* Pointer to phrase expression */
162084  int iPosOffset;                 /* Tokens count up to end of this phrase */
162085  char *pRead;                    /* Cursor used to iterate through aDoclist */
162086  int iPos;                       /* Current position */
162087};
162088
162089/*
162090** If LcsIterator.iCol is set to the following value, the iterator has
162091** finished iterating through all offsets for all columns.
162092*/
162093#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
162094
162095static int fts3MatchinfoLcsCb(
162096  Fts3Expr *pExpr,                /* Phrase expression node */
162097  int iPhrase,                    /* Phrase number (numbered from zero) */
162098  void *pCtx                      /* Pointer to MatchInfo structure */
162099){
162100  LcsIterator *aIter = (LcsIterator *)pCtx;
162101  aIter[iPhrase].pExpr = pExpr;
162102  return SQLITE_OK;
162103}
162104
162105/*
162106** Advance the iterator passed as an argument to the next position. Return
162107** 1 if the iterator is at EOF or if it now points to the start of the
162108** position list for the next column.
162109*/
162110static int fts3LcsIteratorAdvance(LcsIterator *pIter){
162111  char *pRead = pIter->pRead;
162112  sqlite3_int64 iRead;
162113  int rc = 0;
162114
162115  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
162116  if( iRead==0 || iRead==1 ){
162117    pRead = 0;
162118    rc = 1;
162119  }else{
162120    pIter->iPos += (int)(iRead-2);
162121  }
162122
162123  pIter->pRead = pRead;
162124  return rc;
162125}
162126
162127/*
162128** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
162129**
162130** If the call is successful, the longest-common-substring lengths for each
162131** column are written into the first nCol elements of the pInfo->aMatchinfo[]
162132** array before returning. SQLITE_OK is returned in this case.
162133**
162134** Otherwise, if an error occurs, an SQLite error code is returned and the
162135** data written to the first nCol elements of pInfo->aMatchinfo[] is
162136** undefined.
162137*/
162138static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
162139  LcsIterator *aIter;
162140  int i;
162141  int iCol;
162142  int nToken = 0;
162143
162144  /* Allocate and populate the array of LcsIterator objects. The array
162145  ** contains one element for each matchable phrase in the query.
162146  **/
162147  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
162148  if( !aIter ) return SQLITE_NOMEM;
162149  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
162150  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
162151
162152  for(i=0; i<pInfo->nPhrase; i++){
162153    LcsIterator *pIter = &aIter[i];
162154    nToken -= pIter->pExpr->pPhrase->nToken;
162155    pIter->iPosOffset = nToken;
162156  }
162157
162158  for(iCol=0; iCol<pInfo->nCol; iCol++){
162159    int nLcs = 0;                 /* LCS value for this column */
162160    int nLive = 0;                /* Number of iterators in aIter not at EOF */
162161
162162    for(i=0; i<pInfo->nPhrase; i++){
162163      int rc;
162164      LcsIterator *pIt = &aIter[i];
162165      rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
162166      if( rc!=SQLITE_OK ) return rc;
162167      if( pIt->pRead ){
162168        pIt->iPos = pIt->iPosOffset;
162169        fts3LcsIteratorAdvance(&aIter[i]);
162170        nLive++;
162171      }
162172    }
162173
162174    while( nLive>0 ){
162175      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
162176      int nThisLcs = 0;           /* LCS for the current iterator positions */
162177
162178      for(i=0; i<pInfo->nPhrase; i++){
162179        LcsIterator *pIter = &aIter[i];
162180        if( pIter->pRead==0 ){
162181          /* This iterator is already at EOF for this column. */
162182          nThisLcs = 0;
162183        }else{
162184          if( pAdv==0 || pIter->iPos<pAdv->iPos ){
162185            pAdv = pIter;
162186          }
162187          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
162188            nThisLcs++;
162189          }else{
162190            nThisLcs = 1;
162191          }
162192          if( nThisLcs>nLcs ) nLcs = nThisLcs;
162193        }
162194      }
162195      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
162196    }
162197
162198    pInfo->aMatchinfo[iCol] = nLcs;
162199  }
162200
162201  sqlite3_free(aIter);
162202  return SQLITE_OK;
162203}
162204
162205/*
162206** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
162207** be returned by the matchinfo() function. Argument zArg contains the
162208** format string passed as the second argument to matchinfo (or the
162209** default value "pcx" if no second argument was specified). The format
162210** string has already been validated and the pInfo->aMatchinfo[] array
162211** is guaranteed to be large enough for the output.
162212**
162213** If bGlobal is true, then populate all fields of the matchinfo() output.
162214** If it is false, then assume that those fields that do not change between
162215** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
162216** have already been populated.
162217**
162218** Return SQLITE_OK if successful, or an SQLite error code if an error
162219** occurs. If a value other than SQLITE_OK is returned, the state the
162220** pInfo->aMatchinfo[] buffer is left in is undefined.
162221*/
162222static int fts3MatchinfoValues(
162223  Fts3Cursor *pCsr,               /* FTS3 cursor object */
162224  int bGlobal,                    /* True to grab the global stats */
162225  MatchInfo *pInfo,               /* Matchinfo context object */
162226  const char *zArg                /* Matchinfo format string */
162227){
162228  int rc = SQLITE_OK;
162229  int i;
162230  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
162231  sqlite3_stmt *pSelect = 0;
162232
162233  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
162234    pInfo->flag = zArg[i];
162235    switch( zArg[i] ){
162236      case FTS3_MATCHINFO_NPHRASE:
162237        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
162238        break;
162239
162240      case FTS3_MATCHINFO_NCOL:
162241        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
162242        break;
162243
162244      case FTS3_MATCHINFO_NDOC:
162245        if( bGlobal ){
162246          sqlite3_int64 nDoc = 0;
162247          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
162248          pInfo->aMatchinfo[0] = (u32)nDoc;
162249        }
162250        break;
162251
162252      case FTS3_MATCHINFO_AVGLENGTH:
162253        if( bGlobal ){
162254          sqlite3_int64 nDoc;     /* Number of rows in table */
162255          const char *a;          /* Aggregate column length array */
162256
162257          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
162258          if( rc==SQLITE_OK ){
162259            int iCol;
162260            for(iCol=0; iCol<pInfo->nCol; iCol++){
162261              u32 iVal;
162262              sqlite3_int64 nToken;
162263              a += sqlite3Fts3GetVarint(a, &nToken);
162264              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
162265              pInfo->aMatchinfo[iCol] = iVal;
162266            }
162267          }
162268        }
162269        break;
162270
162271      case FTS3_MATCHINFO_LENGTH: {
162272        sqlite3_stmt *pSelectDocsize = 0;
162273        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
162274        if( rc==SQLITE_OK ){
162275          int iCol;
162276          const char *a = sqlite3_column_blob(pSelectDocsize, 0);
162277          for(iCol=0; iCol<pInfo->nCol; iCol++){
162278            sqlite3_int64 nToken;
162279            a += sqlite3Fts3GetVarint(a, &nToken);
162280            pInfo->aMatchinfo[iCol] = (u32)nToken;
162281          }
162282        }
162283        sqlite3_reset(pSelectDocsize);
162284        break;
162285      }
162286
162287      case FTS3_MATCHINFO_LCS:
162288        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
162289        if( rc==SQLITE_OK ){
162290          rc = fts3MatchinfoLcs(pCsr, pInfo);
162291        }
162292        break;
162293
162294      case FTS3_MATCHINFO_LHITS_BM:
162295      case FTS3_MATCHINFO_LHITS: {
162296        int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
162297        memset(pInfo->aMatchinfo, 0, nZero);
162298        fts3ExprLHitGather(pCsr->pExpr, pInfo);
162299        break;
162300      }
162301
162302      default: {
162303        Fts3Expr *pExpr;
162304        assert( zArg[i]==FTS3_MATCHINFO_HITS );
162305        pExpr = pCsr->pExpr;
162306        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
162307        if( rc!=SQLITE_OK ) break;
162308        if( bGlobal ){
162309          if( pCsr->pDeferred ){
162310            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
162311            if( rc!=SQLITE_OK ) break;
162312          }
162313          rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
162314          sqlite3Fts3EvalTestDeferred(pCsr, &rc);
162315          if( rc!=SQLITE_OK ) break;
162316        }
162317        (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
162318        break;
162319      }
162320    }
162321
162322    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
162323  }
162324
162325  sqlite3_reset(pSelect);
162326  return rc;
162327}
162328
162329
162330/*
162331** Populate pCsr->aMatchinfo[] with data for the current row. The
162332** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
162333*/
162334static void fts3GetMatchinfo(
162335  sqlite3_context *pCtx,        /* Return results here */
162336  Fts3Cursor *pCsr,               /* FTS3 Cursor object */
162337  const char *zArg                /* Second argument to matchinfo() function */
162338){
162339  MatchInfo sInfo;
162340  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
162341  int rc = SQLITE_OK;
162342  int bGlobal = 0;                /* Collect 'global' stats as well as local */
162343
162344  u32 *aOut = 0;
162345  void (*xDestroyOut)(void*) = 0;
162346
162347  memset(&sInfo, 0, sizeof(MatchInfo));
162348  sInfo.pCursor = pCsr;
162349  sInfo.nCol = pTab->nColumn;
162350
162351  /* If there is cached matchinfo() data, but the format string for the
162352  ** cache does not match the format string for this request, discard
162353  ** the cached data. */
162354  if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
162355    sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
162356    pCsr->pMIBuffer = 0;
162357  }
162358
162359  /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
162360  ** matchinfo function has been called for this query. In this case
162361  ** allocate the array used to accumulate the matchinfo data and
162362  ** initialize those elements that are constant for every row.
162363  */
162364  if( pCsr->pMIBuffer==0 ){
162365    int nMatchinfo = 0;           /* Number of u32 elements in match-info */
162366    int i;                        /* Used to iterate through zArg */
162367
162368    /* Determine the number of phrases in the query */
162369    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
162370    sInfo.nPhrase = pCsr->nPhrase;
162371
162372    /* Determine the number of integers in the buffer returned by this call. */
162373    for(i=0; zArg[i]; i++){
162374      char *zErr = 0;
162375      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
162376        sqlite3_result_error(pCtx, zErr, -1);
162377        sqlite3_free(zErr);
162378        return;
162379      }
162380      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
162381    }
162382
162383    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
162384    pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
162385    if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
162386
162387    pCsr->isMatchinfoNeeded = 1;
162388    bGlobal = 1;
162389  }
162390
162391  if( rc==SQLITE_OK ){
162392    xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
162393    if( xDestroyOut==0 ){
162394      rc = SQLITE_NOMEM;
162395    }
162396  }
162397
162398  if( rc==SQLITE_OK ){
162399    sInfo.aMatchinfo = aOut;
162400    sInfo.nPhrase = pCsr->nPhrase;
162401    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
162402    if( bGlobal ){
162403      fts3MIBufferSetGlobal(pCsr->pMIBuffer);
162404    }
162405  }
162406
162407  if( rc!=SQLITE_OK ){
162408    sqlite3_result_error_code(pCtx, rc);
162409    if( xDestroyOut ) xDestroyOut(aOut);
162410  }else{
162411    int n = pCsr->pMIBuffer->nElem * sizeof(u32);
162412    sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
162413  }
162414}
162415
162416/*
162417** Implementation of snippet() function.
162418*/
162419SQLITE_PRIVATE void sqlite3Fts3Snippet(
162420  sqlite3_context *pCtx,          /* SQLite function call context */
162421  Fts3Cursor *pCsr,               /* Cursor object */
162422  const char *zStart,             /* Snippet start text - "<b>" */
162423  const char *zEnd,               /* Snippet end text - "</b>" */
162424  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
162425  int iCol,                       /* Extract snippet from this column */
162426  int nToken                      /* Approximate number of tokens in snippet */
162427){
162428  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
162429  int rc = SQLITE_OK;
162430  int i;
162431  StrBuffer res = {0, 0, 0};
162432
162433  /* The returned text includes up to four fragments of text extracted from
162434  ** the data in the current row. The first iteration of the for(...) loop
162435  ** below attempts to locate a single fragment of text nToken tokens in
162436  ** size that contains at least one instance of all phrases in the query
162437  ** expression that appear in the current row. If such a fragment of text
162438  ** cannot be found, the second iteration of the loop attempts to locate
162439  ** a pair of fragments, and so on.
162440  */
162441  int nSnippet = 0;               /* Number of fragments in this snippet */
162442  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
162443  int nFToken = -1;               /* Number of tokens in each fragment */
162444
162445  if( !pCsr->pExpr ){
162446    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
162447    return;
162448  }
162449
162450  for(nSnippet=1; 1; nSnippet++){
162451
162452    int iSnip;                    /* Loop counter 0..nSnippet-1 */
162453    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
162454    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
162455
162456    if( nToken>=0 ){
162457      nFToken = (nToken+nSnippet-1) / nSnippet;
162458    }else{
162459      nFToken = -1 * nToken;
162460    }
162461
162462    for(iSnip=0; iSnip<nSnippet; iSnip++){
162463      int iBestScore = -1;        /* Best score of columns checked so far */
162464      int iRead;                  /* Used to iterate through columns */
162465      SnippetFragment *pFragment = &aSnippet[iSnip];
162466
162467      memset(pFragment, 0, sizeof(*pFragment));
162468
162469      /* Loop through all columns of the table being considered for snippets.
162470      ** If the iCol argument to this function was negative, this means all
162471      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
162472      */
162473      for(iRead=0; iRead<pTab->nColumn; iRead++){
162474        SnippetFragment sF = {0, 0, 0, 0};
162475        int iS = 0;
162476        if( iCol>=0 && iRead!=iCol ) continue;
162477
162478        /* Find the best snippet of nFToken tokens in column iRead. */
162479        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
162480        if( rc!=SQLITE_OK ){
162481          goto snippet_out;
162482        }
162483        if( iS>iBestScore ){
162484          *pFragment = sF;
162485          iBestScore = iS;
162486        }
162487      }
162488
162489      mCovered |= pFragment->covered;
162490    }
162491
162492    /* If all query phrases seen by fts3BestSnippet() are present in at least
162493    ** one of the nSnippet snippet fragments, break out of the loop.
162494    */
162495    assert( (mCovered&mSeen)==mCovered );
162496    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
162497  }
162498
162499  assert( nFToken>0 );
162500
162501  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
162502    rc = fts3SnippetText(pCsr, &aSnippet[i],
162503        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
162504    );
162505  }
162506
162507 snippet_out:
162508  sqlite3Fts3SegmentsClose(pTab);
162509  if( rc!=SQLITE_OK ){
162510    sqlite3_result_error_code(pCtx, rc);
162511    sqlite3_free(res.z);
162512  }else{
162513    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
162514  }
162515}
162516
162517
162518typedef struct TermOffset TermOffset;
162519typedef struct TermOffsetCtx TermOffsetCtx;
162520
162521struct TermOffset {
162522  char *pList;                    /* Position-list */
162523  int iPos;                       /* Position just read from pList */
162524  int iOff;                       /* Offset of this term from read positions */
162525};
162526
162527struct TermOffsetCtx {
162528  Fts3Cursor *pCsr;
162529  int iCol;                       /* Column of table to populate aTerm for */
162530  int iTerm;
162531  sqlite3_int64 iDocid;
162532  TermOffset *aTerm;
162533};
162534
162535/*
162536** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
162537*/
162538static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
162539  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
162540  int nTerm;                      /* Number of tokens in phrase */
162541  int iTerm;                      /* For looping through nTerm phrase terms */
162542  char *pList;                    /* Pointer to position list for phrase */
162543  int iPos = 0;                   /* First position in position-list */
162544  int rc;
162545
162546  UNUSED_PARAMETER(iPhrase);
162547  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
162548  nTerm = pExpr->pPhrase->nToken;
162549  if( pList ){
162550    fts3GetDeltaPosition(&pList, &iPos);
162551    assert( iPos>=0 );
162552  }
162553
162554  for(iTerm=0; iTerm<nTerm; iTerm++){
162555    TermOffset *pT = &p->aTerm[p->iTerm++];
162556    pT->iOff = nTerm-iTerm-1;
162557    pT->pList = pList;
162558    pT->iPos = iPos;
162559  }
162560
162561  return rc;
162562}
162563
162564/*
162565** Implementation of offsets() function.
162566*/
162567SQLITE_PRIVATE void sqlite3Fts3Offsets(
162568  sqlite3_context *pCtx,          /* SQLite function call context */
162569  Fts3Cursor *pCsr                /* Cursor object */
162570){
162571  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
162572  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
162573  int rc;                         /* Return Code */
162574  int nToken;                     /* Number of tokens in query */
162575  int iCol;                       /* Column currently being processed */
162576  StrBuffer res = {0, 0, 0};      /* Result string */
162577  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
162578
162579  if( !pCsr->pExpr ){
162580    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
162581    return;
162582  }
162583
162584  memset(&sCtx, 0, sizeof(sCtx));
162585  assert( pCsr->isRequireSeek==0 );
162586
162587  /* Count the number of terms in the query */
162588  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
162589  if( rc!=SQLITE_OK ) goto offsets_out;
162590
162591  /* Allocate the array of TermOffset iterators. */
162592  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
162593  if( 0==sCtx.aTerm ){
162594    rc = SQLITE_NOMEM;
162595    goto offsets_out;
162596  }
162597  sCtx.iDocid = pCsr->iPrevId;
162598  sCtx.pCsr = pCsr;
162599
162600  /* Loop through the table columns, appending offset information to
162601  ** string-buffer res for each column.
162602  */
162603  for(iCol=0; iCol<pTab->nColumn; iCol++){
162604    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
162605    const char *ZDUMMY;           /* Dummy argument used with xNext() */
162606    int NDUMMY = 0;               /* Dummy argument used with xNext() */
162607    int iStart = 0;
162608    int iEnd = 0;
162609    int iCurrent = 0;
162610    const char *zDoc;
162611    int nDoc;
162612
162613    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
162614    ** no way that this operation can fail, so the return code from
162615    ** fts3ExprIterate() can be discarded.
162616    */
162617    sCtx.iCol = iCol;
162618    sCtx.iTerm = 0;
162619    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
162620
162621    /* Retreive the text stored in column iCol. If an SQL NULL is stored
162622    ** in column iCol, jump immediately to the next iteration of the loop.
162623    ** If an OOM occurs while retrieving the data (this can happen if SQLite
162624    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
162625    ** to the caller.
162626    */
162627    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
162628    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
162629    if( zDoc==0 ){
162630      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
162631        continue;
162632      }
162633      rc = SQLITE_NOMEM;
162634      goto offsets_out;
162635    }
162636
162637    /* Initialize a tokenizer iterator to iterate through column iCol. */
162638    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
162639        zDoc, nDoc, &pC
162640    );
162641    if( rc!=SQLITE_OK ) goto offsets_out;
162642
162643    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
162644    while( rc==SQLITE_OK ){
162645      int i;                      /* Used to loop through terms */
162646      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
162647      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
162648
162649      for(i=0; i<nToken; i++){
162650        TermOffset *pT = &sCtx.aTerm[i];
162651        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
162652          iMinPos = pT->iPos-pT->iOff;
162653          pTerm = pT;
162654        }
162655      }
162656
162657      if( !pTerm ){
162658        /* All offsets for this column have been gathered. */
162659        rc = SQLITE_DONE;
162660      }else{
162661        assert( iCurrent<=iMinPos );
162662        if( 0==(0xFE&*pTerm->pList) ){
162663          pTerm->pList = 0;
162664        }else{
162665          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
162666        }
162667        while( rc==SQLITE_OK && iCurrent<iMinPos ){
162668          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
162669        }
162670        if( rc==SQLITE_OK ){
162671          char aBuffer[64];
162672          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
162673              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
162674          );
162675          rc = fts3StringAppend(&res, aBuffer, -1);
162676        }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
162677          rc = FTS_CORRUPT_VTAB;
162678        }
162679      }
162680    }
162681    if( rc==SQLITE_DONE ){
162682      rc = SQLITE_OK;
162683    }
162684
162685    pMod->xClose(pC);
162686    if( rc!=SQLITE_OK ) goto offsets_out;
162687  }
162688
162689 offsets_out:
162690  sqlite3_free(sCtx.aTerm);
162691  assert( rc!=SQLITE_DONE );
162692  sqlite3Fts3SegmentsClose(pTab);
162693  if( rc!=SQLITE_OK ){
162694    sqlite3_result_error_code(pCtx,  rc);
162695    sqlite3_free(res.z);
162696  }else{
162697    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
162698  }
162699  return;
162700}
162701
162702/*
162703** Implementation of matchinfo() function.
162704*/
162705SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
162706  sqlite3_context *pContext,      /* Function call context */
162707  Fts3Cursor *pCsr,               /* FTS3 table cursor */
162708  const char *zArg                /* Second arg to matchinfo() function */
162709){
162710  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
162711  const char *zFormat;
162712
162713  if( zArg ){
162714    zFormat = zArg;
162715  }else{
162716    zFormat = FTS3_MATCHINFO_DEFAULT;
162717  }
162718
162719  if( !pCsr->pExpr ){
162720    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
162721    return;
162722  }else{
162723    /* Retrieve matchinfo() data. */
162724    fts3GetMatchinfo(pContext, pCsr, zFormat);
162725    sqlite3Fts3SegmentsClose(pTab);
162726  }
162727}
162728
162729#endif
162730
162731/************** End of fts3_snippet.c ****************************************/
162732/************** Begin file fts3_unicode.c ************************************/
162733/*
162734** 2012 May 24
162735**
162736** The author disclaims copyright to this source code.  In place of
162737** a legal notice, here is a blessing:
162738**
162739**    May you do good and not evil.
162740**    May you find forgiveness for yourself and forgive others.
162741**    May you share freely, never taking more than you give.
162742**
162743******************************************************************************
162744**
162745** Implementation of the "unicode" full-text-search tokenizer.
162746*/
162747
162748#ifndef SQLITE_DISABLE_FTS3_UNICODE
162749
162750/* #include "fts3Int.h" */
162751#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
162752
162753/* #include <assert.h> */
162754/* #include <stdlib.h> */
162755/* #include <stdio.h> */
162756/* #include <string.h> */
162757
162758/* #include "fts3_tokenizer.h" */
162759
162760/*
162761** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
162762** from the sqlite3 source file utf.c. If this file is compiled as part
162763** of the amalgamation, they are not required.
162764*/
162765#ifndef SQLITE_AMALGAMATION
162766
162767static const unsigned char sqlite3Utf8Trans1[] = {
162768  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
162769  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
162770  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
162771  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
162772  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
162773  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
162774  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
162775  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
162776};
162777
162778#define READ_UTF8(zIn, zTerm, c)                           \
162779  c = *(zIn++);                                            \
162780  if( c>=0xc0 ){                                           \
162781    c = sqlite3Utf8Trans1[c-0xc0];                         \
162782    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
162783      c = (c<<6) + (0x3f & *(zIn++));                      \
162784    }                                                      \
162785    if( c<0x80                                             \
162786        || (c&0xFFFFF800)==0xD800                          \
162787        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
162788  }
162789
162790#define WRITE_UTF8(zOut, c) {                          \
162791  if( c<0x00080 ){                                     \
162792    *zOut++ = (u8)(c&0xFF);                            \
162793  }                                                    \
162794  else if( c<0x00800 ){                                \
162795    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
162796    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
162797  }                                                    \
162798  else if( c<0x10000 ){                                \
162799    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
162800    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
162801    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
162802  }else{                                               \
162803    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
162804    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
162805    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
162806    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
162807  }                                                    \
162808}
162809
162810#endif /* ifndef SQLITE_AMALGAMATION */
162811
162812typedef struct unicode_tokenizer unicode_tokenizer;
162813typedef struct unicode_cursor unicode_cursor;
162814
162815struct unicode_tokenizer {
162816  sqlite3_tokenizer base;
162817  int bRemoveDiacritic;
162818  int nException;
162819  int *aiException;
162820};
162821
162822struct unicode_cursor {
162823  sqlite3_tokenizer_cursor base;
162824  const unsigned char *aInput;    /* Input text being tokenized */
162825  int nInput;                     /* Size of aInput[] in bytes */
162826  int iOff;                       /* Current offset within aInput[] */
162827  int iToken;                     /* Index of next token to be returned */
162828  char *zToken;                   /* storage for current token */
162829  int nAlloc;                     /* space allocated at zToken */
162830};
162831
162832
162833/*
162834** Destroy a tokenizer allocated by unicodeCreate().
162835*/
162836static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
162837  if( pTokenizer ){
162838    unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
162839    sqlite3_free(p->aiException);
162840    sqlite3_free(p);
162841  }
162842  return SQLITE_OK;
162843}
162844
162845/*
162846** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
162847** statement has specified that the tokenizer for this table shall consider
162848** all characters in string zIn/nIn to be separators (if bAlnum==0) or
162849** token characters (if bAlnum==1).
162850**
162851** For each codepoint in the zIn/nIn string, this function checks if the
162852** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
162853** If so, no action is taken. Otherwise, the codepoint is added to the
162854** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
162855** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
162856** codepoints in the aiException[] array.
162857**
162858** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
162859** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
162860** It is not possible to change the behavior of the tokenizer with respect
162861** to these codepoints.
162862*/
162863static int unicodeAddExceptions(
162864  unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
162865  int bAlnum,                     /* Replace Isalnum() return value with this */
162866  const char *zIn,                /* Array of characters to make exceptions */
162867  int nIn                         /* Length of z in bytes */
162868){
162869  const unsigned char *z = (const unsigned char *)zIn;
162870  const unsigned char *zTerm = &z[nIn];
162871  unsigned int iCode;
162872  int nEntry = 0;
162873
162874  assert( bAlnum==0 || bAlnum==1 );
162875
162876  while( z<zTerm ){
162877    READ_UTF8(z, zTerm, iCode);
162878    assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
162879    if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
162880     && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
162881    ){
162882      nEntry++;
162883    }
162884  }
162885
162886  if( nEntry ){
162887    int *aNew;                    /* New aiException[] array */
162888    int nNew;                     /* Number of valid entries in array aNew[] */
162889
162890    aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
162891    if( aNew==0 ) return SQLITE_NOMEM;
162892    nNew = p->nException;
162893
162894    z = (const unsigned char *)zIn;
162895    while( z<zTerm ){
162896      READ_UTF8(z, zTerm, iCode);
162897      if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
162898       && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
162899      ){
162900        int i, j;
162901        for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
162902        for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
162903        aNew[i] = (int)iCode;
162904        nNew++;
162905      }
162906    }
162907    p->aiException = aNew;
162908    p->nException = nNew;
162909  }
162910
162911  return SQLITE_OK;
162912}
162913
162914/*
162915** Return true if the p->aiException[] array contains the value iCode.
162916*/
162917static int unicodeIsException(unicode_tokenizer *p, int iCode){
162918  if( p->nException>0 ){
162919    int *a = p->aiException;
162920    int iLo = 0;
162921    int iHi = p->nException-1;
162922
162923    while( iHi>=iLo ){
162924      int iTest = (iHi + iLo) / 2;
162925      if( iCode==a[iTest] ){
162926        return 1;
162927      }else if( iCode>a[iTest] ){
162928        iLo = iTest+1;
162929      }else{
162930        iHi = iTest-1;
162931      }
162932    }
162933  }
162934
162935  return 0;
162936}
162937
162938/*
162939** Return true if, for the purposes of tokenization, codepoint iCode is
162940** considered a token character (not a separator).
162941*/
162942static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
162943  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
162944  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
162945}
162946
162947/*
162948** Create a new tokenizer instance.
162949*/
162950static int unicodeCreate(
162951  int nArg,                       /* Size of array argv[] */
162952  const char * const *azArg,      /* Tokenizer creation arguments */
162953  sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
162954){
162955  unicode_tokenizer *pNew;        /* New tokenizer object */
162956  int i;
162957  int rc = SQLITE_OK;
162958
162959  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
162960  if( pNew==NULL ) return SQLITE_NOMEM;
162961  memset(pNew, 0, sizeof(unicode_tokenizer));
162962  pNew->bRemoveDiacritic = 1;
162963
162964  for(i=0; rc==SQLITE_OK && i<nArg; i++){
162965    const char *z = azArg[i];
162966    int n = (int)strlen(z);
162967
162968    if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
162969      pNew->bRemoveDiacritic = 1;
162970    }
162971    else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
162972      pNew->bRemoveDiacritic = 0;
162973    }
162974    else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
162975      rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
162976    }
162977    else if( n>=11 && memcmp("separators=", z, 11)==0 ){
162978      rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
162979    }
162980    else{
162981      /* Unrecognized argument */
162982      rc  = SQLITE_ERROR;
162983    }
162984  }
162985
162986  if( rc!=SQLITE_OK ){
162987    unicodeDestroy((sqlite3_tokenizer *)pNew);
162988    pNew = 0;
162989  }
162990  *pp = (sqlite3_tokenizer *)pNew;
162991  return rc;
162992}
162993
162994/*
162995** Prepare to begin tokenizing a particular string.  The input
162996** string to be tokenized is pInput[0..nBytes-1].  A cursor
162997** used to incrementally tokenize this string is returned in
162998** *ppCursor.
162999*/
163000static int unicodeOpen(
163001  sqlite3_tokenizer *p,           /* The tokenizer */
163002  const char *aInput,             /* Input string */
163003  int nInput,                     /* Size of string aInput in bytes */
163004  sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
163005){
163006  unicode_cursor *pCsr;
163007
163008  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
163009  if( pCsr==0 ){
163010    return SQLITE_NOMEM;
163011  }
163012  memset(pCsr, 0, sizeof(unicode_cursor));
163013
163014  pCsr->aInput = (const unsigned char *)aInput;
163015  if( aInput==0 ){
163016    pCsr->nInput = 0;
163017  }else if( nInput<0 ){
163018    pCsr->nInput = (int)strlen(aInput);
163019  }else{
163020    pCsr->nInput = nInput;
163021  }
163022
163023  *pp = &pCsr->base;
163024  UNUSED_PARAMETER(p);
163025  return SQLITE_OK;
163026}
163027
163028/*
163029** Close a tokenization cursor previously opened by a call to
163030** simpleOpen() above.
163031*/
163032static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
163033  unicode_cursor *pCsr = (unicode_cursor *) pCursor;
163034  sqlite3_free(pCsr->zToken);
163035  sqlite3_free(pCsr);
163036  return SQLITE_OK;
163037}
163038
163039/*
163040** Extract the next token from a tokenization cursor.  The cursor must
163041** have been opened by a prior call to simpleOpen().
163042*/
163043static int unicodeNext(
163044  sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
163045  const char **paToken,           /* OUT: Token text */
163046  int *pnToken,                   /* OUT: Number of bytes at *paToken */
163047  int *piStart,                   /* OUT: Starting offset of token */
163048  int *piEnd,                     /* OUT: Ending offset of token */
163049  int *piPos                      /* OUT: Position integer of token */
163050){
163051  unicode_cursor *pCsr = (unicode_cursor *)pC;
163052  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
163053  unsigned int iCode = 0;
163054  char *zOut;
163055  const unsigned char *z = &pCsr->aInput[pCsr->iOff];
163056  const unsigned char *zStart = z;
163057  const unsigned char *zEnd;
163058  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
163059
163060  /* Scan past any delimiter characters before the start of the next token.
163061  ** Return SQLITE_DONE early if this takes us all the way to the end of
163062  ** the input.  */
163063  while( z<zTerm ){
163064    READ_UTF8(z, zTerm, iCode);
163065    if( unicodeIsAlnum(p, (int)iCode) ) break;
163066    zStart = z;
163067  }
163068  if( zStart>=zTerm ) return SQLITE_DONE;
163069
163070  zOut = pCsr->zToken;
163071  do {
163072    int iOut;
163073
163074    /* Grow the output buffer if required. */
163075    if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
163076      char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
163077      if( !zNew ) return SQLITE_NOMEM;
163078      zOut = &zNew[zOut - pCsr->zToken];
163079      pCsr->zToken = zNew;
163080      pCsr->nAlloc += 64;
163081    }
163082
163083    /* Write the folded case of the last character read to the output */
163084    zEnd = z;
163085    iOut = sqlite3FtsUnicodeFold((int)iCode, p->bRemoveDiacritic);
163086    if( iOut ){
163087      WRITE_UTF8(zOut, iOut);
163088    }
163089
163090    /* If the cursor is not at EOF, read the next character */
163091    if( z>=zTerm ) break;
163092    READ_UTF8(z, zTerm, iCode);
163093  }while( unicodeIsAlnum(p, (int)iCode)
163094       || sqlite3FtsUnicodeIsdiacritic((int)iCode)
163095  );
163096
163097  /* Set the output variables and return. */
163098  pCsr->iOff = (int)(z - pCsr->aInput);
163099  *paToken = pCsr->zToken;
163100  *pnToken = (int)(zOut - pCsr->zToken);
163101  *piStart = (int)(zStart - pCsr->aInput);
163102  *piEnd = (int)(zEnd - pCsr->aInput);
163103  *piPos = pCsr->iToken++;
163104  return SQLITE_OK;
163105}
163106
163107/*
163108** Set *ppModule to a pointer to the sqlite3_tokenizer_module
163109** structure for the unicode tokenizer.
163110*/
163111SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
163112  static const sqlite3_tokenizer_module module = {
163113    0,
163114    unicodeCreate,
163115    unicodeDestroy,
163116    unicodeOpen,
163117    unicodeClose,
163118    unicodeNext,
163119    0,
163120  };
163121  *ppModule = &module;
163122}
163123
163124#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
163125#endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
163126
163127/************** End of fts3_unicode.c ****************************************/
163128/************** Begin file fts3_unicode2.c ***********************************/
163129/*
163130** 2012 May 25
163131**
163132** The author disclaims copyright to this source code.  In place of
163133** a legal notice, here is a blessing:
163134**
163135**    May you do good and not evil.
163136**    May you find forgiveness for yourself and forgive others.
163137**    May you share freely, never taking more than you give.
163138**
163139******************************************************************************
163140*/
163141
163142/*
163143** DO NOT EDIT THIS MACHINE GENERATED FILE.
163144*/
163145
163146#ifndef SQLITE_DISABLE_FTS3_UNICODE
163147#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
163148
163149/* #include <assert.h> */
163150
163151/*
163152** Return true if the argument corresponds to a unicode codepoint
163153** classified as either a letter or a number. Otherwise false.
163154**
163155** The results are undefined if the value passed to this function
163156** is less than zero.
163157*/
163158SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
163159  /* Each unsigned integer in the following array corresponds to a contiguous
163160  ** range of unicode codepoints that are not either letters or numbers (i.e.
163161  ** codepoints for which this function should return 0).
163162  **
163163  ** The most significant 22 bits in each 32-bit value contain the first
163164  ** codepoint in the range. The least significant 10 bits are used to store
163165  ** the size of the range (always at least 1). In other words, the value
163166  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
163167  ** C. It is not possible to represent a range larger than 1023 codepoints
163168  ** using this format.
163169  */
163170  static const unsigned int aEntry[] = {
163171    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
163172    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
163173    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
163174    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
163175    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
163176    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
163177    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
163178    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
163179    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
163180    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
163181    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
163182    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
163183    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
163184    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
163185    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
163186    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
163187    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
163188    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
163189    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
163190    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
163191    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
163192    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
163193    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
163194    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
163195    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
163196    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
163197    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
163198    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
163199    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
163200    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
163201    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
163202    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
163203    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
163204    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
163205    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
163206    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
163207    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
163208    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
163209    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
163210    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
163211    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
163212    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
163213    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
163214    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
163215    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
163216    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
163217    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
163218    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
163219    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
163220    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
163221    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
163222    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
163223    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
163224    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
163225    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
163226    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
163227    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
163228    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
163229    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
163230    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
163231    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
163232    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
163233    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
163234    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
163235    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
163236    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
163237    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
163238    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
163239    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
163240    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
163241    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
163242    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
163243    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
163244    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
163245    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
163246    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
163247    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
163248    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
163249    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
163250    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
163251    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
163252    0x380400F0,
163253  };
163254  static const unsigned int aAscii[4] = {
163255    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
163256  };
163257
163258  if( (unsigned int)c<128 ){
163259    return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
163260  }else if( (unsigned int)c<(1<<22) ){
163261    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
163262    int iRes = 0;
163263    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
163264    int iLo = 0;
163265    while( iHi>=iLo ){
163266      int iTest = (iHi + iLo) / 2;
163267      if( key >= aEntry[iTest] ){
163268        iRes = iTest;
163269        iLo = iTest+1;
163270      }else{
163271        iHi = iTest-1;
163272      }
163273    }
163274    assert( aEntry[0]<key );
163275    assert( key>=aEntry[iRes] );
163276    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
163277  }
163278  return 1;
163279}
163280
163281
163282/*
163283** If the argument is a codepoint corresponding to a lowercase letter
163284** in the ASCII range with a diacritic added, return the codepoint
163285** of the ASCII letter only. For example, if passed 235 - "LATIN
163286** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
163287** E"). The resuls of passing a codepoint that corresponds to an
163288** uppercase letter are undefined.
163289*/
163290static int remove_diacritic(int c){
163291  unsigned short aDia[] = {
163292        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
163293     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
163294     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
163295     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
163296     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
163297     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
163298     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
163299     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
163300    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
163301    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
163302    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
163303    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
163304    62924, 63050, 63082, 63274, 63390,
163305  };
163306  char aChar[] = {
163307    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
163308    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
163309    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
163310    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
163311    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
163312    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
163313    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
163314    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
163315    'e',  'i',  'o',  'u',  'y',
163316  };
163317
163318  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
163319  int iRes = 0;
163320  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
163321  int iLo = 0;
163322  while( iHi>=iLo ){
163323    int iTest = (iHi + iLo) / 2;
163324    if( key >= aDia[iTest] ){
163325      iRes = iTest;
163326      iLo = iTest+1;
163327    }else{
163328      iHi = iTest-1;
163329    }
163330  }
163331  assert( key>=aDia[iRes] );
163332  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
163333}
163334
163335
163336/*
163337** Return true if the argument interpreted as a unicode codepoint
163338** is a diacritical modifier character.
163339*/
163340SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
163341  unsigned int mask0 = 0x08029FDF;
163342  unsigned int mask1 = 0x000361F8;
163343  if( c<768 || c>817 ) return 0;
163344  return (c < 768+32) ?
163345      (mask0 & (1 << (c-768))) :
163346      (mask1 & (1 << (c-768-32)));
163347}
163348
163349
163350/*
163351** Interpret the argument as a unicode codepoint. If the codepoint
163352** is an upper case character that has a lower case equivalent,
163353** return the codepoint corresponding to the lower case version.
163354** Otherwise, return a copy of the argument.
163355**
163356** The results are undefined if the value passed to this function
163357** is less than zero.
163358*/
163359SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
163360  /* Each entry in the following array defines a rule for folding a range
163361  ** of codepoints to lower case. The rule applies to a range of nRange
163362  ** codepoints starting at codepoint iCode.
163363  **
163364  ** If the least significant bit in flags is clear, then the rule applies
163365  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
163366  ** need to be folded). Or, if it is set, then the rule only applies to
163367  ** every second codepoint in the range, starting with codepoint C.
163368  **
163369  ** The 7 most significant bits in flags are an index into the aiOff[]
163370  ** array. If a specific codepoint C does require folding, then its lower
163371  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
163372  **
163373  ** The contents of this array are generated by parsing the CaseFolding.txt
163374  ** file distributed as part of the "Unicode Character Database". See
163375  ** http://www.unicode.org for details.
163376  */
163377  static const struct TableEntry {
163378    unsigned short iCode;
163379    unsigned char flags;
163380    unsigned char nRange;
163381  } aEntry[] = {
163382    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
163383    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
163384    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
163385    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
163386    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
163387    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
163388    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
163389    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
163390    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
163391    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
163392    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
163393    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
163394    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
163395    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
163396    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
163397    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
163398    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
163399    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
163400    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
163401    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
163402    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
163403    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
163404    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
163405    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
163406    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
163407    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
163408    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
163409    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
163410    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
163411    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
163412    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
163413    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
163414    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
163415    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
163416    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
163417    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
163418    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
163419    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
163420    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
163421    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
163422    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
163423    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
163424    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
163425    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
163426    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
163427    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
163428    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
163429    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
163430    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
163431    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
163432    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
163433    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
163434    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
163435    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
163436    {65313, 14, 26},
163437  };
163438  static const unsigned short aiOff[] = {
163439   1,     2,     8,     15,    16,    26,    28,    32,
163440   37,    38,    40,    48,    63,    64,    69,    71,
163441   79,    80,    116,   202,   203,   205,   206,   207,
163442   209,   210,   211,   213,   214,   217,   218,   219,
163443   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
163444   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
163445   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
163446   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
163447   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
163448   65514, 65521, 65527, 65528, 65529,
163449  };
163450
163451  int ret = c;
163452
163453  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
163454
163455  if( c<128 ){
163456    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
163457  }else if( c<65536 ){
163458    const struct TableEntry *p;
163459    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
163460    int iLo = 0;
163461    int iRes = -1;
163462
163463    assert( c>aEntry[0].iCode );
163464    while( iHi>=iLo ){
163465      int iTest = (iHi + iLo) / 2;
163466      int cmp = (c - aEntry[iTest].iCode);
163467      if( cmp>=0 ){
163468        iRes = iTest;
163469        iLo = iTest+1;
163470      }else{
163471        iHi = iTest-1;
163472      }
163473    }
163474
163475    assert( iRes>=0 && c>=aEntry[iRes].iCode );
163476    p = &aEntry[iRes];
163477    if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
163478      ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
163479      assert( ret>0 );
163480    }
163481
163482    if( bRemoveDiacritic ) ret = remove_diacritic(ret);
163483  }
163484
163485  else if( c>=66560 && c<66600 ){
163486    ret = c + 40;
163487  }
163488
163489  return ret;
163490}
163491#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
163492#endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
163493
163494/************** End of fts3_unicode2.c ***************************************/
163495/************** Begin file rtree.c *******************************************/
163496/*
163497** 2001 September 15
163498**
163499** The author disclaims copyright to this source code.  In place of
163500** a legal notice, here is a blessing:
163501**
163502**    May you do good and not evil.
163503**    May you find forgiveness for yourself and forgive others.
163504**    May you share freely, never taking more than you give.
163505**
163506*************************************************************************
163507** This file contains code for implementations of the r-tree and r*-tree
163508** algorithms packaged as an SQLite virtual table module.
163509*/
163510
163511/*
163512** Database Format of R-Tree Tables
163513** --------------------------------
163514**
163515** The data structure for a single virtual r-tree table is stored in three
163516** native SQLite tables declared as follows. In each case, the '%' character
163517** in the table name is replaced with the user-supplied name of the r-tree
163518** table.
163519**
163520**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
163521**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
163522**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
163523**
163524** The data for each node of the r-tree structure is stored in the %_node
163525** table. For each node that is not the root node of the r-tree, there is
163526** an entry in the %_parent table associating the node with its parent.
163527** And for each row of data in the table, there is an entry in the %_rowid
163528** table that maps from the entries rowid to the id of the node that it
163529** is stored on.
163530**
163531** The root node of an r-tree always exists, even if the r-tree table is
163532** empty. The nodeno of the root node is always 1. All other nodes in the
163533** table must be the same size as the root node. The content of each node
163534** is formatted as follows:
163535**
163536**   1. If the node is the root node (node 1), then the first 2 bytes
163537**      of the node contain the tree depth as a big-endian integer.
163538**      For non-root nodes, the first 2 bytes are left unused.
163539**
163540**   2. The next 2 bytes contain the number of entries currently
163541**      stored in the node.
163542**
163543**   3. The remainder of the node contains the node entries. Each entry
163544**      consists of a single 8-byte integer followed by an even number
163545**      of 4-byte coordinates. For leaf nodes the integer is the rowid
163546**      of a record. For internal nodes it is the node number of a
163547**      child page.
163548*/
163549
163550#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
163551
163552#ifndef SQLITE_CORE
163553/*   #include "sqlite3ext.h" */
163554  SQLITE_EXTENSION_INIT1
163555#else
163556/*   #include "sqlite3.h" */
163557#endif
163558
163559/* #include <string.h> */
163560/* #include <assert.h> */
163561/* #include <stdio.h> */
163562
163563#ifndef SQLITE_AMALGAMATION
163564#include "sqlite3rtree.h"
163565typedef sqlite3_int64 i64;
163566typedef sqlite3_uint64 u64;
163567typedef unsigned char u8;
163568typedef unsigned short u16;
163569typedef unsigned int u32;
163570#endif
163571
163572/*  The following macro is used to suppress compiler warnings.
163573*/
163574#ifndef UNUSED_PARAMETER
163575# define UNUSED_PARAMETER(x) (void)(x)
163576#endif
163577
163578typedef struct Rtree Rtree;
163579typedef struct RtreeCursor RtreeCursor;
163580typedef struct RtreeNode RtreeNode;
163581typedef struct RtreeCell RtreeCell;
163582typedef struct RtreeConstraint RtreeConstraint;
163583typedef struct RtreeMatchArg RtreeMatchArg;
163584typedef struct RtreeGeomCallback RtreeGeomCallback;
163585typedef union RtreeCoord RtreeCoord;
163586typedef struct RtreeSearchPoint RtreeSearchPoint;
163587
163588/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
163589#define RTREE_MAX_DIMENSIONS 5
163590
163591/* Size of hash table Rtree.aHash. This hash table is not expected to
163592** ever contain very many entries, so a fixed number of buckets is
163593** used.
163594*/
163595#define HASHSIZE 97
163596
163597/* The xBestIndex method of this virtual table requires an estimate of
163598** the number of rows in the virtual table to calculate the costs of
163599** various strategies. If possible, this estimate is loaded from the
163600** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
163601** Otherwise, if no sqlite_stat1 entry is available, use
163602** RTREE_DEFAULT_ROWEST.
163603*/
163604#define RTREE_DEFAULT_ROWEST 1048576
163605#define RTREE_MIN_ROWEST         100
163606
163607/*
163608** An rtree virtual-table object.
163609*/
163610struct Rtree {
163611  sqlite3_vtab base;          /* Base class.  Must be first */
163612  sqlite3 *db;                /* Host database connection */
163613  int iNodeSize;              /* Size in bytes of each node in the node table */
163614  u8 nDim;                    /* Number of dimensions */
163615  u8 nDim2;                   /* Twice the number of dimensions */
163616  u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
163617  u8 nBytesPerCell;           /* Bytes consumed per cell */
163618  u8 inWrTrans;               /* True if inside write transaction */
163619  int iDepth;                 /* Current depth of the r-tree structure */
163620  char *zDb;                  /* Name of database containing r-tree table */
163621  char *zName;                /* Name of r-tree table */
163622  u32 nBusy;                  /* Current number of users of this structure */
163623  i64 nRowEst;                /* Estimated number of rows in this table */
163624  u32 nCursor;                /* Number of open cursors */
163625
163626  /* List of nodes removed during a CondenseTree operation. List is
163627  ** linked together via the pointer normally used for hash chains -
163628  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
163629  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
163630  */
163631  RtreeNode *pDeleted;
163632  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
163633
163634  /* Blob I/O on xxx_node */
163635  sqlite3_blob *pNodeBlob;
163636
163637  /* Statements to read/write/delete a record from xxx_node */
163638  sqlite3_stmt *pWriteNode;
163639  sqlite3_stmt *pDeleteNode;
163640
163641  /* Statements to read/write/delete a record from xxx_rowid */
163642  sqlite3_stmt *pReadRowid;
163643  sqlite3_stmt *pWriteRowid;
163644  sqlite3_stmt *pDeleteRowid;
163645
163646  /* Statements to read/write/delete a record from xxx_parent */
163647  sqlite3_stmt *pReadParent;
163648  sqlite3_stmt *pWriteParent;
163649  sqlite3_stmt *pDeleteParent;
163650
163651  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
163652};
163653
163654/* Possible values for Rtree.eCoordType: */
163655#define RTREE_COORD_REAL32 0
163656#define RTREE_COORD_INT32  1
163657
163658/*
163659** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
163660** only deal with integer coordinates.  No floating point operations
163661** will be done.
163662*/
163663#ifdef SQLITE_RTREE_INT_ONLY
163664  typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
163665  typedef int RtreeValue;                  /* Low accuracy coordinate */
163666# define RTREE_ZERO 0
163667#else
163668  typedef double RtreeDValue;              /* High accuracy coordinate */
163669  typedef float RtreeValue;                /* Low accuracy coordinate */
163670# define RTREE_ZERO 0.0
163671#endif
163672
163673/*
163674** When doing a search of an r-tree, instances of the following structure
163675** record intermediate results from the tree walk.
163676**
163677** The id is always a node-id.  For iLevel>=1 the id is the node-id of
163678** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
163679** the id is of the parent node and the cell that RtreeSearchPoint
163680** represents is the iCell-th entry in the parent node.
163681*/
163682struct RtreeSearchPoint {
163683  RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
163684  sqlite3_int64 id;      /* Node ID */
163685  u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
163686  u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
163687  u8 iCell;              /* Cell index within the node */
163688};
163689
163690/*
163691** The minimum number of cells allowed for a node is a third of the
163692** maximum. In Gutman's notation:
163693**
163694**     m = M/3
163695**
163696** If an R*-tree "Reinsert" operation is required, the same number of
163697** cells are removed from the overfull node and reinserted into the tree.
163698*/
163699#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
163700#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
163701#define RTREE_MAXCELLS 51
163702
163703/*
163704** The smallest possible node-size is (512-64)==448 bytes. And the largest
163705** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
163706** Therefore all non-root nodes must contain at least 3 entries. Since
163707** 2^40 is greater than 2^64, an r-tree structure always has a depth of
163708** 40 or less.
163709*/
163710#define RTREE_MAX_DEPTH 40
163711
163712
163713/*
163714** Number of entries in the cursor RtreeNode cache.  The first entry is
163715** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
163716** entries cache the RtreeNode for the first elements of the priority queue.
163717*/
163718#define RTREE_CACHE_SZ  5
163719
163720/*
163721** An rtree cursor object.
163722*/
163723struct RtreeCursor {
163724  sqlite3_vtab_cursor base;         /* Base class.  Must be first */
163725  u8 atEOF;                         /* True if at end of search */
163726  u8 bPoint;                        /* True if sPoint is valid */
163727  int iStrategy;                    /* Copy of idxNum search parameter */
163728  int nConstraint;                  /* Number of entries in aConstraint */
163729  RtreeConstraint *aConstraint;     /* Search constraints. */
163730  int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
163731  int nPoint;                       /* Number of slots used in aPoint[] */
163732  int mxLevel;                      /* iLevel value for root of the tree */
163733  RtreeSearchPoint *aPoint;         /* Priority queue for search points */
163734  RtreeSearchPoint sPoint;          /* Cached next search point */
163735  RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
163736  u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
163737};
163738
163739/* Return the Rtree of a RtreeCursor */
163740#define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
163741
163742/*
163743** A coordinate can be either a floating point number or a integer.  All
163744** coordinates within a single R-Tree are always of the same time.
163745*/
163746union RtreeCoord {
163747  RtreeValue f;      /* Floating point value */
163748  int i;             /* Integer value */
163749  u32 u;             /* Unsigned for byte-order conversions */
163750};
163751
163752/*
163753** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
163754** formatted as a RtreeDValue (double or int64). This macro assumes that local
163755** variable pRtree points to the Rtree structure associated with the
163756** RtreeCoord.
163757*/
163758#ifdef SQLITE_RTREE_INT_ONLY
163759# define DCOORD(coord) ((RtreeDValue)coord.i)
163760#else
163761# define DCOORD(coord) (                           \
163762    (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
163763      ((double)coord.f) :                           \
163764      ((double)coord.i)                             \
163765  )
163766#endif
163767
163768/*
163769** A search constraint.
163770*/
163771struct RtreeConstraint {
163772  int iCoord;                     /* Index of constrained coordinate */
163773  int op;                         /* Constraining operation */
163774  union {
163775    RtreeDValue rValue;             /* Constraint value. */
163776    int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
163777    int (*xQueryFunc)(sqlite3_rtree_query_info*);
163778  } u;
163779  sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
163780};
163781
163782/* Possible values for RtreeConstraint.op */
163783#define RTREE_EQ    0x41  /* A */
163784#define RTREE_LE    0x42  /* B */
163785#define RTREE_LT    0x43  /* C */
163786#define RTREE_GE    0x44  /* D */
163787#define RTREE_GT    0x45  /* E */
163788#define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
163789#define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
163790
163791
163792/*
163793** An rtree structure node.
163794*/
163795struct RtreeNode {
163796  RtreeNode *pParent;         /* Parent node */
163797  i64 iNode;                  /* The node number */
163798  int nRef;                   /* Number of references to this node */
163799  int isDirty;                /* True if the node needs to be written to disk */
163800  u8 *zData;                  /* Content of the node, as should be on disk */
163801  RtreeNode *pNext;           /* Next node in this hash collision chain */
163802};
163803
163804/* Return the number of cells in a node  */
163805#define NCELL(pNode) readInt16(&(pNode)->zData[2])
163806
163807/*
163808** A single cell from a node, deserialized
163809*/
163810struct RtreeCell {
163811  i64 iRowid;                                 /* Node or entry ID */
163812  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
163813};
163814
163815
163816/*
163817** This object becomes the sqlite3_user_data() for the SQL functions
163818** that are created by sqlite3_rtree_geometry_callback() and
163819** sqlite3_rtree_query_callback() and which appear on the right of MATCH
163820** operators in order to constrain a search.
163821**
163822** xGeom and xQueryFunc are the callback functions.  Exactly one of
163823** xGeom and xQueryFunc fields is non-NULL, depending on whether the
163824** SQL function was created using sqlite3_rtree_geometry_callback() or
163825** sqlite3_rtree_query_callback().
163826**
163827** This object is deleted automatically by the destructor mechanism in
163828** sqlite3_create_function_v2().
163829*/
163830struct RtreeGeomCallback {
163831  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
163832  int (*xQueryFunc)(sqlite3_rtree_query_info*);
163833  void (*xDestructor)(void*);
163834  void *pContext;
163835};
163836
163837
163838/*
163839** Value for the first field of every RtreeMatchArg object. The MATCH
163840** operator tests that the first field of a blob operand matches this
163841** value to avoid operating on invalid blobs (which could cause a segfault).
163842*/
163843#define RTREE_GEOMETRY_MAGIC 0x891245AB
163844
163845/*
163846** An instance of this structure (in the form of a BLOB) is returned by
163847** the SQL functions that sqlite3_rtree_geometry_callback() and
163848** sqlite3_rtree_query_callback() create, and is read as the right-hand
163849** operand to the MATCH operator of an R-Tree.
163850*/
163851struct RtreeMatchArg {
163852  u32 magic;                  /* Always RTREE_GEOMETRY_MAGIC */
163853  RtreeGeomCallback cb;       /* Info about the callback functions */
163854  int nParam;                 /* Number of parameters to the SQL function */
163855  sqlite3_value **apSqlParam; /* Original SQL parameter values */
163856  RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
163857};
163858
163859#ifndef MAX
163860# define MAX(x,y) ((x) < (y) ? (y) : (x))
163861#endif
163862#ifndef MIN
163863# define MIN(x,y) ((x) > (y) ? (y) : (x))
163864#endif
163865
163866/* What version of GCC is being used.  0 means GCC is not being used .
163867** Note that the GCC_VERSION macro will also be set correctly when using
163868** clang, since clang works hard to be gcc compatible.  So the gcc
163869** optimizations will also work when compiling with clang.
163870*/
163871#ifndef GCC_VERSION
163872#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
163873# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
163874#else
163875# define GCC_VERSION 0
163876#endif
163877#endif
163878
163879/* The testcase() macro should already be defined in the amalgamation.  If
163880** it is not, make it a no-op.
163881*/
163882#ifndef SQLITE_AMALGAMATION
163883# define testcase(X)
163884#endif
163885
163886/*
163887** Macros to determine whether the machine is big or little endian,
163888** and whether or not that determination is run-time or compile-time.
163889**
163890** For best performance, an attempt is made to guess at the byte-order
163891** using C-preprocessor macros.  If that is unsuccessful, or if
163892** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
163893** at run-time.
163894*/
163895#ifndef SQLITE_BYTEORDER
163896#if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
163897    defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
163898    defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
163899    defined(__arm__)
163900# define SQLITE_BYTEORDER    1234
163901#elif defined(sparc)    || defined(__ppc__)
163902# define SQLITE_BYTEORDER    4321
163903#else
163904# define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
163905#endif
163906#endif
163907
163908
163909/* What version of MSVC is being used.  0 means MSVC is not being used */
163910#ifndef MSVC_VERSION
163911#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
163912# define MSVC_VERSION _MSC_VER
163913#else
163914# define MSVC_VERSION 0
163915#endif
163916#endif
163917
163918/*
163919** Functions to deserialize a 16 bit integer, 32 bit real number and
163920** 64 bit integer. The deserialized value is returned.
163921*/
163922static int readInt16(u8 *p){
163923  return (p[0]<<8) + p[1];
163924}
163925static void readCoord(u8 *p, RtreeCoord *pCoord){
163926  assert( ((((char*)p) - (char*)0)&3)==0 );  /* p is always 4-byte aligned */
163927#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
163928  pCoord->u = _byteswap_ulong(*(u32*)p);
163929#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
163930  pCoord->u = __builtin_bswap32(*(u32*)p);
163931#elif SQLITE_BYTEORDER==4321
163932  pCoord->u = *(u32*)p;
163933#else
163934  pCoord->u = (
163935    (((u32)p[0]) << 24) +
163936    (((u32)p[1]) << 16) +
163937    (((u32)p[2]) <<  8) +
163938    (((u32)p[3]) <<  0)
163939  );
163940#endif
163941}
163942static i64 readInt64(u8 *p){
163943#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
163944  u64 x;
163945  memcpy(&x, p, 8);
163946  return (i64)_byteswap_uint64(x);
163947#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
163948  u64 x;
163949  memcpy(&x, p, 8);
163950  return (i64)__builtin_bswap64(x);
163951#elif SQLITE_BYTEORDER==4321
163952  i64 x;
163953  memcpy(&x, p, 8);
163954  return x;
163955#else
163956  return (i64)(
163957    (((u64)p[0]) << 56) +
163958    (((u64)p[1]) << 48) +
163959    (((u64)p[2]) << 40) +
163960    (((u64)p[3]) << 32) +
163961    (((u64)p[4]) << 24) +
163962    (((u64)p[5]) << 16) +
163963    (((u64)p[6]) <<  8) +
163964    (((u64)p[7]) <<  0)
163965  );
163966#endif
163967}
163968
163969/*
163970** Functions to serialize a 16 bit integer, 32 bit real number and
163971** 64 bit integer. The value returned is the number of bytes written
163972** to the argument buffer (always 2, 4 and 8 respectively).
163973*/
163974static void writeInt16(u8 *p, int i){
163975  p[0] = (i>> 8)&0xFF;
163976  p[1] = (i>> 0)&0xFF;
163977}
163978static int writeCoord(u8 *p, RtreeCoord *pCoord){
163979  u32 i;
163980  assert( ((((char*)p) - (char*)0)&3)==0 );  /* p is always 4-byte aligned */
163981  assert( sizeof(RtreeCoord)==4 );
163982  assert( sizeof(u32)==4 );
163983#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
163984  i = __builtin_bswap32(pCoord->u);
163985  memcpy(p, &i, 4);
163986#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
163987  i = _byteswap_ulong(pCoord->u);
163988  memcpy(p, &i, 4);
163989#elif SQLITE_BYTEORDER==4321
163990  i = pCoord->u;
163991  memcpy(p, &i, 4);
163992#else
163993  i = pCoord->u;
163994  p[0] = (i>>24)&0xFF;
163995  p[1] = (i>>16)&0xFF;
163996  p[2] = (i>> 8)&0xFF;
163997  p[3] = (i>> 0)&0xFF;
163998#endif
163999  return 4;
164000}
164001static int writeInt64(u8 *p, i64 i){
164002#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
164003  i = (i64)__builtin_bswap64((u64)i);
164004  memcpy(p, &i, 8);
164005#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
164006  i = (i64)_byteswap_uint64((u64)i);
164007  memcpy(p, &i, 8);
164008#elif SQLITE_BYTEORDER==4321
164009  memcpy(p, &i, 8);
164010#else
164011  p[0] = (i>>56)&0xFF;
164012  p[1] = (i>>48)&0xFF;
164013  p[2] = (i>>40)&0xFF;
164014  p[3] = (i>>32)&0xFF;
164015  p[4] = (i>>24)&0xFF;
164016  p[5] = (i>>16)&0xFF;
164017  p[6] = (i>> 8)&0xFF;
164018  p[7] = (i>> 0)&0xFF;
164019#endif
164020  return 8;
164021}
164022
164023/*
164024** Increment the reference count of node p.
164025*/
164026static void nodeReference(RtreeNode *p){
164027  if( p ){
164028    p->nRef++;
164029  }
164030}
164031
164032/*
164033** Clear the content of node p (set all bytes to 0x00).
164034*/
164035static void nodeZero(Rtree *pRtree, RtreeNode *p){
164036  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
164037  p->isDirty = 1;
164038}
164039
164040/*
164041** Given a node number iNode, return the corresponding key to use
164042** in the Rtree.aHash table.
164043*/
164044static int nodeHash(i64 iNode){
164045  return iNode % HASHSIZE;
164046}
164047
164048/*
164049** Search the node hash table for node iNode. If found, return a pointer
164050** to it. Otherwise, return 0.
164051*/
164052static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
164053  RtreeNode *p;
164054  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
164055  return p;
164056}
164057
164058/*
164059** Add node pNode to the node hash table.
164060*/
164061static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
164062  int iHash;
164063  assert( pNode->pNext==0 );
164064  iHash = nodeHash(pNode->iNode);
164065  pNode->pNext = pRtree->aHash[iHash];
164066  pRtree->aHash[iHash] = pNode;
164067}
164068
164069/*
164070** Remove node pNode from the node hash table.
164071*/
164072static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
164073  RtreeNode **pp;
164074  if( pNode->iNode!=0 ){
164075    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
164076    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
164077    *pp = pNode->pNext;
164078    pNode->pNext = 0;
164079  }
164080}
164081
164082/*
164083** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
164084** indicating that node has not yet been assigned a node number. It is
164085** assigned a node number when nodeWrite() is called to write the
164086** node contents out to the database.
164087*/
164088static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
164089  RtreeNode *pNode;
164090  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
164091  if( pNode ){
164092    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
164093    pNode->zData = (u8 *)&pNode[1];
164094    pNode->nRef = 1;
164095    pNode->pParent = pParent;
164096    pNode->isDirty = 1;
164097    nodeReference(pParent);
164098  }
164099  return pNode;
164100}
164101
164102/*
164103** Clear the Rtree.pNodeBlob object
164104*/
164105static void nodeBlobReset(Rtree *pRtree){
164106  if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
164107    sqlite3_blob *pBlob = pRtree->pNodeBlob;
164108    pRtree->pNodeBlob = 0;
164109    sqlite3_blob_close(pBlob);
164110  }
164111}
164112
164113/*
164114** Obtain a reference to an r-tree node.
164115*/
164116static int nodeAcquire(
164117  Rtree *pRtree,             /* R-tree structure */
164118  i64 iNode,                 /* Node number to load */
164119  RtreeNode *pParent,        /* Either the parent node or NULL */
164120  RtreeNode **ppNode         /* OUT: Acquired node */
164121){
164122  int rc = SQLITE_OK;
164123  RtreeNode *pNode = 0;
164124
164125  /* Check if the requested node is already in the hash table. If so,
164126  ** increase its reference count and return it.
164127  */
164128  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
164129    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
164130    if( pParent && !pNode->pParent ){
164131      nodeReference(pParent);
164132      pNode->pParent = pParent;
164133    }
164134    pNode->nRef++;
164135    *ppNode = pNode;
164136    return SQLITE_OK;
164137  }
164138
164139  if( pRtree->pNodeBlob ){
164140    sqlite3_blob *pBlob = pRtree->pNodeBlob;
164141    pRtree->pNodeBlob = 0;
164142    rc = sqlite3_blob_reopen(pBlob, iNode);
164143    pRtree->pNodeBlob = pBlob;
164144    if( rc ){
164145      nodeBlobReset(pRtree);
164146      if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
164147    }
164148  }
164149  if( pRtree->pNodeBlob==0 ){
164150    char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
164151    if( zTab==0 ) return SQLITE_NOMEM;
164152    rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
164153                           &pRtree->pNodeBlob);
164154    sqlite3_free(zTab);
164155  }
164156  if( rc ){
164157    nodeBlobReset(pRtree);
164158    *ppNode = 0;
164159    /* If unable to open an sqlite3_blob on the desired row, that can only
164160    ** be because the shadow tables hold erroneous data. */
164161    if( rc==SQLITE_ERROR ) rc = SQLITE_CORRUPT_VTAB;
164162  }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
164163    pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
164164    if( !pNode ){
164165      rc = SQLITE_NOMEM;
164166    }else{
164167      pNode->pParent = pParent;
164168      pNode->zData = (u8 *)&pNode[1];
164169      pNode->nRef = 1;
164170      pNode->iNode = iNode;
164171      pNode->isDirty = 0;
164172      pNode->pNext = 0;
164173      rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
164174                             pRtree->iNodeSize, 0);
164175      nodeReference(pParent);
164176    }
164177  }
164178
164179  /* If the root node was just loaded, set pRtree->iDepth to the height
164180  ** of the r-tree structure. A height of zero means all data is stored on
164181  ** the root node. A height of one means the children of the root node
164182  ** are the leaves, and so on. If the depth as specified on the root node
164183  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
164184  */
164185  if( pNode && iNode==1 ){
164186    pRtree->iDepth = readInt16(pNode->zData);
164187    if( pRtree->iDepth>RTREE_MAX_DEPTH ){
164188      rc = SQLITE_CORRUPT_VTAB;
164189    }
164190  }
164191
164192  /* If no error has occurred so far, check if the "number of entries"
164193  ** field on the node is too large. If so, set the return code to
164194  ** SQLITE_CORRUPT_VTAB.
164195  */
164196  if( pNode && rc==SQLITE_OK ){
164197    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
164198      rc = SQLITE_CORRUPT_VTAB;
164199    }
164200  }
164201
164202  if( rc==SQLITE_OK ){
164203    if( pNode!=0 ){
164204      nodeHashInsert(pRtree, pNode);
164205    }else{
164206      rc = SQLITE_CORRUPT_VTAB;
164207    }
164208    *ppNode = pNode;
164209  }else{
164210    sqlite3_free(pNode);
164211    *ppNode = 0;
164212  }
164213
164214  return rc;
164215}
164216
164217/*
164218** Overwrite cell iCell of node pNode with the contents of pCell.
164219*/
164220static void nodeOverwriteCell(
164221  Rtree *pRtree,             /* The overall R-Tree */
164222  RtreeNode *pNode,          /* The node into which the cell is to be written */
164223  RtreeCell *pCell,          /* The cell to write */
164224  int iCell                  /* Index into pNode into which pCell is written */
164225){
164226  int ii;
164227  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
164228  p += writeInt64(p, pCell->iRowid);
164229  for(ii=0; ii<pRtree->nDim2; ii++){
164230    p += writeCoord(p, &pCell->aCoord[ii]);
164231  }
164232  pNode->isDirty = 1;
164233}
164234
164235/*
164236** Remove the cell with index iCell from node pNode.
164237*/
164238static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
164239  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
164240  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
164241  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
164242  memmove(pDst, pSrc, nByte);
164243  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
164244  pNode->isDirty = 1;
164245}
164246
164247/*
164248** Insert the contents of cell pCell into node pNode. If the insert
164249** is successful, return SQLITE_OK.
164250**
164251** If there is not enough free space in pNode, return SQLITE_FULL.
164252*/
164253static int nodeInsertCell(
164254  Rtree *pRtree,                /* The overall R-Tree */
164255  RtreeNode *pNode,             /* Write new cell into this node */
164256  RtreeCell *pCell              /* The cell to be inserted */
164257){
164258  int nCell;                    /* Current number of cells in pNode */
164259  int nMaxCell;                 /* Maximum number of cells for pNode */
164260
164261  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
164262  nCell = NCELL(pNode);
164263
164264  assert( nCell<=nMaxCell );
164265  if( nCell<nMaxCell ){
164266    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
164267    writeInt16(&pNode->zData[2], nCell+1);
164268    pNode->isDirty = 1;
164269  }
164270
164271  return (nCell==nMaxCell);
164272}
164273
164274/*
164275** If the node is dirty, write it out to the database.
164276*/
164277static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
164278  int rc = SQLITE_OK;
164279  if( pNode->isDirty ){
164280    sqlite3_stmt *p = pRtree->pWriteNode;
164281    if( pNode->iNode ){
164282      sqlite3_bind_int64(p, 1, pNode->iNode);
164283    }else{
164284      sqlite3_bind_null(p, 1);
164285    }
164286    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
164287    sqlite3_step(p);
164288    pNode->isDirty = 0;
164289    rc = sqlite3_reset(p);
164290    if( pNode->iNode==0 && rc==SQLITE_OK ){
164291      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
164292      nodeHashInsert(pRtree, pNode);
164293    }
164294  }
164295  return rc;
164296}
164297
164298/*
164299** Release a reference to a node. If the node is dirty and the reference
164300** count drops to zero, the node data is written to the database.
164301*/
164302static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
164303  int rc = SQLITE_OK;
164304  if( pNode ){
164305    assert( pNode->nRef>0 );
164306    pNode->nRef--;
164307    if( pNode->nRef==0 ){
164308      if( pNode->iNode==1 ){
164309        pRtree->iDepth = -1;
164310      }
164311      if( pNode->pParent ){
164312        rc = nodeRelease(pRtree, pNode->pParent);
164313      }
164314      if( rc==SQLITE_OK ){
164315        rc = nodeWrite(pRtree, pNode);
164316      }
164317      nodeHashDelete(pRtree, pNode);
164318      sqlite3_free(pNode);
164319    }
164320  }
164321  return rc;
164322}
164323
164324/*
164325** Return the 64-bit integer value associated with cell iCell of
164326** node pNode. If pNode is a leaf node, this is a rowid. If it is
164327** an internal node, then the 64-bit integer is a child page number.
164328*/
164329static i64 nodeGetRowid(
164330  Rtree *pRtree,       /* The overall R-Tree */
164331  RtreeNode *pNode,    /* The node from which to extract the ID */
164332  int iCell            /* The cell index from which to extract the ID */
164333){
164334  assert( iCell<NCELL(pNode) );
164335  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
164336}
164337
164338/*
164339** Return coordinate iCoord from cell iCell in node pNode.
164340*/
164341static void nodeGetCoord(
164342  Rtree *pRtree,               /* The overall R-Tree */
164343  RtreeNode *pNode,            /* The node from which to extract a coordinate */
164344  int iCell,                   /* The index of the cell within the node */
164345  int iCoord,                  /* Which coordinate to extract */
164346  RtreeCoord *pCoord           /* OUT: Space to write result to */
164347){
164348  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
164349}
164350
164351/*
164352** Deserialize cell iCell of node pNode. Populate the structure pointed
164353** to by pCell with the results.
164354*/
164355static void nodeGetCell(
164356  Rtree *pRtree,               /* The overall R-Tree */
164357  RtreeNode *pNode,            /* The node containing the cell to be read */
164358  int iCell,                   /* Index of the cell within the node */
164359  RtreeCell *pCell             /* OUT: Write the cell contents here */
164360){
164361  u8 *pData;
164362  RtreeCoord *pCoord;
164363  int ii = 0;
164364  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
164365  pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
164366  pCoord = pCell->aCoord;
164367  do{
164368    readCoord(pData, &pCoord[ii]);
164369    readCoord(pData+4, &pCoord[ii+1]);
164370    pData += 8;
164371    ii += 2;
164372  }while( ii<pRtree->nDim2 );
164373}
164374
164375
164376/* Forward declaration for the function that does the work of
164377** the virtual table module xCreate() and xConnect() methods.
164378*/
164379static int rtreeInit(
164380  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
164381);
164382
164383/*
164384** Rtree virtual table module xCreate method.
164385*/
164386static int rtreeCreate(
164387  sqlite3 *db,
164388  void *pAux,
164389  int argc, const char *const*argv,
164390  sqlite3_vtab **ppVtab,
164391  char **pzErr
164392){
164393  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
164394}
164395
164396/*
164397** Rtree virtual table module xConnect method.
164398*/
164399static int rtreeConnect(
164400  sqlite3 *db,
164401  void *pAux,
164402  int argc, const char *const*argv,
164403  sqlite3_vtab **ppVtab,
164404  char **pzErr
164405){
164406  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
164407}
164408
164409/*
164410** Increment the r-tree reference count.
164411*/
164412static void rtreeReference(Rtree *pRtree){
164413  pRtree->nBusy++;
164414}
164415
164416/*
164417** Decrement the r-tree reference count. When the reference count reaches
164418** zero the structure is deleted.
164419*/
164420static void rtreeRelease(Rtree *pRtree){
164421  pRtree->nBusy--;
164422  if( pRtree->nBusy==0 ){
164423    pRtree->inWrTrans = 0;
164424    pRtree->nCursor = 0;
164425    nodeBlobReset(pRtree);
164426    sqlite3_finalize(pRtree->pWriteNode);
164427    sqlite3_finalize(pRtree->pDeleteNode);
164428    sqlite3_finalize(pRtree->pReadRowid);
164429    sqlite3_finalize(pRtree->pWriteRowid);
164430    sqlite3_finalize(pRtree->pDeleteRowid);
164431    sqlite3_finalize(pRtree->pReadParent);
164432    sqlite3_finalize(pRtree->pWriteParent);
164433    sqlite3_finalize(pRtree->pDeleteParent);
164434    sqlite3_free(pRtree);
164435  }
164436}
164437
164438/*
164439** Rtree virtual table module xDisconnect method.
164440*/
164441static int rtreeDisconnect(sqlite3_vtab *pVtab){
164442  rtreeRelease((Rtree *)pVtab);
164443  return SQLITE_OK;
164444}
164445
164446/*
164447** Rtree virtual table module xDestroy method.
164448*/
164449static int rtreeDestroy(sqlite3_vtab *pVtab){
164450  Rtree *pRtree = (Rtree *)pVtab;
164451  int rc;
164452  char *zCreate = sqlite3_mprintf(
164453    "DROP TABLE '%q'.'%q_node';"
164454    "DROP TABLE '%q'.'%q_rowid';"
164455    "DROP TABLE '%q'.'%q_parent';",
164456    pRtree->zDb, pRtree->zName,
164457    pRtree->zDb, pRtree->zName,
164458    pRtree->zDb, pRtree->zName
164459  );
164460  if( !zCreate ){
164461    rc = SQLITE_NOMEM;
164462  }else{
164463    nodeBlobReset(pRtree);
164464    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
164465    sqlite3_free(zCreate);
164466  }
164467  if( rc==SQLITE_OK ){
164468    rtreeRelease(pRtree);
164469  }
164470
164471  return rc;
164472}
164473
164474/*
164475** Rtree virtual table module xOpen method.
164476*/
164477static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
164478  int rc = SQLITE_NOMEM;
164479  Rtree *pRtree = (Rtree *)pVTab;
164480  RtreeCursor *pCsr;
164481
164482  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
164483  if( pCsr ){
164484    memset(pCsr, 0, sizeof(RtreeCursor));
164485    pCsr->base.pVtab = pVTab;
164486    rc = SQLITE_OK;
164487    pRtree->nCursor++;
164488  }
164489  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
164490
164491  return rc;
164492}
164493
164494
164495/*
164496** Free the RtreeCursor.aConstraint[] array and its contents.
164497*/
164498static void freeCursorConstraints(RtreeCursor *pCsr){
164499  if( pCsr->aConstraint ){
164500    int i;                        /* Used to iterate through constraint array */
164501    for(i=0; i<pCsr->nConstraint; i++){
164502      sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
164503      if( pInfo ){
164504        if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
164505        sqlite3_free(pInfo);
164506      }
164507    }
164508    sqlite3_free(pCsr->aConstraint);
164509    pCsr->aConstraint = 0;
164510  }
164511}
164512
164513/*
164514** Rtree virtual table module xClose method.
164515*/
164516static int rtreeClose(sqlite3_vtab_cursor *cur){
164517  Rtree *pRtree = (Rtree *)(cur->pVtab);
164518  int ii;
164519  RtreeCursor *pCsr = (RtreeCursor *)cur;
164520  assert( pRtree->nCursor>0 );
164521  freeCursorConstraints(pCsr);
164522  sqlite3_free(pCsr->aPoint);
164523  for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
164524  sqlite3_free(pCsr);
164525  pRtree->nCursor--;
164526  nodeBlobReset(pRtree);
164527  return SQLITE_OK;
164528}
164529
164530/*
164531** Rtree virtual table module xEof method.
164532**
164533** Return non-zero if the cursor does not currently point to a valid
164534** record (i.e if the scan has finished), or zero otherwise.
164535*/
164536static int rtreeEof(sqlite3_vtab_cursor *cur){
164537  RtreeCursor *pCsr = (RtreeCursor *)cur;
164538  return pCsr->atEOF;
164539}
164540
164541/*
164542** Convert raw bits from the on-disk RTree record into a coordinate value.
164543** The on-disk format is big-endian and needs to be converted for little-
164544** endian platforms.  The on-disk record stores integer coordinates if
164545** eInt is true and it stores 32-bit floating point records if eInt is
164546** false.  a[] is the four bytes of the on-disk record to be decoded.
164547** Store the results in "r".
164548**
164549** There are five versions of this macro.  The last one is generic.  The
164550** other four are various architectures-specific optimizations.
164551*/
164552#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
164553#define RTREE_DECODE_COORD(eInt, a, r) {                        \
164554    RtreeCoord c;    /* Coordinate decoded */                   \
164555    c.u = _byteswap_ulong(*(u32*)a);                            \
164556    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
164557}
164558#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
164559#define RTREE_DECODE_COORD(eInt, a, r) {                        \
164560    RtreeCoord c;    /* Coordinate decoded */                   \
164561    c.u = __builtin_bswap32(*(u32*)a);                          \
164562    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
164563}
164564#elif SQLITE_BYTEORDER==1234
164565#define RTREE_DECODE_COORD(eInt, a, r) {                        \
164566    RtreeCoord c;    /* Coordinate decoded */                   \
164567    memcpy(&c.u,a,4);                                           \
164568    c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
164569          ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
164570    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
164571}
164572#elif SQLITE_BYTEORDER==4321
164573#define RTREE_DECODE_COORD(eInt, a, r) {                        \
164574    RtreeCoord c;    /* Coordinate decoded */                   \
164575    memcpy(&c.u,a,4);                                           \
164576    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
164577}
164578#else
164579#define RTREE_DECODE_COORD(eInt, a, r) {                        \
164580    RtreeCoord c;    /* Coordinate decoded */                   \
164581    c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
164582           +((u32)a[2]<<8) + a[3];                              \
164583    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
164584}
164585#endif
164586
164587/*
164588** Check the RTree node or entry given by pCellData and p against the MATCH
164589** constraint pConstraint.
164590*/
164591static int rtreeCallbackConstraint(
164592  RtreeConstraint *pConstraint,  /* The constraint to test */
164593  int eInt,                      /* True if RTree holding integer coordinates */
164594  u8 *pCellData,                 /* Raw cell content */
164595  RtreeSearchPoint *pSearch,     /* Container of this cell */
164596  sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
164597  int *peWithin                  /* OUT: visibility of the cell */
164598){
164599  sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
164600  int nCoord = pInfo->nCoord;                           /* No. of coordinates */
164601  int rc;                                             /* Callback return code */
164602  RtreeCoord c;                                       /* Translator union */
164603  sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
164604
164605  assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
164606  assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
164607
164608  if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
164609    pInfo->iRowid = readInt64(pCellData);
164610  }
164611  pCellData += 8;
164612#ifndef SQLITE_RTREE_INT_ONLY
164613  if( eInt==0 ){
164614    switch( nCoord ){
164615      case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.f;
164616                readCoord(pCellData+32, &c); aCoord[8] = c.f;
164617      case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.f;
164618                readCoord(pCellData+24, &c); aCoord[6] = c.f;
164619      case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.f;
164620                readCoord(pCellData+16, &c); aCoord[4] = c.f;
164621      case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.f;
164622                readCoord(pCellData+8,  &c); aCoord[2] = c.f;
164623      default:  readCoord(pCellData+4,  &c); aCoord[1] = c.f;
164624                readCoord(pCellData,    &c); aCoord[0] = c.f;
164625    }
164626  }else
164627#endif
164628  {
164629    switch( nCoord ){
164630      case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.i;
164631                readCoord(pCellData+32, &c); aCoord[8] = c.i;
164632      case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.i;
164633                readCoord(pCellData+24, &c); aCoord[6] = c.i;
164634      case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.i;
164635                readCoord(pCellData+16, &c); aCoord[4] = c.i;
164636      case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.i;
164637                readCoord(pCellData+8,  &c); aCoord[2] = c.i;
164638      default:  readCoord(pCellData+4,  &c); aCoord[1] = c.i;
164639                readCoord(pCellData,    &c); aCoord[0] = c.i;
164640    }
164641  }
164642  if( pConstraint->op==RTREE_MATCH ){
164643    int eWithin = 0;
164644    rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
164645                              nCoord, aCoord, &eWithin);
164646    if( eWithin==0 ) *peWithin = NOT_WITHIN;
164647    *prScore = RTREE_ZERO;
164648  }else{
164649    pInfo->aCoord = aCoord;
164650    pInfo->iLevel = pSearch->iLevel - 1;
164651    pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
164652    pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
164653    rc = pConstraint->u.xQueryFunc(pInfo);
164654    if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
164655    if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
164656      *prScore = pInfo->rScore;
164657    }
164658  }
164659  return rc;
164660}
164661
164662/*
164663** Check the internal RTree node given by pCellData against constraint p.
164664** If this constraint cannot be satisfied by any child within the node,
164665** set *peWithin to NOT_WITHIN.
164666*/
164667static void rtreeNonleafConstraint(
164668  RtreeConstraint *p,        /* The constraint to test */
164669  int eInt,                  /* True if RTree holds integer coordinates */
164670  u8 *pCellData,             /* Raw cell content as appears on disk */
164671  int *peWithin              /* Adjust downward, as appropriate */
164672){
164673  sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
164674
164675  /* p->iCoord might point to either a lower or upper bound coordinate
164676  ** in a coordinate pair.  But make pCellData point to the lower bound.
164677  */
164678  pCellData += 8 + 4*(p->iCoord&0xfe);
164679
164680  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
164681      || p->op==RTREE_GT || p->op==RTREE_EQ );
164682  assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */
164683  switch( p->op ){
164684    case RTREE_LE:
164685    case RTREE_LT:
164686    case RTREE_EQ:
164687      RTREE_DECODE_COORD(eInt, pCellData, val);
164688      /* val now holds the lower bound of the coordinate pair */
164689      if( p->u.rValue>=val ) return;
164690      if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
164691      /* Fall through for the RTREE_EQ case */
164692
164693    default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
164694      pCellData += 4;
164695      RTREE_DECODE_COORD(eInt, pCellData, val);
164696      /* val now holds the upper bound of the coordinate pair */
164697      if( p->u.rValue<=val ) return;
164698  }
164699  *peWithin = NOT_WITHIN;
164700}
164701
164702/*
164703** Check the leaf RTree cell given by pCellData against constraint p.
164704** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
164705** If the constraint is satisfied, leave *peWithin unchanged.
164706**
164707** The constraint is of the form:  xN op $val
164708**
164709** The op is given by p->op.  The xN is p->iCoord-th coordinate in
164710** pCellData.  $val is given by p->u.rValue.
164711*/
164712static void rtreeLeafConstraint(
164713  RtreeConstraint *p,        /* The constraint to test */
164714  int eInt,                  /* True if RTree holds integer coordinates */
164715  u8 *pCellData,             /* Raw cell content as appears on disk */
164716  int *peWithin              /* Adjust downward, as appropriate */
164717){
164718  RtreeDValue xN;      /* Coordinate value converted to a double */
164719
164720  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
164721      || p->op==RTREE_GT || p->op==RTREE_EQ );
164722  pCellData += 8 + p->iCoord*4;
164723  assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */
164724  RTREE_DECODE_COORD(eInt, pCellData, xN);
164725  switch( p->op ){
164726    case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
164727    case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
164728    case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
164729    case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
164730    default:       if( xN == p->u.rValue ) return;  break;
164731  }
164732  *peWithin = NOT_WITHIN;
164733}
164734
164735/*
164736** One of the cells in node pNode is guaranteed to have a 64-bit
164737** integer value equal to iRowid. Return the index of this cell.
164738*/
164739static int nodeRowidIndex(
164740  Rtree *pRtree,
164741  RtreeNode *pNode,
164742  i64 iRowid,
164743  int *piIndex
164744){
164745  int ii;
164746  int nCell = NCELL(pNode);
164747  assert( nCell<200 );
164748  for(ii=0; ii<nCell; ii++){
164749    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
164750      *piIndex = ii;
164751      return SQLITE_OK;
164752    }
164753  }
164754  return SQLITE_CORRUPT_VTAB;
164755}
164756
164757/*
164758** Return the index of the cell containing a pointer to node pNode
164759** in its parent. If pNode is the root node, return -1.
164760*/
164761static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
164762  RtreeNode *pParent = pNode->pParent;
164763  if( pParent ){
164764    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
164765  }
164766  *piIndex = -1;
164767  return SQLITE_OK;
164768}
164769
164770/*
164771** Compare two search points.  Return negative, zero, or positive if the first
164772** is less than, equal to, or greater than the second.
164773**
164774** The rScore is the primary key.  Smaller rScore values come first.
164775** If the rScore is a tie, then use iLevel as the tie breaker with smaller
164776** iLevel values coming first.  In this way, if rScore is the same for all
164777** SearchPoints, then iLevel becomes the deciding factor and the result
164778** is a depth-first search, which is the desired default behavior.
164779*/
164780static int rtreeSearchPointCompare(
164781  const RtreeSearchPoint *pA,
164782  const RtreeSearchPoint *pB
164783){
164784  if( pA->rScore<pB->rScore ) return -1;
164785  if( pA->rScore>pB->rScore ) return +1;
164786  if( pA->iLevel<pB->iLevel ) return -1;
164787  if( pA->iLevel>pB->iLevel ) return +1;
164788  return 0;
164789}
164790
164791/*
164792** Interchange two search points in a cursor.
164793*/
164794static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
164795  RtreeSearchPoint t = p->aPoint[i];
164796  assert( i<j );
164797  p->aPoint[i] = p->aPoint[j];
164798  p->aPoint[j] = t;
164799  i++; j++;
164800  if( i<RTREE_CACHE_SZ ){
164801    if( j>=RTREE_CACHE_SZ ){
164802      nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
164803      p->aNode[i] = 0;
164804    }else{
164805      RtreeNode *pTemp = p->aNode[i];
164806      p->aNode[i] = p->aNode[j];
164807      p->aNode[j] = pTemp;
164808    }
164809  }
164810}
164811
164812/*
164813** Return the search point with the lowest current score.
164814*/
164815static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
164816  return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
164817}
164818
164819/*
164820** Get the RtreeNode for the search point with the lowest score.
164821*/
164822static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
164823  sqlite3_int64 id;
164824  int ii = 1 - pCur->bPoint;
164825  assert( ii==0 || ii==1 );
164826  assert( pCur->bPoint || pCur->nPoint );
164827  if( pCur->aNode[ii]==0 ){
164828    assert( pRC!=0 );
164829    id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
164830    *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
164831  }
164832  return pCur->aNode[ii];
164833}
164834
164835/*
164836** Push a new element onto the priority queue
164837*/
164838static RtreeSearchPoint *rtreeEnqueue(
164839  RtreeCursor *pCur,    /* The cursor */
164840  RtreeDValue rScore,   /* Score for the new search point */
164841  u8 iLevel             /* Level for the new search point */
164842){
164843  int i, j;
164844  RtreeSearchPoint *pNew;
164845  if( pCur->nPoint>=pCur->nPointAlloc ){
164846    int nNew = pCur->nPointAlloc*2 + 8;
164847    pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
164848    if( pNew==0 ) return 0;
164849    pCur->aPoint = pNew;
164850    pCur->nPointAlloc = nNew;
164851  }
164852  i = pCur->nPoint++;
164853  pNew = pCur->aPoint + i;
164854  pNew->rScore = rScore;
164855  pNew->iLevel = iLevel;
164856  assert( iLevel<=RTREE_MAX_DEPTH );
164857  while( i>0 ){
164858    RtreeSearchPoint *pParent;
164859    j = (i-1)/2;
164860    pParent = pCur->aPoint + j;
164861    if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
164862    rtreeSearchPointSwap(pCur, j, i);
164863    i = j;
164864    pNew = pParent;
164865  }
164866  return pNew;
164867}
164868
164869/*
164870** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
164871** NULL if malloc fails.
164872*/
164873static RtreeSearchPoint *rtreeSearchPointNew(
164874  RtreeCursor *pCur,    /* The cursor */
164875  RtreeDValue rScore,   /* Score for the new search point */
164876  u8 iLevel             /* Level for the new search point */
164877){
164878  RtreeSearchPoint *pNew, *pFirst;
164879  pFirst = rtreeSearchPointFirst(pCur);
164880  pCur->anQueue[iLevel]++;
164881  if( pFirst==0
164882   || pFirst->rScore>rScore
164883   || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
164884  ){
164885    if( pCur->bPoint ){
164886      int ii;
164887      pNew = rtreeEnqueue(pCur, rScore, iLevel);
164888      if( pNew==0 ) return 0;
164889      ii = (int)(pNew - pCur->aPoint) + 1;
164890      if( ii<RTREE_CACHE_SZ ){
164891        assert( pCur->aNode[ii]==0 );
164892        pCur->aNode[ii] = pCur->aNode[0];
164893       }else{
164894        nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
164895      }
164896      pCur->aNode[0] = 0;
164897      *pNew = pCur->sPoint;
164898    }
164899    pCur->sPoint.rScore = rScore;
164900    pCur->sPoint.iLevel = iLevel;
164901    pCur->bPoint = 1;
164902    return &pCur->sPoint;
164903  }else{
164904    return rtreeEnqueue(pCur, rScore, iLevel);
164905  }
164906}
164907
164908#if 0
164909/* Tracing routines for the RtreeSearchPoint queue */
164910static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
164911  if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
164912  printf(" %d.%05lld.%02d %g %d",
164913    p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
164914  );
164915  idx++;
164916  if( idx<RTREE_CACHE_SZ ){
164917    printf(" %p\n", pCur->aNode[idx]);
164918  }else{
164919    printf("\n");
164920  }
164921}
164922static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
164923  int ii;
164924  printf("=== %9s ", zPrefix);
164925  if( pCur->bPoint ){
164926    tracePoint(&pCur->sPoint, -1, pCur);
164927  }
164928  for(ii=0; ii<pCur->nPoint; ii++){
164929    if( ii>0 || pCur->bPoint ) printf("              ");
164930    tracePoint(&pCur->aPoint[ii], ii, pCur);
164931  }
164932}
164933# define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
164934#else
164935# define RTREE_QUEUE_TRACE(A,B)   /* no-op */
164936#endif
164937
164938/* Remove the search point with the lowest current score.
164939*/
164940static void rtreeSearchPointPop(RtreeCursor *p){
164941  int i, j, k, n;
164942  i = 1 - p->bPoint;
164943  assert( i==0 || i==1 );
164944  if( p->aNode[i] ){
164945    nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
164946    p->aNode[i] = 0;
164947  }
164948  if( p->bPoint ){
164949    p->anQueue[p->sPoint.iLevel]--;
164950    p->bPoint = 0;
164951  }else if( p->nPoint ){
164952    p->anQueue[p->aPoint[0].iLevel]--;
164953    n = --p->nPoint;
164954    p->aPoint[0] = p->aPoint[n];
164955    if( n<RTREE_CACHE_SZ-1 ){
164956      p->aNode[1] = p->aNode[n+1];
164957      p->aNode[n+1] = 0;
164958    }
164959    i = 0;
164960    while( (j = i*2+1)<n ){
164961      k = j+1;
164962      if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
164963        if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
164964          rtreeSearchPointSwap(p, i, k);
164965          i = k;
164966        }else{
164967          break;
164968        }
164969      }else{
164970        if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
164971          rtreeSearchPointSwap(p, i, j);
164972          i = j;
164973        }else{
164974          break;
164975        }
164976      }
164977    }
164978  }
164979}
164980
164981
164982/*
164983** Continue the search on cursor pCur until the front of the queue
164984** contains an entry suitable for returning as a result-set row,
164985** or until the RtreeSearchPoint queue is empty, indicating that the
164986** query has completed.
164987*/
164988static int rtreeStepToLeaf(RtreeCursor *pCur){
164989  RtreeSearchPoint *p;
164990  Rtree *pRtree = RTREE_OF_CURSOR(pCur);
164991  RtreeNode *pNode;
164992  int eWithin;
164993  int rc = SQLITE_OK;
164994  int nCell;
164995  int nConstraint = pCur->nConstraint;
164996  int ii;
164997  int eInt;
164998  RtreeSearchPoint x;
164999
165000  eInt = pRtree->eCoordType==RTREE_COORD_INT32;
165001  while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
165002    pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
165003    if( rc ) return rc;
165004    nCell = NCELL(pNode);
165005    assert( nCell<200 );
165006    while( p->iCell<nCell ){
165007      sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
165008      u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
165009      eWithin = FULLY_WITHIN;
165010      for(ii=0; ii<nConstraint; ii++){
165011        RtreeConstraint *pConstraint = pCur->aConstraint + ii;
165012        if( pConstraint->op>=RTREE_MATCH ){
165013          rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
165014                                       &rScore, &eWithin);
165015          if( rc ) return rc;
165016        }else if( p->iLevel==1 ){
165017          rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
165018        }else{
165019          rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
165020        }
165021        if( eWithin==NOT_WITHIN ) break;
165022      }
165023      p->iCell++;
165024      if( eWithin==NOT_WITHIN ) continue;
165025      x.iLevel = p->iLevel - 1;
165026      if( x.iLevel ){
165027        x.id = readInt64(pCellData);
165028        x.iCell = 0;
165029      }else{
165030        x.id = p->id;
165031        x.iCell = p->iCell - 1;
165032      }
165033      if( p->iCell>=nCell ){
165034        RTREE_QUEUE_TRACE(pCur, "POP-S:");
165035        rtreeSearchPointPop(pCur);
165036      }
165037      if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
165038      p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
165039      if( p==0 ) return SQLITE_NOMEM;
165040      p->eWithin = (u8)eWithin;
165041      p->id = x.id;
165042      p->iCell = x.iCell;
165043      RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
165044      break;
165045    }
165046    if( p->iCell>=nCell ){
165047      RTREE_QUEUE_TRACE(pCur, "POP-Se:");
165048      rtreeSearchPointPop(pCur);
165049    }
165050  }
165051  pCur->atEOF = p==0;
165052  return SQLITE_OK;
165053}
165054
165055/*
165056** Rtree virtual table module xNext method.
165057*/
165058static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
165059  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
165060  int rc = SQLITE_OK;
165061
165062  /* Move to the next entry that matches the configured constraints. */
165063  RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
165064  rtreeSearchPointPop(pCsr);
165065  rc = rtreeStepToLeaf(pCsr);
165066  return rc;
165067}
165068
165069/*
165070** Rtree virtual table module xRowid method.
165071*/
165072static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
165073  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
165074  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
165075  int rc = SQLITE_OK;
165076  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
165077  if( rc==SQLITE_OK && p ){
165078    *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
165079  }
165080  return rc;
165081}
165082
165083/*
165084** Rtree virtual table module xColumn method.
165085*/
165086static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
165087  Rtree *pRtree = (Rtree *)cur->pVtab;
165088  RtreeCursor *pCsr = (RtreeCursor *)cur;
165089  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
165090  RtreeCoord c;
165091  int rc = SQLITE_OK;
165092  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
165093
165094  if( rc ) return rc;
165095  if( p==0 ) return SQLITE_OK;
165096  if( i==0 ){
165097    sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
165098  }else{
165099    nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
165100#ifndef SQLITE_RTREE_INT_ONLY
165101    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
165102      sqlite3_result_double(ctx, c.f);
165103    }else
165104#endif
165105    {
165106      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
165107      sqlite3_result_int(ctx, c.i);
165108    }
165109  }
165110  return SQLITE_OK;
165111}
165112
165113/*
165114** Use nodeAcquire() to obtain the leaf node containing the record with
165115** rowid iRowid. If successful, set *ppLeaf to point to the node and
165116** return SQLITE_OK. If there is no such record in the table, set
165117** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
165118** to zero and return an SQLite error code.
165119*/
165120static int findLeafNode(
165121  Rtree *pRtree,              /* RTree to search */
165122  i64 iRowid,                 /* The rowid searching for */
165123  RtreeNode **ppLeaf,         /* Write the node here */
165124  sqlite3_int64 *piNode       /* Write the node-id here */
165125){
165126  int rc;
165127  *ppLeaf = 0;
165128  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
165129  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
165130    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
165131    if( piNode ) *piNode = iNode;
165132    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
165133    sqlite3_reset(pRtree->pReadRowid);
165134  }else{
165135    rc = sqlite3_reset(pRtree->pReadRowid);
165136  }
165137  return rc;
165138}
165139
165140/*
165141** This function is called to configure the RtreeConstraint object passed
165142** as the second argument for a MATCH constraint. The value passed as the
165143** first argument to this function is the right-hand operand to the MATCH
165144** operator.
165145*/
165146static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
165147  RtreeMatchArg *pBlob;              /* BLOB returned by geometry function */
165148  sqlite3_rtree_query_info *pInfo;   /* Callback information */
165149  int nBlob;                         /* Size of the geometry function blob */
165150  int nExpected;                     /* Expected size of the BLOB */
165151
165152  /* Check that value is actually a blob. */
165153  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
165154
165155  /* Check that the blob is roughly the right size. */
165156  nBlob = sqlite3_value_bytes(pValue);
165157  if( nBlob<(int)sizeof(RtreeMatchArg) ){
165158    return SQLITE_ERROR;
165159  }
165160
165161  pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
165162  if( !pInfo ) return SQLITE_NOMEM;
165163  memset(pInfo, 0, sizeof(*pInfo));
165164  pBlob = (RtreeMatchArg*)&pInfo[1];
165165
165166  memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
165167  nExpected = (int)(sizeof(RtreeMatchArg) +
165168                    pBlob->nParam*sizeof(sqlite3_value*) +
165169                    (pBlob->nParam-1)*sizeof(RtreeDValue));
165170  if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
165171    sqlite3_free(pInfo);
165172    return SQLITE_ERROR;
165173  }
165174  pInfo->pContext = pBlob->cb.pContext;
165175  pInfo->nParam = pBlob->nParam;
165176  pInfo->aParam = pBlob->aParam;
165177  pInfo->apSqlParam = pBlob->apSqlParam;
165178
165179  if( pBlob->cb.xGeom ){
165180    pCons->u.xGeom = pBlob->cb.xGeom;
165181  }else{
165182    pCons->op = RTREE_QUERY;
165183    pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
165184  }
165185  pCons->pInfo = pInfo;
165186  return SQLITE_OK;
165187}
165188
165189/*
165190** Rtree virtual table module xFilter method.
165191*/
165192static int rtreeFilter(
165193  sqlite3_vtab_cursor *pVtabCursor,
165194  int idxNum, const char *idxStr,
165195  int argc, sqlite3_value **argv
165196){
165197  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
165198  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
165199  RtreeNode *pRoot = 0;
165200  int ii;
165201  int rc = SQLITE_OK;
165202  int iCell = 0;
165203
165204  rtreeReference(pRtree);
165205
165206  /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
165207  freeCursorConstraints(pCsr);
165208  sqlite3_free(pCsr->aPoint);
165209  memset(pCsr, 0, sizeof(RtreeCursor));
165210  pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
165211
165212  pCsr->iStrategy = idxNum;
165213  if( idxNum==1 ){
165214    /* Special case - lookup by rowid. */
165215    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
165216    RtreeSearchPoint *p;     /* Search point for the leaf */
165217    i64 iRowid = sqlite3_value_int64(argv[0]);
165218    i64 iNode = 0;
165219    rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
165220    if( rc==SQLITE_OK && pLeaf!=0 ){
165221      p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
165222      assert( p!=0 );  /* Always returns pCsr->sPoint */
165223      pCsr->aNode[0] = pLeaf;
165224      p->id = iNode;
165225      p->eWithin = PARTLY_WITHIN;
165226      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
165227      p->iCell = (u8)iCell;
165228      RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
165229    }else{
165230      pCsr->atEOF = 1;
165231    }
165232  }else{
165233    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
165234    ** with the configured constraints.
165235    */
165236    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
165237    if( rc==SQLITE_OK && argc>0 ){
165238      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
165239      pCsr->nConstraint = argc;
165240      if( !pCsr->aConstraint ){
165241        rc = SQLITE_NOMEM;
165242      }else{
165243        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
165244        memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
165245        assert( (idxStr==0 && argc==0)
165246                || (idxStr && (int)strlen(idxStr)==argc*2) );
165247        for(ii=0; ii<argc; ii++){
165248          RtreeConstraint *p = &pCsr->aConstraint[ii];
165249          p->op = idxStr[ii*2];
165250          p->iCoord = idxStr[ii*2+1]-'0';
165251          if( p->op>=RTREE_MATCH ){
165252            /* A MATCH operator. The right-hand-side must be a blob that
165253            ** can be cast into an RtreeMatchArg object. One created using
165254            ** an sqlite3_rtree_geometry_callback() SQL user function.
165255            */
165256            rc = deserializeGeometry(argv[ii], p);
165257            if( rc!=SQLITE_OK ){
165258              break;
165259            }
165260            p->pInfo->nCoord = pRtree->nDim2;
165261            p->pInfo->anQueue = pCsr->anQueue;
165262            p->pInfo->mxLevel = pRtree->iDepth + 1;
165263          }else{
165264#ifdef SQLITE_RTREE_INT_ONLY
165265            p->u.rValue = sqlite3_value_int64(argv[ii]);
165266#else
165267            p->u.rValue = sqlite3_value_double(argv[ii]);
165268#endif
165269          }
165270        }
165271      }
165272    }
165273    if( rc==SQLITE_OK ){
165274      RtreeSearchPoint *pNew;
165275      pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
165276      if( pNew==0 ) return SQLITE_NOMEM;
165277      pNew->id = 1;
165278      pNew->iCell = 0;
165279      pNew->eWithin = PARTLY_WITHIN;
165280      assert( pCsr->bPoint==1 );
165281      pCsr->aNode[0] = pRoot;
165282      pRoot = 0;
165283      RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
165284      rc = rtreeStepToLeaf(pCsr);
165285    }
165286  }
165287
165288  nodeRelease(pRtree, pRoot);
165289  rtreeRelease(pRtree);
165290  return rc;
165291}
165292
165293/*
165294** Rtree virtual table module xBestIndex method. There are three
165295** table scan strategies to choose from (in order from most to
165296** least desirable):
165297**
165298**   idxNum     idxStr        Strategy
165299**   ------------------------------------------------
165300**     1        Unused        Direct lookup by rowid.
165301**     2        See below     R-tree query or full-table scan.
165302**   ------------------------------------------------
165303**
165304** If strategy 1 is used, then idxStr is not meaningful. If strategy
165305** 2 is used, idxStr is formatted to contain 2 bytes for each
165306** constraint used. The first two bytes of idxStr correspond to
165307** the constraint in sqlite3_index_info.aConstraintUsage[] with
165308** (argvIndex==1) etc.
165309**
165310** The first of each pair of bytes in idxStr identifies the constraint
165311** operator as follows:
165312**
165313**   Operator    Byte Value
165314**   ----------------------
165315**      =        0x41 ('A')
165316**     <=        0x42 ('B')
165317**      <        0x43 ('C')
165318**     >=        0x44 ('D')
165319**      >        0x45 ('E')
165320**   MATCH       0x46 ('F')
165321**   ----------------------
165322**
165323** The second of each pair of bytes identifies the coordinate column
165324** to which the constraint applies. The leftmost coordinate column
165325** is 'a', the second from the left 'b' etc.
165326*/
165327static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
165328  Rtree *pRtree = (Rtree*)tab;
165329  int rc = SQLITE_OK;
165330  int ii;
165331  int bMatch = 0;                 /* True if there exists a MATCH constraint */
165332  i64 nRow;                       /* Estimated rows returned by this scan */
165333
165334  int iIdx = 0;
165335  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
165336  memset(zIdxStr, 0, sizeof(zIdxStr));
165337
165338  /* Check if there exists a MATCH constraint - even an unusable one. If there
165339  ** is, do not consider the lookup-by-rowid plan as using such a plan would
165340  ** require the VDBE to evaluate the MATCH constraint, which is not currently
165341  ** possible. */
165342  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
165343    if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
165344      bMatch = 1;
165345    }
165346  }
165347
165348  assert( pIdxInfo->idxStr==0 );
165349  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
165350    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
165351
165352    if( bMatch==0 && p->usable
165353     && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
165354    ){
165355      /* We have an equality constraint on the rowid. Use strategy 1. */
165356      int jj;
165357      for(jj=0; jj<ii; jj++){
165358        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
165359        pIdxInfo->aConstraintUsage[jj].omit = 0;
165360      }
165361      pIdxInfo->idxNum = 1;
165362      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
165363      pIdxInfo->aConstraintUsage[jj].omit = 1;
165364
165365      /* This strategy involves a two rowid lookups on an B-Tree structures
165366      ** and then a linear search of an R-Tree node. This should be
165367      ** considered almost as quick as a direct rowid lookup (for which
165368      ** sqlite uses an internal cost of 0.0). It is expected to return
165369      ** a single row.
165370      */
165371      pIdxInfo->estimatedCost = 30.0;
165372      pIdxInfo->estimatedRows = 1;
165373      return SQLITE_OK;
165374    }
165375
165376    if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
165377      u8 op;
165378      switch( p->op ){
165379        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
165380        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
165381        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
165382        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
165383        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
165384        default:
165385          assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
165386          op = RTREE_MATCH;
165387          break;
165388      }
165389      zIdxStr[iIdx++] = op;
165390      zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
165391      pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
165392      pIdxInfo->aConstraintUsage[ii].omit = 1;
165393    }
165394  }
165395
165396  pIdxInfo->idxNum = 2;
165397  pIdxInfo->needToFreeIdxStr = 1;
165398  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
165399    return SQLITE_NOMEM;
165400  }
165401
165402  nRow = pRtree->nRowEst >> (iIdx/2);
165403  pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
165404  pIdxInfo->estimatedRows = nRow;
165405
165406  return rc;
165407}
165408
165409/*
165410** Return the N-dimensional volumn of the cell stored in *p.
165411*/
165412static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
165413  RtreeDValue area = (RtreeDValue)1;
165414  assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
165415#ifndef SQLITE_RTREE_INT_ONLY
165416  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
165417    switch( pRtree->nDim ){
165418      case 5:  area  = p->aCoord[9].f - p->aCoord[8].f;
165419      case 4:  area *= p->aCoord[7].f - p->aCoord[6].f;
165420      case 3:  area *= p->aCoord[5].f - p->aCoord[4].f;
165421      case 2:  area *= p->aCoord[3].f - p->aCoord[2].f;
165422      default: area *= p->aCoord[1].f - p->aCoord[0].f;
165423    }
165424  }else
165425#endif
165426  {
165427    switch( pRtree->nDim ){
165428      case 5:  area  = p->aCoord[9].i - p->aCoord[8].i;
165429      case 4:  area *= p->aCoord[7].i - p->aCoord[6].i;
165430      case 3:  area *= p->aCoord[5].i - p->aCoord[4].i;
165431      case 2:  area *= p->aCoord[3].i - p->aCoord[2].i;
165432      default: area *= p->aCoord[1].i - p->aCoord[0].i;
165433    }
165434  }
165435  return area;
165436}
165437
165438/*
165439** Return the margin length of cell p. The margin length is the sum
165440** of the objects size in each dimension.
165441*/
165442static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
165443  RtreeDValue margin = 0;
165444  int ii = pRtree->nDim2 - 2;
165445  do{
165446    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
165447    ii -= 2;
165448  }while( ii>=0 );
165449  return margin;
165450}
165451
165452/*
165453** Store the union of cells p1 and p2 in p1.
165454*/
165455static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
165456  int ii = 0;
165457  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
165458    do{
165459      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
165460      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
165461      ii += 2;
165462    }while( ii<pRtree->nDim2 );
165463  }else{
165464    do{
165465      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
165466      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
165467      ii += 2;
165468    }while( ii<pRtree->nDim2 );
165469  }
165470}
165471
165472/*
165473** Return true if the area covered by p2 is a subset of the area covered
165474** by p1. False otherwise.
165475*/
165476static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
165477  int ii;
165478  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
165479  for(ii=0; ii<pRtree->nDim2; ii+=2){
165480    RtreeCoord *a1 = &p1->aCoord[ii];
165481    RtreeCoord *a2 = &p2->aCoord[ii];
165482    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
165483     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
165484    ){
165485      return 0;
165486    }
165487  }
165488  return 1;
165489}
165490
165491/*
165492** Return the amount cell p would grow by if it were unioned with pCell.
165493*/
165494static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
165495  RtreeDValue area;
165496  RtreeCell cell;
165497  memcpy(&cell, p, sizeof(RtreeCell));
165498  area = cellArea(pRtree, &cell);
165499  cellUnion(pRtree, &cell, pCell);
165500  return (cellArea(pRtree, &cell)-area);
165501}
165502
165503static RtreeDValue cellOverlap(
165504  Rtree *pRtree,
165505  RtreeCell *p,
165506  RtreeCell *aCell,
165507  int nCell
165508){
165509  int ii;
165510  RtreeDValue overlap = RTREE_ZERO;
165511  for(ii=0; ii<nCell; ii++){
165512    int jj;
165513    RtreeDValue o = (RtreeDValue)1;
165514    for(jj=0; jj<pRtree->nDim2; jj+=2){
165515      RtreeDValue x1, x2;
165516      x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
165517      x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
165518      if( x2<x1 ){
165519        o = (RtreeDValue)0;
165520        break;
165521      }else{
165522        o = o * (x2-x1);
165523      }
165524    }
165525    overlap += o;
165526  }
165527  return overlap;
165528}
165529
165530
165531/*
165532** This function implements the ChooseLeaf algorithm from Gutman[84].
165533** ChooseSubTree in r*tree terminology.
165534*/
165535static int ChooseLeaf(
165536  Rtree *pRtree,               /* Rtree table */
165537  RtreeCell *pCell,            /* Cell to insert into rtree */
165538  int iHeight,                 /* Height of sub-tree rooted at pCell */
165539  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
165540){
165541  int rc;
165542  int ii;
165543  RtreeNode *pNode;
165544  rc = nodeAcquire(pRtree, 1, 0, &pNode);
165545
165546  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
165547    int iCell;
165548    sqlite3_int64 iBest = 0;
165549
165550    RtreeDValue fMinGrowth = RTREE_ZERO;
165551    RtreeDValue fMinArea = RTREE_ZERO;
165552
165553    int nCell = NCELL(pNode);
165554    RtreeCell cell;
165555    RtreeNode *pChild;
165556
165557    RtreeCell *aCell = 0;
165558
165559    /* Select the child node which will be enlarged the least if pCell
165560    ** is inserted into it. Resolve ties by choosing the entry with
165561    ** the smallest area.
165562    */
165563    for(iCell=0; iCell<nCell; iCell++){
165564      int bBest = 0;
165565      RtreeDValue growth;
165566      RtreeDValue area;
165567      nodeGetCell(pRtree, pNode, iCell, &cell);
165568      growth = cellGrowth(pRtree, &cell, pCell);
165569      area = cellArea(pRtree, &cell);
165570      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
165571        bBest = 1;
165572      }
165573      if( bBest ){
165574        fMinGrowth = growth;
165575        fMinArea = area;
165576        iBest = cell.iRowid;
165577      }
165578    }
165579
165580    sqlite3_free(aCell);
165581    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
165582    nodeRelease(pRtree, pNode);
165583    pNode = pChild;
165584  }
165585
165586  *ppLeaf = pNode;
165587  return rc;
165588}
165589
165590/*
165591** A cell with the same content as pCell has just been inserted into
165592** the node pNode. This function updates the bounding box cells in
165593** all ancestor elements.
165594*/
165595static int AdjustTree(
165596  Rtree *pRtree,                    /* Rtree table */
165597  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
165598  RtreeCell *pCell                  /* This cell was just inserted */
165599){
165600  RtreeNode *p = pNode;
165601  while( p->pParent ){
165602    RtreeNode *pParent = p->pParent;
165603    RtreeCell cell;
165604    int iCell;
165605
165606    if( nodeParentIndex(pRtree, p, &iCell) ){
165607      return SQLITE_CORRUPT_VTAB;
165608    }
165609
165610    nodeGetCell(pRtree, pParent, iCell, &cell);
165611    if( !cellContains(pRtree, &cell, pCell) ){
165612      cellUnion(pRtree, &cell, pCell);
165613      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
165614    }
165615
165616    p = pParent;
165617  }
165618  return SQLITE_OK;
165619}
165620
165621/*
165622** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
165623*/
165624static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
165625  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
165626  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
165627  sqlite3_step(pRtree->pWriteRowid);
165628  return sqlite3_reset(pRtree->pWriteRowid);
165629}
165630
165631/*
165632** Write mapping (iNode->iPar) to the <rtree>_parent table.
165633*/
165634static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
165635  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
165636  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
165637  sqlite3_step(pRtree->pWriteParent);
165638  return sqlite3_reset(pRtree->pWriteParent);
165639}
165640
165641static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
165642
165643
165644/*
165645** Arguments aIdx, aDistance and aSpare all point to arrays of size
165646** nIdx. The aIdx array contains the set of integers from 0 to
165647** (nIdx-1) in no particular order. This function sorts the values
165648** in aIdx according to the indexed values in aDistance. For
165649** example, assuming the inputs:
165650**
165651**   aIdx      = { 0,   1,   2,   3 }
165652**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
165653**
165654** this function sets the aIdx array to contain:
165655**
165656**   aIdx      = { 0,   1,   2,   3 }
165657**
165658** The aSpare array is used as temporary working space by the
165659** sorting algorithm.
165660*/
165661static void SortByDistance(
165662  int *aIdx,
165663  int nIdx,
165664  RtreeDValue *aDistance,
165665  int *aSpare
165666){
165667  if( nIdx>1 ){
165668    int iLeft = 0;
165669    int iRight = 0;
165670
165671    int nLeft = nIdx/2;
165672    int nRight = nIdx-nLeft;
165673    int *aLeft = aIdx;
165674    int *aRight = &aIdx[nLeft];
165675
165676    SortByDistance(aLeft, nLeft, aDistance, aSpare);
165677    SortByDistance(aRight, nRight, aDistance, aSpare);
165678
165679    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
165680    aLeft = aSpare;
165681
165682    while( iLeft<nLeft || iRight<nRight ){
165683      if( iLeft==nLeft ){
165684        aIdx[iLeft+iRight] = aRight[iRight];
165685        iRight++;
165686      }else if( iRight==nRight ){
165687        aIdx[iLeft+iRight] = aLeft[iLeft];
165688        iLeft++;
165689      }else{
165690        RtreeDValue fLeft = aDistance[aLeft[iLeft]];
165691        RtreeDValue fRight = aDistance[aRight[iRight]];
165692        if( fLeft<fRight ){
165693          aIdx[iLeft+iRight] = aLeft[iLeft];
165694          iLeft++;
165695        }else{
165696          aIdx[iLeft+iRight] = aRight[iRight];
165697          iRight++;
165698        }
165699      }
165700    }
165701
165702#if 0
165703    /* Check that the sort worked */
165704    {
165705      int jj;
165706      for(jj=1; jj<nIdx; jj++){
165707        RtreeDValue left = aDistance[aIdx[jj-1]];
165708        RtreeDValue right = aDistance[aIdx[jj]];
165709        assert( left<=right );
165710      }
165711    }
165712#endif
165713  }
165714}
165715
165716/*
165717** Arguments aIdx, aCell and aSpare all point to arrays of size
165718** nIdx. The aIdx array contains the set of integers from 0 to
165719** (nIdx-1) in no particular order. This function sorts the values
165720** in aIdx according to dimension iDim of the cells in aCell. The
165721** minimum value of dimension iDim is considered first, the
165722** maximum used to break ties.
165723**
165724** The aSpare array is used as temporary working space by the
165725** sorting algorithm.
165726*/
165727static void SortByDimension(
165728  Rtree *pRtree,
165729  int *aIdx,
165730  int nIdx,
165731  int iDim,
165732  RtreeCell *aCell,
165733  int *aSpare
165734){
165735  if( nIdx>1 ){
165736
165737    int iLeft = 0;
165738    int iRight = 0;
165739
165740    int nLeft = nIdx/2;
165741    int nRight = nIdx-nLeft;
165742    int *aLeft = aIdx;
165743    int *aRight = &aIdx[nLeft];
165744
165745    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
165746    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
165747
165748    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
165749    aLeft = aSpare;
165750    while( iLeft<nLeft || iRight<nRight ){
165751      RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
165752      RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
165753      RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
165754      RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
165755      if( (iLeft!=nLeft) && ((iRight==nRight)
165756       || (xleft1<xright1)
165757       || (xleft1==xright1 && xleft2<xright2)
165758      )){
165759        aIdx[iLeft+iRight] = aLeft[iLeft];
165760        iLeft++;
165761      }else{
165762        aIdx[iLeft+iRight] = aRight[iRight];
165763        iRight++;
165764      }
165765    }
165766
165767#if 0
165768    /* Check that the sort worked */
165769    {
165770      int jj;
165771      for(jj=1; jj<nIdx; jj++){
165772        RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
165773        RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
165774        RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
165775        RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
165776        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
165777      }
165778    }
165779#endif
165780  }
165781}
165782
165783/*
165784** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
165785*/
165786static int splitNodeStartree(
165787  Rtree *pRtree,
165788  RtreeCell *aCell,
165789  int nCell,
165790  RtreeNode *pLeft,
165791  RtreeNode *pRight,
165792  RtreeCell *pBboxLeft,
165793  RtreeCell *pBboxRight
165794){
165795  int **aaSorted;
165796  int *aSpare;
165797  int ii;
165798
165799  int iBestDim = 0;
165800  int iBestSplit = 0;
165801  RtreeDValue fBestMargin = RTREE_ZERO;
165802
165803  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
165804
165805  aaSorted = (int **)sqlite3_malloc(nByte);
165806  if( !aaSorted ){
165807    return SQLITE_NOMEM;
165808  }
165809
165810  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
165811  memset(aaSorted, 0, nByte);
165812  for(ii=0; ii<pRtree->nDim; ii++){
165813    int jj;
165814    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
165815    for(jj=0; jj<nCell; jj++){
165816      aaSorted[ii][jj] = jj;
165817    }
165818    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
165819  }
165820
165821  for(ii=0; ii<pRtree->nDim; ii++){
165822    RtreeDValue margin = RTREE_ZERO;
165823    RtreeDValue fBestOverlap = RTREE_ZERO;
165824    RtreeDValue fBestArea = RTREE_ZERO;
165825    int iBestLeft = 0;
165826    int nLeft;
165827
165828    for(
165829      nLeft=RTREE_MINCELLS(pRtree);
165830      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
165831      nLeft++
165832    ){
165833      RtreeCell left;
165834      RtreeCell right;
165835      int kk;
165836      RtreeDValue overlap;
165837      RtreeDValue area;
165838
165839      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
165840      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
165841      for(kk=1; kk<(nCell-1); kk++){
165842        if( kk<nLeft ){
165843          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
165844        }else{
165845          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
165846        }
165847      }
165848      margin += cellMargin(pRtree, &left);
165849      margin += cellMargin(pRtree, &right);
165850      overlap = cellOverlap(pRtree, &left, &right, 1);
165851      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
165852      if( (nLeft==RTREE_MINCELLS(pRtree))
165853       || (overlap<fBestOverlap)
165854       || (overlap==fBestOverlap && area<fBestArea)
165855      ){
165856        iBestLeft = nLeft;
165857        fBestOverlap = overlap;
165858        fBestArea = area;
165859      }
165860    }
165861
165862    if( ii==0 || margin<fBestMargin ){
165863      iBestDim = ii;
165864      fBestMargin = margin;
165865      iBestSplit = iBestLeft;
165866    }
165867  }
165868
165869  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
165870  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
165871  for(ii=0; ii<nCell; ii++){
165872    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
165873    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
165874    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
165875    nodeInsertCell(pRtree, pTarget, pCell);
165876    cellUnion(pRtree, pBbox, pCell);
165877  }
165878
165879  sqlite3_free(aaSorted);
165880  return SQLITE_OK;
165881}
165882
165883
165884static int updateMapping(
165885  Rtree *pRtree,
165886  i64 iRowid,
165887  RtreeNode *pNode,
165888  int iHeight
165889){
165890  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
165891  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
165892  if( iHeight>0 ){
165893    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
165894    if( pChild ){
165895      nodeRelease(pRtree, pChild->pParent);
165896      nodeReference(pNode);
165897      pChild->pParent = pNode;
165898    }
165899  }
165900  return xSetMapping(pRtree, iRowid, pNode->iNode);
165901}
165902
165903static int SplitNode(
165904  Rtree *pRtree,
165905  RtreeNode *pNode,
165906  RtreeCell *pCell,
165907  int iHeight
165908){
165909  int i;
165910  int newCellIsRight = 0;
165911
165912  int rc = SQLITE_OK;
165913  int nCell = NCELL(pNode);
165914  RtreeCell *aCell;
165915  int *aiUsed;
165916
165917  RtreeNode *pLeft = 0;
165918  RtreeNode *pRight = 0;
165919
165920  RtreeCell leftbbox;
165921  RtreeCell rightbbox;
165922
165923  /* Allocate an array and populate it with a copy of pCell and
165924  ** all cells from node pLeft. Then zero the original node.
165925  */
165926  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
165927  if( !aCell ){
165928    rc = SQLITE_NOMEM;
165929    goto splitnode_out;
165930  }
165931  aiUsed = (int *)&aCell[nCell+1];
165932  memset(aiUsed, 0, sizeof(int)*(nCell+1));
165933  for(i=0; i<nCell; i++){
165934    nodeGetCell(pRtree, pNode, i, &aCell[i]);
165935  }
165936  nodeZero(pRtree, pNode);
165937  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
165938  nCell++;
165939
165940  if( pNode->iNode==1 ){
165941    pRight = nodeNew(pRtree, pNode);
165942    pLeft = nodeNew(pRtree, pNode);
165943    pRtree->iDepth++;
165944    pNode->isDirty = 1;
165945    writeInt16(pNode->zData, pRtree->iDepth);
165946  }else{
165947    pLeft = pNode;
165948    pRight = nodeNew(pRtree, pLeft->pParent);
165949    nodeReference(pLeft);
165950  }
165951
165952  if( !pLeft || !pRight ){
165953    rc = SQLITE_NOMEM;
165954    goto splitnode_out;
165955  }
165956
165957  memset(pLeft->zData, 0, pRtree->iNodeSize);
165958  memset(pRight->zData, 0, pRtree->iNodeSize);
165959
165960  rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
165961                         &leftbbox, &rightbbox);
165962  if( rc!=SQLITE_OK ){
165963    goto splitnode_out;
165964  }
165965
165966  /* Ensure both child nodes have node numbers assigned to them by calling
165967  ** nodeWrite(). Node pRight always needs a node number, as it was created
165968  ** by nodeNew() above. But node pLeft sometimes already has a node number.
165969  ** In this case avoid the all to nodeWrite().
165970  */
165971  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
165972   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
165973  ){
165974    goto splitnode_out;
165975  }
165976
165977  rightbbox.iRowid = pRight->iNode;
165978  leftbbox.iRowid = pLeft->iNode;
165979
165980  if( pNode->iNode==1 ){
165981    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
165982    if( rc!=SQLITE_OK ){
165983      goto splitnode_out;
165984    }
165985  }else{
165986    RtreeNode *pParent = pLeft->pParent;
165987    int iCell;
165988    rc = nodeParentIndex(pRtree, pLeft, &iCell);
165989    if( rc==SQLITE_OK ){
165990      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
165991      rc = AdjustTree(pRtree, pParent, &leftbbox);
165992    }
165993    if( rc!=SQLITE_OK ){
165994      goto splitnode_out;
165995    }
165996  }
165997  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
165998    goto splitnode_out;
165999  }
166000
166001  for(i=0; i<NCELL(pRight); i++){
166002    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
166003    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
166004    if( iRowid==pCell->iRowid ){
166005      newCellIsRight = 1;
166006    }
166007    if( rc!=SQLITE_OK ){
166008      goto splitnode_out;
166009    }
166010  }
166011  if( pNode->iNode==1 ){
166012    for(i=0; i<NCELL(pLeft); i++){
166013      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
166014      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
166015      if( rc!=SQLITE_OK ){
166016        goto splitnode_out;
166017      }
166018    }
166019  }else if( newCellIsRight==0 ){
166020    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
166021  }
166022
166023  if( rc==SQLITE_OK ){
166024    rc = nodeRelease(pRtree, pRight);
166025    pRight = 0;
166026  }
166027  if( rc==SQLITE_OK ){
166028    rc = nodeRelease(pRtree, pLeft);
166029    pLeft = 0;
166030  }
166031
166032splitnode_out:
166033  nodeRelease(pRtree, pRight);
166034  nodeRelease(pRtree, pLeft);
166035  sqlite3_free(aCell);
166036  return rc;
166037}
166038
166039/*
166040** If node pLeaf is not the root of the r-tree and its pParent pointer is
166041** still NULL, load all ancestor nodes of pLeaf into memory and populate
166042** the pLeaf->pParent chain all the way up to the root node.
166043**
166044** This operation is required when a row is deleted (or updated - an update
166045** is implemented as a delete followed by an insert). SQLite provides the
166046** rowid of the row to delete, which can be used to find the leaf on which
166047** the entry resides (argument pLeaf). Once the leaf is located, this
166048** function is called to determine its ancestry.
166049*/
166050static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
166051  int rc = SQLITE_OK;
166052  RtreeNode *pChild = pLeaf;
166053  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
166054    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
166055    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
166056    rc = sqlite3_step(pRtree->pReadParent);
166057    if( rc==SQLITE_ROW ){
166058      RtreeNode *pTest;           /* Used to test for reference loops */
166059      i64 iNode;                  /* Node number of parent node */
166060
166061      /* Before setting pChild->pParent, test that we are not creating a
166062      ** loop of references (as we would if, say, pChild==pParent). We don't
166063      ** want to do this as it leads to a memory leak when trying to delete
166064      ** the referenced counted node structures.
166065      */
166066      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
166067      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
166068      if( !pTest ){
166069        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
166070      }
166071    }
166072    rc = sqlite3_reset(pRtree->pReadParent);
166073    if( rc==SQLITE_OK ) rc = rc2;
166074    if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
166075    pChild = pChild->pParent;
166076  }
166077  return rc;
166078}
166079
166080static int deleteCell(Rtree *, RtreeNode *, int, int);
166081
166082static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
166083  int rc;
166084  int rc2;
166085  RtreeNode *pParent = 0;
166086  int iCell;
166087
166088  assert( pNode->nRef==1 );
166089
166090  /* Remove the entry in the parent cell. */
166091  rc = nodeParentIndex(pRtree, pNode, &iCell);
166092  if( rc==SQLITE_OK ){
166093    pParent = pNode->pParent;
166094    pNode->pParent = 0;
166095    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
166096  }
166097  rc2 = nodeRelease(pRtree, pParent);
166098  if( rc==SQLITE_OK ){
166099    rc = rc2;
166100  }
166101  if( rc!=SQLITE_OK ){
166102    return rc;
166103  }
166104
166105  /* Remove the xxx_node entry. */
166106  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
166107  sqlite3_step(pRtree->pDeleteNode);
166108  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
166109    return rc;
166110  }
166111
166112  /* Remove the xxx_parent entry. */
166113  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
166114  sqlite3_step(pRtree->pDeleteParent);
166115  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
166116    return rc;
166117  }
166118
166119  /* Remove the node from the in-memory hash table and link it into
166120  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
166121  */
166122  nodeHashDelete(pRtree, pNode);
166123  pNode->iNode = iHeight;
166124  pNode->pNext = pRtree->pDeleted;
166125  pNode->nRef++;
166126  pRtree->pDeleted = pNode;
166127
166128  return SQLITE_OK;
166129}
166130
166131static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
166132  RtreeNode *pParent = pNode->pParent;
166133  int rc = SQLITE_OK;
166134  if( pParent ){
166135    int ii;
166136    int nCell = NCELL(pNode);
166137    RtreeCell box;                            /* Bounding box for pNode */
166138    nodeGetCell(pRtree, pNode, 0, &box);
166139    for(ii=1; ii<nCell; ii++){
166140      RtreeCell cell;
166141      nodeGetCell(pRtree, pNode, ii, &cell);
166142      cellUnion(pRtree, &box, &cell);
166143    }
166144    box.iRowid = pNode->iNode;
166145    rc = nodeParentIndex(pRtree, pNode, &ii);
166146    if( rc==SQLITE_OK ){
166147      nodeOverwriteCell(pRtree, pParent, &box, ii);
166148      rc = fixBoundingBox(pRtree, pParent);
166149    }
166150  }
166151  return rc;
166152}
166153
166154/*
166155** Delete the cell at index iCell of node pNode. After removing the
166156** cell, adjust the r-tree data structure if required.
166157*/
166158static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
166159  RtreeNode *pParent;
166160  int rc;
166161
166162  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
166163    return rc;
166164  }
166165
166166  /* Remove the cell from the node. This call just moves bytes around
166167  ** the in-memory node image, so it cannot fail.
166168  */
166169  nodeDeleteCell(pRtree, pNode, iCell);
166170
166171  /* If the node is not the tree root and now has less than the minimum
166172  ** number of cells, remove it from the tree. Otherwise, update the
166173  ** cell in the parent node so that it tightly contains the updated
166174  ** node.
166175  */
166176  pParent = pNode->pParent;
166177  assert( pParent || pNode->iNode==1 );
166178  if( pParent ){
166179    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
166180      rc = removeNode(pRtree, pNode, iHeight);
166181    }else{
166182      rc = fixBoundingBox(pRtree, pNode);
166183    }
166184  }
166185
166186  return rc;
166187}
166188
166189static int Reinsert(
166190  Rtree *pRtree,
166191  RtreeNode *pNode,
166192  RtreeCell *pCell,
166193  int iHeight
166194){
166195  int *aOrder;
166196  int *aSpare;
166197  RtreeCell *aCell;
166198  RtreeDValue *aDistance;
166199  int nCell;
166200  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
166201  int iDim;
166202  int ii;
166203  int rc = SQLITE_OK;
166204  int n;
166205
166206  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
166207
166208  nCell = NCELL(pNode)+1;
166209  n = (nCell+1)&(~1);
166210
166211  /* Allocate the buffers used by this operation. The allocation is
166212  ** relinquished before this function returns.
166213  */
166214  aCell = (RtreeCell *)sqlite3_malloc(n * (
166215    sizeof(RtreeCell)     +         /* aCell array */
166216    sizeof(int)           +         /* aOrder array */
166217    sizeof(int)           +         /* aSpare array */
166218    sizeof(RtreeDValue)             /* aDistance array */
166219  ));
166220  if( !aCell ){
166221    return SQLITE_NOMEM;
166222  }
166223  aOrder    = (int *)&aCell[n];
166224  aSpare    = (int *)&aOrder[n];
166225  aDistance = (RtreeDValue *)&aSpare[n];
166226
166227  for(ii=0; ii<nCell; ii++){
166228    if( ii==(nCell-1) ){
166229      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
166230    }else{
166231      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
166232    }
166233    aOrder[ii] = ii;
166234    for(iDim=0; iDim<pRtree->nDim; iDim++){
166235      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
166236      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
166237    }
166238  }
166239  for(iDim=0; iDim<pRtree->nDim; iDim++){
166240    aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
166241  }
166242
166243  for(ii=0; ii<nCell; ii++){
166244    aDistance[ii] = RTREE_ZERO;
166245    for(iDim=0; iDim<pRtree->nDim; iDim++){
166246      RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
166247                               DCOORD(aCell[ii].aCoord[iDim*2]));
166248      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
166249    }
166250  }
166251
166252  SortByDistance(aOrder, nCell, aDistance, aSpare);
166253  nodeZero(pRtree, pNode);
166254
166255  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
166256    RtreeCell *p = &aCell[aOrder[ii]];
166257    nodeInsertCell(pRtree, pNode, p);
166258    if( p->iRowid==pCell->iRowid ){
166259      if( iHeight==0 ){
166260        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
166261      }else{
166262        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
166263      }
166264    }
166265  }
166266  if( rc==SQLITE_OK ){
166267    rc = fixBoundingBox(pRtree, pNode);
166268  }
166269  for(; rc==SQLITE_OK && ii<nCell; ii++){
166270    /* Find a node to store this cell in. pNode->iNode currently contains
166271    ** the height of the sub-tree headed by the cell.
166272    */
166273    RtreeNode *pInsert;
166274    RtreeCell *p = &aCell[aOrder[ii]];
166275    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
166276    if( rc==SQLITE_OK ){
166277      int rc2;
166278      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
166279      rc2 = nodeRelease(pRtree, pInsert);
166280      if( rc==SQLITE_OK ){
166281        rc = rc2;
166282      }
166283    }
166284  }
166285
166286  sqlite3_free(aCell);
166287  return rc;
166288}
166289
166290/*
166291** Insert cell pCell into node pNode. Node pNode is the head of a
166292** subtree iHeight high (leaf nodes have iHeight==0).
166293*/
166294static int rtreeInsertCell(
166295  Rtree *pRtree,
166296  RtreeNode *pNode,
166297  RtreeCell *pCell,
166298  int iHeight
166299){
166300  int rc = SQLITE_OK;
166301  if( iHeight>0 ){
166302    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
166303    if( pChild ){
166304      nodeRelease(pRtree, pChild->pParent);
166305      nodeReference(pNode);
166306      pChild->pParent = pNode;
166307    }
166308  }
166309  if( nodeInsertCell(pRtree, pNode, pCell) ){
166310    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
166311      rc = SplitNode(pRtree, pNode, pCell, iHeight);
166312    }else{
166313      pRtree->iReinsertHeight = iHeight;
166314      rc = Reinsert(pRtree, pNode, pCell, iHeight);
166315    }
166316  }else{
166317    rc = AdjustTree(pRtree, pNode, pCell);
166318    if( rc==SQLITE_OK ){
166319      if( iHeight==0 ){
166320        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
166321      }else{
166322        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
166323      }
166324    }
166325  }
166326  return rc;
166327}
166328
166329static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
166330  int ii;
166331  int rc = SQLITE_OK;
166332  int nCell = NCELL(pNode);
166333
166334  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
166335    RtreeNode *pInsert;
166336    RtreeCell cell;
166337    nodeGetCell(pRtree, pNode, ii, &cell);
166338
166339    /* Find a node to store this cell in. pNode->iNode currently contains
166340    ** the height of the sub-tree headed by the cell.
166341    */
166342    rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
166343    if( rc==SQLITE_OK ){
166344      int rc2;
166345      rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
166346      rc2 = nodeRelease(pRtree, pInsert);
166347      if( rc==SQLITE_OK ){
166348        rc = rc2;
166349      }
166350    }
166351  }
166352  return rc;
166353}
166354
166355/*
166356** Select a currently unused rowid for a new r-tree record.
166357*/
166358static int newRowid(Rtree *pRtree, i64 *piRowid){
166359  int rc;
166360  sqlite3_bind_null(pRtree->pWriteRowid, 1);
166361  sqlite3_bind_null(pRtree->pWriteRowid, 2);
166362  sqlite3_step(pRtree->pWriteRowid);
166363  rc = sqlite3_reset(pRtree->pWriteRowid);
166364  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
166365  return rc;
166366}
166367
166368/*
166369** Remove the entry with rowid=iDelete from the r-tree structure.
166370*/
166371static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
166372  int rc;                         /* Return code */
166373  RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
166374  int iCell;                      /* Index of iDelete cell in pLeaf */
166375  RtreeNode *pRoot;               /* Root node of rtree structure */
166376
166377
166378  /* Obtain a reference to the root node to initialize Rtree.iDepth */
166379  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
166380
166381  /* Obtain a reference to the leaf node that contains the entry
166382  ** about to be deleted.
166383  */
166384  if( rc==SQLITE_OK ){
166385    rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
166386  }
166387
166388  /* Delete the cell in question from the leaf node. */
166389  if( rc==SQLITE_OK ){
166390    int rc2;
166391    rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
166392    if( rc==SQLITE_OK ){
166393      rc = deleteCell(pRtree, pLeaf, iCell, 0);
166394    }
166395    rc2 = nodeRelease(pRtree, pLeaf);
166396    if( rc==SQLITE_OK ){
166397      rc = rc2;
166398    }
166399  }
166400
166401  /* Delete the corresponding entry in the <rtree>_rowid table. */
166402  if( rc==SQLITE_OK ){
166403    sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
166404    sqlite3_step(pRtree->pDeleteRowid);
166405    rc = sqlite3_reset(pRtree->pDeleteRowid);
166406  }
166407
166408  /* Check if the root node now has exactly one child. If so, remove
166409  ** it, schedule the contents of the child for reinsertion and
166410  ** reduce the tree height by one.
166411  **
166412  ** This is equivalent to copying the contents of the child into
166413  ** the root node (the operation that Gutman's paper says to perform
166414  ** in this scenario).
166415  */
166416  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
166417    int rc2;
166418    RtreeNode *pChild;
166419    i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
166420    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
166421    if( rc==SQLITE_OK ){
166422      rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
166423    }
166424    rc2 = nodeRelease(pRtree, pChild);
166425    if( rc==SQLITE_OK ) rc = rc2;
166426    if( rc==SQLITE_OK ){
166427      pRtree->iDepth--;
166428      writeInt16(pRoot->zData, pRtree->iDepth);
166429      pRoot->isDirty = 1;
166430    }
166431  }
166432
166433  /* Re-insert the contents of any underfull nodes removed from the tree. */
166434  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
166435    if( rc==SQLITE_OK ){
166436      rc = reinsertNodeContent(pRtree, pLeaf);
166437    }
166438    pRtree->pDeleted = pLeaf->pNext;
166439    sqlite3_free(pLeaf);
166440  }
166441
166442  /* Release the reference to the root node. */
166443  if( rc==SQLITE_OK ){
166444    rc = nodeRelease(pRtree, pRoot);
166445  }else{
166446    nodeRelease(pRtree, pRoot);
166447  }
166448
166449  return rc;
166450}
166451
166452/*
166453** Rounding constants for float->double conversion.
166454*/
166455#define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
166456#define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
166457
166458#if !defined(SQLITE_RTREE_INT_ONLY)
166459/*
166460** Convert an sqlite3_value into an RtreeValue (presumably a float)
166461** while taking care to round toward negative or positive, respectively.
166462*/
166463static RtreeValue rtreeValueDown(sqlite3_value *v){
166464  double d = sqlite3_value_double(v);
166465  float f = (float)d;
166466  if( f>d ){
166467    f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
166468  }
166469  return f;
166470}
166471static RtreeValue rtreeValueUp(sqlite3_value *v){
166472  double d = sqlite3_value_double(v);
166473  float f = (float)d;
166474  if( f<d ){
166475    f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
166476  }
166477  return f;
166478}
166479#endif /* !defined(SQLITE_RTREE_INT_ONLY) */
166480
166481/*
166482** A constraint has failed while inserting a row into an rtree table.
166483** Assuming no OOM error occurs, this function sets the error message
166484** (at pRtree->base.zErrMsg) to an appropriate value and returns
166485** SQLITE_CONSTRAINT.
166486**
166487** Parameter iCol is the index of the leftmost column involved in the
166488** constraint failure. If it is 0, then the constraint that failed is
166489** the unique constraint on the id column. Otherwise, it is the rtree
166490** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
166491**
166492** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
166493*/
166494static int rtreeConstraintError(Rtree *pRtree, int iCol){
166495  sqlite3_stmt *pStmt = 0;
166496  char *zSql;
166497  int rc;
166498
166499  assert( iCol==0 || iCol%2 );
166500  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
166501  if( zSql ){
166502    rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
166503  }else{
166504    rc = SQLITE_NOMEM;
166505  }
166506  sqlite3_free(zSql);
166507
166508  if( rc==SQLITE_OK ){
166509    if( iCol==0 ){
166510      const char *zCol = sqlite3_column_name(pStmt, 0);
166511      pRtree->base.zErrMsg = sqlite3_mprintf(
166512          "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
166513      );
166514    }else{
166515      const char *zCol1 = sqlite3_column_name(pStmt, iCol);
166516      const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
166517      pRtree->base.zErrMsg = sqlite3_mprintf(
166518          "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
166519      );
166520    }
166521  }
166522
166523  sqlite3_finalize(pStmt);
166524  return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
166525}
166526
166527
166528
166529/*
166530** The xUpdate method for rtree module virtual tables.
166531*/
166532static int rtreeUpdate(
166533  sqlite3_vtab *pVtab,
166534  int nData,
166535  sqlite3_value **azData,
166536  sqlite_int64 *pRowid
166537){
166538  Rtree *pRtree = (Rtree *)pVtab;
166539  int rc = SQLITE_OK;
166540  RtreeCell cell;                 /* New cell to insert if nData>1 */
166541  int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
166542
166543  rtreeReference(pRtree);
166544  assert(nData>=1);
166545
166546  cell.iRowid = 0;  /* Used only to suppress a compiler warning */
166547
166548  /* Constraint handling. A write operation on an r-tree table may return
166549  ** SQLITE_CONSTRAINT for two reasons:
166550  **
166551  **   1. A duplicate rowid value, or
166552  **   2. The supplied data violates the "x2>=x1" constraint.
166553  **
166554  ** In the first case, if the conflict-handling mode is REPLACE, then
166555  ** the conflicting row can be removed before proceeding. In the second
166556  ** case, SQLITE_CONSTRAINT must be returned regardless of the
166557  ** conflict-handling mode specified by the user.
166558  */
166559  if( nData>1 ){
166560    int ii;
166561
166562    /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
166563    **
166564    ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
166565    ** with "column" that are interpreted as table constraints.
166566    ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
166567    ** This problem was discovered after years of use, so we silently ignore
166568    ** these kinds of misdeclared tables to avoid breaking any legacy.
166569    */
166570    assert( nData<=(pRtree->nDim2 + 3) );
166571
166572#ifndef SQLITE_RTREE_INT_ONLY
166573    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
166574      for(ii=0; ii<nData-4; ii+=2){
166575        cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
166576        cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
166577        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
166578          rc = rtreeConstraintError(pRtree, ii+1);
166579          goto constraint;
166580        }
166581      }
166582    }else
166583#endif
166584    {
166585      for(ii=0; ii<nData-4; ii+=2){
166586        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
166587        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
166588        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
166589          rc = rtreeConstraintError(pRtree, ii+1);
166590          goto constraint;
166591        }
166592      }
166593    }
166594
166595    /* If a rowid value was supplied, check if it is already present in
166596    ** the table. If so, the constraint has failed. */
166597    if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
166598      cell.iRowid = sqlite3_value_int64(azData[2]);
166599      if( sqlite3_value_type(azData[0])==SQLITE_NULL
166600       || sqlite3_value_int64(azData[0])!=cell.iRowid
166601      ){
166602        int steprc;
166603        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
166604        steprc = sqlite3_step(pRtree->pReadRowid);
166605        rc = sqlite3_reset(pRtree->pReadRowid);
166606        if( SQLITE_ROW==steprc ){
166607          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
166608            rc = rtreeDeleteRowid(pRtree, cell.iRowid);
166609          }else{
166610            rc = rtreeConstraintError(pRtree, 0);
166611            goto constraint;
166612          }
166613        }
166614      }
166615      bHaveRowid = 1;
166616    }
166617  }
166618
166619  /* If azData[0] is not an SQL NULL value, it is the rowid of a
166620  ** record to delete from the r-tree table. The following block does
166621  ** just that.
166622  */
166623  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
166624    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
166625  }
166626
166627  /* If the azData[] array contains more than one element, elements
166628  ** (azData[2]..azData[argc-1]) contain a new record to insert into
166629  ** the r-tree structure.
166630  */
166631  if( rc==SQLITE_OK && nData>1 ){
166632    /* Insert the new record into the r-tree */
166633    RtreeNode *pLeaf = 0;
166634
166635    /* Figure out the rowid of the new row. */
166636    if( bHaveRowid==0 ){
166637      rc = newRowid(pRtree, &cell.iRowid);
166638    }
166639    *pRowid = cell.iRowid;
166640
166641    if( rc==SQLITE_OK ){
166642      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
166643    }
166644    if( rc==SQLITE_OK ){
166645      int rc2;
166646      pRtree->iReinsertHeight = -1;
166647      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
166648      rc2 = nodeRelease(pRtree, pLeaf);
166649      if( rc==SQLITE_OK ){
166650        rc = rc2;
166651      }
166652    }
166653  }
166654
166655constraint:
166656  rtreeRelease(pRtree);
166657  return rc;
166658}
166659
166660/*
166661** Called when a transaction starts.
166662*/
166663static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
166664  Rtree *pRtree = (Rtree *)pVtab;
166665  assert( pRtree->inWrTrans==0 );
166666  pRtree->inWrTrans++;
166667  return SQLITE_OK;
166668}
166669
166670/*
166671** Called when a transaction completes (either by COMMIT or ROLLBACK).
166672** The sqlite3_blob object should be released at this point.
166673*/
166674static int rtreeEndTransaction(sqlite3_vtab *pVtab){
166675  Rtree *pRtree = (Rtree *)pVtab;
166676  pRtree->inWrTrans = 0;
166677  nodeBlobReset(pRtree);
166678  return SQLITE_OK;
166679}
166680
166681/*
166682** The xRename method for rtree module virtual tables.
166683*/
166684static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
166685  Rtree *pRtree = (Rtree *)pVtab;
166686  int rc = SQLITE_NOMEM;
166687  char *zSql = sqlite3_mprintf(
166688    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
166689    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
166690    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
166691    , pRtree->zDb, pRtree->zName, zNewName
166692    , pRtree->zDb, pRtree->zName, zNewName
166693    , pRtree->zDb, pRtree->zName, zNewName
166694  );
166695  if( zSql ){
166696    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
166697    sqlite3_free(zSql);
166698  }
166699  return rc;
166700}
166701
166702
166703/*
166704** This function populates the pRtree->nRowEst variable with an estimate
166705** of the number of rows in the virtual table. If possible, this is based
166706** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
166707*/
166708static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
166709  const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
166710  char *zSql;
166711  sqlite3_stmt *p;
166712  int rc;
166713  i64 nRow = 0;
166714
166715  rc = sqlite3_table_column_metadata(
166716      db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
166717  );
166718  if( rc!=SQLITE_OK ){
166719    pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
166720    return rc==SQLITE_ERROR ? SQLITE_OK : rc;
166721  }
166722  zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
166723  if( zSql==0 ){
166724    rc = SQLITE_NOMEM;
166725  }else{
166726    rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
166727    if( rc==SQLITE_OK ){
166728      if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
166729      rc = sqlite3_finalize(p);
166730    }else if( rc!=SQLITE_NOMEM ){
166731      rc = SQLITE_OK;
166732    }
166733
166734    if( rc==SQLITE_OK ){
166735      if( nRow==0 ){
166736        pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
166737      }else{
166738        pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
166739      }
166740    }
166741    sqlite3_free(zSql);
166742  }
166743
166744  return rc;
166745}
166746
166747static sqlite3_module rtreeModule = {
166748  0,                          /* iVersion */
166749  rtreeCreate,                /* xCreate - create a table */
166750  rtreeConnect,               /* xConnect - connect to an existing table */
166751  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
166752  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
166753  rtreeDestroy,               /* xDestroy - Drop a table */
166754  rtreeOpen,                  /* xOpen - open a cursor */
166755  rtreeClose,                 /* xClose - close a cursor */
166756  rtreeFilter,                /* xFilter - configure scan constraints */
166757  rtreeNext,                  /* xNext - advance a cursor */
166758  rtreeEof,                   /* xEof */
166759  rtreeColumn,                /* xColumn - read data */
166760  rtreeRowid,                 /* xRowid - read data */
166761  rtreeUpdate,                /* xUpdate - write data */
166762  rtreeBeginTransaction,      /* xBegin - begin transaction */
166763  rtreeEndTransaction,        /* xSync - sync transaction */
166764  rtreeEndTransaction,        /* xCommit - commit transaction */
166765  rtreeEndTransaction,        /* xRollback - rollback transaction */
166766  0,                          /* xFindFunction - function overloading */
166767  rtreeRename,                /* xRename - rename the table */
166768  0,                          /* xSavepoint */
166769  0,                          /* xRelease */
166770  0,                          /* xRollbackTo */
166771};
166772
166773static int rtreeSqlInit(
166774  Rtree *pRtree,
166775  sqlite3 *db,
166776  const char *zDb,
166777  const char *zPrefix,
166778  int isCreate
166779){
166780  int rc = SQLITE_OK;
166781
166782  #define N_STATEMENT 8
166783  static const char *azSql[N_STATEMENT] = {
166784    /* Write the xxx_node table */
166785    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
166786    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
166787
166788    /* Read and write the xxx_rowid table */
166789    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
166790    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
166791    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
166792
166793    /* Read and write the xxx_parent table */
166794    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
166795    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
166796    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
166797  };
166798  sqlite3_stmt **appStmt[N_STATEMENT];
166799  int i;
166800
166801  pRtree->db = db;
166802
166803  if( isCreate ){
166804    char *zCreate = sqlite3_mprintf(
166805"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
166806"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
166807"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
166808                                  " parentnode INTEGER);"
166809"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
166810      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
166811    );
166812    if( !zCreate ){
166813      return SQLITE_NOMEM;
166814    }
166815    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
166816    sqlite3_free(zCreate);
166817    if( rc!=SQLITE_OK ){
166818      return rc;
166819    }
166820  }
166821
166822  appStmt[0] = &pRtree->pWriteNode;
166823  appStmt[1] = &pRtree->pDeleteNode;
166824  appStmt[2] = &pRtree->pReadRowid;
166825  appStmt[3] = &pRtree->pWriteRowid;
166826  appStmt[4] = &pRtree->pDeleteRowid;
166827  appStmt[5] = &pRtree->pReadParent;
166828  appStmt[6] = &pRtree->pWriteParent;
166829  appStmt[7] = &pRtree->pDeleteParent;
166830
166831  rc = rtreeQueryStat1(db, pRtree);
166832  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
166833    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
166834    if( zSql ){
166835      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
166836    }else{
166837      rc = SQLITE_NOMEM;
166838    }
166839    sqlite3_free(zSql);
166840  }
166841
166842  return rc;
166843}
166844
166845/*
166846** The second argument to this function contains the text of an SQL statement
166847** that returns a single integer value. The statement is compiled and executed
166848** using database connection db. If successful, the integer value returned
166849** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
166850** code is returned and the value of *piVal after returning is not defined.
166851*/
166852static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
166853  int rc = SQLITE_NOMEM;
166854  if( zSql ){
166855    sqlite3_stmt *pStmt = 0;
166856    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
166857    if( rc==SQLITE_OK ){
166858      if( SQLITE_ROW==sqlite3_step(pStmt) ){
166859        *piVal = sqlite3_column_int(pStmt, 0);
166860      }
166861      rc = sqlite3_finalize(pStmt);
166862    }
166863  }
166864  return rc;
166865}
166866
166867/*
166868** This function is called from within the xConnect() or xCreate() method to
166869** determine the node-size used by the rtree table being created or connected
166870** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
166871** Otherwise, an SQLite error code is returned.
166872**
166873** If this function is being called as part of an xConnect(), then the rtree
166874** table already exists. In this case the node-size is determined by inspecting
166875** the root node of the tree.
166876**
166877** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
166878** This ensures that each node is stored on a single database page. If the
166879** database page-size is so large that more than RTREE_MAXCELLS entries
166880** would fit in a single node, use a smaller node-size.
166881*/
166882static int getNodeSize(
166883  sqlite3 *db,                    /* Database handle */
166884  Rtree *pRtree,                  /* Rtree handle */
166885  int isCreate,                   /* True for xCreate, false for xConnect */
166886  char **pzErr                    /* OUT: Error message, if any */
166887){
166888  int rc;
166889  char *zSql;
166890  if( isCreate ){
166891    int iPageSize = 0;
166892    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
166893    rc = getIntFromStmt(db, zSql, &iPageSize);
166894    if( rc==SQLITE_OK ){
166895      pRtree->iNodeSize = iPageSize-64;
166896      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
166897        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
166898      }
166899    }else{
166900      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
166901    }
166902  }else{
166903    zSql = sqlite3_mprintf(
166904        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
166905        pRtree->zDb, pRtree->zName
166906    );
166907    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
166908    if( rc!=SQLITE_OK ){
166909      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
166910    }
166911  }
166912
166913  sqlite3_free(zSql);
166914  return rc;
166915}
166916
166917/*
166918** This function is the implementation of both the xConnect and xCreate
166919** methods of the r-tree virtual table.
166920**
166921**   argv[0]   -> module name
166922**   argv[1]   -> database name
166923**   argv[2]   -> table name
166924**   argv[...] -> column names...
166925*/
166926static int rtreeInit(
166927  sqlite3 *db,                        /* Database connection */
166928  void *pAux,                         /* One of the RTREE_COORD_* constants */
166929  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
166930  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
166931  char **pzErr,                       /* OUT: Error message, if any */
166932  int isCreate                        /* True for xCreate, false for xConnect */
166933){
166934  int rc = SQLITE_OK;
166935  Rtree *pRtree;
166936  int nDb;              /* Length of string argv[1] */
166937  int nName;            /* Length of string argv[2] */
166938  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
166939
166940  const char *aErrMsg[] = {
166941    0,                                                    /* 0 */
166942    "Wrong number of columns for an rtree table",         /* 1 */
166943    "Too few columns for an rtree table",                 /* 2 */
166944    "Too many columns for an rtree table"                 /* 3 */
166945  };
166946
166947  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
166948  if( aErrMsg[iErr] ){
166949    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
166950    return SQLITE_ERROR;
166951  }
166952
166953  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
166954
166955  /* Allocate the sqlite3_vtab structure */
166956  nDb = (int)strlen(argv[1]);
166957  nName = (int)strlen(argv[2]);
166958  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
166959  if( !pRtree ){
166960    return SQLITE_NOMEM;
166961  }
166962  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
166963  pRtree->nBusy = 1;
166964  pRtree->base.pModule = &rtreeModule;
166965  pRtree->zDb = (char *)&pRtree[1];
166966  pRtree->zName = &pRtree->zDb[nDb+1];
166967  pRtree->nDim = (u8)((argc-4)/2);
166968  pRtree->nDim2 = pRtree->nDim*2;
166969  pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
166970  pRtree->eCoordType = (u8)eCoordType;
166971  memcpy(pRtree->zDb, argv[1], nDb);
166972  memcpy(pRtree->zName, argv[2], nName);
166973
166974  /* Figure out the node size to use. */
166975  rc = getNodeSize(db, pRtree, isCreate, pzErr);
166976
166977  /* Create/Connect to the underlying relational database schema. If
166978  ** that is successful, call sqlite3_declare_vtab() to configure
166979  ** the r-tree table schema.
166980  */
166981  if( rc==SQLITE_OK ){
166982    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
166983      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
166984    }else{
166985      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
166986      char *zTmp;
166987      int ii;
166988      for(ii=4; zSql && ii<argc; ii++){
166989        zTmp = zSql;
166990        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
166991        sqlite3_free(zTmp);
166992      }
166993      if( zSql ){
166994        zTmp = zSql;
166995        zSql = sqlite3_mprintf("%s);", zTmp);
166996        sqlite3_free(zTmp);
166997      }
166998      if( !zSql ){
166999        rc = SQLITE_NOMEM;
167000      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
167001        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
167002      }
167003      sqlite3_free(zSql);
167004    }
167005  }
167006
167007  if( rc==SQLITE_OK ){
167008    *ppVtab = (sqlite3_vtab *)pRtree;
167009  }else{
167010    assert( *ppVtab==0 );
167011    assert( pRtree->nBusy==1 );
167012    rtreeRelease(pRtree);
167013  }
167014  return rc;
167015}
167016
167017
167018/*
167019** Implementation of a scalar function that decodes r-tree nodes to
167020** human readable strings. This can be used for debugging and analysis.
167021**
167022** The scalar function takes two arguments: (1) the number of dimensions
167023** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
167024** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
167025** deserialize all nodes, a statement like:
167026**
167027**   SELECT rtreenode(2, data) FROM rt_node;
167028**
167029** The human readable string takes the form of a Tcl list with one
167030** entry for each cell in the r-tree node. Each entry is itself a
167031** list, containing the 8-byte rowid/pageno followed by the
167032** <num-dimension>*2 coordinates.
167033*/
167034static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
167035  char *zText = 0;
167036  RtreeNode node;
167037  Rtree tree;
167038  int ii;
167039
167040  UNUSED_PARAMETER(nArg);
167041  memset(&node, 0, sizeof(RtreeNode));
167042  memset(&tree, 0, sizeof(Rtree));
167043  tree.nDim = (u8)sqlite3_value_int(apArg[0]);
167044  tree.nDim2 = tree.nDim*2;
167045  tree.nBytesPerCell = 8 + 8 * tree.nDim;
167046  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
167047
167048  for(ii=0; ii<NCELL(&node); ii++){
167049    char zCell[512];
167050    int nCell = 0;
167051    RtreeCell cell;
167052    int jj;
167053
167054    nodeGetCell(&tree, &node, ii, &cell);
167055    sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
167056    nCell = (int)strlen(zCell);
167057    for(jj=0; jj<tree.nDim2; jj++){
167058#ifndef SQLITE_RTREE_INT_ONLY
167059      sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
167060                       (double)cell.aCoord[jj].f);
167061#else
167062      sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
167063                       cell.aCoord[jj].i);
167064#endif
167065      nCell = (int)strlen(zCell);
167066    }
167067
167068    if( zText ){
167069      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
167070      sqlite3_free(zText);
167071      zText = zTextNew;
167072    }else{
167073      zText = sqlite3_mprintf("{%s}", zCell);
167074    }
167075  }
167076
167077  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
167078}
167079
167080/* This routine implements an SQL function that returns the "depth" parameter
167081** from the front of a blob that is an r-tree node.  For example:
167082**
167083**     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
167084**
167085** The depth value is 0 for all nodes other than the root node, and the root
167086** node always has nodeno=1, so the example above is the primary use for this
167087** routine.  This routine is intended for testing and analysis only.
167088*/
167089static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
167090  UNUSED_PARAMETER(nArg);
167091  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
167092   || sqlite3_value_bytes(apArg[0])<2
167093  ){
167094    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
167095  }else{
167096    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
167097    sqlite3_result_int(ctx, readInt16(zBlob));
167098  }
167099}
167100
167101/*
167102** Register the r-tree module with database handle db. This creates the
167103** virtual table module "rtree" and the debugging/analysis scalar
167104** function "rtreenode".
167105*/
167106SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
167107  const int utf8 = SQLITE_UTF8;
167108  int rc;
167109
167110  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
167111  if( rc==SQLITE_OK ){
167112    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
167113  }
167114  if( rc==SQLITE_OK ){
167115#ifdef SQLITE_RTREE_INT_ONLY
167116    void *c = (void *)RTREE_COORD_INT32;
167117#else
167118    void *c = (void *)RTREE_COORD_REAL32;
167119#endif
167120    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
167121  }
167122  if( rc==SQLITE_OK ){
167123    void *c = (void *)RTREE_COORD_INT32;
167124    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
167125  }
167126
167127  return rc;
167128}
167129
167130/*
167131** This routine deletes the RtreeGeomCallback object that was attached
167132** one of the SQL functions create by sqlite3_rtree_geometry_callback()
167133** or sqlite3_rtree_query_callback().  In other words, this routine is the
167134** destructor for an RtreeGeomCallback objecct.  This routine is called when
167135** the corresponding SQL function is deleted.
167136*/
167137static void rtreeFreeCallback(void *p){
167138  RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
167139  if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
167140  sqlite3_free(p);
167141}
167142
167143/*
167144** This routine frees the BLOB that is returned by geomCallback().
167145*/
167146static void rtreeMatchArgFree(void *pArg){
167147  int i;
167148  RtreeMatchArg *p = (RtreeMatchArg*)pArg;
167149  for(i=0; i<p->nParam; i++){
167150    sqlite3_value_free(p->apSqlParam[i]);
167151  }
167152  sqlite3_free(p);
167153}
167154
167155/*
167156** Each call to sqlite3_rtree_geometry_callback() or
167157** sqlite3_rtree_query_callback() creates an ordinary SQLite
167158** scalar function that is implemented by this routine.
167159**
167160** All this function does is construct an RtreeMatchArg object that
167161** contains the geometry-checking callback routines and a list of
167162** parameters to this function, then return that RtreeMatchArg object
167163** as a BLOB.
167164**
167165** The R-Tree MATCH operator will read the returned BLOB, deserialize
167166** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
167167** out which elements of the R-Tree should be returned by the query.
167168*/
167169static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
167170  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
167171  RtreeMatchArg *pBlob;
167172  int nBlob;
167173  int memErr = 0;
167174
167175  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
167176           + nArg*sizeof(sqlite3_value*);
167177  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
167178  if( !pBlob ){
167179    sqlite3_result_error_nomem(ctx);
167180  }else{
167181    int i;
167182    pBlob->magic = RTREE_GEOMETRY_MAGIC;
167183    pBlob->cb = pGeomCtx[0];
167184    pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
167185    pBlob->nParam = nArg;
167186    for(i=0; i<nArg; i++){
167187      pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
167188      if( pBlob->apSqlParam[i]==0 ) memErr = 1;
167189#ifdef SQLITE_RTREE_INT_ONLY
167190      pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
167191#else
167192      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
167193#endif
167194    }
167195    if( memErr ){
167196      sqlite3_result_error_nomem(ctx);
167197      rtreeMatchArgFree(pBlob);
167198    }else{
167199      sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
167200    }
167201  }
167202}
167203
167204/*
167205** Register a new geometry function for use with the r-tree MATCH operator.
167206*/
167207SQLITE_API int sqlite3_rtree_geometry_callback(
167208  sqlite3 *db,                  /* Register SQL function on this connection */
167209  const char *zGeom,            /* Name of the new SQL function */
167210  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
167211  void *pContext                /* Extra data associated with the callback */
167212){
167213  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
167214
167215  /* Allocate and populate the context object. */
167216  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
167217  if( !pGeomCtx ) return SQLITE_NOMEM;
167218  pGeomCtx->xGeom = xGeom;
167219  pGeomCtx->xQueryFunc = 0;
167220  pGeomCtx->xDestructor = 0;
167221  pGeomCtx->pContext = pContext;
167222  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
167223      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
167224  );
167225}
167226
167227/*
167228** Register a new 2nd-generation geometry function for use with the
167229** r-tree MATCH operator.
167230*/
167231SQLITE_API int sqlite3_rtree_query_callback(
167232  sqlite3 *db,                 /* Register SQL function on this connection */
167233  const char *zQueryFunc,      /* Name of new SQL function */
167234  int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
167235  void *pContext,              /* Extra data passed into the callback */
167236  void (*xDestructor)(void*)   /* Destructor for the extra data */
167237){
167238  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
167239
167240  /* Allocate and populate the context object. */
167241  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
167242  if( !pGeomCtx ) return SQLITE_NOMEM;
167243  pGeomCtx->xGeom = 0;
167244  pGeomCtx->xQueryFunc = xQueryFunc;
167245  pGeomCtx->xDestructor = xDestructor;
167246  pGeomCtx->pContext = pContext;
167247  return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
167248      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
167249  );
167250}
167251
167252#if !SQLITE_CORE
167253#ifdef _WIN32
167254__declspec(dllexport)
167255#endif
167256SQLITE_API int sqlite3_rtree_init(
167257  sqlite3 *db,
167258  char **pzErrMsg,
167259  const sqlite3_api_routines *pApi
167260){
167261  SQLITE_EXTENSION_INIT2(pApi)
167262  return sqlite3RtreeInit(db);
167263}
167264#endif
167265
167266#endif
167267
167268/************** End of rtree.c ***********************************************/
167269/************** Begin file icu.c *********************************************/
167270/*
167271** 2007 May 6
167272**
167273** The author disclaims copyright to this source code.  In place of
167274** a legal notice, here is a blessing:
167275**
167276**    May you do good and not evil.
167277**    May you find forgiveness for yourself and forgive others.
167278**    May you share freely, never taking more than you give.
167279**
167280*************************************************************************
167281** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
167282**
167283** This file implements an integration between the ICU library
167284** ("International Components for Unicode", an open-source library
167285** for handling unicode data) and SQLite. The integration uses
167286** ICU to provide the following to SQLite:
167287**
167288**   * An implementation of the SQL regexp() function (and hence REGEXP
167289**     operator) using the ICU uregex_XX() APIs.
167290**
167291**   * Implementations of the SQL scalar upper() and lower() functions
167292**     for case mapping.
167293**
167294**   * Integration of ICU and SQLite collation sequences.
167295**
167296**   * An implementation of the LIKE operator that uses ICU to
167297**     provide case-independent matching.
167298*/
167299
167300#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
167301
167302/* Include ICU headers */
167303#include <unicode/utypes.h>
167304#include <unicode/uregex.h>
167305#include <unicode/ustring.h>
167306#include <unicode/ucol.h>
167307
167308/* #include <assert.h> */
167309
167310#ifndef SQLITE_CORE
167311/*   #include "sqlite3ext.h" */
167312  SQLITE_EXTENSION_INIT1
167313#else
167314/*   #include "sqlite3.h" */
167315#endif
167316
167317/*
167318** Maximum length (in bytes) of the pattern in a LIKE or GLOB
167319** operator.
167320*/
167321#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
167322# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
167323#endif
167324
167325/*
167326** Version of sqlite3_free() that is always a function, never a macro.
167327*/
167328static void xFree(void *p){
167329  sqlite3_free(p);
167330}
167331
167332/*
167333** This lookup table is used to help decode the first byte of
167334** a multi-byte UTF8 character. It is copied here from SQLite source
167335** code file utf8.c.
167336*/
167337static const unsigned char icuUtf8Trans1[] = {
167338  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
167339  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
167340  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
167341  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
167342  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
167343  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
167344  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
167345  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
167346};
167347
167348#define SQLITE_ICU_READ_UTF8(zIn, c)                       \
167349  c = *(zIn++);                                            \
167350  if( c>=0xc0 ){                                           \
167351    c = icuUtf8Trans1[c-0xc0];                             \
167352    while( (*zIn & 0xc0)==0x80 ){                          \
167353      c = (c<<6) + (0x3f & *(zIn++));                      \
167354    }                                                      \
167355  }
167356
167357#define SQLITE_ICU_SKIP_UTF8(zIn)                          \
167358  assert( *zIn );                                          \
167359  if( *(zIn++)>=0xc0 ){                                    \
167360    while( (*zIn & 0xc0)==0x80 ){zIn++;}                   \
167361  }
167362
167363
167364/*
167365** Compare two UTF-8 strings for equality where the first string is
167366** a "LIKE" expression. Return true (1) if they are the same and
167367** false (0) if they are different.
167368*/
167369static int icuLikeCompare(
167370  const uint8_t *zPattern,   /* LIKE pattern */
167371  const uint8_t *zString,    /* The UTF-8 string to compare against */
167372  const UChar32 uEsc         /* The escape character */
167373){
167374  static const int MATCH_ONE = (UChar32)'_';
167375  static const int MATCH_ALL = (UChar32)'%';
167376
167377  int prevEscape = 0;     /* True if the previous character was uEsc */
167378
167379  while( 1 ){
167380
167381    /* Read (and consume) the next character from the input pattern. */
167382    UChar32 uPattern;
167383    SQLITE_ICU_READ_UTF8(zPattern, uPattern);
167384    if( uPattern==0 ) break;
167385
167386    /* There are now 4 possibilities:
167387    **
167388    **     1. uPattern is an unescaped match-all character "%",
167389    **     2. uPattern is an unescaped match-one character "_",
167390    **     3. uPattern is an unescaped escape character, or
167391    **     4. uPattern is to be handled as an ordinary character
167392    */
167393    if( !prevEscape && uPattern==MATCH_ALL ){
167394      /* Case 1. */
167395      uint8_t c;
167396
167397      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
167398      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
167399      ** test string.
167400      */
167401      while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
167402        if( c==MATCH_ONE ){
167403          if( *zString==0 ) return 0;
167404          SQLITE_ICU_SKIP_UTF8(zString);
167405        }
167406        zPattern++;
167407      }
167408
167409      if( *zPattern==0 ) return 1;
167410
167411      while( *zString ){
167412        if( icuLikeCompare(zPattern, zString, uEsc) ){
167413          return 1;
167414        }
167415        SQLITE_ICU_SKIP_UTF8(zString);
167416      }
167417      return 0;
167418
167419    }else if( !prevEscape && uPattern==MATCH_ONE ){
167420      /* Case 2. */
167421      if( *zString==0 ) return 0;
167422      SQLITE_ICU_SKIP_UTF8(zString);
167423
167424    }else if( !prevEscape && uPattern==uEsc){
167425      /* Case 3. */
167426      prevEscape = 1;
167427
167428    }else{
167429      /* Case 4. */
167430      UChar32 uString;
167431      SQLITE_ICU_READ_UTF8(zString, uString);
167432      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
167433      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
167434      if( uString!=uPattern ){
167435        return 0;
167436      }
167437      prevEscape = 0;
167438    }
167439  }
167440
167441  return *zString==0;
167442}
167443
167444/*
167445** Implementation of the like() SQL function.  This function implements
167446** the build-in LIKE operator.  The first argument to the function is the
167447** pattern and the second argument is the string.  So, the SQL statements:
167448**
167449**       A LIKE B
167450**
167451** is implemented as like(B, A). If there is an escape character E,
167452**
167453**       A LIKE B ESCAPE E
167454**
167455** is mapped to like(B, A, E).
167456*/
167457static void icuLikeFunc(
167458  sqlite3_context *context,
167459  int argc,
167460  sqlite3_value **argv
167461){
167462  const unsigned char *zA = sqlite3_value_text(argv[0]);
167463  const unsigned char *zB = sqlite3_value_text(argv[1]);
167464  UChar32 uEsc = 0;
167465
167466  /* Limit the length of the LIKE or GLOB pattern to avoid problems
167467  ** of deep recursion and N*N behavior in patternCompare().
167468  */
167469  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
167470    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
167471    return;
167472  }
167473
167474
167475  if( argc==3 ){
167476    /* The escape character string must consist of a single UTF-8 character.
167477    ** Otherwise, return an error.
167478    */
167479    int nE= sqlite3_value_bytes(argv[2]);
167480    const unsigned char *zE = sqlite3_value_text(argv[2]);
167481    int i = 0;
167482    if( zE==0 ) return;
167483    U8_NEXT(zE, i, nE, uEsc);
167484    if( i!=nE){
167485      sqlite3_result_error(context,
167486          "ESCAPE expression must be a single character", -1);
167487      return;
167488    }
167489  }
167490
167491  if( zA && zB ){
167492    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
167493  }
167494}
167495
167496/*
167497** This function is called when an ICU function called from within
167498** the implementation of an SQL scalar function returns an error.
167499**
167500** The scalar function context passed as the first argument is
167501** loaded with an error message based on the following two args.
167502*/
167503static void icuFunctionError(
167504  sqlite3_context *pCtx,       /* SQLite scalar function context */
167505  const char *zName,           /* Name of ICU function that failed */
167506  UErrorCode e                 /* Error code returned by ICU function */
167507){
167508  char zBuf[128];
167509  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
167510  zBuf[127] = '\0';
167511  sqlite3_result_error(pCtx, zBuf, -1);
167512}
167513
167514/*
167515** Function to delete compiled regexp objects. Registered as
167516** a destructor function with sqlite3_set_auxdata().
167517*/
167518static void icuRegexpDelete(void *p){
167519  URegularExpression *pExpr = (URegularExpression *)p;
167520  uregex_close(pExpr);
167521}
167522
167523/*
167524** Implementation of SQLite REGEXP operator. This scalar function takes
167525** two arguments. The first is a regular expression pattern to compile
167526** the second is a string to match against that pattern. If either
167527** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
167528** is 1 if the string matches the pattern, or 0 otherwise.
167529**
167530** SQLite maps the regexp() function to the regexp() operator such
167531** that the following two are equivalent:
167532**
167533**     zString REGEXP zPattern
167534**     regexp(zPattern, zString)
167535**
167536** Uses the following ICU regexp APIs:
167537**
167538**     uregex_open()
167539**     uregex_matches()
167540**     uregex_close()
167541*/
167542static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
167543  UErrorCode status = U_ZERO_ERROR;
167544  URegularExpression *pExpr;
167545  UBool res;
167546  const UChar *zString = sqlite3_value_text16(apArg[1]);
167547
167548  (void)nArg;  /* Unused parameter */
167549
167550  /* If the left hand side of the regexp operator is NULL,
167551  ** then the result is also NULL.
167552  */
167553  if( !zString ){
167554    return;
167555  }
167556
167557  pExpr = sqlite3_get_auxdata(p, 0);
167558  if( !pExpr ){
167559    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
167560    if( !zPattern ){
167561      return;
167562    }
167563    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
167564
167565    if( U_SUCCESS(status) ){
167566      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
167567    }else{
167568      assert(!pExpr);
167569      icuFunctionError(p, "uregex_open", status);
167570      return;
167571    }
167572  }
167573
167574  /* Configure the text that the regular expression operates on. */
167575  uregex_setText(pExpr, zString, -1, &status);
167576  if( !U_SUCCESS(status) ){
167577    icuFunctionError(p, "uregex_setText", status);
167578    return;
167579  }
167580
167581  /* Attempt the match */
167582  res = uregex_matches(pExpr, 0, &status);
167583  if( !U_SUCCESS(status) ){
167584    icuFunctionError(p, "uregex_matches", status);
167585    return;
167586  }
167587
167588  /* Set the text that the regular expression operates on to a NULL
167589  ** pointer. This is not really necessary, but it is tidier than
167590  ** leaving the regular expression object configured with an invalid
167591  ** pointer after this function returns.
167592  */
167593  uregex_setText(pExpr, 0, 0, &status);
167594
167595  /* Return 1 or 0. */
167596  sqlite3_result_int(p, res ? 1 : 0);
167597}
167598
167599/*
167600** Implementations of scalar functions for case mapping - upper() and
167601** lower(). Function upper() converts its input to upper-case (ABC).
167602** Function lower() converts to lower-case (abc).
167603**
167604** ICU provides two types of case mapping, "general" case mapping and
167605** "language specific". Refer to ICU documentation for the differences
167606** between the two.
167607**
167608** To utilise "general" case mapping, the upper() or lower() scalar
167609** functions are invoked with one argument:
167610**
167611**     upper('ABC') -> 'abc'
167612**     lower('abc') -> 'ABC'
167613**
167614** To access ICU "language specific" case mapping, upper() or lower()
167615** should be invoked with two arguments. The second argument is the name
167616** of the locale to use. Passing an empty string ("") or SQL NULL value
167617** as the second argument is the same as invoking the 1 argument version
167618** of upper() or lower().
167619**
167620**     lower('I', 'en_us') -> 'i'
167621**     lower('I', 'tr_tr') -> '\u131' (small dotless i)
167622**
167623** http://www.icu-project.org/userguide/posix.html#case_mappings
167624*/
167625static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
167626  const UChar *zInput;            /* Pointer to input string */
167627  UChar *zOutput = 0;             /* Pointer to output buffer */
167628  int nInput;                     /* Size of utf-16 input string in bytes */
167629  int nOut;                       /* Size of output buffer in bytes */
167630  int cnt;
167631  int bToUpper;                   /* True for toupper(), false for tolower() */
167632  UErrorCode status;
167633  const char *zLocale = 0;
167634
167635  assert(nArg==1 || nArg==2);
167636  bToUpper = (sqlite3_user_data(p)!=0);
167637  if( nArg==2 ){
167638    zLocale = (const char *)sqlite3_value_text(apArg[1]);
167639  }
167640
167641  zInput = sqlite3_value_text16(apArg[0]);
167642  if( !zInput ){
167643    return;
167644  }
167645  nOut = nInput = sqlite3_value_bytes16(apArg[0]);
167646  if( nOut==0 ){
167647    sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
167648    return;
167649  }
167650
167651  for(cnt=0; cnt<2; cnt++){
167652    UChar *zNew = sqlite3_realloc(zOutput, nOut);
167653    if( zNew==0 ){
167654      sqlite3_free(zOutput);
167655      sqlite3_result_error_nomem(p);
167656      return;
167657    }
167658    zOutput = zNew;
167659    status = U_ZERO_ERROR;
167660    if( bToUpper ){
167661      nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
167662    }else{
167663      nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
167664    }
167665
167666    if( U_SUCCESS(status) ){
167667      sqlite3_result_text16(p, zOutput, nOut, xFree);
167668    }else if( status==U_BUFFER_OVERFLOW_ERROR ){
167669      assert( cnt==0 );
167670      continue;
167671    }else{
167672      icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
167673    }
167674    return;
167675  }
167676  assert( 0 );     /* Unreachable */
167677}
167678
167679/*
167680** Collation sequence destructor function. The pCtx argument points to
167681** a UCollator structure previously allocated using ucol_open().
167682*/
167683static void icuCollationDel(void *pCtx){
167684  UCollator *p = (UCollator *)pCtx;
167685  ucol_close(p);
167686}
167687
167688/*
167689** Collation sequence comparison function. The pCtx argument points to
167690** a UCollator structure previously allocated using ucol_open().
167691*/
167692static int icuCollationColl(
167693  void *pCtx,
167694  int nLeft,
167695  const void *zLeft,
167696  int nRight,
167697  const void *zRight
167698){
167699  UCollationResult res;
167700  UCollator *p = (UCollator *)pCtx;
167701  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
167702  switch( res ){
167703    case UCOL_LESS:    return -1;
167704    case UCOL_GREATER: return +1;
167705    case UCOL_EQUAL:   return 0;
167706  }
167707  assert(!"Unexpected return value from ucol_strcoll()");
167708  return 0;
167709}
167710
167711/*
167712** Implementation of the scalar function icu_load_collation().
167713**
167714** This scalar function is used to add ICU collation based collation
167715** types to an SQLite database connection. It is intended to be called
167716** as follows:
167717**
167718**     SELECT icu_load_collation(<locale>, <collation-name>);
167719**
167720** Where <locale> is a string containing an ICU locale identifier (i.e.
167721** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
167722** collation sequence to create.
167723*/
167724static void icuLoadCollation(
167725  sqlite3_context *p,
167726  int nArg,
167727  sqlite3_value **apArg
167728){
167729  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
167730  UErrorCode status = U_ZERO_ERROR;
167731  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
167732  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
167733  UCollator *pUCollator;    /* ICU library collation object */
167734  int rc;                   /* Return code from sqlite3_create_collation_x() */
167735
167736  assert(nArg==2);
167737  (void)nArg; /* Unused parameter */
167738  zLocale = (const char *)sqlite3_value_text(apArg[0]);
167739  zName = (const char *)sqlite3_value_text(apArg[1]);
167740
167741  if( !zLocale || !zName ){
167742    return;
167743  }
167744
167745  pUCollator = ucol_open(zLocale, &status);
167746  if( !U_SUCCESS(status) ){
167747    icuFunctionError(p, "ucol_open", status);
167748    return;
167749  }
167750  assert(p);
167751
167752  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
167753      icuCollationColl, icuCollationDel
167754  );
167755  if( rc!=SQLITE_OK ){
167756    ucol_close(pUCollator);
167757    sqlite3_result_error(p, "Error registering collation function", -1);
167758  }
167759}
167760
167761/*
167762** Register the ICU extension functions with database db.
167763*/
167764SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
167765  static const struct IcuScalar {
167766    const char *zName;                        /* Function name */
167767    unsigned char nArg;                       /* Number of arguments */
167768    unsigned short enc;                       /* Optimal text encoding */
167769    unsigned char iContext;                   /* sqlite3_user_data() context */
167770    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
167771  } scalars[] = {
167772    {"icu_load_collation",  2, SQLITE_UTF8,                1, icuLoadCollation},
167773    {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC,         0, icuRegexpFunc},
167774    {"lower",  1, SQLITE_UTF16|SQLITE_DETERMINISTIC,       0, icuCaseFunc16},
167775    {"lower",  2, SQLITE_UTF16|SQLITE_DETERMINISTIC,       0, icuCaseFunc16},
167776    {"upper",  1, SQLITE_UTF16|SQLITE_DETERMINISTIC,       1, icuCaseFunc16},
167777    {"upper",  2, SQLITE_UTF16|SQLITE_DETERMINISTIC,       1, icuCaseFunc16},
167778    {"lower",  1, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuCaseFunc16},
167779    {"lower",  2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuCaseFunc16},
167780    {"upper",  1, SQLITE_UTF8|SQLITE_DETERMINISTIC,        1, icuCaseFunc16},
167781    {"upper",  2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        1, icuCaseFunc16},
167782    {"like",   2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuLikeFunc},
167783    {"like",   3, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuLikeFunc},
167784  };
167785  int rc = SQLITE_OK;
167786  int i;
167787
167788
167789  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
167790    const struct IcuScalar *p = &scalars[i];
167791    rc = sqlite3_create_function(
167792        db, p->zName, p->nArg, p->enc,
167793        p->iContext ? (void*)db : (void*)0,
167794        p->xFunc, 0, 0
167795    );
167796  }
167797
167798  return rc;
167799}
167800
167801#if !SQLITE_CORE
167802#ifdef _WIN32
167803__declspec(dllexport)
167804#endif
167805SQLITE_API int sqlite3_icu_init(
167806  sqlite3 *db,
167807  char **pzErrMsg,
167808  const sqlite3_api_routines *pApi
167809){
167810  SQLITE_EXTENSION_INIT2(pApi)
167811  return sqlite3IcuInit(db);
167812}
167813#endif
167814
167815#endif
167816
167817/************** End of icu.c *************************************************/
167818/************** Begin file fts3_icu.c ****************************************/
167819/*
167820** 2007 June 22
167821**
167822** The author disclaims copyright to this source code.  In place of
167823** a legal notice, here is a blessing:
167824**
167825**    May you do good and not evil.
167826**    May you find forgiveness for yourself and forgive others.
167827**    May you share freely, never taking more than you give.
167828**
167829*************************************************************************
167830** This file implements a tokenizer for fts3 based on the ICU library.
167831*/
167832/* #include "fts3Int.h" */
167833#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
167834#ifdef SQLITE_ENABLE_ICU
167835
167836/* #include <assert.h> */
167837/* #include <string.h> */
167838/* #include "fts3_tokenizer.h" */
167839
167840#include <unicode/ubrk.h>
167841/* #include <unicode/ucol.h> */
167842/* #include <unicode/ustring.h> */
167843#include <unicode/utf16.h>
167844
167845typedef struct IcuTokenizer IcuTokenizer;
167846typedef struct IcuCursor IcuCursor;
167847
167848struct IcuTokenizer {
167849  sqlite3_tokenizer base;
167850  char *zLocale;
167851};
167852
167853struct IcuCursor {
167854  sqlite3_tokenizer_cursor base;
167855
167856  UBreakIterator *pIter;      /* ICU break-iterator object */
167857  int nChar;                  /* Number of UChar elements in pInput */
167858  UChar *aChar;               /* Copy of input using utf-16 encoding */
167859  int *aOffset;               /* Offsets of each character in utf-8 input */
167860
167861  int nBuffer;
167862  char *zBuffer;
167863
167864  int iToken;
167865};
167866
167867/*
167868** Create a new tokenizer instance.
167869*/
167870static int icuCreate(
167871  int argc,                            /* Number of entries in argv[] */
167872  const char * const *argv,            /* Tokenizer creation arguments */
167873  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
167874){
167875  IcuTokenizer *p;
167876  int n = 0;
167877
167878  if( argc>0 ){
167879    n = strlen(argv[0])+1;
167880  }
167881  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
167882  if( !p ){
167883    return SQLITE_NOMEM;
167884  }
167885  memset(p, 0, sizeof(IcuTokenizer));
167886
167887  if( n ){
167888    p->zLocale = (char *)&p[1];
167889    memcpy(p->zLocale, argv[0], n);
167890  }
167891
167892  *ppTokenizer = (sqlite3_tokenizer *)p;
167893
167894  return SQLITE_OK;
167895}
167896
167897/*
167898** Destroy a tokenizer
167899*/
167900static int icuDestroy(sqlite3_tokenizer *pTokenizer){
167901  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
167902  sqlite3_free(p);
167903  return SQLITE_OK;
167904}
167905
167906/*
167907** Prepare to begin tokenizing a particular string.  The input
167908** string to be tokenized is pInput[0..nBytes-1].  A cursor
167909** used to incrementally tokenize this string is returned in
167910** *ppCursor.
167911*/
167912static int icuOpen(
167913  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
167914  const char *zInput,                    /* Input string */
167915  int nInput,                            /* Length of zInput in bytes */
167916  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
167917){
167918  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
167919  IcuCursor *pCsr;
167920
167921  const int32_t opt = U_FOLD_CASE_DEFAULT;
167922  UErrorCode status = U_ZERO_ERROR;
167923  int nChar;
167924
167925  UChar32 c;
167926  int iInput = 0;
167927  int iOut = 0;
167928
167929  *ppCursor = 0;
167930
167931  if( zInput==0 ){
167932    nInput = 0;
167933    zInput = "";
167934  }else if( nInput<0 ){
167935    nInput = strlen(zInput);
167936  }
167937  nChar = nInput+1;
167938  pCsr = (IcuCursor *)sqlite3_malloc(
167939      sizeof(IcuCursor) +                /* IcuCursor */
167940      ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
167941      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
167942  );
167943  if( !pCsr ){
167944    return SQLITE_NOMEM;
167945  }
167946  memset(pCsr, 0, sizeof(IcuCursor));
167947  pCsr->aChar = (UChar *)&pCsr[1];
167948  pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
167949
167950  pCsr->aOffset[iOut] = iInput;
167951  U8_NEXT(zInput, iInput, nInput, c);
167952  while( c>0 ){
167953    int isError = 0;
167954    c = u_foldCase(c, opt);
167955    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
167956    if( isError ){
167957      sqlite3_free(pCsr);
167958      return SQLITE_ERROR;
167959    }
167960    pCsr->aOffset[iOut] = iInput;
167961
167962    if( iInput<nInput ){
167963      U8_NEXT(zInput, iInput, nInput, c);
167964    }else{
167965      c = 0;
167966    }
167967  }
167968
167969  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
167970  if( !U_SUCCESS(status) ){
167971    sqlite3_free(pCsr);
167972    return SQLITE_ERROR;
167973  }
167974  pCsr->nChar = iOut;
167975
167976  ubrk_first(pCsr->pIter);
167977  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
167978  return SQLITE_OK;
167979}
167980
167981/*
167982** Close a tokenization cursor previously opened by a call to icuOpen().
167983*/
167984static int icuClose(sqlite3_tokenizer_cursor *pCursor){
167985  IcuCursor *pCsr = (IcuCursor *)pCursor;
167986  ubrk_close(pCsr->pIter);
167987  sqlite3_free(pCsr->zBuffer);
167988  sqlite3_free(pCsr);
167989  return SQLITE_OK;
167990}
167991
167992/*
167993** Extract the next token from a tokenization cursor.
167994*/
167995static int icuNext(
167996  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
167997  const char **ppToken,               /* OUT: *ppToken is the token text */
167998  int *pnBytes,                       /* OUT: Number of bytes in token */
167999  int *piStartOffset,                 /* OUT: Starting offset of token */
168000  int *piEndOffset,                   /* OUT: Ending offset of token */
168001  int *piPosition                     /* OUT: Position integer of token */
168002){
168003  IcuCursor *pCsr = (IcuCursor *)pCursor;
168004
168005  int iStart = 0;
168006  int iEnd = 0;
168007  int nByte = 0;
168008
168009  while( iStart==iEnd ){
168010    UChar32 c;
168011
168012    iStart = ubrk_current(pCsr->pIter);
168013    iEnd = ubrk_next(pCsr->pIter);
168014    if( iEnd==UBRK_DONE ){
168015      return SQLITE_DONE;
168016    }
168017
168018    while( iStart<iEnd ){
168019      int iWhite = iStart;
168020      U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
168021      if( u_isspace(c) ){
168022        iStart = iWhite;
168023      }else{
168024        break;
168025      }
168026    }
168027    assert(iStart<=iEnd);
168028  }
168029
168030  do {
168031    UErrorCode status = U_ZERO_ERROR;
168032    if( nByte ){
168033      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
168034      if( !zNew ){
168035        return SQLITE_NOMEM;
168036      }
168037      pCsr->zBuffer = zNew;
168038      pCsr->nBuffer = nByte;
168039    }
168040
168041    u_strToUTF8(
168042        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
168043        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
168044        &status                                  /* Output success/failure */
168045    );
168046  } while( nByte>pCsr->nBuffer );
168047
168048  *ppToken = pCsr->zBuffer;
168049  *pnBytes = nByte;
168050  *piStartOffset = pCsr->aOffset[iStart];
168051  *piEndOffset = pCsr->aOffset[iEnd];
168052  *piPosition = pCsr->iToken++;
168053
168054  return SQLITE_OK;
168055}
168056
168057/*
168058** The set of routines that implement the simple tokenizer
168059*/
168060static const sqlite3_tokenizer_module icuTokenizerModule = {
168061  0,                           /* iVersion    */
168062  icuCreate,                   /* xCreate     */
168063  icuDestroy,                  /* xCreate     */
168064  icuOpen,                     /* xOpen       */
168065  icuClose,                    /* xClose      */
168066  icuNext,                     /* xNext       */
168067  0,                           /* xLanguageid */
168068};
168069
168070/*
168071** Set *ppModule to point at the implementation of the ICU tokenizer.
168072*/
168073SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
168074  sqlite3_tokenizer_module const**ppModule
168075){
168076  *ppModule = &icuTokenizerModule;
168077}
168078
168079#endif /* defined(SQLITE_ENABLE_ICU) */
168080#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
168081
168082/************** End of fts3_icu.c ********************************************/
168083/************** Begin file sqlite3rbu.c **************************************/
168084/*
168085** 2014 August 30
168086**
168087** The author disclaims copyright to this source code.  In place of
168088** a legal notice, here is a blessing:
168089**
168090**    May you do good and not evil.
168091**    May you find forgiveness for yourself and forgive others.
168092**    May you share freely, never taking more than you give.
168093**
168094*************************************************************************
168095**
168096**
168097** OVERVIEW
168098**
168099**  The RBU extension requires that the RBU update be packaged as an
168100**  SQLite database. The tables it expects to find are described in
168101**  sqlite3rbu.h.  Essentially, for each table xyz in the target database
168102**  that the user wishes to write to, a corresponding data_xyz table is
168103**  created in the RBU database and populated with one row for each row to
168104**  update, insert or delete from the target table.
168105**
168106**  The update proceeds in three stages:
168107**
168108**  1) The database is updated. The modified database pages are written
168109**     to a *-oal file. A *-oal file is just like a *-wal file, except
168110**     that it is named "<database>-oal" instead of "<database>-wal".
168111**     Because regular SQLite clients do not look for file named
168112**     "<database>-oal", they go on using the original database in
168113**     rollback mode while the *-oal file is being generated.
168114**
168115**     During this stage RBU does not update the database by writing
168116**     directly to the target tables. Instead it creates "imposter"
168117**     tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
168118**     to update each b-tree individually. All updates required by each
168119**     b-tree are completed before moving on to the next, and all
168120**     updates are done in sorted key order.
168121**
168122**  2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
168123**     location using a call to rename(2). Before doing this the RBU
168124**     module takes an EXCLUSIVE lock on the database file, ensuring
168125**     that there are no other active readers.
168126**
168127**     Once the EXCLUSIVE lock is released, any other database readers
168128**     detect the new *-wal file and read the database in wal mode. At
168129**     this point they see the new version of the database - including
168130**     the updates made as part of the RBU update.
168131**
168132**  3) The new *-wal file is checkpointed. This proceeds in the same way
168133**     as a regular database checkpoint, except that a single frame is
168134**     checkpointed each time sqlite3rbu_step() is called. If the RBU
168135**     handle is closed before the entire *-wal file is checkpointed,
168136**     the checkpoint progress is saved in the RBU database and the
168137**     checkpoint can be resumed by another RBU client at some point in
168138**     the future.
168139**
168140** POTENTIAL PROBLEMS
168141**
168142**  The rename() call might not be portable. And RBU is not currently
168143**  syncing the directory after renaming the file.
168144**
168145**  When state is saved, any commit to the *-oal file and the commit to
168146**  the RBU update database are not atomic. So if the power fails at the
168147**  wrong moment they might get out of sync. As the main database will be
168148**  committed before the RBU update database this will likely either just
168149**  pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
168150**  constraint violations).
168151**
168152**  If some client does modify the target database mid RBU update, or some
168153**  other error occurs, the RBU extension will keep throwing errors. It's
168154**  not really clear how to get out of this state. The system could just
168155**  by delete the RBU update database and *-oal file and have the device
168156**  download the update again and start over.
168157**
168158**  At present, for an UPDATE, both the new.* and old.* records are
168159**  collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
168160**  fields are collected.  This means we're probably writing a lot more
168161**  data to disk when saving the state of an ongoing update to the RBU
168162**  update database than is strictly necessary.
168163**
168164*/
168165
168166/* #include <assert.h> */
168167/* #include <string.h> */
168168/* #include <stdio.h> */
168169
168170/* #include "sqlite3.h" */
168171
168172#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
168173/************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
168174/************** Begin file sqlite3rbu.h **************************************/
168175/*
168176** 2014 August 30
168177**
168178** The author disclaims copyright to this source code.  In place of
168179** a legal notice, here is a blessing:
168180**
168181**    May you do good and not evil.
168182**    May you find forgiveness for yourself and forgive others.
168183**    May you share freely, never taking more than you give.
168184**
168185*************************************************************************
168186**
168187** This file contains the public interface for the RBU extension.
168188*/
168189
168190/*
168191** SUMMARY
168192**
168193** Writing a transaction containing a large number of operations on
168194** b-tree indexes that are collectively larger than the available cache
168195** memory can be very inefficient.
168196**
168197** The problem is that in order to update a b-tree, the leaf page (at least)
168198** containing the entry being inserted or deleted must be modified. If the
168199** working set of leaves is larger than the available cache memory, then a
168200** single leaf that is modified more than once as part of the transaction
168201** may be loaded from or written to the persistent media multiple times.
168202** Additionally, because the index updates are likely to be applied in
168203** random order, access to pages within the database is also likely to be in
168204** random order, which is itself quite inefficient.
168205**
168206** One way to improve the situation is to sort the operations on each index
168207** by index key before applying them to the b-tree. This leads to an IO
168208** pattern that resembles a single linear scan through the index b-tree,
168209** and all but guarantees each modified leaf page is loaded and stored
168210** exactly once. SQLite uses this trick to improve the performance of
168211** CREATE INDEX commands. This extension allows it to be used to improve
168212** the performance of large transactions on existing databases.
168213**
168214** Additionally, this extension allows the work involved in writing the
168215** large transaction to be broken down into sub-transactions performed
168216** sequentially by separate processes. This is useful if the system cannot
168217** guarantee that a single update process will run for long enough to apply
168218** the entire update, for example because the update is being applied on a
168219** mobile device that is frequently rebooted. Even after the writer process
168220** has committed one or more sub-transactions, other database clients continue
168221** to read from the original database snapshot. In other words, partially
168222** applied transactions are not visible to other clients.
168223**
168224** "RBU" stands for "Resumable Bulk Update". As in a large database update
168225** transmitted via a wireless network to a mobile device. A transaction
168226** applied using this extension is hence refered to as an "RBU update".
168227**
168228**
168229** LIMITATIONS
168230**
168231** An "RBU update" transaction is subject to the following limitations:
168232**
168233**   * The transaction must consist of INSERT, UPDATE and DELETE operations
168234**     only.
168235**
168236**   * INSERT statements may not use any default values.
168237**
168238**   * UPDATE and DELETE statements must identify their target rows by
168239**     non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
168240**     KEY fields may not be updated or deleted. If the table being written
168241**     has no PRIMARY KEY, affected rows must be identified by rowid.
168242**
168243**   * UPDATE statements may not modify PRIMARY KEY columns.
168244**
168245**   * No triggers will be fired.
168246**
168247**   * No foreign key violations are detected or reported.
168248**
168249**   * CHECK constraints are not enforced.
168250**
168251**   * No constraint handling mode except for "OR ROLLBACK" is supported.
168252**
168253**
168254** PREPARATION
168255**
168256** An "RBU update" is stored as a separate SQLite database. A database
168257** containing an RBU update is an "RBU database". For each table in the
168258** target database to be updated, the RBU database should contain a table
168259** named "data_<target name>" containing the same set of columns as the
168260** target table, and one more - "rbu_control". The data_% table should
168261** have no PRIMARY KEY or UNIQUE constraints, but each column should have
168262** the same type as the corresponding column in the target database.
168263** The "rbu_control" column should have no type at all. For example, if
168264** the target database contains:
168265**
168266**   CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
168267**
168268** Then the RBU database should contain:
168269**
168270**   CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
168271**
168272** The order of the columns in the data_% table does not matter.
168273**
168274** Instead of a regular table, the RBU database may also contain virtual
168275** tables or view named using the data_<target> naming scheme.
168276**
168277** Instead of the plain data_<target> naming scheme, RBU database tables
168278** may also be named data<integer>_<target>, where <integer> is any sequence
168279** of zero or more numeric characters (0-9). This can be significant because
168280** tables within the RBU database are always processed in order sorted by
168281** name. By judicious selection of the <integer> portion of the names
168282** of the RBU tables the user can therefore control the order in which they
168283** are processed. This can be useful, for example, to ensure that "external
168284** content" FTS4 tables are updated before their underlying content tables.
168285**
168286** If the target database table is a virtual table or a table that has no
168287** PRIMARY KEY declaration, the data_% table must also contain a column
168288** named "rbu_rowid". This column is mapped to the tables implicit primary
168289** key column - "rowid". Virtual tables for which the "rowid" column does
168290** not function like a primary key value cannot be updated using RBU. For
168291** example, if the target db contains either of the following:
168292**
168293**   CREATE VIRTUAL TABLE x1 USING fts3(a, b);
168294**   CREATE TABLE x1(a, b)
168295**
168296** then the RBU database should contain:
168297**
168298**   CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
168299**
168300** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
168301** target table must be present in the input table. For virtual tables,
168302** hidden columns are optional - they are updated by RBU if present in
168303** the input table, or not otherwise. For example, to write to an fts4
168304** table with a hidden languageid column such as:
168305**
168306**   CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
168307**
168308** Either of the following input table schemas may be used:
168309**
168310**   CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
168311**   CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
168312**
168313** For each row to INSERT into the target database as part of the RBU
168314** update, the corresponding data_% table should contain a single record
168315** with the "rbu_control" column set to contain integer value 0. The
168316** other columns should be set to the values that make up the new record
168317** to insert.
168318**
168319** If the target database table has an INTEGER PRIMARY KEY, it is not
168320** possible to insert a NULL value into the IPK column. Attempting to
168321** do so results in an SQLITE_MISMATCH error.
168322**
168323** For each row to DELETE from the target database as part of the RBU
168324** update, the corresponding data_% table should contain a single record
168325** with the "rbu_control" column set to contain integer value 1. The
168326** real primary key values of the row to delete should be stored in the
168327** corresponding columns of the data_% table. The values stored in the
168328** other columns are not used.
168329**
168330** For each row to UPDATE from the target database as part of the RBU
168331** update, the corresponding data_% table should contain a single record
168332** with the "rbu_control" column set to contain a value of type text.
168333** The real primary key values identifying the row to update should be
168334** stored in the corresponding columns of the data_% table row, as should
168335** the new values of all columns being update. The text value in the
168336** "rbu_control" column must contain the same number of characters as
168337** there are columns in the target database table, and must consist entirely
168338** of 'x' and '.' characters (or in some special cases 'd' - see below). For
168339** each column that is being updated, the corresponding character is set to
168340** 'x'. For those that remain as they are, the corresponding character of the
168341** rbu_control value should be set to '.'. For example, given the tables
168342** above, the update statement:
168343**
168344**   UPDATE t1 SET c = 'usa' WHERE a = 4;
168345**
168346** is represented by the data_t1 row created by:
168347**
168348**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
168349**
168350** Instead of an 'x' character, characters of the rbu_control value specified
168351** for UPDATEs may also be set to 'd'. In this case, instead of updating the
168352** target table with the value stored in the corresponding data_% column, the
168353** user-defined SQL function "rbu_delta()" is invoked and the result stored in
168354** the target table column. rbu_delta() is invoked with two arguments - the
168355** original value currently stored in the target table column and the
168356** value specified in the data_xxx table.
168357**
168358** For example, this row:
168359**
168360**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
168361**
168362** is similar to an UPDATE statement such as:
168363**
168364**   UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
168365**
168366** Finally, if an 'f' character appears in place of a 'd' or 's' in an
168367** ota_control string, the contents of the data_xxx table column is assumed
168368** to be a "fossil delta" - a patch to be applied to a blob value in the
168369** format used by the fossil source-code management system. In this case
168370** the existing value within the target database table must be of type BLOB.
168371** It is replaced by the result of applying the specified fossil delta to
168372** itself.
168373**
168374** If the target database table is a virtual table or a table with no PRIMARY
168375** KEY, the rbu_control value should not include a character corresponding
168376** to the rbu_rowid value. For example, this:
168377**
168378**   INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
168379**       VALUES(NULL, 'usa', 12, '.x');
168380**
168381** causes a result similar to:
168382**
168383**   UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
168384**
168385** The data_xxx tables themselves should have no PRIMARY KEY declarations.
168386** However, RBU is more efficient if reading the rows in from each data_xxx
168387** table in "rowid" order is roughly the same as reading them sorted by
168388** the PRIMARY KEY of the corresponding target database table. In other
168389** words, rows should be sorted using the destination table PRIMARY KEY
168390** fields before they are inserted into the data_xxx tables.
168391**
168392** USAGE
168393**
168394** The API declared below allows an application to apply an RBU update
168395** stored on disk to an existing target database. Essentially, the
168396** application:
168397**
168398**     1) Opens an RBU handle using the sqlite3rbu_open() function.
168399**
168400**     2) Registers any required virtual table modules with the database
168401**        handle returned by sqlite3rbu_db(). Also, if required, register
168402**        the rbu_delta() implementation.
168403**
168404**     3) Calls the sqlite3rbu_step() function one or more times on
168405**        the new handle. Each call to sqlite3rbu_step() performs a single
168406**        b-tree operation, so thousands of calls may be required to apply
168407**        a complete update.
168408**
168409**     4) Calls sqlite3rbu_close() to close the RBU update handle. If
168410**        sqlite3rbu_step() has been called enough times to completely
168411**        apply the update to the target database, then the RBU database
168412**        is marked as fully applied. Otherwise, the state of the RBU
168413**        update application is saved in the RBU database for later
168414**        resumption.
168415**
168416** See comments below for more detail on APIs.
168417**
168418** If an update is only partially applied to the target database by the
168419** time sqlite3rbu_close() is called, various state information is saved
168420** within the RBU database. This allows subsequent processes to automatically
168421** resume the RBU update from where it left off.
168422**
168423** To remove all RBU extension state information, returning an RBU database
168424** to its original contents, it is sufficient to drop all tables that begin
168425** with the prefix "rbu_"
168426**
168427** DATABASE LOCKING
168428**
168429** An RBU update may not be applied to a database in WAL mode. Attempting
168430** to do so is an error (SQLITE_ERROR).
168431**
168432** While an RBU handle is open, a SHARED lock may be held on the target
168433** database file. This means it is possible for other clients to read the
168434** database, but not to write it.
168435**
168436** If an RBU update is started and then suspended before it is completed,
168437** then an external client writes to the database, then attempting to resume
168438** the suspended RBU update is also an error (SQLITE_BUSY).
168439*/
168440
168441#ifndef _SQLITE3RBU_H
168442#define _SQLITE3RBU_H
168443
168444/* #include "sqlite3.h"              ** Required for error code definitions ** */
168445
168446#if 0
168447extern "C" {
168448#endif
168449
168450typedef struct sqlite3rbu sqlite3rbu;
168451
168452/*
168453** Open an RBU handle.
168454**
168455** Argument zTarget is the path to the target database. Argument zRbu is
168456** the path to the RBU database. Each call to this function must be matched
168457** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
168458** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
168459** or zRbu begin with "file:", it will be interpreted as an SQLite
168460** database URI, not a regular file name.
168461**
168462** If the zState argument is passed a NULL value, the RBU extension stores
168463** the current state of the update (how many rows have been updated, which
168464** indexes are yet to be updated etc.) within the RBU database itself. This
168465** can be convenient, as it means that the RBU application does not need to
168466** organize removing a separate state file after the update is concluded.
168467** Or, if zState is non-NULL, it must be a path to a database file in which
168468** the RBU extension can store the state of the update.
168469**
168470** When resuming an RBU update, the zState argument must be passed the same
168471** value as when the RBU update was started.
168472**
168473** Once the RBU update is finished, the RBU extension does not
168474** automatically remove any zState database file, even if it created it.
168475**
168476** By default, RBU uses the default VFS to access the files on disk. To
168477** use a VFS other than the default, an SQLite "file:" URI containing a
168478** "vfs=..." option may be passed as the zTarget option.
168479**
168480** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
168481** SQLite's built-in VFSs, including the multiplexor VFS. However it does
168482** not work out of the box with zipvfs. Refer to the comment describing
168483** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
168484*/
168485SQLITE_API sqlite3rbu *sqlite3rbu_open(
168486  const char *zTarget,
168487  const char *zRbu,
168488  const char *zState
168489);
168490
168491/*
168492** Open an RBU handle to perform an RBU vacuum on database file zTarget.
168493** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
168494** that it can be suspended and resumed like an RBU update.
168495**
168496** The second argument to this function identifies a database in which
168497** to store the state of the RBU vacuum operation if it is suspended. The
168498** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
168499** operation, the state database should either not exist or be empty
168500** (contain no tables). If an RBU vacuum is suspended by calling
168501** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
168502** returned SQLITE_DONE, the vacuum state is stored in the state database.
168503** The vacuum can be resumed by calling this function to open a new RBU
168504** handle specifying the same target and state databases.
168505**
168506** If the second argument passed to this function is NULL, then the
168507** name of the state database is "<database>-vacuum", where <database>
168508** is the name of the target database file. In this case, on UNIX, if the
168509** state database is not already present in the file-system, it is created
168510** with the same permissions as the target db is made.
168511**
168512** This function does not delete the state database after an RBU vacuum
168513** is completed, even if it created it. However, if the call to
168514** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
168515** of the state tables within the state database are zeroed. This way,
168516** the next call to sqlite3rbu_vacuum() opens a handle that starts a
168517** new RBU vacuum operation.
168518**
168519** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
168520** describing the sqlite3rbu_create_vfs() API function below for
168521** a description of the complications associated with using RBU with
168522** zipvfs databases.
168523*/
168524SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
168525  const char *zTarget,
168526  const char *zState
168527);
168528
168529/*
168530** Internally, each RBU connection uses a separate SQLite database
168531** connection to access the target and rbu update databases. This
168532** API allows the application direct access to these database handles.
168533**
168534** The first argument passed to this function must be a valid, open, RBU
168535** handle. The second argument should be passed zero to access the target
168536** database handle, or non-zero to access the rbu update database handle.
168537** Accessing the underlying database handles may be useful in the
168538** following scenarios:
168539**
168540**   * If any target tables are virtual tables, it may be necessary to
168541**     call sqlite3_create_module() on the target database handle to
168542**     register the required virtual table implementations.
168543**
168544**   * If the data_xxx tables in the RBU source database are virtual
168545**     tables, the application may need to call sqlite3_create_module() on
168546**     the rbu update db handle to any required virtual table
168547**     implementations.
168548**
168549**   * If the application uses the "rbu_delta()" feature described above,
168550**     it must use sqlite3_create_function() or similar to register the
168551**     rbu_delta() implementation with the target database handle.
168552**
168553** If an error has occurred, either while opening or stepping the RBU object,
168554** this function may return NULL. The error code and message may be collected
168555** when sqlite3rbu_close() is called.
168556**
168557** Database handles returned by this function remain valid until the next
168558** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
168559*/
168560SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
168561
168562/*
168563** Do some work towards applying the RBU update to the target db.
168564**
168565** Return SQLITE_DONE if the update has been completely applied, or
168566** SQLITE_OK if no error occurs but there remains work to do to apply
168567** the RBU update. If an error does occur, some other error code is
168568** returned.
168569**
168570** Once a call to sqlite3rbu_step() has returned a value other than
168571** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
168572** that immediately return the same value.
168573*/
168574SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
168575
168576/*
168577** Force RBU to save its state to disk.
168578**
168579** If a power failure or application crash occurs during an update, following
168580** system recovery RBU may resume the update from the point at which the state
168581** was last saved. In other words, from the most recent successful call to
168582** sqlite3rbu_close() or this function.
168583**
168584** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
168585*/
168586SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
168587
168588/*
168589** Close an RBU handle.
168590**
168591** If the RBU update has been completely applied, mark the RBU database
168592** as fully applied. Otherwise, assuming no error has occurred, save the
168593** current state of the RBU update appliation to the RBU database.
168594**
168595** If an error has already occurred as part of an sqlite3rbu_step()
168596** or sqlite3rbu_open() call, or if one occurs within this function, an
168597** SQLite error code is returned. Additionally, *pzErrmsg may be set to
168598** point to a buffer containing a utf-8 formatted English language error
168599** message. It is the responsibility of the caller to eventually free any
168600** such buffer using sqlite3_free().
168601**
168602** Otherwise, if no error occurs, this function returns SQLITE_OK if the
168603** update has been partially applied, or SQLITE_DONE if it has been
168604** completely applied.
168605*/
168606SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
168607
168608/*
168609** Return the total number of key-value operations (inserts, deletes or
168610** updates) that have been performed on the target database since the
168611** current RBU update was started.
168612*/
168613SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
168614
168615/*
168616** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
168617** progress indications for the two stages of an RBU update. This API may
168618** be useful for driving GUI progress indicators and similar.
168619**
168620** An RBU update is divided into two stages:
168621**
168622**   * Stage 1, in which changes are accumulated in an oal/wal file, and
168623**   * Stage 2, in which the contents of the wal file are copied into the
168624**     main database.
168625**
168626** The update is visible to non-RBU clients during stage 2. During stage 1
168627** non-RBU reader clients may see the original database.
168628**
168629** If this API is called during stage 2 of the update, output variable
168630** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
168631** to a value between 0 and 10000 to indicate the permyriadage progress of
168632** stage 2. A value of 5000 indicates that stage 2 is half finished,
168633** 9000 indicates that it is 90% finished, and so on.
168634**
168635** If this API is called during stage 1 of the update, output variable
168636** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
168637** value to which (*pnOne) is set depends on whether or not the RBU
168638** database contains an "rbu_count" table. The rbu_count table, if it
168639** exists, must contain the same columns as the following:
168640**
168641**   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
168642**
168643** There must be one row in the table for each source (data_xxx) table within
168644** the RBU database. The 'tbl' column should contain the name of the source
168645** table. The 'cnt' column should contain the number of rows within the
168646** source table.
168647**
168648** If the rbu_count table is present and populated correctly and this
168649** API is called during stage 1, the *pnOne output variable is set to the
168650** permyriadage progress of the same stage. If the rbu_count table does
168651** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
168652** table exists but is not correctly populated, the value of the *pnOne
168653** output variable during stage 1 is undefined.
168654*/
168655SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo);
168656
168657/*
168658** Obtain an indication as to the current stage of an RBU update or vacuum.
168659** This function always returns one of the SQLITE_RBU_STATE_XXX constants
168660** defined in this file. Return values should be interpreted as follows:
168661**
168662** SQLITE_RBU_STATE_OAL:
168663**   RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
168664**   may either add further data to the *-oal file, or compute data that will
168665**   be added by a subsequent call.
168666**
168667** SQLITE_RBU_STATE_MOVE:
168668**   RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
168669**   will move the *-oal file to the equivalent *-wal path. If the current
168670**   operation is an RBU update, then the updated version of the database
168671**   file will become visible to ordinary SQLite clients following the next
168672**   call to sqlite3rbu_step().
168673**
168674** SQLITE_RBU_STATE_CHECKPOINT:
168675**   RBU is currently performing an incremental checkpoint. The next call to
168676**   sqlite3rbu_step() will copy a page of data from the *-wal file into
168677**   the target database file.
168678**
168679** SQLITE_RBU_STATE_DONE:
168680**   The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
168681**   will immediately return SQLITE_DONE.
168682**
168683** SQLITE_RBU_STATE_ERROR:
168684**   An error has occurred. Any subsequent calls to sqlite3rbu_step() will
168685**   immediately return the SQLite error code associated with the error.
168686*/
168687#define SQLITE_RBU_STATE_OAL        1
168688#define SQLITE_RBU_STATE_MOVE       2
168689#define SQLITE_RBU_STATE_CHECKPOINT 3
168690#define SQLITE_RBU_STATE_DONE       4
168691#define SQLITE_RBU_STATE_ERROR      5
168692
168693SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
168694
168695/*
168696** Create an RBU VFS named zName that accesses the underlying file-system
168697** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
168698** then the new RBU VFS uses the default system VFS to access the file-system.
168699** The new object is registered as a non-default VFS with SQLite before
168700** returning.
168701**
168702** Part of the RBU implementation uses a custom VFS object. Usually, this
168703** object is created and deleted automatically by RBU.
168704**
168705** The exception is for applications that also use zipvfs. In this case,
168706** the custom VFS must be explicitly created by the user before the RBU
168707** handle is opened. The RBU VFS should be installed so that the zipvfs
168708** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
168709** (for example multiplexor) to access the file-system. For example,
168710** to assemble an RBU enabled VFS stack that uses both zipvfs and
168711** multiplexor (error checking omitted):
168712**
168713**     // Create a VFS named "multiplex" (not the default).
168714**     sqlite3_multiplex_initialize(0, 0);
168715**
168716**     // Create an rbu VFS named "rbu" that uses multiplexor. If the
168717**     // second argument were replaced with NULL, the "rbu" VFS would
168718**     // access the file-system via the system default VFS, bypassing the
168719**     // multiplexor.
168720**     sqlite3rbu_create_vfs("rbu", "multiplex");
168721**
168722**     // Create a zipvfs VFS named "zipvfs" that uses rbu.
168723**     zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
168724**
168725**     // Make zipvfs the default VFS.
168726**     sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
168727**
168728** Because the default VFS created above includes a RBU functionality, it
168729** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
168730** that does not include the RBU layer results in an error.
168731**
168732** The overhead of adding the "rbu" VFS to the system is negligible for
168733** non-RBU users. There is no harm in an application accessing the
168734** file-system via "rbu" all the time, even if it only uses RBU functionality
168735** occasionally.
168736*/
168737SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
168738
168739/*
168740** Deregister and destroy an RBU vfs created by an earlier call to
168741** sqlite3rbu_create_vfs().
168742**
168743** VFS objects are not reference counted. If a VFS object is destroyed
168744** before all database handles that use it have been closed, the results
168745** are undefined.
168746*/
168747SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
168748
168749#if 0
168750}  /* end of the 'extern "C"' block */
168751#endif
168752
168753#endif /* _SQLITE3RBU_H */
168754
168755/************** End of sqlite3rbu.h ******************************************/
168756/************** Continuing where we left off in sqlite3rbu.c *****************/
168757
168758#if defined(_WIN32_WCE)
168759/* #include "windows.h" */
168760#endif
168761
168762/* Maximum number of prepared UPDATE statements held by this module */
168763#define SQLITE_RBU_UPDATE_CACHESIZE 16
168764
168765/*
168766** Swap two objects of type TYPE.
168767*/
168768#if !defined(SQLITE_AMALGAMATION)
168769# define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
168770#endif
168771
168772/*
168773** The rbu_state table is used to save the state of a partially applied
168774** update so that it can be resumed later. The table consists of integer
168775** keys mapped to values as follows:
168776**
168777** RBU_STATE_STAGE:
168778**   May be set to integer values 1, 2, 4 or 5. As follows:
168779**       1: the *-rbu file is currently under construction.
168780**       2: the *-rbu file has been constructed, but not yet moved
168781**          to the *-wal path.
168782**       4: the checkpoint is underway.
168783**       5: the rbu update has been checkpointed.
168784**
168785** RBU_STATE_TBL:
168786**   Only valid if STAGE==1. The target database name of the table
168787**   currently being written.
168788**
168789** RBU_STATE_IDX:
168790**   Only valid if STAGE==1. The target database name of the index
168791**   currently being written, or NULL if the main table is currently being
168792**   updated.
168793**
168794** RBU_STATE_ROW:
168795**   Only valid if STAGE==1. Number of rows already processed for the current
168796**   table/index.
168797**
168798** RBU_STATE_PROGRESS:
168799**   Trbul number of sqlite3rbu_step() calls made so far as part of this
168800**   rbu update.
168801**
168802** RBU_STATE_CKPT:
168803**   Valid if STAGE==4. The 64-bit checksum associated with the wal-index
168804**   header created by recovering the *-wal file. This is used to detect
168805**   cases when another client appends frames to the *-wal file in the
168806**   middle of an incremental checkpoint (an incremental checkpoint cannot
168807**   be continued if this happens).
168808**
168809** RBU_STATE_COOKIE:
168810**   Valid if STAGE==1. The current change-counter cookie value in the
168811**   target db file.
168812**
168813** RBU_STATE_OALSZ:
168814**   Valid if STAGE==1. The size in bytes of the *-oal file.
168815*/
168816#define RBU_STATE_STAGE        1
168817#define RBU_STATE_TBL          2
168818#define RBU_STATE_IDX          3
168819#define RBU_STATE_ROW          4
168820#define RBU_STATE_PROGRESS     5
168821#define RBU_STATE_CKPT         6
168822#define RBU_STATE_COOKIE       7
168823#define RBU_STATE_OALSZ        8
168824#define RBU_STATE_PHASEONESTEP 9
168825
168826#define RBU_STAGE_OAL         1
168827#define RBU_STAGE_MOVE        2
168828#define RBU_STAGE_CAPTURE     3
168829#define RBU_STAGE_CKPT        4
168830#define RBU_STAGE_DONE        5
168831
168832
168833#define RBU_CREATE_STATE \
168834  "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
168835
168836typedef struct RbuFrame RbuFrame;
168837typedef struct RbuObjIter RbuObjIter;
168838typedef struct RbuState RbuState;
168839typedef struct rbu_vfs rbu_vfs;
168840typedef struct rbu_file rbu_file;
168841typedef struct RbuUpdateStmt RbuUpdateStmt;
168842
168843#if !defined(SQLITE_AMALGAMATION)
168844typedef unsigned int u32;
168845typedef unsigned short u16;
168846typedef unsigned char u8;
168847typedef sqlite3_int64 i64;
168848#endif
168849
168850/*
168851** These values must match the values defined in wal.c for the equivalent
168852** locks. These are not magic numbers as they are part of the SQLite file
168853** format.
168854*/
168855#define WAL_LOCK_WRITE  0
168856#define WAL_LOCK_CKPT   1
168857#define WAL_LOCK_READ0  3
168858
168859#define SQLITE_FCNTL_RBUCNT    5149216
168860
168861/*
168862** A structure to store values read from the rbu_state table in memory.
168863*/
168864struct RbuState {
168865  int eStage;
168866  char *zTbl;
168867  char *zIdx;
168868  i64 iWalCksum;
168869  int nRow;
168870  i64 nProgress;
168871  u32 iCookie;
168872  i64 iOalSz;
168873  i64 nPhaseOneStep;
168874};
168875
168876struct RbuUpdateStmt {
168877  char *zMask;                    /* Copy of update mask used with pUpdate */
168878  sqlite3_stmt *pUpdate;          /* Last update statement (or NULL) */
168879  RbuUpdateStmt *pNext;
168880};
168881
168882/*
168883** An iterator of this type is used to iterate through all objects in
168884** the target database that require updating. For each such table, the
168885** iterator visits, in order:
168886**
168887**     * the table itself,
168888**     * each index of the table (zero or more points to visit), and
168889**     * a special "cleanup table" state.
168890**
168891** abIndexed:
168892**   If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
168893**   it points to an array of flags nTblCol elements in size. The flag is
168894**   set for each column that is either a part of the PK or a part of an
168895**   index. Or clear otherwise.
168896**
168897*/
168898struct RbuObjIter {
168899  sqlite3_stmt *pTblIter;         /* Iterate through tables */
168900  sqlite3_stmt *pIdxIter;         /* Index iterator */
168901  int nTblCol;                    /* Size of azTblCol[] array */
168902  char **azTblCol;                /* Array of unquoted target column names */
168903  char **azTblType;               /* Array of target column types */
168904  int *aiSrcOrder;                /* src table col -> target table col */
168905  u8 *abTblPk;                    /* Array of flags, set on target PK columns */
168906  u8 *abNotNull;                  /* Array of flags, set on NOT NULL columns */
168907  u8 *abIndexed;                  /* Array of flags, set on indexed & PK cols */
168908  int eType;                      /* Table type - an RBU_PK_XXX value */
168909
168910  /* Output variables. zTbl==0 implies EOF. */
168911  int bCleanup;                   /* True in "cleanup" state */
168912  const char *zTbl;               /* Name of target db table */
168913  const char *zDataTbl;           /* Name of rbu db table (or null) */
168914  const char *zIdx;               /* Name of target db index (or null) */
168915  int iTnum;                      /* Root page of current object */
168916  int iPkTnum;                    /* If eType==EXTERNAL, root of PK index */
168917  int bUnique;                    /* Current index is unique */
168918  int nIndex;                     /* Number of aux. indexes on table zTbl */
168919
168920  /* Statements created by rbuObjIterPrepareAll() */
168921  int nCol;                       /* Number of columns in current object */
168922  sqlite3_stmt *pSelect;          /* Source data */
168923  sqlite3_stmt *pInsert;          /* Statement for INSERT operations */
168924  sqlite3_stmt *pDelete;          /* Statement for DELETE ops */
168925  sqlite3_stmt *pTmpInsert;       /* Insert into rbu_tmp_$zDataTbl */
168926
168927  /* Last UPDATE used (for PK b-tree updates only), or NULL. */
168928  RbuUpdateStmt *pRbuUpdate;
168929};
168930
168931/*
168932** Values for RbuObjIter.eType
168933**
168934**     0: Table does not exist (error)
168935**     1: Table has an implicit rowid.
168936**     2: Table has an explicit IPK column.
168937**     3: Table has an external PK index.
168938**     4: Table is WITHOUT ROWID.
168939**     5: Table is a virtual table.
168940*/
168941#define RBU_PK_NOTABLE        0
168942#define RBU_PK_NONE           1
168943#define RBU_PK_IPK            2
168944#define RBU_PK_EXTERNAL       3
168945#define RBU_PK_WITHOUT_ROWID  4
168946#define RBU_PK_VTAB           5
168947
168948
168949/*
168950** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
168951** one of the following operations.
168952*/
168953#define RBU_INSERT     1          /* Insert on a main table b-tree */
168954#define RBU_DELETE     2          /* Delete a row from a main table b-tree */
168955#define RBU_REPLACE    3          /* Delete and then insert a row */
168956#define RBU_IDX_DELETE 4          /* Delete a row from an aux. index b-tree */
168957#define RBU_IDX_INSERT 5          /* Insert on an aux. index b-tree */
168958
168959#define RBU_UPDATE     6          /* Update a row in a main table b-tree */
168960
168961/*
168962** A single step of an incremental checkpoint - frame iWalFrame of the wal
168963** file should be copied to page iDbPage of the database file.
168964*/
168965struct RbuFrame {
168966  u32 iDbPage;
168967  u32 iWalFrame;
168968};
168969
168970/*
168971** RBU handle.
168972**
168973** nPhaseOneStep:
168974**   If the RBU database contains an rbu_count table, this value is set to
168975**   a running estimate of the number of b-tree operations required to
168976**   finish populating the *-oal file. This allows the sqlite3_bp_progress()
168977**   API to calculate the permyriadage progress of populating the *-oal file
168978**   using the formula:
168979**
168980**     permyriadage = (10000 * nProgress) / nPhaseOneStep
168981**
168982**   nPhaseOneStep is initialized to the sum of:
168983**
168984**     nRow * (nIndex + 1)
168985**
168986**   for all source tables in the RBU database, where nRow is the number
168987**   of rows in the source table and nIndex the number of indexes on the
168988**   corresponding target database table.
168989**
168990**   This estimate is accurate if the RBU update consists entirely of
168991**   INSERT operations. However, it is inaccurate if:
168992**
168993**     * the RBU update contains any UPDATE operations. If the PK specified
168994**       for an UPDATE operation does not exist in the target table, then
168995**       no b-tree operations are required on index b-trees. Or if the
168996**       specified PK does exist, then (nIndex*2) such operations are
168997**       required (one delete and one insert on each index b-tree).
168998**
168999**     * the RBU update contains any DELETE operations for which the specified
169000**       PK does not exist. In this case no operations are required on index
169001**       b-trees.
169002**
169003**     * the RBU update contains REPLACE operations. These are similar to
169004**       UPDATE operations.
169005**
169006**   nPhaseOneStep is updated to account for the conditions above during the
169007**   first pass of each source table. The updated nPhaseOneStep value is
169008**   stored in the rbu_state table if the RBU update is suspended.
169009*/
169010struct sqlite3rbu {
169011  int eStage;                     /* Value of RBU_STATE_STAGE field */
169012  sqlite3 *dbMain;                /* target database handle */
169013  sqlite3 *dbRbu;                 /* rbu database handle */
169014  char *zTarget;                  /* Path to target db */
169015  char *zRbu;                     /* Path to rbu db */
169016  char *zState;                   /* Path to state db (or NULL if zRbu) */
169017  char zStateDb[5];               /* Db name for state ("stat" or "main") */
169018  int rc;                         /* Value returned by last rbu_step() call */
169019  char *zErrmsg;                  /* Error message if rc!=SQLITE_OK */
169020  int nStep;                      /* Rows processed for current object */
169021  int nProgress;                  /* Rows processed for all objects */
169022  RbuObjIter objiter;             /* Iterator for skipping through tbl/idx */
169023  const char *zVfsName;           /* Name of automatically created rbu vfs */
169024  rbu_file *pTargetFd;            /* File handle open on target db */
169025  int nPagePerSector;             /* Pages per sector for pTargetFd */
169026  i64 iOalSz;
169027  i64 nPhaseOneStep;
169028
169029  /* The following state variables are used as part of the incremental
169030  ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
169031  ** function rbuSetupCheckpoint() for details.  */
169032  u32 iMaxFrame;                  /* Largest iWalFrame value in aFrame[] */
169033  u32 mLock;
169034  int nFrame;                     /* Entries in aFrame[] array */
169035  int nFrameAlloc;                /* Allocated size of aFrame[] array */
169036  RbuFrame *aFrame;
169037  int pgsz;
169038  u8 *aBuf;
169039  i64 iWalCksum;
169040
169041  /* Used in RBU vacuum mode only */
169042  int nRbu;                       /* Number of RBU VFS in the stack */
169043  rbu_file *pRbuFd;               /* Fd for main db of dbRbu */
169044};
169045
169046/*
169047** An rbu VFS is implemented using an instance of this structure.
169048*/
169049struct rbu_vfs {
169050  sqlite3_vfs base;               /* rbu VFS shim methods */
169051  sqlite3_vfs *pRealVfs;          /* Underlying VFS */
169052  sqlite3_mutex *mutex;           /* Mutex to protect pMain */
169053  rbu_file *pMain;                /* Linked list of main db files */
169054};
169055
169056/*
169057** Each file opened by an rbu VFS is represented by an instance of
169058** the following structure.
169059*/
169060struct rbu_file {
169061  sqlite3_file base;              /* sqlite3_file methods */
169062  sqlite3_file *pReal;            /* Underlying file handle */
169063  rbu_vfs *pRbuVfs;               /* Pointer to the rbu_vfs object */
169064  sqlite3rbu *pRbu;               /* Pointer to rbu object (rbu target only) */
169065
169066  int openFlags;                  /* Flags this file was opened with */
169067  u32 iCookie;                    /* Cookie value for main db files */
169068  u8 iWriteVer;                   /* "write-version" value for main db files */
169069  u8 bNolock;                     /* True to fail EXCLUSIVE locks */
169070
169071  int nShm;                       /* Number of entries in apShm[] array */
169072  char **apShm;                   /* Array of mmap'd *-shm regions */
169073  char *zDel;                     /* Delete this when closing file */
169074
169075  const char *zWal;               /* Wal filename for this main db file */
169076  rbu_file *pWalFd;               /* Wal file descriptor for this main db */
169077  rbu_file *pMainNext;            /* Next MAIN_DB file */
169078};
169079
169080/*
169081** True for an RBU vacuum handle, or false otherwise.
169082*/
169083#define rbuIsVacuum(p) ((p)->zTarget==0)
169084
169085
169086/*************************************************************************
169087** The following three functions, found below:
169088**
169089**   rbuDeltaGetInt()
169090**   rbuDeltaChecksum()
169091**   rbuDeltaApply()
169092**
169093** are lifted from the fossil source code (http://fossil-scm.org). They
169094** are used to implement the scalar SQL function rbu_fossil_delta().
169095*/
169096
169097/*
169098** Read bytes from *pz and convert them into a positive integer.  When
169099** finished, leave *pz pointing to the first character past the end of
169100** the integer.  The *pLen parameter holds the length of the string
169101** in *pz and is decremented once for each character in the integer.
169102*/
169103static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
169104  static const signed char zValue[] = {
169105    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
169106    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
169107    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
169108     0,  1,  2,  3,  4,  5,  6,  7,    8,  9, -1, -1, -1, -1, -1, -1,
169109    -1, 10, 11, 12, 13, 14, 15, 16,   17, 18, 19, 20, 21, 22, 23, 24,
169110    25, 26, 27, 28, 29, 30, 31, 32,   33, 34, 35, -1, -1, -1, -1, 36,
169111    -1, 37, 38, 39, 40, 41, 42, 43,   44, 45, 46, 47, 48, 49, 50, 51,
169112    52, 53, 54, 55, 56, 57, 58, 59,   60, 61, 62, -1, -1, -1, 63, -1,
169113  };
169114  unsigned int v = 0;
169115  int c;
169116  unsigned char *z = (unsigned char*)*pz;
169117  unsigned char *zStart = z;
169118  while( (c = zValue[0x7f&*(z++)])>=0 ){
169119     v = (v<<6) + c;
169120  }
169121  z--;
169122  *pLen -= z - zStart;
169123  *pz = (char*)z;
169124  return v;
169125}
169126
169127/*
169128** Compute a 32-bit checksum on the N-byte buffer.  Return the result.
169129*/
169130static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
169131  const unsigned char *z = (const unsigned char *)zIn;
169132  unsigned sum0 = 0;
169133  unsigned sum1 = 0;
169134  unsigned sum2 = 0;
169135  unsigned sum3 = 0;
169136  while(N >= 16){
169137    sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
169138    sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
169139    sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
169140    sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
169141    z += 16;
169142    N -= 16;
169143  }
169144  while(N >= 4){
169145    sum0 += z[0];
169146    sum1 += z[1];
169147    sum2 += z[2];
169148    sum3 += z[3];
169149    z += 4;
169150    N -= 4;
169151  }
169152  sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
169153  switch(N){
169154    case 3:   sum3 += (z[2] << 8);
169155    case 2:   sum3 += (z[1] << 16);
169156    case 1:   sum3 += (z[0] << 24);
169157    default:  ;
169158  }
169159  return sum3;
169160}
169161
169162/*
169163** Apply a delta.
169164**
169165** The output buffer should be big enough to hold the whole output
169166** file and a NUL terminator at the end.  The delta_output_size()
169167** routine will determine this size for you.
169168**
169169** The delta string should be null-terminated.  But the delta string
169170** may contain embedded NUL characters (if the input and output are
169171** binary files) so we also have to pass in the length of the delta in
169172** the lenDelta parameter.
169173**
169174** This function returns the size of the output file in bytes (excluding
169175** the final NUL terminator character).  Except, if the delta string is
169176** malformed or intended for use with a source file other than zSrc,
169177** then this routine returns -1.
169178**
169179** Refer to the delta_create() documentation above for a description
169180** of the delta file format.
169181*/
169182static int rbuDeltaApply(
169183  const char *zSrc,      /* The source or pattern file */
169184  int lenSrc,            /* Length of the source file */
169185  const char *zDelta,    /* Delta to apply to the pattern */
169186  int lenDelta,          /* Length of the delta */
169187  char *zOut             /* Write the output into this preallocated buffer */
169188){
169189  unsigned int limit;
169190  unsigned int total = 0;
169191#ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
169192  char *zOrigOut = zOut;
169193#endif
169194
169195  limit = rbuDeltaGetInt(&zDelta, &lenDelta);
169196  if( *zDelta!='\n' ){
169197    /* ERROR: size integer not terminated by "\n" */
169198    return -1;
169199  }
169200  zDelta++; lenDelta--;
169201  while( *zDelta && lenDelta>0 ){
169202    unsigned int cnt, ofst;
169203    cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
169204    switch( zDelta[0] ){
169205      case '@': {
169206        zDelta++; lenDelta--;
169207        ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
169208        if( lenDelta>0 && zDelta[0]!=',' ){
169209          /* ERROR: copy command not terminated by ',' */
169210          return -1;
169211        }
169212        zDelta++; lenDelta--;
169213        total += cnt;
169214        if( total>limit ){
169215          /* ERROR: copy exceeds output file size */
169216          return -1;
169217        }
169218        if( (int)(ofst+cnt) > lenSrc ){
169219          /* ERROR: copy extends past end of input */
169220          return -1;
169221        }
169222        memcpy(zOut, &zSrc[ofst], cnt);
169223        zOut += cnt;
169224        break;
169225      }
169226      case ':': {
169227        zDelta++; lenDelta--;
169228        total += cnt;
169229        if( total>limit ){
169230          /* ERROR:  insert command gives an output larger than predicted */
169231          return -1;
169232        }
169233        if( (int)cnt>lenDelta ){
169234          /* ERROR: insert count exceeds size of delta */
169235          return -1;
169236        }
169237        memcpy(zOut, zDelta, cnt);
169238        zOut += cnt;
169239        zDelta += cnt;
169240        lenDelta -= cnt;
169241        break;
169242      }
169243      case ';': {
169244        zDelta++; lenDelta--;
169245        zOut[0] = 0;
169246#ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
169247        if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
169248          /* ERROR:  bad checksum */
169249          return -1;
169250        }
169251#endif
169252        if( total!=limit ){
169253          /* ERROR: generated size does not match predicted size */
169254          return -1;
169255        }
169256        return total;
169257      }
169258      default: {
169259        /* ERROR: unknown delta operator */
169260        return -1;
169261      }
169262    }
169263  }
169264  /* ERROR: unterminated delta */
169265  return -1;
169266}
169267
169268static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
169269  int size;
169270  size = rbuDeltaGetInt(&zDelta, &lenDelta);
169271  if( *zDelta!='\n' ){
169272    /* ERROR: size integer not terminated by "\n" */
169273    return -1;
169274  }
169275  return size;
169276}
169277
169278/*
169279** End of code taken from fossil.
169280*************************************************************************/
169281
169282/*
169283** Implementation of SQL scalar function rbu_fossil_delta().
169284**
169285** This function applies a fossil delta patch to a blob. Exactly two
169286** arguments must be passed to this function. The first is the blob to
169287** patch and the second the patch to apply. If no error occurs, this
169288** function returns the patched blob.
169289*/
169290static void rbuFossilDeltaFunc(
169291  sqlite3_context *context,
169292  int argc,
169293  sqlite3_value **argv
169294){
169295  const char *aDelta;
169296  int nDelta;
169297  const char *aOrig;
169298  int nOrig;
169299
169300  int nOut;
169301  int nOut2;
169302  char *aOut;
169303
169304  assert( argc==2 );
169305
169306  nOrig = sqlite3_value_bytes(argv[0]);
169307  aOrig = (const char*)sqlite3_value_blob(argv[0]);
169308  nDelta = sqlite3_value_bytes(argv[1]);
169309  aDelta = (const char*)sqlite3_value_blob(argv[1]);
169310
169311  /* Figure out the size of the output */
169312  nOut = rbuDeltaOutputSize(aDelta, nDelta);
169313  if( nOut<0 ){
169314    sqlite3_result_error(context, "corrupt fossil delta", -1);
169315    return;
169316  }
169317
169318  aOut = sqlite3_malloc(nOut+1);
169319  if( aOut==0 ){
169320    sqlite3_result_error_nomem(context);
169321  }else{
169322    nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
169323    if( nOut2!=nOut ){
169324      sqlite3_result_error(context, "corrupt fossil delta", -1);
169325    }else{
169326      sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
169327    }
169328  }
169329}
169330
169331
169332/*
169333** Prepare the SQL statement in buffer zSql against database handle db.
169334** If successful, set *ppStmt to point to the new statement and return
169335** SQLITE_OK.
169336**
169337** Otherwise, if an error does occur, set *ppStmt to NULL and return
169338** an SQLite error code. Additionally, set output variable *pzErrmsg to
169339** point to a buffer containing an error message. It is the responsibility
169340** of the caller to (eventually) free this buffer using sqlite3_free().
169341*/
169342static int prepareAndCollectError(
169343  sqlite3 *db,
169344  sqlite3_stmt **ppStmt,
169345  char **pzErrmsg,
169346  const char *zSql
169347){
169348  int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
169349  if( rc!=SQLITE_OK ){
169350    *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
169351    *ppStmt = 0;
169352  }
169353  return rc;
169354}
169355
169356/*
169357** Reset the SQL statement passed as the first argument. Return a copy
169358** of the value returned by sqlite3_reset().
169359**
169360** If an error has occurred, then set *pzErrmsg to point to a buffer
169361** containing an error message. It is the responsibility of the caller
169362** to eventually free this buffer using sqlite3_free().
169363*/
169364static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
169365  int rc = sqlite3_reset(pStmt);
169366  if( rc!=SQLITE_OK ){
169367    *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
169368  }
169369  return rc;
169370}
169371
169372/*
169373** Unless it is NULL, argument zSql points to a buffer allocated using
169374** sqlite3_malloc containing an SQL statement. This function prepares the SQL
169375** statement against database db and frees the buffer. If statement
169376** compilation is successful, *ppStmt is set to point to the new statement
169377** handle and SQLITE_OK is returned.
169378**
169379** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
169380** returned. In this case, *pzErrmsg may also be set to point to an error
169381** message. It is the responsibility of the caller to free this error message
169382** buffer using sqlite3_free().
169383**
169384** If argument zSql is NULL, this function assumes that an OOM has occurred.
169385** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
169386*/
169387static int prepareFreeAndCollectError(
169388  sqlite3 *db,
169389  sqlite3_stmt **ppStmt,
169390  char **pzErrmsg,
169391  char *zSql
169392){
169393  int rc;
169394  assert( *pzErrmsg==0 );
169395  if( zSql==0 ){
169396    rc = SQLITE_NOMEM;
169397    *ppStmt = 0;
169398  }else{
169399    rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
169400    sqlite3_free(zSql);
169401  }
169402  return rc;
169403}
169404
169405/*
169406** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
169407** by an earlier call to rbuObjIterCacheTableInfo().
169408*/
169409static void rbuObjIterFreeCols(RbuObjIter *pIter){
169410  int i;
169411  for(i=0; i<pIter->nTblCol; i++){
169412    sqlite3_free(pIter->azTblCol[i]);
169413    sqlite3_free(pIter->azTblType[i]);
169414  }
169415  sqlite3_free(pIter->azTblCol);
169416  pIter->azTblCol = 0;
169417  pIter->azTblType = 0;
169418  pIter->aiSrcOrder = 0;
169419  pIter->abTblPk = 0;
169420  pIter->abNotNull = 0;
169421  pIter->nTblCol = 0;
169422  pIter->eType = 0;               /* Invalid value */
169423}
169424
169425/*
169426** Finalize all statements and free all allocations that are specific to
169427** the current object (table/index pair).
169428*/
169429static void rbuObjIterClearStatements(RbuObjIter *pIter){
169430  RbuUpdateStmt *pUp;
169431
169432  sqlite3_finalize(pIter->pSelect);
169433  sqlite3_finalize(pIter->pInsert);
169434  sqlite3_finalize(pIter->pDelete);
169435  sqlite3_finalize(pIter->pTmpInsert);
169436  pUp = pIter->pRbuUpdate;
169437  while( pUp ){
169438    RbuUpdateStmt *pTmp = pUp->pNext;
169439    sqlite3_finalize(pUp->pUpdate);
169440    sqlite3_free(pUp);
169441    pUp = pTmp;
169442  }
169443
169444  pIter->pSelect = 0;
169445  pIter->pInsert = 0;
169446  pIter->pDelete = 0;
169447  pIter->pRbuUpdate = 0;
169448  pIter->pTmpInsert = 0;
169449  pIter->nCol = 0;
169450}
169451
169452/*
169453** Clean up any resources allocated as part of the iterator object passed
169454** as the only argument.
169455*/
169456static void rbuObjIterFinalize(RbuObjIter *pIter){
169457  rbuObjIterClearStatements(pIter);
169458  sqlite3_finalize(pIter->pTblIter);
169459  sqlite3_finalize(pIter->pIdxIter);
169460  rbuObjIterFreeCols(pIter);
169461  memset(pIter, 0, sizeof(RbuObjIter));
169462}
169463
169464/*
169465** Advance the iterator to the next position.
169466**
169467** If no error occurs, SQLITE_OK is returned and the iterator is left
169468** pointing to the next entry. Otherwise, an error code and message is
169469** left in the RBU handle passed as the first argument. A copy of the
169470** error code is returned.
169471*/
169472static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
169473  int rc = p->rc;
169474  if( rc==SQLITE_OK ){
169475
169476    /* Free any SQLite statements used while processing the previous object */
169477    rbuObjIterClearStatements(pIter);
169478    if( pIter->zIdx==0 ){
169479      rc = sqlite3_exec(p->dbMain,
169480          "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
169481          "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
169482          "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
169483          "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
169484          , 0, 0, &p->zErrmsg
169485      );
169486    }
169487
169488    if( rc==SQLITE_OK ){
169489      if( pIter->bCleanup ){
169490        rbuObjIterFreeCols(pIter);
169491        pIter->bCleanup = 0;
169492        rc = sqlite3_step(pIter->pTblIter);
169493        if( rc!=SQLITE_ROW ){
169494          rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
169495          pIter->zTbl = 0;
169496        }else{
169497          pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
169498          pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
169499          rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
169500        }
169501      }else{
169502        if( pIter->zIdx==0 ){
169503          sqlite3_stmt *pIdx = pIter->pIdxIter;
169504          rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
169505        }
169506        if( rc==SQLITE_OK ){
169507          rc = sqlite3_step(pIter->pIdxIter);
169508          if( rc!=SQLITE_ROW ){
169509            rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
169510            pIter->bCleanup = 1;
169511            pIter->zIdx = 0;
169512          }else{
169513            pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
169514            pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
169515            pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
169516            rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
169517          }
169518        }
169519      }
169520    }
169521  }
169522
169523  if( rc!=SQLITE_OK ){
169524    rbuObjIterFinalize(pIter);
169525    p->rc = rc;
169526  }
169527  return rc;
169528}
169529
169530
169531/*
169532** The implementation of the rbu_target_name() SQL function. This function
169533** accepts one or two arguments. The first argument is the name of a table -
169534** the name of a table in the RBU database.  The second, if it is present, is 1
169535** for a view or 0 for a table.
169536**
169537** For a non-vacuum RBU handle, if the table name matches the pattern:
169538**
169539**     data[0-9]_<name>
169540**
169541** where <name> is any sequence of 1 or more characters, <name> is returned.
169542** Otherwise, if the only argument does not match the above pattern, an SQL
169543** NULL is returned.
169544**
169545**     "data_t1"     -> "t1"
169546**     "data0123_t2" -> "t2"
169547**     "dataAB_t3"   -> NULL
169548**
169549** For an rbu vacuum handle, a copy of the first argument is returned if
169550** the second argument is either missing or 0 (not a view).
169551*/
169552static void rbuTargetNameFunc(
169553  sqlite3_context *pCtx,
169554  int argc,
169555  sqlite3_value **argv
169556){
169557  sqlite3rbu *p = sqlite3_user_data(pCtx);
169558  const char *zIn;
169559  assert( argc==1 || argc==2 );
169560
169561  zIn = (const char*)sqlite3_value_text(argv[0]);
169562  if( zIn ){
169563    if( rbuIsVacuum(p) ){
169564      if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
169565        sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
169566      }
169567    }else{
169568      if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
169569        int i;
169570        for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
169571        if( zIn[i]=='_' && zIn[i+1] ){
169572          sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
169573        }
169574      }
169575    }
169576  }
169577}
169578
169579/*
169580** Initialize the iterator structure passed as the second argument.
169581**
169582** If no error occurs, SQLITE_OK is returned and the iterator is left
169583** pointing to the first entry. Otherwise, an error code and message is
169584** left in the RBU handle passed as the first argument. A copy of the
169585** error code is returned.
169586*/
169587static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
169588  int rc;
169589  memset(pIter, 0, sizeof(RbuObjIter));
169590
169591  rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
169592    sqlite3_mprintf(
169593      "SELECT rbu_target_name(name, type='view') AS target, name "
169594      "FROM sqlite_master "
169595      "WHERE type IN ('table', 'view') AND target IS NOT NULL "
169596      " %s "
169597      "ORDER BY name"
169598  , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
169599
169600  if( rc==SQLITE_OK ){
169601    rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
169602        "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
169603        "  FROM main.sqlite_master "
169604        "  WHERE type='index' AND tbl_name = ?"
169605    );
169606  }
169607
169608  pIter->bCleanup = 1;
169609  p->rc = rc;
169610  return rbuObjIterNext(p, pIter);
169611}
169612
169613/*
169614** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
169615** an error code is stored in the RBU handle passed as the first argument.
169616**
169617** If an error has already occurred (p->rc is already set to something other
169618** than SQLITE_OK), then this function returns NULL without modifying the
169619** stored error code. In this case it still calls sqlite3_free() on any
169620** printf() parameters associated with %z conversions.
169621*/
169622static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
169623  char *zSql = 0;
169624  va_list ap;
169625  va_start(ap, zFmt);
169626  zSql = sqlite3_vmprintf(zFmt, ap);
169627  if( p->rc==SQLITE_OK ){
169628    if( zSql==0 ) p->rc = SQLITE_NOMEM;
169629  }else{
169630    sqlite3_free(zSql);
169631    zSql = 0;
169632  }
169633  va_end(ap);
169634  return zSql;
169635}
169636
169637/*
169638** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
169639** arguments are the usual subsitution values. This function performs
169640** the printf() style substitutions and executes the result as an SQL
169641** statement on the RBU handles database.
169642**
169643** If an error occurs, an error code and error message is stored in the
169644** RBU handle. If an error has already occurred when this function is
169645** called, it is a no-op.
169646*/
169647static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
169648  va_list ap;
169649  char *zSql;
169650  va_start(ap, zFmt);
169651  zSql = sqlite3_vmprintf(zFmt, ap);
169652  if( p->rc==SQLITE_OK ){
169653    if( zSql==0 ){
169654      p->rc = SQLITE_NOMEM;
169655    }else{
169656      p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
169657    }
169658  }
169659  sqlite3_free(zSql);
169660  va_end(ap);
169661  return p->rc;
169662}
169663
169664/*
169665** Attempt to allocate and return a pointer to a zeroed block of nByte
169666** bytes.
169667**
169668** If an error (i.e. an OOM condition) occurs, return NULL and leave an
169669** error code in the rbu handle passed as the first argument. Or, if an
169670** error has already occurred when this function is called, return NULL
169671** immediately without attempting the allocation or modifying the stored
169672** error code.
169673*/
169674static void *rbuMalloc(sqlite3rbu *p, int nByte){
169675  void *pRet = 0;
169676  if( p->rc==SQLITE_OK ){
169677    assert( nByte>0 );
169678    pRet = sqlite3_malloc64(nByte);
169679    if( pRet==0 ){
169680      p->rc = SQLITE_NOMEM;
169681    }else{
169682      memset(pRet, 0, nByte);
169683    }
169684  }
169685  return pRet;
169686}
169687
169688
169689/*
169690** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
169691** there is room for at least nCol elements. If an OOM occurs, store an
169692** error code in the RBU handle passed as the first argument.
169693*/
169694static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
169695  int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
169696  char **azNew;
169697
169698  azNew = (char**)rbuMalloc(p, nByte);
169699  if( azNew ){
169700    pIter->azTblCol = azNew;
169701    pIter->azTblType = &azNew[nCol];
169702    pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
169703    pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
169704    pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
169705    pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
169706  }
169707}
169708
169709/*
169710** The first argument must be a nul-terminated string. This function
169711** returns a copy of the string in memory obtained from sqlite3_malloc().
169712** It is the responsibility of the caller to eventually free this memory
169713** using sqlite3_free().
169714**
169715** If an OOM condition is encountered when attempting to allocate memory,
169716** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
169717** if the allocation succeeds, (*pRc) is left unchanged.
169718*/
169719static char *rbuStrndup(const char *zStr, int *pRc){
169720  char *zRet = 0;
169721
169722  assert( *pRc==SQLITE_OK );
169723  if( zStr ){
169724    size_t nCopy = strlen(zStr) + 1;
169725    zRet = (char*)sqlite3_malloc64(nCopy);
169726    if( zRet ){
169727      memcpy(zRet, zStr, nCopy);
169728    }else{
169729      *pRc = SQLITE_NOMEM;
169730    }
169731  }
169732
169733  return zRet;
169734}
169735
169736/*
169737** Finalize the statement passed as the second argument.
169738**
169739** If the sqlite3_finalize() call indicates that an error occurs, and the
169740** rbu handle error code is not already set, set the error code and error
169741** message accordingly.
169742*/
169743static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
169744  sqlite3 *db = sqlite3_db_handle(pStmt);
169745  int rc = sqlite3_finalize(pStmt);
169746  if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
169747    p->rc = rc;
169748    p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
169749  }
169750}
169751
169752/* Determine the type of a table.
169753**
169754**   peType is of type (int*), a pointer to an output parameter of type
169755**   (int). This call sets the output parameter as follows, depending
169756**   on the type of the table specified by parameters dbName and zTbl.
169757**
169758**     RBU_PK_NOTABLE:       No such table.
169759**     RBU_PK_NONE:          Table has an implicit rowid.
169760**     RBU_PK_IPK:           Table has an explicit IPK column.
169761**     RBU_PK_EXTERNAL:      Table has an external PK index.
169762**     RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
169763**     RBU_PK_VTAB:          Table is a virtual table.
169764**
169765**   Argument *piPk is also of type (int*), and also points to an output
169766**   parameter. Unless the table has an external primary key index
169767**   (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
169768**   if the table does have an external primary key index, then *piPk
169769**   is set to the root page number of the primary key index before
169770**   returning.
169771**
169772** ALGORITHM:
169773**
169774**   if( no entry exists in sqlite_master ){
169775**     return RBU_PK_NOTABLE
169776**   }else if( sql for the entry starts with "CREATE VIRTUAL" ){
169777**     return RBU_PK_VTAB
169778**   }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
169779**     if( the index that is the pk exists in sqlite_master ){
169780**       *piPK = rootpage of that index.
169781**       return RBU_PK_EXTERNAL
169782**     }else{
169783**       return RBU_PK_WITHOUT_ROWID
169784**     }
169785**   }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
169786**     return RBU_PK_IPK
169787**   }else{
169788**     return RBU_PK_NONE
169789**   }
169790*/
169791static void rbuTableType(
169792  sqlite3rbu *p,
169793  const char *zTab,
169794  int *peType,
169795  int *piTnum,
169796  int *piPk
169797){
169798  /*
169799  ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
169800  ** 1) PRAGMA index_list = ?
169801  ** 2) SELECT count(*) FROM sqlite_master where name=%Q
169802  ** 3) PRAGMA table_info = ?
169803  */
169804  sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
169805
169806  *peType = RBU_PK_NOTABLE;
169807  *piPk = 0;
169808
169809  assert( p->rc==SQLITE_OK );
169810  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
169811    sqlite3_mprintf(
169812          "SELECT (sql LIKE 'create virtual%%'), rootpage"
169813          "  FROM sqlite_master"
169814          " WHERE name=%Q", zTab
169815  ));
169816  if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
169817    /* Either an error, or no such table. */
169818    goto rbuTableType_end;
169819  }
169820  if( sqlite3_column_int(aStmt[0], 0) ){
169821    *peType = RBU_PK_VTAB;                     /* virtual table */
169822    goto rbuTableType_end;
169823  }
169824  *piTnum = sqlite3_column_int(aStmt[0], 1);
169825
169826  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
169827    sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
169828  );
169829  if( p->rc ) goto rbuTableType_end;
169830  while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
169831    const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
169832    const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
169833    if( zOrig && zIdx && zOrig[0]=='p' ){
169834      p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
169835          sqlite3_mprintf(
169836            "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
169837      ));
169838      if( p->rc==SQLITE_OK ){
169839        if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
169840          *piPk = sqlite3_column_int(aStmt[2], 0);
169841          *peType = RBU_PK_EXTERNAL;
169842        }else{
169843          *peType = RBU_PK_WITHOUT_ROWID;
169844        }
169845      }
169846      goto rbuTableType_end;
169847    }
169848  }
169849
169850  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
169851    sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
169852  );
169853  if( p->rc==SQLITE_OK ){
169854    while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
169855      if( sqlite3_column_int(aStmt[3],5)>0 ){
169856        *peType = RBU_PK_IPK;                /* explicit IPK column */
169857        goto rbuTableType_end;
169858      }
169859    }
169860    *peType = RBU_PK_NONE;
169861  }
169862
169863rbuTableType_end: {
169864    unsigned int i;
169865    for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
169866      rbuFinalize(p, aStmt[i]);
169867    }
169868  }
169869}
169870
169871/*
169872** This is a helper function for rbuObjIterCacheTableInfo(). It populates
169873** the pIter->abIndexed[] array.
169874*/
169875static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
169876  sqlite3_stmt *pList = 0;
169877  int bIndex = 0;
169878
169879  if( p->rc==SQLITE_OK ){
169880    memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
169881    p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
169882        sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
169883    );
169884  }
169885
169886  pIter->nIndex = 0;
169887  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
169888    const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
169889    sqlite3_stmt *pXInfo = 0;
169890    if( zIdx==0 ) break;
169891    p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
169892        sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
169893    );
169894    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
169895      int iCid = sqlite3_column_int(pXInfo, 1);
169896      if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
169897    }
169898    rbuFinalize(p, pXInfo);
169899    bIndex = 1;
169900    pIter->nIndex++;
169901  }
169902
169903  if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
169904    /* "PRAGMA index_list" includes the main PK b-tree */
169905    pIter->nIndex--;
169906  }
169907
169908  rbuFinalize(p, pList);
169909  if( bIndex==0 ) pIter->abIndexed = 0;
169910}
169911
169912
169913/*
169914** If they are not already populated, populate the pIter->azTblCol[],
169915** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
169916** the table (not index) that the iterator currently points to.
169917**
169918** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
169919** an error does occur, an error code and error message are also left in
169920** the RBU handle.
169921*/
169922static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
169923  if( pIter->azTblCol==0 ){
169924    sqlite3_stmt *pStmt = 0;
169925    int nCol = 0;
169926    int i;                        /* for() loop iterator variable */
169927    int bRbuRowid = 0;            /* If input table has column "rbu_rowid" */
169928    int iOrder = 0;
169929    int iTnum = 0;
169930
169931    /* Figure out the type of table this step will deal with. */
169932    assert( pIter->eType==0 );
169933    rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
169934    if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
169935      p->rc = SQLITE_ERROR;
169936      p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
169937    }
169938    if( p->rc ) return p->rc;
169939    if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
169940
169941    assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
169942         || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
169943         || pIter->eType==RBU_PK_VTAB
169944    );
169945
169946    /* Populate the azTblCol[] and nTblCol variables based on the columns
169947    ** of the input table. Ignore any input table columns that begin with
169948    ** "rbu_".  */
169949    p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
169950        sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
169951    );
169952    if( p->rc==SQLITE_OK ){
169953      nCol = sqlite3_column_count(pStmt);
169954      rbuAllocateIterArrays(p, pIter, nCol);
169955    }
169956    for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
169957      const char *zName = (const char*)sqlite3_column_name(pStmt, i);
169958      if( sqlite3_strnicmp("rbu_", zName, 4) ){
169959        char *zCopy = rbuStrndup(zName, &p->rc);
169960        pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
169961        pIter->azTblCol[pIter->nTblCol++] = zCopy;
169962      }
169963      else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
169964        bRbuRowid = 1;
169965      }
169966    }
169967    sqlite3_finalize(pStmt);
169968    pStmt = 0;
169969
169970    if( p->rc==SQLITE_OK
169971     && rbuIsVacuum(p)==0
169972     && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
169973    ){
169974      p->rc = SQLITE_ERROR;
169975      p->zErrmsg = sqlite3_mprintf(
169976          "table %q %s rbu_rowid column", pIter->zDataTbl,
169977          (bRbuRowid ? "may not have" : "requires")
169978      );
169979    }
169980
169981    /* Check that all non-HIDDEN columns in the destination table are also
169982    ** present in the input table. Populate the abTblPk[], azTblType[] and
169983    ** aiTblOrder[] arrays at the same time.  */
169984    if( p->rc==SQLITE_OK ){
169985      p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
169986          sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
169987      );
169988    }
169989    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
169990      const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
169991      if( zName==0 ) break;  /* An OOM - finalize() below returns S_NOMEM */
169992      for(i=iOrder; i<pIter->nTblCol; i++){
169993        if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
169994      }
169995      if( i==pIter->nTblCol ){
169996        p->rc = SQLITE_ERROR;
169997        p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
169998            pIter->zDataTbl, zName
169999        );
170000      }else{
170001        int iPk = sqlite3_column_int(pStmt, 5);
170002        int bNotNull = sqlite3_column_int(pStmt, 3);
170003        const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
170004
170005        if( i!=iOrder ){
170006          SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
170007          SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
170008        }
170009
170010        pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
170011        pIter->abTblPk[iOrder] = (iPk!=0);
170012        pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
170013        iOrder++;
170014      }
170015    }
170016
170017    rbuFinalize(p, pStmt);
170018    rbuObjIterCacheIndexedCols(p, pIter);
170019    assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
170020    assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
170021  }
170022
170023  return p->rc;
170024}
170025
170026/*
170027** This function constructs and returns a pointer to a nul-terminated
170028** string containing some SQL clause or list based on one or more of the
170029** column names currently stored in the pIter->azTblCol[] array.
170030*/
170031static char *rbuObjIterGetCollist(
170032  sqlite3rbu *p,                  /* RBU object */
170033  RbuObjIter *pIter               /* Object iterator for column names */
170034){
170035  char *zList = 0;
170036  const char *zSep = "";
170037  int i;
170038  for(i=0; i<pIter->nTblCol; i++){
170039    const char *z = pIter->azTblCol[i];
170040    zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
170041    zSep = ", ";
170042  }
170043  return zList;
170044}
170045
170046/*
170047** This function is used to create a SELECT list (the list of SQL
170048** expressions that follows a SELECT keyword) for a SELECT statement
170049** used to read from an data_xxx or rbu_tmp_xxx table while updating the
170050** index object currently indicated by the iterator object passed as the
170051** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
170052** to obtain the required information.
170053**
170054** If the index is of the following form:
170055**
170056**   CREATE INDEX i1 ON t1(c, b COLLATE nocase);
170057**
170058** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
170059** "ipk", the returned string is:
170060**
170061**   "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
170062**
170063** As well as the returned string, three other malloc'd strings are
170064** returned via output parameters. As follows:
170065**
170066**   pzImposterCols: ...
170067**   pzImposterPk: ...
170068**   pzWhere: ...
170069*/
170070static char *rbuObjIterGetIndexCols(
170071  sqlite3rbu *p,                  /* RBU object */
170072  RbuObjIter *pIter,              /* Object iterator for column names */
170073  char **pzImposterCols,          /* OUT: Columns for imposter table */
170074  char **pzImposterPk,            /* OUT: Imposter PK clause */
170075  char **pzWhere,                 /* OUT: WHERE clause */
170076  int *pnBind                     /* OUT: Trbul number of columns */
170077){
170078  int rc = p->rc;                 /* Error code */
170079  int rc2;                        /* sqlite3_finalize() return code */
170080  char *zRet = 0;                 /* String to return */
170081  char *zImpCols = 0;             /* String to return via *pzImposterCols */
170082  char *zImpPK = 0;               /* String to return via *pzImposterPK */
170083  char *zWhere = 0;               /* String to return via *pzWhere */
170084  int nBind = 0;                  /* Value to return via *pnBind */
170085  const char *zCom = "";          /* Set to ", " later on */
170086  const char *zAnd = "";          /* Set to " AND " later on */
170087  sqlite3_stmt *pXInfo = 0;       /* PRAGMA index_xinfo = ? */
170088
170089  if( rc==SQLITE_OK ){
170090    assert( p->zErrmsg==0 );
170091    rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
170092        sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
170093    );
170094  }
170095
170096  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
170097    int iCid = sqlite3_column_int(pXInfo, 1);
170098    int bDesc = sqlite3_column_int(pXInfo, 3);
170099    const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
170100    const char *zCol;
170101    const char *zType;
170102
170103    if( iCid<0 ){
170104      /* An integer primary key. If the table has an explicit IPK, use
170105      ** its name. Otherwise, use "rbu_rowid".  */
170106      if( pIter->eType==RBU_PK_IPK ){
170107        int i;
170108        for(i=0; pIter->abTblPk[i]==0; i++);
170109        assert( i<pIter->nTblCol );
170110        zCol = pIter->azTblCol[i];
170111      }else if( rbuIsVacuum(p) ){
170112        zCol = "_rowid_";
170113      }else{
170114        zCol = "rbu_rowid";
170115      }
170116      zType = "INTEGER";
170117    }else{
170118      zCol = pIter->azTblCol[iCid];
170119      zType = pIter->azTblType[iCid];
170120    }
170121
170122    zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
170123    if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
170124      const char *zOrder = (bDesc ? " DESC" : "");
170125      zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
170126          zImpPK, zCom, nBind, zCol, zOrder
170127      );
170128    }
170129    zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
170130        zImpCols, zCom, nBind, zCol, zType, zCollate
170131    );
170132    zWhere = sqlite3_mprintf(
170133        "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
170134    );
170135    if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
170136    zCom = ", ";
170137    zAnd = " AND ";
170138    nBind++;
170139  }
170140
170141  rc2 = sqlite3_finalize(pXInfo);
170142  if( rc==SQLITE_OK ) rc = rc2;
170143
170144  if( rc!=SQLITE_OK ){
170145    sqlite3_free(zRet);
170146    sqlite3_free(zImpCols);
170147    sqlite3_free(zImpPK);
170148    sqlite3_free(zWhere);
170149    zRet = 0;
170150    zImpCols = 0;
170151    zImpPK = 0;
170152    zWhere = 0;
170153    p->rc = rc;
170154  }
170155
170156  *pzImposterCols = zImpCols;
170157  *pzImposterPk = zImpPK;
170158  *pzWhere = zWhere;
170159  *pnBind = nBind;
170160  return zRet;
170161}
170162
170163/*
170164** Assuming the current table columns are "a", "b" and "c", and the zObj
170165** paramter is passed "old", return a string of the form:
170166**
170167**     "old.a, old.b, old.b"
170168**
170169** With the column names escaped.
170170**
170171** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
170172** the text ", old._rowid_" to the returned value.
170173*/
170174static char *rbuObjIterGetOldlist(
170175  sqlite3rbu *p,
170176  RbuObjIter *pIter,
170177  const char *zObj
170178){
170179  char *zList = 0;
170180  if( p->rc==SQLITE_OK && pIter->abIndexed ){
170181    const char *zS = "";
170182    int i;
170183    for(i=0; i<pIter->nTblCol; i++){
170184      if( pIter->abIndexed[i] ){
170185        const char *zCol = pIter->azTblCol[i];
170186        zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
170187      }else{
170188        zList = sqlite3_mprintf("%z%sNULL", zList, zS);
170189      }
170190      zS = ", ";
170191      if( zList==0 ){
170192        p->rc = SQLITE_NOMEM;
170193        break;
170194      }
170195    }
170196
170197    /* For a table with implicit rowids, append "old._rowid_" to the list. */
170198    if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
170199      zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
170200    }
170201  }
170202  return zList;
170203}
170204
170205/*
170206** Return an expression that can be used in a WHERE clause to match the
170207** primary key of the current table. For example, if the table is:
170208**
170209**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
170210**
170211** Return the string:
170212**
170213**   "b = ?1 AND c = ?2"
170214*/
170215static char *rbuObjIterGetWhere(
170216  sqlite3rbu *p,
170217  RbuObjIter *pIter
170218){
170219  char *zList = 0;
170220  if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
170221    zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
170222  }else if( pIter->eType==RBU_PK_EXTERNAL ){
170223    const char *zSep = "";
170224    int i;
170225    for(i=0; i<pIter->nTblCol; i++){
170226      if( pIter->abTblPk[i] ){
170227        zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
170228        zSep = " AND ";
170229      }
170230    }
170231    zList = rbuMPrintf(p,
170232        "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
170233    );
170234
170235  }else{
170236    const char *zSep = "";
170237    int i;
170238    for(i=0; i<pIter->nTblCol; i++){
170239      if( pIter->abTblPk[i] ){
170240        const char *zCol = pIter->azTblCol[i];
170241        zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
170242        zSep = " AND ";
170243      }
170244    }
170245  }
170246  return zList;
170247}
170248
170249/*
170250** The SELECT statement iterating through the keys for the current object
170251** (p->objiter.pSelect) currently points to a valid row. However, there
170252** is something wrong with the rbu_control value in the rbu_control value
170253** stored in the (p->nCol+1)'th column. Set the error code and error message
170254** of the RBU handle to something reflecting this.
170255*/
170256static void rbuBadControlError(sqlite3rbu *p){
170257  p->rc = SQLITE_ERROR;
170258  p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
170259}
170260
170261
170262/*
170263** Return a nul-terminated string containing the comma separated list of
170264** assignments that should be included following the "SET" keyword of
170265** an UPDATE statement used to update the table object that the iterator
170266** passed as the second argument currently points to if the rbu_control
170267** column of the data_xxx table entry is set to zMask.
170268**
170269** The memory for the returned string is obtained from sqlite3_malloc().
170270** It is the responsibility of the caller to eventually free it using
170271** sqlite3_free().
170272**
170273** If an OOM error is encountered when allocating space for the new
170274** string, an error code is left in the rbu handle passed as the first
170275** argument and NULL is returned. Or, if an error has already occurred
170276** when this function is called, NULL is returned immediately, without
170277** attempting the allocation or modifying the stored error code.
170278*/
170279static char *rbuObjIterGetSetlist(
170280  sqlite3rbu *p,
170281  RbuObjIter *pIter,
170282  const char *zMask
170283){
170284  char *zList = 0;
170285  if( p->rc==SQLITE_OK ){
170286    int i;
170287
170288    if( (int)strlen(zMask)!=pIter->nTblCol ){
170289      rbuBadControlError(p);
170290    }else{
170291      const char *zSep = "";
170292      for(i=0; i<pIter->nTblCol; i++){
170293        char c = zMask[pIter->aiSrcOrder[i]];
170294        if( c=='x' ){
170295          zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
170296              zList, zSep, pIter->azTblCol[i], i+1
170297          );
170298          zSep = ", ";
170299        }
170300        else if( c=='d' ){
170301          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
170302              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
170303          );
170304          zSep = ", ";
170305        }
170306        else if( c=='f' ){
170307          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
170308              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
170309          );
170310          zSep = ", ";
170311        }
170312      }
170313    }
170314  }
170315  return zList;
170316}
170317
170318/*
170319** Return a nul-terminated string consisting of nByte comma separated
170320** "?" expressions. For example, if nByte is 3, return a pointer to
170321** a buffer containing the string "?,?,?".
170322**
170323** The memory for the returned string is obtained from sqlite3_malloc().
170324** It is the responsibility of the caller to eventually free it using
170325** sqlite3_free().
170326**
170327** If an OOM error is encountered when allocating space for the new
170328** string, an error code is left in the rbu handle passed as the first
170329** argument and NULL is returned. Or, if an error has already occurred
170330** when this function is called, NULL is returned immediately, without
170331** attempting the allocation or modifying the stored error code.
170332*/
170333static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
170334  char *zRet = 0;
170335  int nByte = nBind*2 + 1;
170336
170337  zRet = (char*)rbuMalloc(p, nByte);
170338  if( zRet ){
170339    int i;
170340    for(i=0; i<nBind; i++){
170341      zRet[i*2] = '?';
170342      zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
170343    }
170344  }
170345  return zRet;
170346}
170347
170348/*
170349** The iterator currently points to a table (not index) of type
170350** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
170351** declaration for the corresponding imposter table. For example,
170352** if the iterator points to a table created as:
170353**
170354**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
170355**
170356** this function returns:
170357**
170358**   PRIMARY KEY("b", "a" DESC)
170359*/
170360static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
170361  char *z = 0;
170362  assert( pIter->zIdx==0 );
170363  if( p->rc==SQLITE_OK ){
170364    const char *zSep = "PRIMARY KEY(";
170365    sqlite3_stmt *pXList = 0;     /* PRAGMA index_list = (pIter->zTbl) */
170366    sqlite3_stmt *pXInfo = 0;     /* PRAGMA index_xinfo = <pk-index> */
170367
170368    p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
170369        sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
170370    );
170371    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
170372      const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
170373      if( zOrig && strcmp(zOrig, "pk")==0 ){
170374        const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
170375        if( zIdx ){
170376          p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
170377              sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
170378          );
170379        }
170380        break;
170381      }
170382    }
170383    rbuFinalize(p, pXList);
170384
170385    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
170386      if( sqlite3_column_int(pXInfo, 5) ){
170387        /* int iCid = sqlite3_column_int(pXInfo, 0); */
170388        const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
170389        const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
170390        z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
170391        zSep = ", ";
170392      }
170393    }
170394    z = rbuMPrintf(p, "%z)", z);
170395    rbuFinalize(p, pXInfo);
170396  }
170397  return z;
170398}
170399
170400/*
170401** This function creates the second imposter table used when writing to
170402** a table b-tree where the table has an external primary key. If the
170403** iterator passed as the second argument does not currently point to
170404** a table (not index) with an external primary key, this function is a
170405** no-op.
170406**
170407** Assuming the iterator does point to a table with an external PK, this
170408** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
170409** used to access that PK index. For example, if the target table is
170410** declared as follows:
170411**
170412**   CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
170413**
170414** then the imposter table schema is:
170415**
170416**   CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
170417**
170418*/
170419static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
170420  if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
170421    int tnum = pIter->iPkTnum;    /* Root page of PK index */
170422    sqlite3_stmt *pQuery = 0;     /* SELECT name ... WHERE rootpage = $tnum */
170423    const char *zIdx = 0;         /* Name of PK index */
170424    sqlite3_stmt *pXInfo = 0;     /* PRAGMA main.index_xinfo = $zIdx */
170425    const char *zComma = "";
170426    char *zCols = 0;              /* Used to build up list of table cols */
170427    char *zPk = 0;                /* Used to build up table PK declaration */
170428
170429    /* Figure out the name of the primary key index for the current table.
170430    ** This is needed for the argument to "PRAGMA index_xinfo". Set
170431    ** zIdx to point to a nul-terminated string containing this name. */
170432    p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
170433        "SELECT name FROM sqlite_master WHERE rootpage = ?"
170434    );
170435    if( p->rc==SQLITE_OK ){
170436      sqlite3_bind_int(pQuery, 1, tnum);
170437      if( SQLITE_ROW==sqlite3_step(pQuery) ){
170438        zIdx = (const char*)sqlite3_column_text(pQuery, 0);
170439      }
170440    }
170441    if( zIdx ){
170442      p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
170443          sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
170444      );
170445    }
170446    rbuFinalize(p, pQuery);
170447
170448    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
170449      int bKey = sqlite3_column_int(pXInfo, 5);
170450      if( bKey ){
170451        int iCid = sqlite3_column_int(pXInfo, 1);
170452        int bDesc = sqlite3_column_int(pXInfo, 3);
170453        const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
170454        zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
170455            iCid, pIter->azTblType[iCid], zCollate
170456        );
170457        zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
170458        zComma = ", ";
170459      }
170460    }
170461    zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
170462    rbuFinalize(p, pXInfo);
170463
170464    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
170465    rbuMPrintfExec(p, p->dbMain,
170466        "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
170467        zCols, zPk
170468    );
170469    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
170470  }
170471}
170472
170473/*
170474** If an error has already occurred when this function is called, it
170475** immediately returns zero (without doing any work). Or, if an error
170476** occurs during the execution of this function, it sets the error code
170477** in the sqlite3rbu object indicated by the first argument and returns
170478** zero.
170479**
170480** The iterator passed as the second argument is guaranteed to point to
170481** a table (not an index) when this function is called. This function
170482** attempts to create any imposter table required to write to the main
170483** table b-tree of the table before returning. Non-zero is returned if
170484** an imposter table are created, or zero otherwise.
170485**
170486** An imposter table is required in all cases except RBU_PK_VTAB. Only
170487** virtual tables are written to directly. The imposter table has the
170488** same schema as the actual target table (less any UNIQUE constraints).
170489** More precisely, the "same schema" means the same columns, types,
170490** collation sequences. For tables that do not have an external PRIMARY
170491** KEY, it also means the same PRIMARY KEY declaration.
170492*/
170493static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
170494  if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
170495    int tnum = pIter->iTnum;
170496    const char *zComma = "";
170497    char *zSql = 0;
170498    int iCol;
170499    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
170500
170501    for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
170502      const char *zPk = "";
170503      const char *zCol = pIter->azTblCol[iCol];
170504      const char *zColl = 0;
170505
170506      p->rc = sqlite3_table_column_metadata(
170507          p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
170508      );
170509
170510      if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
170511        /* If the target table column is an "INTEGER PRIMARY KEY", add
170512        ** "PRIMARY KEY" to the imposter table column declaration. */
170513        zPk = "PRIMARY KEY ";
170514      }
170515      zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
170516          zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
170517          (pIter->abNotNull[iCol] ? " NOT NULL" : "")
170518      );
170519      zComma = ", ";
170520    }
170521
170522    if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
170523      char *zPk = rbuWithoutRowidPK(p, pIter);
170524      if( zPk ){
170525        zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
170526      }
170527    }
170528
170529    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
170530    rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
170531        pIter->zTbl, zSql,
170532        (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
170533    );
170534    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
170535  }
170536}
170537
170538/*
170539** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
170540** Specifically a statement of the form:
170541**
170542**     INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
170543**
170544** The number of bound variables is equal to the number of columns in
170545** the target table, plus one (for the rbu_control column), plus one more
170546** (for the rbu_rowid column) if the target table is an implicit IPK or
170547** virtual table.
170548*/
170549static void rbuObjIterPrepareTmpInsert(
170550  sqlite3rbu *p,
170551  RbuObjIter *pIter,
170552  const char *zCollist,
170553  const char *zRbuRowid
170554){
170555  int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
170556  char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
170557  if( zBind ){
170558    assert( pIter->pTmpInsert==0 );
170559    p->rc = prepareFreeAndCollectError(
170560        p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
170561          "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
170562          p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
170563    ));
170564  }
170565}
170566
170567static void rbuTmpInsertFunc(
170568  sqlite3_context *pCtx,
170569  int nVal,
170570  sqlite3_value **apVal
170571){
170572  sqlite3rbu *p = sqlite3_user_data(pCtx);
170573  int rc = SQLITE_OK;
170574  int i;
170575
170576  assert( sqlite3_value_int(apVal[0])!=0
170577      || p->objiter.eType==RBU_PK_EXTERNAL
170578      || p->objiter.eType==RBU_PK_NONE
170579  );
170580  if( sqlite3_value_int(apVal[0])!=0 ){
170581    p->nPhaseOneStep += p->objiter.nIndex;
170582  }
170583
170584  for(i=0; rc==SQLITE_OK && i<nVal; i++){
170585    rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
170586  }
170587  if( rc==SQLITE_OK ){
170588    sqlite3_step(p->objiter.pTmpInsert);
170589    rc = sqlite3_reset(p->objiter.pTmpInsert);
170590  }
170591
170592  if( rc!=SQLITE_OK ){
170593    sqlite3_result_error_code(pCtx, rc);
170594  }
170595}
170596
170597/*
170598** Ensure that the SQLite statement handles required to update the
170599** target database object currently indicated by the iterator passed
170600** as the second argument are available.
170601*/
170602static int rbuObjIterPrepareAll(
170603  sqlite3rbu *p,
170604  RbuObjIter *pIter,
170605  int nOffset                     /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
170606){
170607  assert( pIter->bCleanup==0 );
170608  if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
170609    const int tnum = pIter->iTnum;
170610    char *zCollist = 0;           /* List of indexed columns */
170611    char **pz = &p->zErrmsg;
170612    const char *zIdx = pIter->zIdx;
170613    char *zLimit = 0;
170614
170615    if( nOffset ){
170616      zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
170617      if( !zLimit ) p->rc = SQLITE_NOMEM;
170618    }
170619
170620    if( zIdx ){
170621      const char *zTbl = pIter->zTbl;
170622      char *zImposterCols = 0;    /* Columns for imposter table */
170623      char *zImposterPK = 0;      /* Primary key declaration for imposter */
170624      char *zWhere = 0;           /* WHERE clause on PK columns */
170625      char *zBind = 0;
170626      int nBind = 0;
170627
170628      assert( pIter->eType!=RBU_PK_VTAB );
170629      zCollist = rbuObjIterGetIndexCols(
170630          p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
170631      );
170632      zBind = rbuObjIterGetBindlist(p, nBind);
170633
170634      /* Create the imposter table used to write to this index. */
170635      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
170636      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
170637      rbuMPrintfExec(p, p->dbMain,
170638          "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
170639          zTbl, zImposterCols, zImposterPK
170640      );
170641      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
170642
170643      /* Create the statement to insert index entries */
170644      pIter->nCol = nBind;
170645      if( p->rc==SQLITE_OK ){
170646        p->rc = prepareFreeAndCollectError(
170647            p->dbMain, &pIter->pInsert, &p->zErrmsg,
170648          sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
170649        );
170650      }
170651
170652      /* And to delete index entries */
170653      if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
170654        p->rc = prepareFreeAndCollectError(
170655            p->dbMain, &pIter->pDelete, &p->zErrmsg,
170656          sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
170657        );
170658      }
170659
170660      /* Create the SELECT statement to read keys in sorted order */
170661      if( p->rc==SQLITE_OK ){
170662        char *zSql;
170663        if( rbuIsVacuum(p) ){
170664          zSql = sqlite3_mprintf(
170665              "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
170666              zCollist,
170667              pIter->zDataTbl,
170668              zCollist, zLimit
170669          );
170670        }else
170671
170672        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
170673          zSql = sqlite3_mprintf(
170674              "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
170675              zCollist, p->zStateDb, pIter->zDataTbl,
170676              zCollist, zLimit
170677          );
170678        }else{
170679          zSql = sqlite3_mprintf(
170680              "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
170681              "UNION ALL "
170682              "SELECT %s, rbu_control FROM '%q' "
170683              "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
170684              "ORDER BY %s%s",
170685              zCollist, p->zStateDb, pIter->zDataTbl,
170686              zCollist, pIter->zDataTbl,
170687              zCollist, zLimit
170688          );
170689        }
170690        p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
170691      }
170692
170693      sqlite3_free(zImposterCols);
170694      sqlite3_free(zImposterPK);
170695      sqlite3_free(zWhere);
170696      sqlite3_free(zBind);
170697    }else{
170698      int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
170699                    ||(pIter->eType==RBU_PK_NONE)
170700                    ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
170701      const char *zTbl = pIter->zTbl;       /* Table this step applies to */
170702      const char *zWrite;                   /* Imposter table name */
170703
170704      char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
170705      char *zWhere = rbuObjIterGetWhere(p, pIter);
170706      char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
170707      char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
170708
170709      zCollist = rbuObjIterGetCollist(p, pIter);
170710      pIter->nCol = pIter->nTblCol;
170711
170712      /* Create the imposter table or tables (if required). */
170713      rbuCreateImposterTable(p, pIter);
170714      rbuCreateImposterTable2(p, pIter);
170715      zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
170716
170717      /* Create the INSERT statement to write to the target PK b-tree */
170718      if( p->rc==SQLITE_OK ){
170719        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
170720            sqlite3_mprintf(
170721              "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
170722              zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
170723            )
170724        );
170725      }
170726
170727      /* Create the DELETE statement to write to the target PK b-tree.
170728      ** Because it only performs INSERT operations, this is not required for
170729      ** an rbu vacuum handle.  */
170730      if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
170731        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
170732            sqlite3_mprintf(
170733              "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
170734            )
170735        );
170736      }
170737
170738      if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
170739        const char *zRbuRowid = "";
170740        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
170741          zRbuRowid = ", rbu_rowid";
170742        }
170743
170744        /* Create the rbu_tmp_xxx table and the triggers to populate it. */
170745        rbuMPrintfExec(p, p->dbRbu,
170746            "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
170747            "SELECT *%s FROM '%q' WHERE 0;"
170748            , p->zStateDb, pIter->zDataTbl
170749            , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
170750            , pIter->zDataTbl
170751        );
170752
170753        rbuMPrintfExec(p, p->dbMain,
170754            "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
170755            "BEGIN "
170756            "  SELECT rbu_tmp_insert(3, %s);"
170757            "END;"
170758
170759            "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
170760            "BEGIN "
170761            "  SELECT rbu_tmp_insert(3, %s);"
170762            "END;"
170763
170764            "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
170765            "BEGIN "
170766            "  SELECT rbu_tmp_insert(4, %s);"
170767            "END;",
170768            zWrite, zTbl, zOldlist,
170769            zWrite, zTbl, zOldlist,
170770            zWrite, zTbl, zNewlist
170771        );
170772
170773        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
170774          rbuMPrintfExec(p, p->dbMain,
170775              "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
170776              "BEGIN "
170777              "  SELECT rbu_tmp_insert(0, %s);"
170778              "END;",
170779              zWrite, zTbl, zNewlist
170780          );
170781        }
170782
170783        rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
170784      }
170785
170786      /* Create the SELECT statement to read keys from data_xxx */
170787      if( p->rc==SQLITE_OK ){
170788        const char *zRbuRowid = "";
170789        if( bRbuRowid ){
170790          zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
170791        }
170792        p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
170793            sqlite3_mprintf(
170794              "SELECT %s,%s rbu_control%s FROM '%q'%s",
170795              zCollist,
170796              (rbuIsVacuum(p) ? "0 AS " : ""),
170797              zRbuRowid,
170798              pIter->zDataTbl, zLimit
170799            )
170800        );
170801      }
170802
170803      sqlite3_free(zWhere);
170804      sqlite3_free(zOldlist);
170805      sqlite3_free(zNewlist);
170806      sqlite3_free(zBindings);
170807    }
170808    sqlite3_free(zCollist);
170809    sqlite3_free(zLimit);
170810  }
170811
170812  return p->rc;
170813}
170814
170815/*
170816** Set output variable *ppStmt to point to an UPDATE statement that may
170817** be used to update the imposter table for the main table b-tree of the
170818** table object that pIter currently points to, assuming that the
170819** rbu_control column of the data_xyz table contains zMask.
170820**
170821** If the zMask string does not specify any columns to update, then this
170822** is not an error. Output variable *ppStmt is set to NULL in this case.
170823*/
170824static int rbuGetUpdateStmt(
170825  sqlite3rbu *p,                  /* RBU handle */
170826  RbuObjIter *pIter,              /* Object iterator */
170827  const char *zMask,              /* rbu_control value ('x.x.') */
170828  sqlite3_stmt **ppStmt           /* OUT: UPDATE statement handle */
170829){
170830  RbuUpdateStmt **pp;
170831  RbuUpdateStmt *pUp = 0;
170832  int nUp = 0;
170833
170834  /* In case an error occurs */
170835  *ppStmt = 0;
170836
170837  /* Search for an existing statement. If one is found, shift it to the front
170838  ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
170839  ** to the number of statements currently in the cache and pUp to the
170840  ** last object in the list.  */
170841  for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
170842    pUp = *pp;
170843    if( strcmp(pUp->zMask, zMask)==0 ){
170844      *pp = pUp->pNext;
170845      pUp->pNext = pIter->pRbuUpdate;
170846      pIter->pRbuUpdate = pUp;
170847      *ppStmt = pUp->pUpdate;
170848      return SQLITE_OK;
170849    }
170850    nUp++;
170851  }
170852  assert( pUp==0 || pUp->pNext==0 );
170853
170854  if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
170855    for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
170856    *pp = 0;
170857    sqlite3_finalize(pUp->pUpdate);
170858    pUp->pUpdate = 0;
170859  }else{
170860    pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
170861  }
170862
170863  if( pUp ){
170864    char *zWhere = rbuObjIterGetWhere(p, pIter);
170865    char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
170866    char *zUpdate = 0;
170867
170868    pUp->zMask = (char*)&pUp[1];
170869    memcpy(pUp->zMask, zMask, pIter->nTblCol);
170870    pUp->pNext = pIter->pRbuUpdate;
170871    pIter->pRbuUpdate = pUp;
170872
170873    if( zSet ){
170874      const char *zPrefix = "";
170875
170876      if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
170877      zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
170878          zPrefix, pIter->zTbl, zSet, zWhere
170879      );
170880      p->rc = prepareFreeAndCollectError(
170881          p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
170882      );
170883      *ppStmt = pUp->pUpdate;
170884    }
170885    sqlite3_free(zWhere);
170886    sqlite3_free(zSet);
170887  }
170888
170889  return p->rc;
170890}
170891
170892static sqlite3 *rbuOpenDbhandle(
170893  sqlite3rbu *p,
170894  const char *zName,
170895  int bUseVfs
170896){
170897  sqlite3 *db = 0;
170898  if( p->rc==SQLITE_OK ){
170899    const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
170900    p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
170901    if( p->rc ){
170902      p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
170903      sqlite3_close(db);
170904      db = 0;
170905    }
170906  }
170907  return db;
170908}
170909
170910/*
170911** Free an RbuState object allocated by rbuLoadState().
170912*/
170913static void rbuFreeState(RbuState *p){
170914  if( p ){
170915    sqlite3_free(p->zTbl);
170916    sqlite3_free(p->zIdx);
170917    sqlite3_free(p);
170918  }
170919}
170920
170921/*
170922** Allocate an RbuState object and load the contents of the rbu_state
170923** table into it. Return a pointer to the new object. It is the
170924** responsibility of the caller to eventually free the object using
170925** sqlite3_free().
170926**
170927** If an error occurs, leave an error code and message in the rbu handle
170928** and return NULL.
170929*/
170930static RbuState *rbuLoadState(sqlite3rbu *p){
170931  RbuState *pRet = 0;
170932  sqlite3_stmt *pStmt = 0;
170933  int rc;
170934  int rc2;
170935
170936  pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
170937  if( pRet==0 ) return 0;
170938
170939  rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
170940      sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
170941  );
170942  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
170943    switch( sqlite3_column_int(pStmt, 0) ){
170944      case RBU_STATE_STAGE:
170945        pRet->eStage = sqlite3_column_int(pStmt, 1);
170946        if( pRet->eStage!=RBU_STAGE_OAL
170947         && pRet->eStage!=RBU_STAGE_MOVE
170948         && pRet->eStage!=RBU_STAGE_CKPT
170949        ){
170950          p->rc = SQLITE_CORRUPT;
170951        }
170952        break;
170953
170954      case RBU_STATE_TBL:
170955        pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
170956        break;
170957
170958      case RBU_STATE_IDX:
170959        pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
170960        break;
170961
170962      case RBU_STATE_ROW:
170963        pRet->nRow = sqlite3_column_int(pStmt, 1);
170964        break;
170965
170966      case RBU_STATE_PROGRESS:
170967        pRet->nProgress = sqlite3_column_int64(pStmt, 1);
170968        break;
170969
170970      case RBU_STATE_CKPT:
170971        pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
170972        break;
170973
170974      case RBU_STATE_COOKIE:
170975        pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
170976        break;
170977
170978      case RBU_STATE_OALSZ:
170979        pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
170980        break;
170981
170982      case RBU_STATE_PHASEONESTEP:
170983        pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
170984        break;
170985
170986      default:
170987        rc = SQLITE_CORRUPT;
170988        break;
170989    }
170990  }
170991  rc2 = sqlite3_finalize(pStmt);
170992  if( rc==SQLITE_OK ) rc = rc2;
170993
170994  p->rc = rc;
170995  return pRet;
170996}
170997
170998
170999/*
171000** Open the database handle and attach the RBU database as "rbu". If an
171001** error occurs, leave an error code and message in the RBU handle.
171002*/
171003static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
171004  assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
171005  assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
171006
171007  /* Open the RBU database */
171008  p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
171009
171010  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
171011    sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
171012    if( p->zState==0 ){
171013      const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
171014      p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
171015    }
171016  }
171017
171018  /* If using separate RBU and state databases, attach the state database to
171019  ** the RBU db handle now.  */
171020  if( p->zState ){
171021    rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
171022    memcpy(p->zStateDb, "stat", 4);
171023  }else{
171024    memcpy(p->zStateDb, "main", 4);
171025  }
171026
171027#if 0
171028  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
171029    p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
171030  }
171031#endif
171032
171033  /* If it has not already been created, create the rbu_state table */
171034  rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
171035
171036#if 0
171037  if( rbuIsVacuum(p) ){
171038    if( p->rc==SQLITE_OK ){
171039      int rc2;
171040      int bOk = 0;
171041      sqlite3_stmt *pCnt = 0;
171042      p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
171043          "SELECT count(*) FROM stat.sqlite_master"
171044      );
171045      if( p->rc==SQLITE_OK
171046       && sqlite3_step(pCnt)==SQLITE_ROW
171047       && 1==sqlite3_column_int(pCnt, 0)
171048      ){
171049        bOk = 1;
171050      }
171051      rc2 = sqlite3_finalize(pCnt);
171052      if( p->rc==SQLITE_OK ) p->rc = rc2;
171053
171054      if( p->rc==SQLITE_OK && bOk==0 ){
171055        p->rc = SQLITE_ERROR;
171056        p->zErrmsg = sqlite3_mprintf("invalid state database");
171057      }
171058
171059      if( p->rc==SQLITE_OK ){
171060        p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
171061      }
171062    }
171063  }
171064#endif
171065
171066  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
171067    int bOpen = 0;
171068    int rc;
171069    p->nRbu = 0;
171070    p->pRbuFd = 0;
171071    rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
171072    if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
171073    if( p->eStage>=RBU_STAGE_MOVE ){
171074      bOpen = 1;
171075    }else{
171076      RbuState *pState = rbuLoadState(p);
171077      if( pState ){
171078        bOpen = (pState->eStage>=RBU_STAGE_MOVE);
171079        rbuFreeState(pState);
171080      }
171081    }
171082    if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
171083  }
171084
171085  p->eStage = 0;
171086  if( p->rc==SQLITE_OK && p->dbMain==0 ){
171087    if( !rbuIsVacuum(p) ){
171088      p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
171089    }else if( p->pRbuFd->pWalFd ){
171090      if( pbRetry ){
171091        p->pRbuFd->bNolock = 0;
171092        sqlite3_close(p->dbRbu);
171093        sqlite3_close(p->dbMain);
171094        p->dbMain = 0;
171095        p->dbRbu = 0;
171096        *pbRetry = 1;
171097        return;
171098      }
171099      p->rc = SQLITE_ERROR;
171100      p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
171101    }else{
171102      char *zTarget;
171103      char *zExtra = 0;
171104      if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
171105        zExtra = &p->zRbu[5];
171106        while( *zExtra ){
171107          if( *zExtra++=='?' ) break;
171108        }
171109        if( *zExtra=='\0' ) zExtra = 0;
171110      }
171111
171112      zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
171113          sqlite3_db_filename(p->dbRbu, "main"),
171114          (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
171115      );
171116
171117      if( zTarget==0 ){
171118        p->rc = SQLITE_NOMEM;
171119        return;
171120      }
171121      p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
171122      sqlite3_free(zTarget);
171123    }
171124  }
171125
171126  if( p->rc==SQLITE_OK ){
171127    p->rc = sqlite3_create_function(p->dbMain,
171128        "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
171129    );
171130  }
171131
171132  if( p->rc==SQLITE_OK ){
171133    p->rc = sqlite3_create_function(p->dbMain,
171134        "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
171135    );
171136  }
171137
171138  if( p->rc==SQLITE_OK ){
171139    p->rc = sqlite3_create_function(p->dbRbu,
171140        "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
171141    );
171142  }
171143
171144  if( p->rc==SQLITE_OK ){
171145    p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
171146  }
171147  rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
171148
171149  /* Mark the database file just opened as an RBU target database. If
171150  ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
171151  ** This is an error.  */
171152  if( p->rc==SQLITE_OK ){
171153    p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
171154  }
171155
171156  if( p->rc==SQLITE_NOTFOUND ){
171157    p->rc = SQLITE_ERROR;
171158    p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
171159  }
171160}
171161
171162/*
171163** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
171164** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
171165**
171166** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
171167** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
171168** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
171169** three characters, then shorten the suffix on z[] to be the last three
171170** characters of the original suffix.
171171**
171172** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
171173** do the suffix shortening regardless of URI parameter.
171174**
171175** Examples:
171176**
171177**     test.db-journal    =>   test.nal
171178**     test.db-wal        =>   test.wal
171179**     test.db-shm        =>   test.shm
171180**     test.db-mj7f3319fa =>   test.9fa
171181*/
171182static void rbuFileSuffix3(const char *zBase, char *z){
171183#ifdef SQLITE_ENABLE_8_3_NAMES
171184#if SQLITE_ENABLE_8_3_NAMES<2
171185  if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
171186#endif
171187  {
171188    int i, sz;
171189    sz = (int)strlen(z)&0xffffff;
171190    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
171191    if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
171192  }
171193#endif
171194}
171195
171196/*
171197** Return the current wal-index header checksum for the target database
171198** as a 64-bit integer.
171199**
171200** The checksum is store in the first page of xShmMap memory as an 8-byte
171201** blob starting at byte offset 40.
171202*/
171203static i64 rbuShmChecksum(sqlite3rbu *p){
171204  i64 iRet = 0;
171205  if( p->rc==SQLITE_OK ){
171206    sqlite3_file *pDb = p->pTargetFd->pReal;
171207    u32 volatile *ptr;
171208    p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
171209    if( p->rc==SQLITE_OK ){
171210      iRet = ((i64)ptr[10] << 32) + ptr[11];
171211    }
171212  }
171213  return iRet;
171214}
171215
171216/*
171217** This function is called as part of initializing or reinitializing an
171218** incremental checkpoint.
171219**
171220** It populates the sqlite3rbu.aFrame[] array with the set of
171221** (wal frame -> db page) copy operations required to checkpoint the
171222** current wal file, and obtains the set of shm locks required to safely
171223** perform the copy operations directly on the file-system.
171224**
171225** If argument pState is not NULL, then the incremental checkpoint is
171226** being resumed. In this case, if the checksum of the wal-index-header
171227** following recovery is not the same as the checksum saved in the RbuState
171228** object, then the rbu handle is set to DONE state. This occurs if some
171229** other client appends a transaction to the wal file in the middle of
171230** an incremental checkpoint.
171231*/
171232static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
171233
171234  /* If pState is NULL, then the wal file may not have been opened and
171235  ** recovered. Running a read-statement here to ensure that doing so
171236  ** does not interfere with the "capture" process below.  */
171237  if( pState==0 ){
171238    p->eStage = 0;
171239    if( p->rc==SQLITE_OK ){
171240      p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
171241    }
171242  }
171243
171244  /* Assuming no error has occurred, run a "restart" checkpoint with the
171245  ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
171246  ** special behaviour in the rbu VFS:
171247  **
171248  **   * If the exclusive shm WRITER or READ0 lock cannot be obtained,
171249  **     the checkpoint fails with SQLITE_BUSY (normally SQLite would
171250  **     proceed with running a passive checkpoint instead of failing).
171251  **
171252  **   * Attempts to read from the *-wal file or write to the database file
171253  **     do not perform any IO. Instead, the frame/page combinations that
171254  **     would be read/written are recorded in the sqlite3rbu.aFrame[]
171255  **     array.
171256  **
171257  **   * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
171258  **     READ0 and CHECKPOINT locks taken as part of the checkpoint are
171259  **     no-ops. These locks will not be released until the connection
171260  **     is closed.
171261  **
171262  **   * Attempting to xSync() the database file causes an SQLITE_INTERNAL
171263  **     error.
171264  **
171265  ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
171266  ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
171267  ** array populated with a set of (frame -> page) mappings. Because the
171268  ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
171269  ** data from the wal file into the database file according to the
171270  ** contents of aFrame[].
171271  */
171272  if( p->rc==SQLITE_OK ){
171273    int rc2;
171274    p->eStage = RBU_STAGE_CAPTURE;
171275    rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
171276    if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
171277  }
171278
171279  if( p->rc==SQLITE_OK && p->nFrame>0 ){
171280    p->eStage = RBU_STAGE_CKPT;
171281    p->nStep = (pState ? pState->nRow : 0);
171282    p->aBuf = rbuMalloc(p, p->pgsz);
171283    p->iWalCksum = rbuShmChecksum(p);
171284  }
171285
171286  if( p->rc==SQLITE_OK ){
171287    if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
171288      p->rc = SQLITE_DONE;
171289      p->eStage = RBU_STAGE_DONE;
171290    }else{
171291      int nSectorSize;
171292      sqlite3_file *pDb = p->pTargetFd->pReal;
171293      sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
171294      assert( p->nPagePerSector==0 );
171295      nSectorSize = pDb->pMethods->xSectorSize(pDb);
171296      if( nSectorSize>p->pgsz ){
171297        p->nPagePerSector = nSectorSize / p->pgsz;
171298      }else{
171299        p->nPagePerSector = 1;
171300      }
171301
171302      /* Call xSync() on the wal file. This causes SQLite to sync the
171303      ** directory in which the target database and the wal file reside, in
171304      ** case it has not been synced since the rename() call in
171305      ** rbuMoveOalFile(). */
171306      p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
171307    }
171308  }
171309}
171310
171311/*
171312** Called when iAmt bytes are read from offset iOff of the wal file while
171313** the rbu object is in capture mode. Record the frame number of the frame
171314** being read in the aFrame[] array.
171315*/
171316static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
171317  const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
171318  u32 iFrame;
171319
171320  if( pRbu->mLock!=mReq ){
171321    pRbu->rc = SQLITE_BUSY;
171322    return SQLITE_INTERNAL;
171323  }
171324
171325  pRbu->pgsz = iAmt;
171326  if( pRbu->nFrame==pRbu->nFrameAlloc ){
171327    int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
171328    RbuFrame *aNew;
171329    aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
171330    if( aNew==0 ) return SQLITE_NOMEM;
171331    pRbu->aFrame = aNew;
171332    pRbu->nFrameAlloc = nNew;
171333  }
171334
171335  iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
171336  if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
171337  pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
171338  pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
171339  pRbu->nFrame++;
171340  return SQLITE_OK;
171341}
171342
171343/*
171344** Called when a page of data is written to offset iOff of the database
171345** file while the rbu handle is in capture mode. Record the page number
171346** of the page being written in the aFrame[] array.
171347*/
171348static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
171349  pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
171350  return SQLITE_OK;
171351}
171352
171353/*
171354** This is called as part of an incremental checkpoint operation. Copy
171355** a single frame of data from the wal file into the database file, as
171356** indicated by the RbuFrame object.
171357*/
171358static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
171359  sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
171360  sqlite3_file *pDb = p->pTargetFd->pReal;
171361  i64 iOff;
171362
171363  assert( p->rc==SQLITE_OK );
171364  iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
171365  p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
171366  if( p->rc ) return;
171367
171368  iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
171369  p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
171370}
171371
171372
171373/*
171374** Take an EXCLUSIVE lock on the database file.
171375*/
171376static void rbuLockDatabase(sqlite3rbu *p){
171377  sqlite3_file *pReal = p->pTargetFd->pReal;
171378  assert( p->rc==SQLITE_OK );
171379  p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
171380  if( p->rc==SQLITE_OK ){
171381    p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
171382  }
171383}
171384
171385#if defined(_WIN32_WCE)
171386static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
171387  int nChar;
171388  LPWSTR zWideFilename;
171389
171390  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
171391  if( nChar==0 ){
171392    return 0;
171393  }
171394  zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
171395  if( zWideFilename==0 ){
171396    return 0;
171397  }
171398  memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
171399  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
171400                                nChar);
171401  if( nChar==0 ){
171402    sqlite3_free(zWideFilename);
171403    zWideFilename = 0;
171404  }
171405  return zWideFilename;
171406}
171407#endif
171408
171409/*
171410** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
171411** on the database file. This proc moves the *-oal file to the *-wal path,
171412** then reopens the database file (this time in vanilla, non-oal, WAL mode).
171413** If an error occurs, leave an error code and error message in the rbu
171414** handle.
171415*/
171416static void rbuMoveOalFile(sqlite3rbu *p){
171417  const char *zBase = sqlite3_db_filename(p->dbMain, "main");
171418  const char *zMove = zBase;
171419  char *zOal;
171420  char *zWal;
171421
171422  if( rbuIsVacuum(p) ){
171423    zMove = sqlite3_db_filename(p->dbRbu, "main");
171424  }
171425  zOal = sqlite3_mprintf("%s-oal", zMove);
171426  zWal = sqlite3_mprintf("%s-wal", zMove);
171427
171428  assert( p->eStage==RBU_STAGE_MOVE );
171429  assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
171430  if( zWal==0 || zOal==0 ){
171431    p->rc = SQLITE_NOMEM;
171432  }else{
171433    /* Move the *-oal file to *-wal. At this point connection p->db is
171434    ** holding a SHARED lock on the target database file (because it is
171435    ** in WAL mode). So no other connection may be writing the db.
171436    **
171437    ** In order to ensure that there are no database readers, an EXCLUSIVE
171438    ** lock is obtained here before the *-oal is moved to *-wal.
171439    */
171440    rbuLockDatabase(p);
171441    if( p->rc==SQLITE_OK ){
171442      rbuFileSuffix3(zBase, zWal);
171443      rbuFileSuffix3(zBase, zOal);
171444
171445      /* Re-open the databases. */
171446      rbuObjIterFinalize(&p->objiter);
171447      sqlite3_close(p->dbRbu);
171448      sqlite3_close(p->dbMain);
171449      p->dbMain = 0;
171450      p->dbRbu = 0;
171451
171452#if defined(_WIN32_WCE)
171453      {
171454        LPWSTR zWideOal;
171455        LPWSTR zWideWal;
171456
171457        zWideOal = rbuWinUtf8ToUnicode(zOal);
171458        if( zWideOal ){
171459          zWideWal = rbuWinUtf8ToUnicode(zWal);
171460          if( zWideWal ){
171461            if( MoveFileW(zWideOal, zWideWal) ){
171462              p->rc = SQLITE_OK;
171463            }else{
171464              p->rc = SQLITE_IOERR;
171465            }
171466            sqlite3_free(zWideWal);
171467          }else{
171468            p->rc = SQLITE_IOERR_NOMEM;
171469          }
171470          sqlite3_free(zWideOal);
171471        }else{
171472          p->rc = SQLITE_IOERR_NOMEM;
171473        }
171474      }
171475#else
171476      p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
171477#endif
171478
171479      if( p->rc==SQLITE_OK ){
171480        rbuOpenDatabase(p, 0);
171481        rbuSetupCheckpoint(p, 0);
171482      }
171483    }
171484  }
171485
171486  sqlite3_free(zWal);
171487  sqlite3_free(zOal);
171488}
171489
171490/*
171491** The SELECT statement iterating through the keys for the current object
171492** (p->objiter.pSelect) currently points to a valid row. This function
171493** determines the type of operation requested by this row and returns
171494** one of the following values to indicate the result:
171495**
171496**     * RBU_INSERT
171497**     * RBU_DELETE
171498**     * RBU_IDX_DELETE
171499**     * RBU_UPDATE
171500**
171501** If RBU_UPDATE is returned, then output variable *pzMask is set to
171502** point to the text value indicating the columns to update.
171503**
171504** If the rbu_control field contains an invalid value, an error code and
171505** message are left in the RBU handle and zero returned.
171506*/
171507static int rbuStepType(sqlite3rbu *p, const char **pzMask){
171508  int iCol = p->objiter.nCol;     /* Index of rbu_control column */
171509  int res = 0;                    /* Return value */
171510
171511  switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
171512    case SQLITE_INTEGER: {
171513      int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
171514      switch( iVal ){
171515        case 0: res = RBU_INSERT;     break;
171516        case 1: res = RBU_DELETE;     break;
171517        case 2: res = RBU_REPLACE;    break;
171518        case 3: res = RBU_IDX_DELETE; break;
171519        case 4: res = RBU_IDX_INSERT; break;
171520      }
171521      break;
171522    }
171523
171524    case SQLITE_TEXT: {
171525      const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
171526      if( z==0 ){
171527        p->rc = SQLITE_NOMEM;
171528      }else{
171529        *pzMask = (const char*)z;
171530      }
171531      res = RBU_UPDATE;
171532
171533      break;
171534    }
171535
171536    default:
171537      break;
171538  }
171539
171540  if( res==0 ){
171541    rbuBadControlError(p);
171542  }
171543  return res;
171544}
171545
171546#ifdef SQLITE_DEBUG
171547/*
171548** Assert that column iCol of statement pStmt is named zName.
171549*/
171550static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
171551  const char *zCol = sqlite3_column_name(pStmt, iCol);
171552  assert( 0==sqlite3_stricmp(zName, zCol) );
171553}
171554#else
171555# define assertColumnName(x,y,z)
171556#endif
171557
171558/*
171559** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
171560** RBU_IDX_DELETE. This function performs the work of a single
171561** sqlite3rbu_step() call for the type of operation specified by eType.
171562*/
171563static void rbuStepOneOp(sqlite3rbu *p, int eType){
171564  RbuObjIter *pIter = &p->objiter;
171565  sqlite3_value *pVal;
171566  sqlite3_stmt *pWriter;
171567  int i;
171568
171569  assert( p->rc==SQLITE_OK );
171570  assert( eType!=RBU_DELETE || pIter->zIdx==0 );
171571  assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
171572       || eType==RBU_INSERT || eType==RBU_IDX_INSERT
171573  );
171574
171575  /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
171576  ** statement below does actually delete a row, nPhaseOneStep will be
171577  ** incremented by the same amount when SQL function rbu_tmp_insert()
171578  ** is invoked by the trigger.  */
171579  if( eType==RBU_DELETE ){
171580    p->nPhaseOneStep -= p->objiter.nIndex;
171581  }
171582
171583  if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
171584    pWriter = pIter->pDelete;
171585  }else{
171586    pWriter = pIter->pInsert;
171587  }
171588
171589  for(i=0; i<pIter->nCol; i++){
171590    /* If this is an INSERT into a table b-tree and the table has an
171591    ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
171592    ** to write a NULL into the IPK column. That is not permitted.  */
171593    if( eType==RBU_INSERT
171594     && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
171595     && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
171596    ){
171597      p->rc = SQLITE_MISMATCH;
171598      p->zErrmsg = sqlite3_mprintf("datatype mismatch");
171599      return;
171600    }
171601
171602    if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
171603      continue;
171604    }
171605
171606    pVal = sqlite3_column_value(pIter->pSelect, i);
171607    p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
171608    if( p->rc ) return;
171609  }
171610  if( pIter->zIdx==0 ){
171611    if( pIter->eType==RBU_PK_VTAB
171612     || pIter->eType==RBU_PK_NONE
171613     || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
171614    ){
171615      /* For a virtual table, or a table with no primary key, the
171616      ** SELECT statement is:
171617      **
171618      **   SELECT <cols>, rbu_control, rbu_rowid FROM ....
171619      **
171620      ** Hence column_value(pIter->nCol+1).
171621      */
171622      assertColumnName(pIter->pSelect, pIter->nCol+1,
171623          rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
171624      );
171625      pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
171626      p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
171627    }
171628  }
171629  if( p->rc==SQLITE_OK ){
171630    sqlite3_step(pWriter);
171631    p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
171632  }
171633}
171634
171635/*
171636** This function does the work for an sqlite3rbu_step() call.
171637**
171638** The object-iterator (p->objiter) currently points to a valid object,
171639** and the input cursor (p->objiter.pSelect) currently points to a valid
171640** input row. Perform whatever processing is required and return.
171641**
171642** If no  error occurs, SQLITE_OK is returned. Otherwise, an error code
171643** and message is left in the RBU handle and a copy of the error code
171644** returned.
171645*/
171646static int rbuStep(sqlite3rbu *p){
171647  RbuObjIter *pIter = &p->objiter;
171648  const char *zMask = 0;
171649  int eType = rbuStepType(p, &zMask);
171650
171651  if( eType ){
171652    assert( eType==RBU_INSERT     || eType==RBU_DELETE
171653         || eType==RBU_REPLACE    || eType==RBU_IDX_DELETE
171654         || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
171655    );
171656    assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
171657
171658    if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
171659      rbuBadControlError(p);
171660    }
171661    else if( eType==RBU_REPLACE ){
171662      if( pIter->zIdx==0 ){
171663        p->nPhaseOneStep += p->objiter.nIndex;
171664        rbuStepOneOp(p, RBU_DELETE);
171665      }
171666      if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
171667    }
171668    else if( eType!=RBU_UPDATE ){
171669      rbuStepOneOp(p, eType);
171670    }
171671    else{
171672      sqlite3_value *pVal;
171673      sqlite3_stmt *pUpdate = 0;
171674      assert( eType==RBU_UPDATE );
171675      p->nPhaseOneStep -= p->objiter.nIndex;
171676      rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
171677      if( pUpdate ){
171678        int i;
171679        for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
171680          char c = zMask[pIter->aiSrcOrder[i]];
171681          pVal = sqlite3_column_value(pIter->pSelect, i);
171682          if( pIter->abTblPk[i] || c!='.' ){
171683            p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
171684          }
171685        }
171686        if( p->rc==SQLITE_OK
171687         && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
171688        ){
171689          /* Bind the rbu_rowid value to column _rowid_ */
171690          assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
171691          pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
171692          p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
171693        }
171694        if( p->rc==SQLITE_OK ){
171695          sqlite3_step(pUpdate);
171696          p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
171697        }
171698      }
171699    }
171700  }
171701  return p->rc;
171702}
171703
171704/*
171705** Increment the schema cookie of the main database opened by p->dbMain.
171706**
171707** Or, if this is an RBU vacuum, set the schema cookie of the main db
171708** opened by p->dbMain to one more than the schema cookie of the main
171709** db opened by p->dbRbu.
171710*/
171711static void rbuIncrSchemaCookie(sqlite3rbu *p){
171712  if( p->rc==SQLITE_OK ){
171713    sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
171714    int iCookie = 1000000;
171715    sqlite3_stmt *pStmt;
171716
171717    p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
171718        "PRAGMA schema_version"
171719    );
171720    if( p->rc==SQLITE_OK ){
171721      /* Coverage: it may be that this sqlite3_step() cannot fail. There
171722      ** is already a transaction open, so the prepared statement cannot
171723      ** throw an SQLITE_SCHEMA exception. The only database page the
171724      ** statement reads is page 1, which is guaranteed to be in the cache.
171725      ** And no memory allocations are required.  */
171726      if( SQLITE_ROW==sqlite3_step(pStmt) ){
171727        iCookie = sqlite3_column_int(pStmt, 0);
171728      }
171729      rbuFinalize(p, pStmt);
171730    }
171731    if( p->rc==SQLITE_OK ){
171732      rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
171733    }
171734  }
171735}
171736
171737/*
171738** Update the contents of the rbu_state table within the rbu database. The
171739** value stored in the RBU_STATE_STAGE column is eStage. All other values
171740** are determined by inspecting the rbu handle passed as the first argument.
171741*/
171742static void rbuSaveState(sqlite3rbu *p, int eStage){
171743  if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
171744    sqlite3_stmt *pInsert = 0;
171745    rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
171746    int rc;
171747
171748    assert( p->zErrmsg==0 );
171749    rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
171750        sqlite3_mprintf(
171751          "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
171752          "(%d, %d), "
171753          "(%d, %Q), "
171754          "(%d, %Q), "
171755          "(%d, %d), "
171756          "(%d, %d), "
171757          "(%d, %lld), "
171758          "(%d, %lld), "
171759          "(%d, %lld), "
171760          "(%d, %lld) ",
171761          p->zStateDb,
171762          RBU_STATE_STAGE, eStage,
171763          RBU_STATE_TBL, p->objiter.zTbl,
171764          RBU_STATE_IDX, p->objiter.zIdx,
171765          RBU_STATE_ROW, p->nStep,
171766          RBU_STATE_PROGRESS, p->nProgress,
171767          RBU_STATE_CKPT, p->iWalCksum,
171768          RBU_STATE_COOKIE, (i64)pFd->iCookie,
171769          RBU_STATE_OALSZ, p->iOalSz,
171770          RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
171771      )
171772    );
171773    assert( pInsert==0 || rc==SQLITE_OK );
171774
171775    if( rc==SQLITE_OK ){
171776      sqlite3_step(pInsert);
171777      rc = sqlite3_finalize(pInsert);
171778    }
171779    if( rc!=SQLITE_OK ) p->rc = rc;
171780  }
171781}
171782
171783
171784/*
171785** The second argument passed to this function is the name of a PRAGMA
171786** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
171787** This function executes the following on sqlite3rbu.dbRbu:
171788**
171789**   "PRAGMA main.$zPragma"
171790**
171791** where $zPragma is the string passed as the second argument, then
171792** on sqlite3rbu.dbMain:
171793**
171794**   "PRAGMA main.$zPragma = $val"
171795**
171796** where $val is the value returned by the first PRAGMA invocation.
171797**
171798** In short, it copies the value  of the specified PRAGMA setting from
171799** dbRbu to dbMain.
171800*/
171801static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
171802  if( p->rc==SQLITE_OK ){
171803    sqlite3_stmt *pPragma = 0;
171804    p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
171805        sqlite3_mprintf("PRAGMA main.%s", zPragma)
171806    );
171807    if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
171808      p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
171809          zPragma, sqlite3_column_int(pPragma, 0)
171810      );
171811    }
171812    rbuFinalize(p, pPragma);
171813  }
171814}
171815
171816/*
171817** The RBU handle passed as the only argument has just been opened and
171818** the state database is empty. If this RBU handle was opened for an
171819** RBU vacuum operation, create the schema in the target db.
171820*/
171821static void rbuCreateTargetSchema(sqlite3rbu *p){
171822  sqlite3_stmt *pSql = 0;
171823  sqlite3_stmt *pInsert = 0;
171824
171825  assert( rbuIsVacuum(p) );
171826  p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
171827  if( p->rc==SQLITE_OK ){
171828    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
171829      "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
171830      " AND name!='sqlite_sequence' "
171831      " ORDER BY type DESC"
171832    );
171833  }
171834
171835  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
171836    const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
171837    p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
171838  }
171839  rbuFinalize(p, pSql);
171840  if( p->rc!=SQLITE_OK ) return;
171841
171842  if( p->rc==SQLITE_OK ){
171843    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
171844        "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
171845    );
171846  }
171847
171848  if( p->rc==SQLITE_OK ){
171849    p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
171850        "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
171851    );
171852  }
171853
171854  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
171855    int i;
171856    for(i=0; i<5; i++){
171857      sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
171858    }
171859    sqlite3_step(pInsert);
171860    p->rc = sqlite3_reset(pInsert);
171861  }
171862  if( p->rc==SQLITE_OK ){
171863    p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
171864  }
171865
171866  rbuFinalize(p, pSql);
171867  rbuFinalize(p, pInsert);
171868}
171869
171870/*
171871** Step the RBU object.
171872*/
171873SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
171874  if( p ){
171875    switch( p->eStage ){
171876      case RBU_STAGE_OAL: {
171877        RbuObjIter *pIter = &p->objiter;
171878
171879        /* If this is an RBU vacuum operation and the state table was empty
171880        ** when this handle was opened, create the target database schema. */
171881        if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
171882          rbuCreateTargetSchema(p);
171883          rbuCopyPragma(p, "user_version");
171884          rbuCopyPragma(p, "application_id");
171885        }
171886
171887        while( p->rc==SQLITE_OK && pIter->zTbl ){
171888
171889          if( pIter->bCleanup ){
171890            /* Clean up the rbu_tmp_xxx table for the previous table. It
171891            ** cannot be dropped as there are currently active SQL statements.
171892            ** But the contents can be deleted.  */
171893            if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
171894              rbuMPrintfExec(p, p->dbRbu,
171895                  "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
171896              );
171897            }
171898          }else{
171899            rbuObjIterPrepareAll(p, pIter, 0);
171900
171901            /* Advance to the next row to process. */
171902            if( p->rc==SQLITE_OK ){
171903              int rc = sqlite3_step(pIter->pSelect);
171904              if( rc==SQLITE_ROW ){
171905                p->nProgress++;
171906                p->nStep++;
171907                return rbuStep(p);
171908              }
171909              p->rc = sqlite3_reset(pIter->pSelect);
171910              p->nStep = 0;
171911            }
171912          }
171913
171914          rbuObjIterNext(p, pIter);
171915        }
171916
171917        if( p->rc==SQLITE_OK ){
171918          assert( pIter->zTbl==0 );
171919          rbuSaveState(p, RBU_STAGE_MOVE);
171920          rbuIncrSchemaCookie(p);
171921          if( p->rc==SQLITE_OK ){
171922            p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
171923          }
171924          if( p->rc==SQLITE_OK ){
171925            p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
171926          }
171927          p->eStage = RBU_STAGE_MOVE;
171928        }
171929        break;
171930      }
171931
171932      case RBU_STAGE_MOVE: {
171933        if( p->rc==SQLITE_OK ){
171934          rbuMoveOalFile(p);
171935          p->nProgress++;
171936        }
171937        break;
171938      }
171939
171940      case RBU_STAGE_CKPT: {
171941        if( p->rc==SQLITE_OK ){
171942          if( p->nStep>=p->nFrame ){
171943            sqlite3_file *pDb = p->pTargetFd->pReal;
171944
171945            /* Sync the db file */
171946            p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
171947
171948            /* Update nBackfill */
171949            if( p->rc==SQLITE_OK ){
171950              void volatile *ptr;
171951              p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
171952              if( p->rc==SQLITE_OK ){
171953                ((u32 volatile*)ptr)[24] = p->iMaxFrame;
171954              }
171955            }
171956
171957            if( p->rc==SQLITE_OK ){
171958              p->eStage = RBU_STAGE_DONE;
171959              p->rc = SQLITE_DONE;
171960            }
171961          }else{
171962            /* At one point the following block copied a single frame from the
171963            ** wal file to the database file. So that one call to sqlite3rbu_step()
171964            ** checkpointed a single frame.
171965            **
171966            ** However, if the sector-size is larger than the page-size, and the
171967            ** application calls sqlite3rbu_savestate() or close() immediately
171968            ** after this step, then rbu_step() again, then a power failure occurs,
171969            ** then the database page written here may be damaged. Work around
171970            ** this by checkpointing frames until the next page in the aFrame[]
171971            ** lies on a different disk sector to the current one. */
171972            u32 iSector;
171973            do{
171974              RbuFrame *pFrame = &p->aFrame[p->nStep];
171975              iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
171976              rbuCheckpointFrame(p, pFrame);
171977              p->nStep++;
171978            }while( p->nStep<p->nFrame
171979                 && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
171980                 && p->rc==SQLITE_OK
171981            );
171982          }
171983          p->nProgress++;
171984        }
171985        break;
171986      }
171987
171988      default:
171989        break;
171990    }
171991    return p->rc;
171992  }else{
171993    return SQLITE_NOMEM;
171994  }
171995}
171996
171997/*
171998** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
171999** otherwise. Either or both argument may be NULL. Two NULL values are
172000** considered equal, and NULL is considered distinct from all other values.
172001*/
172002static int rbuStrCompare(const char *z1, const char *z2){
172003  if( z1==0 && z2==0 ) return 0;
172004  if( z1==0 || z2==0 ) return 1;
172005  return (sqlite3_stricmp(z1, z2)!=0);
172006}
172007
172008/*
172009** This function is called as part of sqlite3rbu_open() when initializing
172010** an rbu handle in OAL stage. If the rbu update has not started (i.e.
172011** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
172012** things so that the next call to sqlite3rbu_step() continues on from
172013** where the previous rbu handle left off.
172014**
172015** If an error occurs, an error code and error message are left in the
172016** rbu handle passed as the first argument.
172017*/
172018static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
172019  assert( p->rc==SQLITE_OK );
172020  if( pState->zTbl ){
172021    RbuObjIter *pIter = &p->objiter;
172022    int rc = SQLITE_OK;
172023
172024    while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
172025       || rbuStrCompare(pIter->zIdx, pState->zIdx)
172026       || rbuStrCompare(pIter->zTbl, pState->zTbl)
172027    )){
172028      rc = rbuObjIterNext(p, pIter);
172029    }
172030
172031    if( rc==SQLITE_OK && !pIter->zTbl ){
172032      rc = SQLITE_ERROR;
172033      p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
172034    }
172035
172036    if( rc==SQLITE_OK ){
172037      p->nStep = pState->nRow;
172038      rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
172039    }
172040
172041    p->rc = rc;
172042  }
172043}
172044
172045/*
172046** If there is a "*-oal" file in the file-system corresponding to the
172047** target database in the file-system, delete it. If an error occurs,
172048** leave an error code and error message in the rbu handle.
172049*/
172050static void rbuDeleteOalFile(sqlite3rbu *p){
172051  char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
172052  if( zOal ){
172053    sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
172054    assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
172055    pVfs->xDelete(pVfs, zOal, 0);
172056    sqlite3_free(zOal);
172057  }
172058}
172059
172060/*
172061** Allocate a private rbu VFS for the rbu handle passed as the only
172062** argument. This VFS will be used unless the call to sqlite3rbu_open()
172063** specified a URI with a vfs=? option in place of a target database
172064** file name.
172065*/
172066static void rbuCreateVfs(sqlite3rbu *p){
172067  int rnd;
172068  char zRnd[64];
172069
172070  assert( p->rc==SQLITE_OK );
172071  sqlite3_randomness(sizeof(int), (void*)&rnd);
172072  sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
172073  p->rc = sqlite3rbu_create_vfs(zRnd, 0);
172074  if( p->rc==SQLITE_OK ){
172075    sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
172076    assert( pVfs );
172077    p->zVfsName = pVfs->zName;
172078  }
172079}
172080
172081/*
172082** Destroy the private VFS created for the rbu handle passed as the only
172083** argument by an earlier call to rbuCreateVfs().
172084*/
172085static void rbuDeleteVfs(sqlite3rbu *p){
172086  if( p->zVfsName ){
172087    sqlite3rbu_destroy_vfs(p->zVfsName);
172088    p->zVfsName = 0;
172089  }
172090}
172091
172092/*
172093** This user-defined SQL function is invoked with a single argument - the
172094** name of a table expected to appear in the target database. It returns
172095** the number of auxilliary indexes on the table.
172096*/
172097static void rbuIndexCntFunc(
172098  sqlite3_context *pCtx,
172099  int nVal,
172100  sqlite3_value **apVal
172101){
172102  sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
172103  sqlite3_stmt *pStmt = 0;
172104  char *zErrmsg = 0;
172105  int rc;
172106
172107  assert( nVal==1 );
172108
172109  rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
172110      sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
172111        "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
172112  );
172113  if( rc!=SQLITE_OK ){
172114    sqlite3_result_error(pCtx, zErrmsg, -1);
172115  }else{
172116    int nIndex = 0;
172117    if( SQLITE_ROW==sqlite3_step(pStmt) ){
172118      nIndex = sqlite3_column_int(pStmt, 0);
172119    }
172120    rc = sqlite3_finalize(pStmt);
172121    if( rc==SQLITE_OK ){
172122      sqlite3_result_int(pCtx, nIndex);
172123    }else{
172124      sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
172125    }
172126  }
172127
172128  sqlite3_free(zErrmsg);
172129}
172130
172131/*
172132** If the RBU database contains the rbu_count table, use it to initialize
172133** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
172134** is assumed to contain the same columns as:
172135**
172136**   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
172137**
172138** There should be one row in the table for each data_xxx table in the
172139** database. The 'tbl' column should contain the name of a data_xxx table,
172140** and the cnt column the number of rows it contains.
172141**
172142** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
172143** for all rows in the rbu_count table, where nIndex is the number of
172144** indexes on the corresponding target database table.
172145*/
172146static void rbuInitPhaseOneSteps(sqlite3rbu *p){
172147  if( p->rc==SQLITE_OK ){
172148    sqlite3_stmt *pStmt = 0;
172149    int bExists = 0;                /* True if rbu_count exists */
172150
172151    p->nPhaseOneStep = -1;
172152
172153    p->rc = sqlite3_create_function(p->dbRbu,
172154        "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
172155    );
172156
172157    /* Check for the rbu_count table. If it does not exist, or if an error
172158    ** occurs, nPhaseOneStep will be left set to -1. */
172159    if( p->rc==SQLITE_OK ){
172160      p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
172161          "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
172162      );
172163    }
172164    if( p->rc==SQLITE_OK ){
172165      if( SQLITE_ROW==sqlite3_step(pStmt) ){
172166        bExists = 1;
172167      }
172168      p->rc = sqlite3_finalize(pStmt);
172169    }
172170
172171    if( p->rc==SQLITE_OK && bExists ){
172172      p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
172173          "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
172174          "FROM rbu_count"
172175      );
172176      if( p->rc==SQLITE_OK ){
172177        if( SQLITE_ROW==sqlite3_step(pStmt) ){
172178          p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
172179        }
172180        p->rc = sqlite3_finalize(pStmt);
172181      }
172182    }
172183  }
172184}
172185
172186
172187static sqlite3rbu *openRbuHandle(
172188  const char *zTarget,
172189  const char *zRbu,
172190  const char *zState
172191){
172192  sqlite3rbu *p;
172193  size_t nTarget = zTarget ? strlen(zTarget) : 0;
172194  size_t nRbu = strlen(zRbu);
172195  size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
172196
172197  p = (sqlite3rbu*)sqlite3_malloc64(nByte);
172198  if( p ){
172199    RbuState *pState = 0;
172200
172201    /* Create the custom VFS. */
172202    memset(p, 0, sizeof(sqlite3rbu));
172203    rbuCreateVfs(p);
172204
172205    /* Open the target, RBU and state databases */
172206    if( p->rc==SQLITE_OK ){
172207      char *pCsr = (char*)&p[1];
172208      int bRetry = 0;
172209      if( zTarget ){
172210        p->zTarget = pCsr;
172211        memcpy(p->zTarget, zTarget, nTarget+1);
172212        pCsr += nTarget+1;
172213      }
172214      p->zRbu = pCsr;
172215      memcpy(p->zRbu, zRbu, nRbu+1);
172216      pCsr += nRbu+1;
172217      if( zState ){
172218        p->zState = rbuMPrintf(p, "%s", zState);
172219      }
172220
172221      /* If the first attempt to open the database file fails and the bRetry
172222      ** flag it set, this means that the db was not opened because it seemed
172223      ** to be a wal-mode db. But, this may have happened due to an earlier
172224      ** RBU vacuum operation leaving an old wal file in the directory.
172225      ** If this is the case, it will have been checkpointed and deleted
172226      ** when the handle was closed and a second attempt to open the
172227      ** database may succeed.  */
172228      rbuOpenDatabase(p, &bRetry);
172229      if( bRetry ){
172230        rbuOpenDatabase(p, 0);
172231      }
172232    }
172233
172234    if( p->rc==SQLITE_OK ){
172235      pState = rbuLoadState(p);
172236      assert( pState || p->rc!=SQLITE_OK );
172237      if( p->rc==SQLITE_OK ){
172238
172239        if( pState->eStage==0 ){
172240          rbuDeleteOalFile(p);
172241          rbuInitPhaseOneSteps(p);
172242          p->eStage = RBU_STAGE_OAL;
172243        }else{
172244          p->eStage = pState->eStage;
172245          p->nPhaseOneStep = pState->nPhaseOneStep;
172246        }
172247        p->nProgress = pState->nProgress;
172248        p->iOalSz = pState->iOalSz;
172249      }
172250    }
172251    assert( p->rc!=SQLITE_OK || p->eStage!=0 );
172252
172253    if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
172254      if( p->eStage==RBU_STAGE_OAL ){
172255        p->rc = SQLITE_ERROR;
172256        p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
172257      }else if( p->eStage==RBU_STAGE_MOVE ){
172258        p->eStage = RBU_STAGE_CKPT;
172259        p->nStep = 0;
172260      }
172261    }
172262
172263    if( p->rc==SQLITE_OK
172264     && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
172265     && pState->eStage!=0
172266    ){
172267      rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
172268      if( pFd->iCookie!=pState->iCookie ){
172269        /* At this point (pTargetFd->iCookie) contains the value of the
172270        ** change-counter cookie (the thing that gets incremented when a
172271        ** transaction is committed in rollback mode) currently stored on
172272        ** page 1 of the database file. */
172273        p->rc = SQLITE_BUSY;
172274        p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
172275            (rbuIsVacuum(p) ? "vacuum" : "update")
172276        );
172277      }
172278    }
172279
172280    if( p->rc==SQLITE_OK ){
172281      if( p->eStage==RBU_STAGE_OAL ){
172282        sqlite3 *db = p->dbMain;
172283        p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
172284
172285        /* Point the object iterator at the first object */
172286        if( p->rc==SQLITE_OK ){
172287          p->rc = rbuObjIterFirst(p, &p->objiter);
172288        }
172289
172290        /* If the RBU database contains no data_xxx tables, declare the RBU
172291        ** update finished.  */
172292        if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
172293          p->rc = SQLITE_DONE;
172294          p->eStage = RBU_STAGE_DONE;
172295        }else{
172296          if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
172297            rbuCopyPragma(p, "page_size");
172298            rbuCopyPragma(p, "auto_vacuum");
172299          }
172300
172301          /* Open transactions both databases. The *-oal file is opened or
172302          ** created at this point. */
172303          if( p->rc==SQLITE_OK ){
172304            p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
172305          }
172306
172307          /* Check if the main database is a zipvfs db. If it is, set the upper
172308          ** level pager to use "journal_mode=off". This prevents it from
172309          ** generating a large journal using a temp file.  */
172310          if( p->rc==SQLITE_OK ){
172311            int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
172312            if( frc==SQLITE_OK ){
172313              p->rc = sqlite3_exec(
172314                db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
172315            }
172316          }
172317
172318          if( p->rc==SQLITE_OK ){
172319            rbuSetupOal(p, pState);
172320          }
172321        }
172322      }else if( p->eStage==RBU_STAGE_MOVE ){
172323        /* no-op */
172324      }else if( p->eStage==RBU_STAGE_CKPT ){
172325        rbuSetupCheckpoint(p, pState);
172326      }else if( p->eStage==RBU_STAGE_DONE ){
172327        p->rc = SQLITE_DONE;
172328      }else{
172329        p->rc = SQLITE_CORRUPT;
172330      }
172331    }
172332
172333    rbuFreeState(pState);
172334  }
172335
172336  return p;
172337}
172338
172339/*
172340** Allocate and return an RBU handle with all fields zeroed except for the
172341** error code, which is set to SQLITE_MISUSE.
172342*/
172343static sqlite3rbu *rbuMisuseError(void){
172344  sqlite3rbu *pRet;
172345  pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
172346  if( pRet ){
172347    memset(pRet, 0, sizeof(sqlite3rbu));
172348    pRet->rc = SQLITE_MISUSE;
172349  }
172350  return pRet;
172351}
172352
172353/*
172354** Open and return a new RBU handle.
172355*/
172356SQLITE_API sqlite3rbu *sqlite3rbu_open(
172357  const char *zTarget,
172358  const char *zRbu,
172359  const char *zState
172360){
172361  if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
172362  /* TODO: Check that zTarget and zRbu are non-NULL */
172363  return openRbuHandle(zTarget, zRbu, zState);
172364}
172365
172366/*
172367** Open a handle to begin or resume an RBU VACUUM operation.
172368*/
172369SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
172370  const char *zTarget,
172371  const char *zState
172372){
172373  if( zTarget==0 ){ return rbuMisuseError(); }
172374  /* TODO: Check that both arguments are non-NULL */
172375  return openRbuHandle(0, zTarget, zState);
172376}
172377
172378/*
172379** Return the database handle used by pRbu.
172380*/
172381SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
172382  sqlite3 *db = 0;
172383  if( pRbu ){
172384    db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
172385  }
172386  return db;
172387}
172388
172389
172390/*
172391** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
172392** then edit any error message string so as to remove all occurrences of
172393** the pattern "rbu_imp_[0-9]*".
172394*/
172395static void rbuEditErrmsg(sqlite3rbu *p){
172396  if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
172397    unsigned int i;
172398    size_t nErrmsg = strlen(p->zErrmsg);
172399    for(i=0; i<(nErrmsg-8); i++){
172400      if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
172401        int nDel = 8;
172402        while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
172403        memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
172404        nErrmsg -= nDel;
172405      }
172406    }
172407  }
172408}
172409
172410/*
172411** Close the RBU handle.
172412*/
172413SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
172414  int rc;
172415  if( p ){
172416
172417    /* Commit the transaction to the *-oal file. */
172418    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
172419      p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
172420    }
172421
172422    /* Sync the db file if currently doing an incremental checkpoint */
172423    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
172424      sqlite3_file *pDb = p->pTargetFd->pReal;
172425      p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
172426    }
172427
172428    rbuSaveState(p, p->eStage);
172429
172430    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
172431      p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
172432    }
172433
172434    /* Close any open statement handles. */
172435    rbuObjIterFinalize(&p->objiter);
172436
172437    /* If this is an RBU vacuum handle and the vacuum has either finished
172438    ** successfully or encountered an error, delete the contents of the
172439    ** state table. This causes the next call to sqlite3rbu_vacuum()
172440    ** specifying the current target and state databases to start a new
172441    ** vacuum from scratch.  */
172442    if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
172443      int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
172444      if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
172445    }
172446
172447    /* Close the open database handle and VFS object. */
172448    sqlite3_close(p->dbRbu);
172449    sqlite3_close(p->dbMain);
172450    rbuDeleteVfs(p);
172451    sqlite3_free(p->aBuf);
172452    sqlite3_free(p->aFrame);
172453
172454    rbuEditErrmsg(p);
172455    rc = p->rc;
172456    *pzErrmsg = p->zErrmsg;
172457    sqlite3_free(p->zState);
172458    sqlite3_free(p);
172459  }else{
172460    rc = SQLITE_NOMEM;
172461    *pzErrmsg = 0;
172462  }
172463  return rc;
172464}
172465
172466/*
172467** Return the total number of key-value operations (inserts, deletes or
172468** updates) that have been performed on the target database since the
172469** current RBU update was started.
172470*/
172471SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
172472  return pRbu->nProgress;
172473}
172474
172475/*
172476** Return permyriadage progress indications for the two main stages of
172477** an RBU update.
172478*/
172479SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
172480  const int MAX_PROGRESS = 10000;
172481  switch( p->eStage ){
172482    case RBU_STAGE_OAL:
172483      if( p->nPhaseOneStep>0 ){
172484        *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
172485      }else{
172486        *pnOne = -1;
172487      }
172488      *pnTwo = 0;
172489      break;
172490
172491    case RBU_STAGE_MOVE:
172492      *pnOne = MAX_PROGRESS;
172493      *pnTwo = 0;
172494      break;
172495
172496    case RBU_STAGE_CKPT:
172497      *pnOne = MAX_PROGRESS;
172498      *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
172499      break;
172500
172501    case RBU_STAGE_DONE:
172502      *pnOne = MAX_PROGRESS;
172503      *pnTwo = MAX_PROGRESS;
172504      break;
172505
172506    default:
172507      assert( 0 );
172508  }
172509}
172510
172511/*
172512** Return the current state of the RBU vacuum or update operation.
172513*/
172514SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
172515  int aRes[] = {
172516    0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
172517    0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
172518  };
172519
172520  assert( RBU_STAGE_OAL==1 );
172521  assert( RBU_STAGE_MOVE==2 );
172522  assert( RBU_STAGE_CKPT==4 );
172523  assert( RBU_STAGE_DONE==5 );
172524  assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
172525  assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
172526  assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
172527  assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
172528
172529  if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
172530    return SQLITE_RBU_STATE_ERROR;
172531  }else{
172532    assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
172533    assert( p->eStage==RBU_STAGE_OAL
172534         || p->eStage==RBU_STAGE_MOVE
172535         || p->eStage==RBU_STAGE_CKPT
172536         || p->eStage==RBU_STAGE_DONE
172537    );
172538    return aRes[p->eStage];
172539  }
172540}
172541
172542SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
172543  int rc = p->rc;
172544  if( rc==SQLITE_DONE ) return SQLITE_OK;
172545
172546  assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
172547  if( p->eStage==RBU_STAGE_OAL ){
172548    assert( rc!=SQLITE_DONE );
172549    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
172550  }
172551
172552  /* Sync the db file */
172553  if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
172554    sqlite3_file *pDb = p->pTargetFd->pReal;
172555    rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
172556  }
172557
172558  p->rc = rc;
172559  rbuSaveState(p, p->eStage);
172560  rc = p->rc;
172561
172562  if( p->eStage==RBU_STAGE_OAL ){
172563    assert( rc!=SQLITE_DONE );
172564    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
172565    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
172566    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
172567  }
172568
172569  p->rc = rc;
172570  return rc;
172571}
172572
172573/**************************************************************************
172574** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
172575** of a standard VFS in the following ways:
172576**
172577** 1. Whenever the first page of a main database file is read or
172578**    written, the value of the change-counter cookie is stored in
172579**    rbu_file.iCookie. Similarly, the value of the "write-version"
172580**    database header field is stored in rbu_file.iWriteVer. This ensures
172581**    that the values are always trustworthy within an open transaction.
172582**
172583** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
172584**    member variable of the associated database file descriptor is set
172585**    to point to the new file. A mutex protected linked list of all main
172586**    db fds opened using a particular RBU VFS is maintained at
172587**    rbu_vfs.pMain to facilitate this.
172588**
172589** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
172590**    object can be marked as the target database of an RBU update. This
172591**    turns on the following extra special behaviour:
172592**
172593** 3a. If xAccess() is called to check if there exists a *-wal file
172594**     associated with an RBU target database currently in RBU_STAGE_OAL
172595**     stage (preparing the *-oal file), the following special handling
172596**     applies:
172597**
172598**      * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
172599**        target database may not be in wal mode already.
172600**
172601**      * if the *-wal file does not exist, set the output parameter to
172602**        non-zero (to tell SQLite that it does exist) anyway.
172603**
172604**     Then, when xOpen() is called to open the *-wal file associated with
172605**     the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
172606**     file, the rbu vfs opens the corresponding *-oal file instead.
172607**
172608** 3b. The *-shm pages returned by xShmMap() for a target db file in
172609**     RBU_STAGE_OAL mode are actually stored in heap memory. This is to
172610**     avoid creating a *-shm file on disk. Additionally, xShmLock() calls
172611**     are no-ops on target database files in RBU_STAGE_OAL mode. This is
172612**     because assert() statements in some VFS implementations fail if
172613**     xShmLock() is called before xShmMap().
172614**
172615** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
172616**     mode except RBU_STAGE_DONE (all work completed and checkpointed), it
172617**     fails with an SQLITE_BUSY error. This is to stop RBU connections
172618**     from automatically checkpointing a *-wal (or *-oal) file from within
172619**     sqlite3_close().
172620**
172621** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
172622**     all xWrite() calls on the target database file perform no IO.
172623**     Instead the frame and page numbers that would be read and written
172624**     are recorded. Additionally, successful attempts to obtain exclusive
172625**     xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
172626**     database file are recorded. xShmLock() calls to unlock the same
172627**     locks are no-ops (so that once obtained, these locks are never
172628**     relinquished). Finally, calls to xSync() on the target database
172629**     file fail with SQLITE_INTERNAL errors.
172630*/
172631
172632static void rbuUnlockShm(rbu_file *p){
172633  if( p->pRbu ){
172634    int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
172635    int i;
172636    for(i=0; i<SQLITE_SHM_NLOCK;i++){
172637      if( (1<<i) & p->pRbu->mLock ){
172638        xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
172639      }
172640    }
172641    p->pRbu->mLock = 0;
172642  }
172643}
172644
172645/*
172646** Close an rbu file.
172647*/
172648static int rbuVfsClose(sqlite3_file *pFile){
172649  rbu_file *p = (rbu_file*)pFile;
172650  int rc;
172651  int i;
172652
172653  /* Free the contents of the apShm[] array. And the array itself. */
172654  for(i=0; i<p->nShm; i++){
172655    sqlite3_free(p->apShm[i]);
172656  }
172657  sqlite3_free(p->apShm);
172658  p->apShm = 0;
172659  sqlite3_free(p->zDel);
172660
172661  if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
172662    rbu_file **pp;
172663    sqlite3_mutex_enter(p->pRbuVfs->mutex);
172664    for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
172665    *pp = p->pMainNext;
172666    sqlite3_mutex_leave(p->pRbuVfs->mutex);
172667    rbuUnlockShm(p);
172668    p->pReal->pMethods->xShmUnmap(p->pReal, 0);
172669  }
172670
172671  /* Close the underlying file handle */
172672  rc = p->pReal->pMethods->xClose(p->pReal);
172673  return rc;
172674}
172675
172676
172677/*
172678** Read and return an unsigned 32-bit big-endian integer from the buffer
172679** passed as the only argument.
172680*/
172681static u32 rbuGetU32(u8 *aBuf){
172682  return ((u32)aBuf[0] << 24)
172683       + ((u32)aBuf[1] << 16)
172684       + ((u32)aBuf[2] <<  8)
172685       + ((u32)aBuf[3]);
172686}
172687
172688/*
172689** Write an unsigned 32-bit value in big-endian format to the supplied
172690** buffer.
172691*/
172692static void rbuPutU32(u8 *aBuf, u32 iVal){
172693  aBuf[0] = (iVal >> 24) & 0xFF;
172694  aBuf[1] = (iVal >> 16) & 0xFF;
172695  aBuf[2] = (iVal >>  8) & 0xFF;
172696  aBuf[3] = (iVal >>  0) & 0xFF;
172697}
172698
172699static void rbuPutU16(u8 *aBuf, u16 iVal){
172700  aBuf[0] = (iVal >>  8) & 0xFF;
172701  aBuf[1] = (iVal >>  0) & 0xFF;
172702}
172703
172704/*
172705** Read data from an rbuVfs-file.
172706*/
172707static int rbuVfsRead(
172708  sqlite3_file *pFile,
172709  void *zBuf,
172710  int iAmt,
172711  sqlite_int64 iOfst
172712){
172713  rbu_file *p = (rbu_file*)pFile;
172714  sqlite3rbu *pRbu = p->pRbu;
172715  int rc;
172716
172717  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
172718    assert( p->openFlags & SQLITE_OPEN_WAL );
172719    rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
172720  }else{
172721    if( pRbu && pRbu->eStage==RBU_STAGE_OAL
172722     && (p->openFlags & SQLITE_OPEN_WAL)
172723     && iOfst>=pRbu->iOalSz
172724    ){
172725      rc = SQLITE_OK;
172726      memset(zBuf, 0, iAmt);
172727    }else{
172728      rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
172729#if 1
172730      /* If this is being called to read the first page of the target
172731      ** database as part of an rbu vacuum operation, synthesize the
172732      ** contents of the first page if it does not yet exist. Otherwise,
172733      ** SQLite will not check for a *-wal file.  */
172734      if( pRbu && rbuIsVacuum(pRbu)
172735          && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
172736          && (p->openFlags & SQLITE_OPEN_MAIN_DB)
172737          && pRbu->rc==SQLITE_OK
172738      ){
172739        sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
172740        rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
172741        if( rc==SQLITE_OK ){
172742          u8 *aBuf = (u8*)zBuf;
172743          u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
172744          rbuPutU32(&aBuf[52], iRoot);      /* largest root page number */
172745          rbuPutU32(&aBuf[36], 0);          /* number of free pages */
172746          rbuPutU32(&aBuf[32], 0);          /* first page on free list trunk */
172747          rbuPutU32(&aBuf[28], 1);          /* size of db file in pages */
172748          rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1);  /* Change counter */
172749
172750          if( iAmt>100 ){
172751            memset(&aBuf[100], 0, iAmt-100);
172752            rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
172753            aBuf[100] = 0x0D;
172754          }
172755        }
172756      }
172757#endif
172758    }
172759    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
172760      /* These look like magic numbers. But they are stable, as they are part
172761       ** of the definition of the SQLite file format, which may not change. */
172762      u8 *pBuf = (u8*)zBuf;
172763      p->iCookie = rbuGetU32(&pBuf[24]);
172764      p->iWriteVer = pBuf[19];
172765    }
172766  }
172767  return rc;
172768}
172769
172770/*
172771** Write data to an rbuVfs-file.
172772*/
172773static int rbuVfsWrite(
172774  sqlite3_file *pFile,
172775  const void *zBuf,
172776  int iAmt,
172777  sqlite_int64 iOfst
172778){
172779  rbu_file *p = (rbu_file*)pFile;
172780  sqlite3rbu *pRbu = p->pRbu;
172781  int rc;
172782
172783  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
172784    assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
172785    rc = rbuCaptureDbWrite(p->pRbu, iOfst);
172786  }else{
172787    if( pRbu && pRbu->eStage==RBU_STAGE_OAL
172788     && (p->openFlags & SQLITE_OPEN_WAL)
172789     && iOfst>=pRbu->iOalSz
172790    ){
172791      pRbu->iOalSz = iAmt + iOfst;
172792    }
172793    rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
172794    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
172795      /* These look like magic numbers. But they are stable, as they are part
172796      ** of the definition of the SQLite file format, which may not change. */
172797      u8 *pBuf = (u8*)zBuf;
172798      p->iCookie = rbuGetU32(&pBuf[24]);
172799      p->iWriteVer = pBuf[19];
172800    }
172801  }
172802  return rc;
172803}
172804
172805/*
172806** Truncate an rbuVfs-file.
172807*/
172808static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
172809  rbu_file *p = (rbu_file*)pFile;
172810  return p->pReal->pMethods->xTruncate(p->pReal, size);
172811}
172812
172813/*
172814** Sync an rbuVfs-file.
172815*/
172816static int rbuVfsSync(sqlite3_file *pFile, int flags){
172817  rbu_file *p = (rbu_file *)pFile;
172818  if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
172819    if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
172820      return SQLITE_INTERNAL;
172821    }
172822    return SQLITE_OK;
172823  }
172824  return p->pReal->pMethods->xSync(p->pReal, flags);
172825}
172826
172827/*
172828** Return the current file-size of an rbuVfs-file.
172829*/
172830static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
172831  rbu_file *p = (rbu_file *)pFile;
172832  int rc;
172833  rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
172834
172835  /* If this is an RBU vacuum operation and this is the target database,
172836  ** pretend that it has at least one page. Otherwise, SQLite will not
172837  ** check for the existance of a *-wal file. rbuVfsRead() contains
172838  ** similar logic.  */
172839  if( rc==SQLITE_OK && *pSize==0
172840   && p->pRbu && rbuIsVacuum(p->pRbu)
172841   && (p->openFlags & SQLITE_OPEN_MAIN_DB)
172842  ){
172843    *pSize = 1024;
172844  }
172845  return rc;
172846}
172847
172848/*
172849** Lock an rbuVfs-file.
172850*/
172851static int rbuVfsLock(sqlite3_file *pFile, int eLock){
172852  rbu_file *p = (rbu_file*)pFile;
172853  sqlite3rbu *pRbu = p->pRbu;
172854  int rc = SQLITE_OK;
172855
172856  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
172857  if( eLock==SQLITE_LOCK_EXCLUSIVE
172858   && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
172859  ){
172860    /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
172861    ** prevents it from checkpointing the database from sqlite3_close(). */
172862    rc = SQLITE_BUSY;
172863  }else{
172864    rc = p->pReal->pMethods->xLock(p->pReal, eLock);
172865  }
172866
172867  return rc;
172868}
172869
172870/*
172871** Unlock an rbuVfs-file.
172872*/
172873static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
172874  rbu_file *p = (rbu_file *)pFile;
172875  return p->pReal->pMethods->xUnlock(p->pReal, eLock);
172876}
172877
172878/*
172879** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
172880*/
172881static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
172882  rbu_file *p = (rbu_file *)pFile;
172883  return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
172884}
172885
172886/*
172887** File control method. For custom operations on an rbuVfs-file.
172888*/
172889static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
172890  rbu_file *p = (rbu_file *)pFile;
172891  int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
172892  int rc;
172893
172894  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
172895       || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
172896  );
172897  if( op==SQLITE_FCNTL_RBU ){
172898    sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
172899
172900    /* First try to find another RBU vfs lower down in the vfs stack. If
172901    ** one is found, this vfs will operate in pass-through mode. The lower
172902    ** level vfs will do the special RBU handling.  */
172903    rc = xControl(p->pReal, op, pArg);
172904
172905    if( rc==SQLITE_NOTFOUND ){
172906      /* Now search for a zipvfs instance lower down in the VFS stack. If
172907      ** one is found, this is an error.  */
172908      void *dummy = 0;
172909      rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
172910      if( rc==SQLITE_OK ){
172911        rc = SQLITE_ERROR;
172912        pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
172913      }else if( rc==SQLITE_NOTFOUND ){
172914        pRbu->pTargetFd = p;
172915        p->pRbu = pRbu;
172916        if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
172917        rc = SQLITE_OK;
172918      }
172919    }
172920    return rc;
172921  }
172922  else if( op==SQLITE_FCNTL_RBUCNT ){
172923    sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
172924    pRbu->nRbu++;
172925    pRbu->pRbuFd = p;
172926    p->bNolock = 1;
172927  }
172928
172929  rc = xControl(p->pReal, op, pArg);
172930  if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
172931    rbu_vfs *pRbuVfs = p->pRbuVfs;
172932    char *zIn = *(char**)pArg;
172933    char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
172934    *(char**)pArg = zOut;
172935    if( zOut==0 ) rc = SQLITE_NOMEM;
172936  }
172937
172938  return rc;
172939}
172940
172941/*
172942** Return the sector-size in bytes for an rbuVfs-file.
172943*/
172944static int rbuVfsSectorSize(sqlite3_file *pFile){
172945  rbu_file *p = (rbu_file *)pFile;
172946  return p->pReal->pMethods->xSectorSize(p->pReal);
172947}
172948
172949/*
172950** Return the device characteristic flags supported by an rbuVfs-file.
172951*/
172952static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
172953  rbu_file *p = (rbu_file *)pFile;
172954  return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
172955}
172956
172957/*
172958** Take or release a shared-memory lock.
172959*/
172960static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
172961  rbu_file *p = (rbu_file*)pFile;
172962  sqlite3rbu *pRbu = p->pRbu;
172963  int rc = SQLITE_OK;
172964
172965#ifdef SQLITE_AMALGAMATION
172966    assert( WAL_CKPT_LOCK==1 );
172967#endif
172968
172969  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
172970  if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
172971    /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
172972    ** taking this lock also prevents any checkpoints from occurring.
172973    ** todo: really, it's not clear why this might occur, as
172974    ** wal_autocheckpoint ought to be turned off.  */
172975    if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
172976  }else{
172977    int bCapture = 0;
172978    if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
172979     && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
172980     && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
172981    ){
172982      bCapture = 1;
172983    }
172984
172985    if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
172986      rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
172987      if( bCapture && rc==SQLITE_OK ){
172988        pRbu->mLock |= (1 << ofst);
172989      }
172990    }
172991  }
172992
172993  return rc;
172994}
172995
172996/*
172997** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
172998*/
172999static int rbuVfsShmMap(
173000  sqlite3_file *pFile,
173001  int iRegion,
173002  int szRegion,
173003  int isWrite,
173004  void volatile **pp
173005){
173006  rbu_file *p = (rbu_file*)pFile;
173007  int rc = SQLITE_OK;
173008  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
173009
173010  /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
173011  ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
173012  ** instead of a file on disk.  */
173013  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
173014  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
173015    if( iRegion<=p->nShm ){
173016      int nByte = (iRegion+1) * sizeof(char*);
173017      char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
173018      if( apNew==0 ){
173019        rc = SQLITE_NOMEM;
173020      }else{
173021        memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
173022        p->apShm = apNew;
173023        p->nShm = iRegion+1;
173024      }
173025    }
173026
173027    if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
173028      char *pNew = (char*)sqlite3_malloc64(szRegion);
173029      if( pNew==0 ){
173030        rc = SQLITE_NOMEM;
173031      }else{
173032        memset(pNew, 0, szRegion);
173033        p->apShm[iRegion] = pNew;
173034      }
173035    }
173036
173037    if( rc==SQLITE_OK ){
173038      *pp = p->apShm[iRegion];
173039    }else{
173040      *pp = 0;
173041    }
173042  }else{
173043    assert( p->apShm==0 );
173044    rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
173045  }
173046
173047  return rc;
173048}
173049
173050/*
173051** Memory barrier.
173052*/
173053static void rbuVfsShmBarrier(sqlite3_file *pFile){
173054  rbu_file *p = (rbu_file *)pFile;
173055  p->pReal->pMethods->xShmBarrier(p->pReal);
173056}
173057
173058/*
173059** The xShmUnmap method.
173060*/
173061static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
173062  rbu_file *p = (rbu_file*)pFile;
173063  int rc = SQLITE_OK;
173064  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
173065
173066  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
173067  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
173068    /* no-op */
173069  }else{
173070    /* Release the checkpointer and writer locks */
173071    rbuUnlockShm(p);
173072    rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
173073  }
173074  return rc;
173075}
173076
173077/*
173078** Given that zWal points to a buffer containing a wal file name passed to
173079** either the xOpen() or xAccess() VFS method, return a pointer to the
173080** file-handle opened by the same database connection on the corresponding
173081** database file.
173082*/
173083static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
173084  rbu_file *pDb;
173085  sqlite3_mutex_enter(pRbuVfs->mutex);
173086  for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
173087  sqlite3_mutex_leave(pRbuVfs->mutex);
173088  return pDb;
173089}
173090
173091/*
173092** A main database named zName has just been opened. The following
173093** function returns a pointer to a buffer owned by SQLite that contains
173094** the name of the *-wal file this db connection will use. SQLite
173095** happens to pass a pointer to this buffer when using xAccess()
173096** or xOpen() to operate on the *-wal file.
173097*/
173098static const char *rbuMainToWal(const char *zName, int flags){
173099  int n = (int)strlen(zName);
173100  const char *z = &zName[n];
173101  if( flags & SQLITE_OPEN_URI ){
173102    int odd = 0;
173103    while( 1 ){
173104      if( z[0]==0 ){
173105        odd = 1 - odd;
173106        if( odd && z[1]==0 ) break;
173107      }
173108      z++;
173109    }
173110    z += 2;
173111  }else{
173112    while( *z==0 ) z++;
173113  }
173114  z += (n + 8 + 1);
173115  return z;
173116}
173117
173118/*
173119** Open an rbu file handle.
173120*/
173121static int rbuVfsOpen(
173122  sqlite3_vfs *pVfs,
173123  const char *zName,
173124  sqlite3_file *pFile,
173125  int flags,
173126  int *pOutFlags
173127){
173128  static sqlite3_io_methods rbuvfs_io_methods = {
173129    2,                            /* iVersion */
173130    rbuVfsClose,                  /* xClose */
173131    rbuVfsRead,                   /* xRead */
173132    rbuVfsWrite,                  /* xWrite */
173133    rbuVfsTruncate,               /* xTruncate */
173134    rbuVfsSync,                   /* xSync */
173135    rbuVfsFileSize,               /* xFileSize */
173136    rbuVfsLock,                   /* xLock */
173137    rbuVfsUnlock,                 /* xUnlock */
173138    rbuVfsCheckReservedLock,      /* xCheckReservedLock */
173139    rbuVfsFileControl,            /* xFileControl */
173140    rbuVfsSectorSize,             /* xSectorSize */
173141    rbuVfsDeviceCharacteristics,  /* xDeviceCharacteristics */
173142    rbuVfsShmMap,                 /* xShmMap */
173143    rbuVfsShmLock,                /* xShmLock */
173144    rbuVfsShmBarrier,             /* xShmBarrier */
173145    rbuVfsShmUnmap,               /* xShmUnmap */
173146    0, 0                          /* xFetch, xUnfetch */
173147  };
173148  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
173149  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
173150  rbu_file *pFd = (rbu_file *)pFile;
173151  int rc = SQLITE_OK;
173152  const char *zOpen = zName;
173153  int oflags = flags;
173154
173155  memset(pFd, 0, sizeof(rbu_file));
173156  pFd->pReal = (sqlite3_file*)&pFd[1];
173157  pFd->pRbuVfs = pRbuVfs;
173158  pFd->openFlags = flags;
173159  if( zName ){
173160    if( flags & SQLITE_OPEN_MAIN_DB ){
173161      /* A main database has just been opened. The following block sets
173162      ** (pFd->zWal) to point to a buffer owned by SQLite that contains
173163      ** the name of the *-wal file this db connection will use. SQLite
173164      ** happens to pass a pointer to this buffer when using xAccess()
173165      ** or xOpen() to operate on the *-wal file.  */
173166      pFd->zWal = rbuMainToWal(zName, flags);
173167    }
173168    else if( flags & SQLITE_OPEN_WAL ){
173169      rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
173170      if( pDb ){
173171        if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
173172          /* This call is to open a *-wal file. Intead, open the *-oal. This
173173          ** code ensures that the string passed to xOpen() is terminated by a
173174          ** pair of '\0' bytes in case the VFS attempts to extract a URI
173175          ** parameter from it.  */
173176          const char *zBase = zName;
173177          size_t nCopy;
173178          char *zCopy;
173179          if( rbuIsVacuum(pDb->pRbu) ){
173180            zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
173181            zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
173182          }
173183          nCopy = strlen(zBase);
173184          zCopy = sqlite3_malloc64(nCopy+2);
173185          if( zCopy ){
173186            memcpy(zCopy, zBase, nCopy);
173187            zCopy[nCopy-3] = 'o';
173188            zCopy[nCopy] = '\0';
173189            zCopy[nCopy+1] = '\0';
173190            zOpen = (const char*)(pFd->zDel = zCopy);
173191          }else{
173192            rc = SQLITE_NOMEM;
173193          }
173194          pFd->pRbu = pDb->pRbu;
173195        }
173196        pDb->pWalFd = pFd;
173197      }
173198    }
173199  }
173200
173201  if( oflags & SQLITE_OPEN_MAIN_DB
173202   && sqlite3_uri_boolean(zName, "rbu_memory", 0)
173203  ){
173204    assert( oflags & SQLITE_OPEN_MAIN_DB );
173205    oflags =  SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
173206              SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
173207    zOpen = 0;
173208  }
173209
173210  if( rc==SQLITE_OK ){
173211    rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
173212  }
173213  if( pFd->pReal->pMethods ){
173214    /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
173215    ** pointer and, if the file is a main database file, link it into the
173216    ** mutex protected linked list of all such files.  */
173217    pFile->pMethods = &rbuvfs_io_methods;
173218    if( flags & SQLITE_OPEN_MAIN_DB ){
173219      sqlite3_mutex_enter(pRbuVfs->mutex);
173220      pFd->pMainNext = pRbuVfs->pMain;
173221      pRbuVfs->pMain = pFd;
173222      sqlite3_mutex_leave(pRbuVfs->mutex);
173223    }
173224  }else{
173225    sqlite3_free(pFd->zDel);
173226  }
173227
173228  return rc;
173229}
173230
173231/*
173232** Delete the file located at zPath.
173233*/
173234static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
173235  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
173236  return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
173237}
173238
173239/*
173240** Test for access permissions. Return true if the requested permission
173241** is available, or false otherwise.
173242*/
173243static int rbuVfsAccess(
173244  sqlite3_vfs *pVfs,
173245  const char *zPath,
173246  int flags,
173247  int *pResOut
173248){
173249  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
173250  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
173251  int rc;
173252
173253  rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
173254
173255  /* If this call is to check if a *-wal file associated with an RBU target
173256  ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
173257  ** the following special handling is activated:
173258  **
173259  **   a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
173260  **      ensures that the RBU extension never tries to update a database
173261  **      in wal mode, even if the first page of the database file has
173262  **      been damaged.
173263  **
173264  **   b) if the *-wal file does not exist, claim that it does anyway,
173265  **      causing SQLite to call xOpen() to open it. This call will also
173266  **      be intercepted (see the rbuVfsOpen() function) and the *-oal
173267  **      file opened instead.
173268  */
173269  if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
173270    rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
173271    if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
173272      if( *pResOut ){
173273        rc = SQLITE_CANTOPEN;
173274      }else{
173275        *pResOut = 1;
173276      }
173277    }
173278  }
173279
173280  return rc;
173281}
173282
173283/*
173284** Populate buffer zOut with the full canonical pathname corresponding
173285** to the pathname in zPath. zOut is guaranteed to point to a buffer
173286** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
173287*/
173288static int rbuVfsFullPathname(
173289  sqlite3_vfs *pVfs,
173290  const char *zPath,
173291  int nOut,
173292  char *zOut
173293){
173294  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
173295  return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
173296}
173297
173298#ifndef SQLITE_OMIT_LOAD_EXTENSION
173299/*
173300** Open the dynamic library located at zPath and return a handle.
173301*/
173302static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
173303  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
173304  return pRealVfs->xDlOpen(pRealVfs, zPath);
173305}
173306
173307/*
173308** Populate the buffer zErrMsg (size nByte bytes) with a human readable
173309** utf-8 string describing the most recent error encountered associated
173310** with dynamic libraries.
173311*/
173312static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
173313  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
173314  pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
173315}
173316
173317/*
173318** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
173319*/
173320static void (*rbuVfsDlSym(
173321  sqlite3_vfs *pVfs,
173322  void *pArg,
173323  const char *zSym
173324))(void){
173325  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
173326  return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
173327}
173328
173329/*
173330** Close the dynamic library handle pHandle.
173331*/
173332static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
173333  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
173334  pRealVfs->xDlClose(pRealVfs, pHandle);
173335}
173336#endif /* SQLITE_OMIT_LOAD_EXTENSION */
173337
173338/*
173339** Populate the buffer pointed to by zBufOut with nByte bytes of
173340** random data.
173341*/
173342static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
173343  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
173344  return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
173345}
173346
173347/*
173348** Sleep for nMicro microseconds. Return the number of microseconds
173349** actually slept.
173350*/
173351static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
173352  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
173353  return pRealVfs->xSleep(pRealVfs, nMicro);
173354}
173355
173356/*
173357** Return the current time as a Julian Day number in *pTimeOut.
173358*/
173359static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
173360  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
173361  return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
173362}
173363
173364/*
173365** No-op.
173366*/
173367static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
173368  return 0;
173369}
173370
173371/*
173372** Deregister and destroy an RBU vfs created by an earlier call to
173373** sqlite3rbu_create_vfs().
173374*/
173375SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
173376  sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
173377  if( pVfs && pVfs->xOpen==rbuVfsOpen ){
173378    sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
173379    sqlite3_vfs_unregister(pVfs);
173380    sqlite3_free(pVfs);
173381  }
173382}
173383
173384/*
173385** Create an RBU VFS named zName that accesses the underlying file-system
173386** via existing VFS zParent. The new object is registered as a non-default
173387** VFS with SQLite before returning.
173388*/
173389SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
173390
173391  /* Template for VFS */
173392  static sqlite3_vfs vfs_template = {
173393    1,                            /* iVersion */
173394    0,                            /* szOsFile */
173395    0,                            /* mxPathname */
173396    0,                            /* pNext */
173397    0,                            /* zName */
173398    0,                            /* pAppData */
173399    rbuVfsOpen,                   /* xOpen */
173400    rbuVfsDelete,                 /* xDelete */
173401    rbuVfsAccess,                 /* xAccess */
173402    rbuVfsFullPathname,           /* xFullPathname */
173403
173404#ifndef SQLITE_OMIT_LOAD_EXTENSION
173405    rbuVfsDlOpen,                 /* xDlOpen */
173406    rbuVfsDlError,                /* xDlError */
173407    rbuVfsDlSym,                  /* xDlSym */
173408    rbuVfsDlClose,                /* xDlClose */
173409#else
173410    0, 0, 0, 0,
173411#endif
173412
173413    rbuVfsRandomness,             /* xRandomness */
173414    rbuVfsSleep,                  /* xSleep */
173415    rbuVfsCurrentTime,            /* xCurrentTime */
173416    rbuVfsGetLastError,           /* xGetLastError */
173417    0,                            /* xCurrentTimeInt64 (version 2) */
173418    0, 0, 0                       /* Unimplemented version 3 methods */
173419  };
173420
173421  rbu_vfs *pNew = 0;              /* Newly allocated VFS */
173422  int rc = SQLITE_OK;
173423  size_t nName;
173424  size_t nByte;
173425
173426  nName = strlen(zName);
173427  nByte = sizeof(rbu_vfs) + nName + 1;
173428  pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
173429  if( pNew==0 ){
173430    rc = SQLITE_NOMEM;
173431  }else{
173432    sqlite3_vfs *pParent;           /* Parent VFS */
173433    memset(pNew, 0, nByte);
173434    pParent = sqlite3_vfs_find(zParent);
173435    if( pParent==0 ){
173436      rc = SQLITE_NOTFOUND;
173437    }else{
173438      char *zSpace;
173439      memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
173440      pNew->base.mxPathname = pParent->mxPathname;
173441      pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
173442      pNew->pRealVfs = pParent;
173443      pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
173444      memcpy(zSpace, zName, nName);
173445
173446      /* Allocate the mutex and register the new VFS (not as the default) */
173447      pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
173448      if( pNew->mutex==0 ){
173449        rc = SQLITE_NOMEM;
173450      }else{
173451        rc = sqlite3_vfs_register(&pNew->base, 0);
173452      }
173453    }
173454
173455    if( rc!=SQLITE_OK ){
173456      sqlite3_mutex_free(pNew->mutex);
173457      sqlite3_free(pNew);
173458    }
173459  }
173460
173461  return rc;
173462}
173463
173464
173465/**************************************************************************/
173466
173467#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
173468
173469/************** End of sqlite3rbu.c ******************************************/
173470/************** Begin file dbstat.c ******************************************/
173471/*
173472** 2010 July 12
173473**
173474** The author disclaims copyright to this source code.  In place of
173475** a legal notice, here is a blessing:
173476**
173477**    May you do good and not evil.
173478**    May you find forgiveness for yourself and forgive others.
173479**    May you share freely, never taking more than you give.
173480**
173481******************************************************************************
173482**
173483** This file contains an implementation of the "dbstat" virtual table.
173484**
173485** The dbstat virtual table is used to extract low-level formatting
173486** information from an SQLite database in order to implement the
173487** "sqlite3_analyzer" utility.  See the ../tool/spaceanal.tcl script
173488** for an example implementation.
173489**
173490** Additional information is available on the "dbstat.html" page of the
173491** official SQLite documentation.
173492*/
173493
173494/* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
173495#if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
173496    && !defined(SQLITE_OMIT_VIRTUALTABLE)
173497
173498/*
173499** Page paths:
173500**
173501**   The value of the 'path' column describes the path taken from the
173502**   root-node of the b-tree structure to each page. The value of the
173503**   root-node path is '/'.
173504**
173505**   The value of the path for the left-most child page of the root of
173506**   a b-tree is '/000/'. (Btrees store content ordered from left to right
173507**   so the pages to the left have smaller keys than the pages to the right.)
173508**   The next to left-most child of the root page is
173509**   '/001', and so on, each sibling page identified by a 3-digit hex
173510**   value. The children of the 451st left-most sibling have paths such
173511**   as '/1c2/000/, '/1c2/001/' etc.
173512**
173513**   Overflow pages are specified by appending a '+' character and a
173514**   six-digit hexadecimal value to the path to the cell they are linked
173515**   from. For example, the three overflow pages in a chain linked from
173516**   the left-most cell of the 450th child of the root page are identified
173517**   by the paths:
173518**
173519**      '/1c2/000+000000'         // First page in overflow chain
173520**      '/1c2/000+000001'         // Second page in overflow chain
173521**      '/1c2/000+000002'         // Third page in overflow chain
173522**
173523**   If the paths are sorted using the BINARY collation sequence, then
173524**   the overflow pages associated with a cell will appear earlier in the
173525**   sort-order than its child page:
173526**
173527**      '/1c2/000/'               // Left-most child of 451st child of root
173528*/
173529#define VTAB_SCHEMA                                                         \
173530  "CREATE TABLE xx( "                                                       \
173531  "  name       TEXT,             /* Name of table or index */"             \
173532  "  path       TEXT,             /* Path to page from root */"             \
173533  "  pageno     INTEGER,          /* Page number */"                        \
173534  "  pagetype   TEXT,             /* 'internal', 'leaf' or 'overflow' */"   \
173535  "  ncell      INTEGER,          /* Cells on page (0 for overflow) */"     \
173536  "  payload    INTEGER,          /* Bytes of payload on this page */"      \
173537  "  unused     INTEGER,          /* Bytes of unused space on this page */" \
173538  "  mx_payload INTEGER,          /* Largest payload size of all cells */"  \
173539  "  pgoffset   INTEGER,          /* Offset of page in file */"             \
173540  "  pgsize     INTEGER,          /* Size of the page */"                   \
173541  "  schema     TEXT HIDDEN       /* Database schema being analyzed */"     \
173542  ");"
173543
173544
173545typedef struct StatTable StatTable;
173546typedef struct StatCursor StatCursor;
173547typedef struct StatPage StatPage;
173548typedef struct StatCell StatCell;
173549
173550struct StatCell {
173551  int nLocal;                     /* Bytes of local payload */
173552  u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
173553  int nOvfl;                      /* Entries in aOvfl[] */
173554  u32 *aOvfl;                     /* Array of overflow page numbers */
173555  int nLastOvfl;                  /* Bytes of payload on final overflow page */
173556  int iOvfl;                      /* Iterates through aOvfl[] */
173557};
173558
173559struct StatPage {
173560  u32 iPgno;
173561  DbPage *pPg;
173562  int iCell;
173563
173564  char *zPath;                    /* Path to this page */
173565
173566  /* Variables populated by statDecodePage(): */
173567  u8 flags;                       /* Copy of flags byte */
173568  int nCell;                      /* Number of cells on page */
173569  int nUnused;                    /* Number of unused bytes on page */
173570  StatCell *aCell;                /* Array of parsed cells */
173571  u32 iRightChildPg;              /* Right-child page number (or 0) */
173572  int nMxPayload;                 /* Largest payload of any cell on this page */
173573};
173574
173575struct StatCursor {
173576  sqlite3_vtab_cursor base;
173577  sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
173578  int isEof;                      /* After pStmt has returned SQLITE_DONE */
173579  int iDb;                        /* Schema used for this query */
173580
173581  StatPage aPage[32];
173582  int iPage;                      /* Current entry in aPage[] */
173583
173584  /* Values to return. */
173585  char *zName;                    /* Value of 'name' column */
173586  char *zPath;                    /* Value of 'path' column */
173587  u32 iPageno;                    /* Value of 'pageno' column */
173588  char *zPagetype;                /* Value of 'pagetype' column */
173589  int nCell;                      /* Value of 'ncell' column */
173590  int nPayload;                   /* Value of 'payload' column */
173591  int nUnused;                    /* Value of 'unused' column */
173592  int nMxPayload;                 /* Value of 'mx_payload' column */
173593  i64 iOffset;                    /* Value of 'pgOffset' column */
173594  int szPage;                     /* Value of 'pgSize' column */
173595};
173596
173597struct StatTable {
173598  sqlite3_vtab base;
173599  sqlite3 *db;
173600  int iDb;                        /* Index of database to analyze */
173601};
173602
173603#ifndef get2byte
173604# define get2byte(x)   ((x)[0]<<8 | (x)[1])
173605#endif
173606
173607/*
173608** Connect to or create a statvfs virtual table.
173609*/
173610static int statConnect(
173611  sqlite3 *db,
173612  void *pAux,
173613  int argc, const char *const*argv,
173614  sqlite3_vtab **ppVtab,
173615  char **pzErr
173616){
173617  StatTable *pTab = 0;
173618  int rc = SQLITE_OK;
173619  int iDb;
173620
173621  if( argc>=4 ){
173622    Token nm;
173623    sqlite3TokenInit(&nm, (char*)argv[3]);
173624    iDb = sqlite3FindDb(db, &nm);
173625    if( iDb<0 ){
173626      *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
173627      return SQLITE_ERROR;
173628    }
173629  }else{
173630    iDb = 0;
173631  }
173632  rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
173633  if( rc==SQLITE_OK ){
173634    pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
173635    if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
173636  }
173637
173638  assert( rc==SQLITE_OK || pTab==0 );
173639  if( rc==SQLITE_OK ){
173640    memset(pTab, 0, sizeof(StatTable));
173641    pTab->db = db;
173642    pTab->iDb = iDb;
173643  }
173644
173645  *ppVtab = (sqlite3_vtab*)pTab;
173646  return rc;
173647}
173648
173649/*
173650** Disconnect from or destroy a statvfs virtual table.
173651*/
173652static int statDisconnect(sqlite3_vtab *pVtab){
173653  sqlite3_free(pVtab);
173654  return SQLITE_OK;
173655}
173656
173657/*
173658** There is no "best-index". This virtual table always does a linear
173659** scan.  However, a schema=? constraint should cause this table to
173660** operate on a different database schema, so check for it.
173661**
173662** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
173663*/
173664static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
173665  int i;
173666
173667  pIdxInfo->estimatedCost = 1.0e6;  /* Initial cost estimate */
173668
173669  /* Look for a valid schema=? constraint.  If found, change the idxNum to
173670  ** 1 and request the value of that constraint be sent to xFilter.  And
173671  ** lower the cost estimate to encourage the constrained version to be
173672  ** used.
173673  */
173674  for(i=0; i<pIdxInfo->nConstraint; i++){
173675    if( pIdxInfo->aConstraint[i].usable==0 ) continue;
173676    if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
173677    if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
173678    pIdxInfo->idxNum = 1;
173679    pIdxInfo->estimatedCost = 1.0;
173680    pIdxInfo->aConstraintUsage[i].argvIndex = 1;
173681    pIdxInfo->aConstraintUsage[i].omit = 1;
173682    break;
173683  }
173684
173685
173686  /* Records are always returned in ascending order of (name, path).
173687  ** If this will satisfy the client, set the orderByConsumed flag so that
173688  ** SQLite does not do an external sort.
173689  */
173690  if( ( pIdxInfo->nOrderBy==1
173691     && pIdxInfo->aOrderBy[0].iColumn==0
173692     && pIdxInfo->aOrderBy[0].desc==0
173693     ) ||
173694      ( pIdxInfo->nOrderBy==2
173695     && pIdxInfo->aOrderBy[0].iColumn==0
173696     && pIdxInfo->aOrderBy[0].desc==0
173697     && pIdxInfo->aOrderBy[1].iColumn==1
173698     && pIdxInfo->aOrderBy[1].desc==0
173699     )
173700  ){
173701    pIdxInfo->orderByConsumed = 1;
173702  }
173703
173704  return SQLITE_OK;
173705}
173706
173707/*
173708** Open a new statvfs cursor.
173709*/
173710static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
173711  StatTable *pTab = (StatTable *)pVTab;
173712  StatCursor *pCsr;
173713
173714  pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
173715  if( pCsr==0 ){
173716    return SQLITE_NOMEM_BKPT;
173717  }else{
173718    memset(pCsr, 0, sizeof(StatCursor));
173719    pCsr->base.pVtab = pVTab;
173720    pCsr->iDb = pTab->iDb;
173721  }
173722
173723  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
173724  return SQLITE_OK;
173725}
173726
173727static void statClearPage(StatPage *p){
173728  int i;
173729  if( p->aCell ){
173730    for(i=0; i<p->nCell; i++){
173731      sqlite3_free(p->aCell[i].aOvfl);
173732    }
173733    sqlite3_free(p->aCell);
173734  }
173735  sqlite3PagerUnref(p->pPg);
173736  sqlite3_free(p->zPath);
173737  memset(p, 0, sizeof(StatPage));
173738}
173739
173740static void statResetCsr(StatCursor *pCsr){
173741  int i;
173742  sqlite3_reset(pCsr->pStmt);
173743  for(i=0; i<ArraySize(pCsr->aPage); i++){
173744    statClearPage(&pCsr->aPage[i]);
173745  }
173746  pCsr->iPage = 0;
173747  sqlite3_free(pCsr->zPath);
173748  pCsr->zPath = 0;
173749  pCsr->isEof = 0;
173750}
173751
173752/*
173753** Close a statvfs cursor.
173754*/
173755static int statClose(sqlite3_vtab_cursor *pCursor){
173756  StatCursor *pCsr = (StatCursor *)pCursor;
173757  statResetCsr(pCsr);
173758  sqlite3_finalize(pCsr->pStmt);
173759  sqlite3_free(pCsr);
173760  return SQLITE_OK;
173761}
173762
173763static void getLocalPayload(
173764  int nUsable,                    /* Usable bytes per page */
173765  u8 flags,                       /* Page flags */
173766  int nTotal,                     /* Total record (payload) size */
173767  int *pnLocal                    /* OUT: Bytes stored locally */
173768){
173769  int nLocal;
173770  int nMinLocal;
173771  int nMaxLocal;
173772
173773  if( flags==0x0D ){              /* Table leaf node */
173774    nMinLocal = (nUsable - 12) * 32 / 255 - 23;
173775    nMaxLocal = nUsable - 35;
173776  }else{                          /* Index interior and leaf nodes */
173777    nMinLocal = (nUsable - 12) * 32 / 255 - 23;
173778    nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
173779  }
173780
173781  nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
173782  if( nLocal>nMaxLocal ) nLocal = nMinLocal;
173783  *pnLocal = nLocal;
173784}
173785
173786static int statDecodePage(Btree *pBt, StatPage *p){
173787  int nUnused;
173788  int iOff;
173789  int nHdr;
173790  int isLeaf;
173791  int szPage;
173792
173793  u8 *aData = sqlite3PagerGetData(p->pPg);
173794  u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
173795
173796  p->flags = aHdr[0];
173797  p->nCell = get2byte(&aHdr[3]);
173798  p->nMxPayload = 0;
173799
173800  isLeaf = (p->flags==0x0A || p->flags==0x0D);
173801  nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
173802
173803  nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
173804  nUnused += (int)aHdr[7];
173805  iOff = get2byte(&aHdr[1]);
173806  while( iOff ){
173807    nUnused += get2byte(&aData[iOff+2]);
173808    iOff = get2byte(&aData[iOff]);
173809  }
173810  p->nUnused = nUnused;
173811  p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
173812  szPage = sqlite3BtreeGetPageSize(pBt);
173813
173814  if( p->nCell ){
173815    int i;                        /* Used to iterate through cells */
173816    int nUsable;                  /* Usable bytes per page */
173817
173818    sqlite3BtreeEnter(pBt);
173819    nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
173820    sqlite3BtreeLeave(pBt);
173821    p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
173822    if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
173823    memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
173824
173825    for(i=0; i<p->nCell; i++){
173826      StatCell *pCell = &p->aCell[i];
173827
173828      iOff = get2byte(&aData[nHdr+i*2]);
173829      if( !isLeaf ){
173830        pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
173831        iOff += 4;
173832      }
173833      if( p->flags==0x05 ){
173834        /* A table interior node. nPayload==0. */
173835      }else{
173836        u32 nPayload;             /* Bytes of payload total (local+overflow) */
173837        int nLocal;               /* Bytes of payload stored locally */
173838        iOff += getVarint32(&aData[iOff], nPayload);
173839        if( p->flags==0x0D ){
173840          u64 dummy;
173841          iOff += sqlite3GetVarint(&aData[iOff], &dummy);
173842        }
173843        if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
173844        getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
173845        pCell->nLocal = nLocal;
173846        assert( nLocal>=0 );
173847        assert( nPayload>=(u32)nLocal );
173848        assert( nLocal<=(nUsable-35) );
173849        if( nPayload>(u32)nLocal ){
173850          int j;
173851          int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
173852          pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
173853          pCell->nOvfl = nOvfl;
173854          pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
173855          if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
173856          pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
173857          for(j=1; j<nOvfl; j++){
173858            int rc;
173859            u32 iPrev = pCell->aOvfl[j-1];
173860            DbPage *pPg = 0;
173861            rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
173862            if( rc!=SQLITE_OK ){
173863              assert( pPg==0 );
173864              return rc;
173865            }
173866            pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
173867            sqlite3PagerUnref(pPg);
173868          }
173869        }
173870      }
173871    }
173872  }
173873
173874  return SQLITE_OK;
173875}
173876
173877/*
173878** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
173879** the current value of pCsr->iPageno.
173880*/
173881static void statSizeAndOffset(StatCursor *pCsr){
173882  StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
173883  Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
173884  Pager *pPager = sqlite3BtreePager(pBt);
173885  sqlite3_file *fd;
173886  sqlite3_int64 x[2];
173887
173888  /* The default page size and offset */
173889  pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
173890  pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
173891
173892  /* If connected to a ZIPVFS backend, override the page size and
173893  ** offset with actual values obtained from ZIPVFS.
173894  */
173895  fd = sqlite3PagerFile(pPager);
173896  x[0] = pCsr->iPageno;
173897  if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
173898    pCsr->iOffset = x[0];
173899    pCsr->szPage = (int)x[1];
173900  }
173901}
173902
173903/*
173904** Move a statvfs cursor to the next entry in the file.
173905*/
173906static int statNext(sqlite3_vtab_cursor *pCursor){
173907  int rc;
173908  int nPayload;
173909  char *z;
173910  StatCursor *pCsr = (StatCursor *)pCursor;
173911  StatTable *pTab = (StatTable *)pCursor->pVtab;
173912  Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
173913  Pager *pPager = sqlite3BtreePager(pBt);
173914
173915  sqlite3_free(pCsr->zPath);
173916  pCsr->zPath = 0;
173917
173918statNextRestart:
173919  if( pCsr->aPage[0].pPg==0 ){
173920    rc = sqlite3_step(pCsr->pStmt);
173921    if( rc==SQLITE_ROW ){
173922      int nPage;
173923      u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
173924      sqlite3PagerPagecount(pPager, &nPage);
173925      if( nPage==0 ){
173926        pCsr->isEof = 1;
173927        return sqlite3_reset(pCsr->pStmt);
173928      }
173929      rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
173930      pCsr->aPage[0].iPgno = iRoot;
173931      pCsr->aPage[0].iCell = 0;
173932      pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
173933      pCsr->iPage = 0;
173934      if( z==0 ) rc = SQLITE_NOMEM_BKPT;
173935    }else{
173936      pCsr->isEof = 1;
173937      return sqlite3_reset(pCsr->pStmt);
173938    }
173939  }else{
173940
173941    /* Page p itself has already been visited. */
173942    StatPage *p = &pCsr->aPage[pCsr->iPage];
173943
173944    while( p->iCell<p->nCell ){
173945      StatCell *pCell = &p->aCell[p->iCell];
173946      if( pCell->iOvfl<pCell->nOvfl ){
173947        int nUsable;
173948        sqlite3BtreeEnter(pBt);
173949        nUsable = sqlite3BtreeGetPageSize(pBt) -
173950                        sqlite3BtreeGetReserveNoMutex(pBt);
173951        sqlite3BtreeLeave(pBt);
173952        pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
173953        pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
173954        pCsr->zPagetype = "overflow";
173955        pCsr->nCell = 0;
173956        pCsr->nMxPayload = 0;
173957        pCsr->zPath = z = sqlite3_mprintf(
173958            "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
173959        );
173960        if( pCell->iOvfl<pCell->nOvfl-1 ){
173961          pCsr->nUnused = 0;
173962          pCsr->nPayload = nUsable - 4;
173963        }else{
173964          pCsr->nPayload = pCell->nLastOvfl;
173965          pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
173966        }
173967        pCell->iOvfl++;
173968        statSizeAndOffset(pCsr);
173969        return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
173970      }
173971      if( p->iRightChildPg ) break;
173972      p->iCell++;
173973    }
173974
173975    if( !p->iRightChildPg || p->iCell>p->nCell ){
173976      statClearPage(p);
173977      if( pCsr->iPage==0 ) return statNext(pCursor);
173978      pCsr->iPage--;
173979      goto statNextRestart; /* Tail recursion */
173980    }
173981    pCsr->iPage++;
173982    assert( p==&pCsr->aPage[pCsr->iPage-1] );
173983
173984    if( p->iCell==p->nCell ){
173985      p[1].iPgno = p->iRightChildPg;
173986    }else{
173987      p[1].iPgno = p->aCell[p->iCell].iChildPg;
173988    }
173989    rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
173990    p[1].iCell = 0;
173991    p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
173992    p->iCell++;
173993    if( z==0 ) rc = SQLITE_NOMEM_BKPT;
173994  }
173995
173996
173997  /* Populate the StatCursor fields with the values to be returned
173998  ** by the xColumn() and xRowid() methods.
173999  */
174000  if( rc==SQLITE_OK ){
174001    int i;
174002    StatPage *p = &pCsr->aPage[pCsr->iPage];
174003    pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
174004    pCsr->iPageno = p->iPgno;
174005
174006    rc = statDecodePage(pBt, p);
174007    if( rc==SQLITE_OK ){
174008      statSizeAndOffset(pCsr);
174009
174010      switch( p->flags ){
174011        case 0x05:             /* table internal */
174012        case 0x02:             /* index internal */
174013          pCsr->zPagetype = "internal";
174014          break;
174015        case 0x0D:             /* table leaf */
174016        case 0x0A:             /* index leaf */
174017          pCsr->zPagetype = "leaf";
174018          break;
174019        default:
174020          pCsr->zPagetype = "corrupted";
174021          break;
174022      }
174023      pCsr->nCell = p->nCell;
174024      pCsr->nUnused = p->nUnused;
174025      pCsr->nMxPayload = p->nMxPayload;
174026      pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
174027      if( z==0 ) rc = SQLITE_NOMEM_BKPT;
174028      nPayload = 0;
174029      for(i=0; i<p->nCell; i++){
174030        nPayload += p->aCell[i].nLocal;
174031      }
174032      pCsr->nPayload = nPayload;
174033    }
174034  }
174035
174036  return rc;
174037}
174038
174039static int statEof(sqlite3_vtab_cursor *pCursor){
174040  StatCursor *pCsr = (StatCursor *)pCursor;
174041  return pCsr->isEof;
174042}
174043
174044static int statFilter(
174045  sqlite3_vtab_cursor *pCursor,
174046  int idxNum, const char *idxStr,
174047  int argc, sqlite3_value **argv
174048){
174049  StatCursor *pCsr = (StatCursor *)pCursor;
174050  StatTable *pTab = (StatTable*)(pCursor->pVtab);
174051  char *zSql;
174052  int rc = SQLITE_OK;
174053  char *zMaster;
174054
174055  if( idxNum==1 ){
174056    const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
174057    pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
174058    if( pCsr->iDb<0 ){
174059      sqlite3_free(pCursor->pVtab->zErrMsg);
174060      pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
174061      return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
174062    }
174063  }else{
174064    pCsr->iDb = pTab->iDb;
174065  }
174066  statResetCsr(pCsr);
174067  sqlite3_finalize(pCsr->pStmt);
174068  pCsr->pStmt = 0;
174069  zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
174070  zSql = sqlite3_mprintf(
174071      "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
174072      "  UNION ALL  "
174073      "SELECT name, rootpage, type"
174074      "  FROM \"%w\".%s WHERE rootpage!=0"
174075      "  ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
174076  if( zSql==0 ){
174077    return SQLITE_NOMEM_BKPT;
174078  }else{
174079    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
174080    sqlite3_free(zSql);
174081  }
174082
174083  if( rc==SQLITE_OK ){
174084    rc = statNext(pCursor);
174085  }
174086  return rc;
174087}
174088
174089static int statColumn(
174090  sqlite3_vtab_cursor *pCursor,
174091  sqlite3_context *ctx,
174092  int i
174093){
174094  StatCursor *pCsr = (StatCursor *)pCursor;
174095  switch( i ){
174096    case 0:            /* name */
174097      sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
174098      break;
174099    case 1:            /* path */
174100      sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
174101      break;
174102    case 2:            /* pageno */
174103      sqlite3_result_int64(ctx, pCsr->iPageno);
174104      break;
174105    case 3:            /* pagetype */
174106      sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
174107      break;
174108    case 4:            /* ncell */
174109      sqlite3_result_int(ctx, pCsr->nCell);
174110      break;
174111    case 5:            /* payload */
174112      sqlite3_result_int(ctx, pCsr->nPayload);
174113      break;
174114    case 6:            /* unused */
174115      sqlite3_result_int(ctx, pCsr->nUnused);
174116      break;
174117    case 7:            /* mx_payload */
174118      sqlite3_result_int(ctx, pCsr->nMxPayload);
174119      break;
174120    case 8:            /* pgoffset */
174121      sqlite3_result_int64(ctx, pCsr->iOffset);
174122      break;
174123    case 9:            /* pgsize */
174124      sqlite3_result_int(ctx, pCsr->szPage);
174125      break;
174126    default: {          /* schema */
174127      sqlite3 *db = sqlite3_context_db_handle(ctx);
174128      int iDb = pCsr->iDb;
174129      sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
174130      break;
174131    }
174132  }
174133  return SQLITE_OK;
174134}
174135
174136static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
174137  StatCursor *pCsr = (StatCursor *)pCursor;
174138  *pRowid = pCsr->iPageno;
174139  return SQLITE_OK;
174140}
174141
174142/*
174143** Invoke this routine to register the "dbstat" virtual table module
174144*/
174145SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
174146  static sqlite3_module dbstat_module = {
174147    0,                            /* iVersion */
174148    statConnect,                  /* xCreate */
174149    statConnect,                  /* xConnect */
174150    statBestIndex,                /* xBestIndex */
174151    statDisconnect,               /* xDisconnect */
174152    statDisconnect,               /* xDestroy */
174153    statOpen,                     /* xOpen - open a cursor */
174154    statClose,                    /* xClose - close a cursor */
174155    statFilter,                   /* xFilter - configure scan constraints */
174156    statNext,                     /* xNext - advance a cursor */
174157    statEof,                      /* xEof - check for end of scan */
174158    statColumn,                   /* xColumn - read data */
174159    statRowid,                    /* xRowid - read data */
174160    0,                            /* xUpdate */
174161    0,                            /* xBegin */
174162    0,                            /* xSync */
174163    0,                            /* xCommit */
174164    0,                            /* xRollback */
174165    0,                            /* xFindMethod */
174166    0,                            /* xRename */
174167  };
174168  return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
174169}
174170#elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
174171SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
174172#endif /* SQLITE_ENABLE_DBSTAT_VTAB */
174173
174174/************** End of dbstat.c **********************************************/
174175/************** Begin file sqlite3session.c **********************************/
174176
174177#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
174178/* #include "sqlite3session.h" */
174179/* #include <assert.h> */
174180/* #include <string.h> */
174181
174182#ifndef SQLITE_AMALGAMATION
174183/* # include "sqliteInt.h" */
174184/* # include "vdbeInt.h" */
174185#endif
174186
174187typedef struct SessionTable SessionTable;
174188typedef struct SessionChange SessionChange;
174189typedef struct SessionBuffer SessionBuffer;
174190typedef struct SessionInput SessionInput;
174191
174192/*
174193** Minimum chunk size used by streaming versions of functions.
174194*/
174195#ifndef SESSIONS_STRM_CHUNK_SIZE
174196# ifdef SQLITE_TEST
174197#   define SESSIONS_STRM_CHUNK_SIZE 64
174198# else
174199#   define SESSIONS_STRM_CHUNK_SIZE 1024
174200# endif
174201#endif
174202
174203typedef struct SessionHook SessionHook;
174204struct SessionHook {
174205  void *pCtx;
174206  int (*xOld)(void*,int,sqlite3_value**);
174207  int (*xNew)(void*,int,sqlite3_value**);
174208  int (*xCount)(void*);
174209  int (*xDepth)(void*);
174210};
174211
174212/*
174213** Session handle structure.
174214*/
174215struct sqlite3_session {
174216  sqlite3 *db;                    /* Database handle session is attached to */
174217  char *zDb;                      /* Name of database session is attached to */
174218  int bEnable;                    /* True if currently recording */
174219  int bIndirect;                  /* True if all changes are indirect */
174220  int bAutoAttach;                /* True to auto-attach tables */
174221  int rc;                         /* Non-zero if an error has occurred */
174222  void *pFilterCtx;               /* First argument to pass to xTableFilter */
174223  int (*xTableFilter)(void *pCtx, const char *zTab);
174224  sqlite3_session *pNext;         /* Next session object on same db. */
174225  SessionTable *pTable;           /* List of attached tables */
174226  SessionHook hook;               /* APIs to grab new and old data with */
174227};
174228
174229/*
174230** Instances of this structure are used to build strings or binary records.
174231*/
174232struct SessionBuffer {
174233  u8 *aBuf;                       /* Pointer to changeset buffer */
174234  int nBuf;                       /* Size of buffer aBuf */
174235  int nAlloc;                     /* Size of allocation containing aBuf */
174236};
174237
174238/*
174239** An object of this type is used internally as an abstraction for
174240** input data. Input data may be supplied either as a single large buffer
174241** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
174242**  sqlite3changeset_start_strm()).
174243*/
174244struct SessionInput {
174245  int bNoDiscard;                 /* If true, discard no data */
174246  int iCurrent;                   /* Offset in aData[] of current change */
174247  int iNext;                      /* Offset in aData[] of next change */
174248  u8 *aData;                      /* Pointer to buffer containing changeset */
174249  int nData;                      /* Number of bytes in aData */
174250
174251  SessionBuffer buf;              /* Current read buffer */
174252  int (*xInput)(void*, void*, int*);        /* Input stream call (or NULL) */
174253  void *pIn;                                /* First argument to xInput */
174254  int bEof;                       /* Set to true after xInput finished */
174255};
174256
174257/*
174258** Structure for changeset iterators.
174259*/
174260struct sqlite3_changeset_iter {
174261  SessionInput in;                /* Input buffer or stream */
174262  SessionBuffer tblhdr;           /* Buffer to hold apValue/zTab/abPK/ */
174263  int bPatchset;                  /* True if this is a patchset */
174264  int rc;                         /* Iterator error code */
174265  sqlite3_stmt *pConflict;        /* Points to conflicting row, if any */
174266  char *zTab;                     /* Current table */
174267  int nCol;                       /* Number of columns in zTab */
174268  int op;                         /* Current operation */
174269  int bIndirect;                  /* True if current change was indirect */
174270  u8 *abPK;                       /* Primary key array */
174271  sqlite3_value **apValue;        /* old.* and new.* values */
174272};
174273
174274/*
174275** Each session object maintains a set of the following structures, one
174276** for each table the session object is monitoring. The structures are
174277** stored in a linked list starting at sqlite3_session.pTable.
174278**
174279** The keys of the SessionTable.aChange[] hash table are all rows that have
174280** been modified in any way since the session object was attached to the
174281** table.
174282**
174283** The data associated with each hash-table entry is a structure containing
174284** a subset of the initial values that the modified row contained at the
174285** start of the session. Or no initial values if the row was inserted.
174286*/
174287struct SessionTable {
174288  SessionTable *pNext;
174289  char *zName;                    /* Local name of table */
174290  int nCol;                       /* Number of columns in table zName */
174291  const char **azCol;             /* Column names */
174292  u8 *abPK;                       /* Array of primary key flags */
174293  int nEntry;                     /* Total number of entries in hash table */
174294  int nChange;                    /* Size of apChange[] array */
174295  SessionChange **apChange;       /* Hash table buckets */
174296};
174297
174298/*
174299** RECORD FORMAT:
174300**
174301** The following record format is similar to (but not compatible with) that
174302** used in SQLite database files. This format is used as part of the
174303** change-set binary format, and so must be architecture independent.
174304**
174305** Unlike the SQLite database record format, each field is self-contained -
174306** there is no separation of header and data. Each field begins with a
174307** single byte describing its type, as follows:
174308**
174309**       0x00: Undefined value.
174310**       0x01: Integer value.
174311**       0x02: Real value.
174312**       0x03: Text value.
174313**       0x04: Blob value.
174314**       0x05: SQL NULL value.
174315**
174316** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
174317** and so on in sqlite3.h. For undefined and NULL values, the field consists
174318** only of the single type byte. For other types of values, the type byte
174319** is followed by:
174320**
174321**   Text values:
174322**     A varint containing the number of bytes in the value (encoded using
174323**     UTF-8). Followed by a buffer containing the UTF-8 representation
174324**     of the text value. There is no nul terminator.
174325**
174326**   Blob values:
174327**     A varint containing the number of bytes in the value, followed by
174328**     a buffer containing the value itself.
174329**
174330**   Integer values:
174331**     An 8-byte big-endian integer value.
174332**
174333**   Real values:
174334**     An 8-byte big-endian IEEE 754-2008 real value.
174335**
174336** Varint values are encoded in the same way as varints in the SQLite
174337** record format.
174338**
174339** CHANGESET FORMAT:
174340**
174341** A changeset is a collection of DELETE, UPDATE and INSERT operations on
174342** one or more tables. Operations on a single table are grouped together,
174343** but may occur in any order (i.e. deletes, updates and inserts are all
174344** mixed together).
174345**
174346** Each group of changes begins with a table header:
174347**
174348**   1 byte: Constant 0x54 (capital 'T')
174349**   Varint: Number of columns in the table.
174350**   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
174351**   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
174352**
174353** Followed by one or more changes to the table.
174354**
174355**   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
174356**   1 byte: The "indirect-change" flag.
174357**   old.* record: (delete and update only)
174358**   new.* record: (insert and update only)
174359**
174360** The "old.*" and "new.*" records, if present, are N field records in the
174361** format described above under "RECORD FORMAT", where N is the number of
174362** columns in the table. The i'th field of each record is associated with
174363** the i'th column of the table, counting from left to right in the order
174364** in which columns were declared in the CREATE TABLE statement.
174365**
174366** The new.* record that is part of each INSERT change contains the values
174367** that make up the new row. Similarly, the old.* record that is part of each
174368** DELETE change contains the values that made up the row that was deleted
174369** from the database. In the changeset format, the records that are part
174370** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
174371** fields.
174372**
174373** Within the old.* record associated with an UPDATE change, all fields
174374** associated with table columns that are not PRIMARY KEY columns and are
174375** not modified by the UPDATE change are set to "undefined". Other fields
174376** are set to the values that made up the row before the UPDATE that the
174377** change records took place. Within the new.* record, fields associated
174378** with table columns modified by the UPDATE change contain the new
174379** values. Fields associated with table columns that are not modified
174380** are set to "undefined".
174381**
174382** PATCHSET FORMAT:
174383**
174384** A patchset is also a collection of changes. It is similar to a changeset,
174385** but leaves undefined those fields that are not useful if no conflict
174386** resolution is required when applying the changeset.
174387**
174388** Each group of changes begins with a table header:
174389**
174390**   1 byte: Constant 0x50 (capital 'P')
174391**   Varint: Number of columns in the table.
174392**   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
174393**   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
174394**
174395** Followed by one or more changes to the table.
174396**
174397**   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
174398**   1 byte: The "indirect-change" flag.
174399**   single record: (PK fields for DELETE, PK and modified fields for UPDATE,
174400**                   full record for INSERT).
174401**
174402** As in the changeset format, each field of the single record that is part
174403** of a patchset change is associated with the correspondingly positioned
174404** table column, counting from left to right within the CREATE TABLE
174405** statement.
174406**
174407** For a DELETE change, all fields within the record except those associated
174408** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
174409** contain the values identifying the row to delete.
174410**
174411** For an UPDATE change, all fields except those associated with PRIMARY KEY
174412** columns and columns that are modified by the UPDATE are set to "undefined".
174413** PRIMARY KEY fields contain the values identifying the table row to update,
174414** and fields associated with modified columns contain the new column values.
174415**
174416** The records associated with INSERT changes are in the same format as for
174417** changesets. It is not possible for a record associated with an INSERT
174418** change to contain a field set to "undefined".
174419*/
174420
174421/*
174422** For each row modified during a session, there exists a single instance of
174423** this structure stored in a SessionTable.aChange[] hash table.
174424*/
174425struct SessionChange {
174426  int op;                         /* One of UPDATE, DELETE, INSERT */
174427  int bIndirect;                  /* True if this change is "indirect" */
174428  int nRecord;                    /* Number of bytes in buffer aRecord[] */
174429  u8 *aRecord;                    /* Buffer containing old.* record */
174430  SessionChange *pNext;           /* For hash-table collisions */
174431};
174432
174433/*
174434** Write a varint with value iVal into the buffer at aBuf. Return the
174435** number of bytes written.
174436*/
174437static int sessionVarintPut(u8 *aBuf, int iVal){
174438  return putVarint32(aBuf, iVal);
174439}
174440
174441/*
174442** Return the number of bytes required to store value iVal as a varint.
174443*/
174444static int sessionVarintLen(int iVal){
174445  return sqlite3VarintLen(iVal);
174446}
174447
174448/*
174449** Read a varint value from aBuf[] into *piVal. Return the number of
174450** bytes read.
174451*/
174452static int sessionVarintGet(u8 *aBuf, int *piVal){
174453  return getVarint32(aBuf, *piVal);
174454}
174455
174456/* Load an unaligned and unsigned 32-bit integer */
174457#define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
174458
174459/*
174460** Read a 64-bit big-endian integer value from buffer aRec[]. Return
174461** the value read.
174462*/
174463static sqlite3_int64 sessionGetI64(u8 *aRec){
174464  u64 x = SESSION_UINT32(aRec);
174465  u32 y = SESSION_UINT32(aRec+4);
174466  x = (x<<32) + y;
174467  return (sqlite3_int64)x;
174468}
174469
174470/*
174471** Write a 64-bit big-endian integer value to the buffer aBuf[].
174472*/
174473static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
174474  aBuf[0] = (i>>56) & 0xFF;
174475  aBuf[1] = (i>>48) & 0xFF;
174476  aBuf[2] = (i>>40) & 0xFF;
174477  aBuf[3] = (i>>32) & 0xFF;
174478  aBuf[4] = (i>>24) & 0xFF;
174479  aBuf[5] = (i>>16) & 0xFF;
174480  aBuf[6] = (i>> 8) & 0xFF;
174481  aBuf[7] = (i>> 0) & 0xFF;
174482}
174483
174484/*
174485** This function is used to serialize the contents of value pValue (see
174486** comment titled "RECORD FORMAT" above).
174487**
174488** If it is non-NULL, the serialized form of the value is written to
174489** buffer aBuf. *pnWrite is set to the number of bytes written before
174490** returning. Or, if aBuf is NULL, the only thing this function does is
174491** set *pnWrite.
174492**
174493** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
174494** within a call to sqlite3_value_text() (may fail if the db is utf-16))
174495** SQLITE_NOMEM is returned.
174496*/
174497static int sessionSerializeValue(
174498  u8 *aBuf,                       /* If non-NULL, write serialized value here */
174499  sqlite3_value *pValue,          /* Value to serialize */
174500  int *pnWrite                    /* IN/OUT: Increment by bytes written */
174501){
174502  int nByte;                      /* Size of serialized value in bytes */
174503
174504  if( pValue ){
174505    int eType;                    /* Value type (SQLITE_NULL, TEXT etc.) */
174506
174507    eType = sqlite3_value_type(pValue);
174508    if( aBuf ) aBuf[0] = eType;
174509
174510    switch( eType ){
174511      case SQLITE_NULL:
174512        nByte = 1;
174513        break;
174514
174515      case SQLITE_INTEGER:
174516      case SQLITE_FLOAT:
174517        if( aBuf ){
174518          /* TODO: SQLite does something special to deal with mixed-endian
174519          ** floating point values (e.g. ARM7). This code probably should
174520          ** too.  */
174521          u64 i;
174522          if( eType==SQLITE_INTEGER ){
174523            i = (u64)sqlite3_value_int64(pValue);
174524          }else{
174525            double r;
174526            assert( sizeof(double)==8 && sizeof(u64)==8 );
174527            r = sqlite3_value_double(pValue);
174528            memcpy(&i, &r, 8);
174529          }
174530          sessionPutI64(&aBuf[1], i);
174531        }
174532        nByte = 9;
174533        break;
174534
174535      default: {
174536        u8 *z;
174537        int n;
174538        int nVarint;
174539
174540        assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
174541        if( eType==SQLITE_TEXT ){
174542          z = (u8 *)sqlite3_value_text(pValue);
174543        }else{
174544          z = (u8 *)sqlite3_value_blob(pValue);
174545        }
174546        n = sqlite3_value_bytes(pValue);
174547        if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
174548        nVarint = sessionVarintLen(n);
174549
174550        if( aBuf ){
174551          sessionVarintPut(&aBuf[1], n);
174552          if( n ) memcpy(&aBuf[nVarint + 1], z, n);
174553        }
174554
174555        nByte = 1 + nVarint + n;
174556        break;
174557      }
174558    }
174559  }else{
174560    nByte = 1;
174561    if( aBuf ) aBuf[0] = '\0';
174562  }
174563
174564  if( pnWrite ) *pnWrite += nByte;
174565  return SQLITE_OK;
174566}
174567
174568
174569/*
174570** This macro is used to calculate hash key values for data structures. In
174571** order to use this macro, the entire data structure must be represented
174572** as a series of unsigned integers. In order to calculate a hash-key value
174573** for a data structure represented as three such integers, the macro may
174574** then be used as follows:
174575**
174576**    int hash_key_value;
174577**    hash_key_value = HASH_APPEND(0, <value 1>);
174578**    hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
174579**    hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
174580**
174581** In practice, the data structures this macro is used for are the primary
174582** key values of modified rows.
174583*/
174584#define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
174585
174586/*
174587** Append the hash of the 64-bit integer passed as the second argument to the
174588** hash-key value passed as the first. Return the new hash-key value.
174589*/
174590static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
174591  h = HASH_APPEND(h, i & 0xFFFFFFFF);
174592  return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
174593}
174594
174595/*
174596** Append the hash of the blob passed via the second and third arguments to
174597** the hash-key value passed as the first. Return the new hash-key value.
174598*/
174599static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
174600  int i;
174601  for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
174602  return h;
174603}
174604
174605/*
174606** Append the hash of the data type passed as the second argument to the
174607** hash-key value passed as the first. Return the new hash-key value.
174608*/
174609static unsigned int sessionHashAppendType(unsigned int h, int eType){
174610  return HASH_APPEND(h, eType);
174611}
174612
174613/*
174614** This function may only be called from within a pre-update callback.
174615** It calculates a hash based on the primary key values of the old.* or
174616** new.* row currently available and, assuming no error occurs, writes it to
174617** *piHash before returning. If the primary key contains one or more NULL
174618** values, *pbNullPK is set to true before returning.
174619**
174620** If an error occurs, an SQLite error code is returned and the final values
174621** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
174622** and the output variables are set as described above.
174623*/
174624static int sessionPreupdateHash(
174625  sqlite3_session *pSession,      /* Session object that owns pTab */
174626  SessionTable *pTab,             /* Session table handle */
174627  int bNew,                       /* True to hash the new.* PK */
174628  int *piHash,                    /* OUT: Hash value */
174629  int *pbNullPK                   /* OUT: True if there are NULL values in PK */
174630){
174631  unsigned int h = 0;             /* Hash value to return */
174632  int i;                          /* Used to iterate through columns */
174633
174634  assert( *pbNullPK==0 );
174635  assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
174636  for(i=0; i<pTab->nCol; i++){
174637    if( pTab->abPK[i] ){
174638      int rc;
174639      int eType;
174640      sqlite3_value *pVal;
174641
174642      if( bNew ){
174643        rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
174644      }else{
174645        rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
174646      }
174647      if( rc!=SQLITE_OK ) return rc;
174648
174649      eType = sqlite3_value_type(pVal);
174650      h = sessionHashAppendType(h, eType);
174651      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
174652        i64 iVal;
174653        if( eType==SQLITE_INTEGER ){
174654          iVal = sqlite3_value_int64(pVal);
174655        }else{
174656          double rVal = sqlite3_value_double(pVal);
174657          assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
174658          memcpy(&iVal, &rVal, 8);
174659        }
174660        h = sessionHashAppendI64(h, iVal);
174661      }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
174662        const u8 *z;
174663        int n;
174664        if( eType==SQLITE_TEXT ){
174665          z = (const u8 *)sqlite3_value_text(pVal);
174666        }else{
174667          z = (const u8 *)sqlite3_value_blob(pVal);
174668        }
174669        n = sqlite3_value_bytes(pVal);
174670        if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
174671        h = sessionHashAppendBlob(h, n, z);
174672      }else{
174673        assert( eType==SQLITE_NULL );
174674        *pbNullPK = 1;
174675      }
174676    }
174677  }
174678
174679  *piHash = (h % pTab->nChange);
174680  return SQLITE_OK;
174681}
174682
174683/*
174684** The buffer that the argument points to contains a serialized SQL value.
174685** Return the number of bytes of space occupied by the value (including
174686** the type byte).
174687*/
174688static int sessionSerialLen(u8 *a){
174689  int e = *a;
174690  int n;
174691  if( e==0 ) return 1;
174692  if( e==SQLITE_NULL ) return 1;
174693  if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
174694  return sessionVarintGet(&a[1], &n) + 1 + n;
174695}
174696
174697/*
174698** Based on the primary key values stored in change aRecord, calculate a
174699** hash key. Assume the has table has nBucket buckets. The hash keys
174700** calculated by this function are compatible with those calculated by
174701** sessionPreupdateHash().
174702**
174703** The bPkOnly argument is non-zero if the record at aRecord[] is from
174704** a patchset DELETE. In this case the non-PK fields are omitted entirely.
174705*/
174706static unsigned int sessionChangeHash(
174707  SessionTable *pTab,             /* Table handle */
174708  int bPkOnly,                    /* Record consists of PK fields only */
174709  u8 *aRecord,                    /* Change record */
174710  int nBucket                     /* Assume this many buckets in hash table */
174711){
174712  unsigned int h = 0;             /* Value to return */
174713  int i;                          /* Used to iterate through columns */
174714  u8 *a = aRecord;                /* Used to iterate through change record */
174715
174716  for(i=0; i<pTab->nCol; i++){
174717    int eType = *a;
174718    int isPK = pTab->abPK[i];
174719    if( bPkOnly && isPK==0 ) continue;
174720
174721    /* It is not possible for eType to be SQLITE_NULL here. The session
174722    ** module does not record changes for rows with NULL values stored in
174723    ** primary key columns. */
174724    assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
174725         || eType==SQLITE_TEXT || eType==SQLITE_BLOB
174726         || eType==SQLITE_NULL || eType==0
174727    );
174728    assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
174729
174730    if( isPK ){
174731      a++;
174732      h = sessionHashAppendType(h, eType);
174733      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
174734        h = sessionHashAppendI64(h, sessionGetI64(a));
174735        a += 8;
174736      }else{
174737        int n;
174738        a += sessionVarintGet(a, &n);
174739        h = sessionHashAppendBlob(h, n, a);
174740        a += n;
174741      }
174742    }else{
174743      a += sessionSerialLen(a);
174744    }
174745  }
174746  return (h % nBucket);
174747}
174748
174749/*
174750** Arguments aLeft and aRight are pointers to change records for table pTab.
174751** This function returns true if the two records apply to the same row (i.e.
174752** have the same values stored in the primary key columns), or false
174753** otherwise.
174754*/
174755static int sessionChangeEqual(
174756  SessionTable *pTab,             /* Table used for PK definition */
174757  int bLeftPkOnly,                /* True if aLeft[] contains PK fields only */
174758  u8 *aLeft,                      /* Change record */
174759  int bRightPkOnly,               /* True if aRight[] contains PK fields only */
174760  u8 *aRight                      /* Change record */
174761){
174762  u8 *a1 = aLeft;                 /* Cursor to iterate through aLeft */
174763  u8 *a2 = aRight;                /* Cursor to iterate through aRight */
174764  int iCol;                       /* Used to iterate through table columns */
174765
174766  for(iCol=0; iCol<pTab->nCol; iCol++){
174767    if( pTab->abPK[iCol] ){
174768      int n1 = sessionSerialLen(a1);
174769      int n2 = sessionSerialLen(a2);
174770
174771      if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
174772        return 0;
174773      }
174774      a1 += n1;
174775      a2 += n2;
174776    }else{
174777      if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
174778      if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
174779    }
174780  }
174781
174782  return 1;
174783}
174784
174785/*
174786** Arguments aLeft and aRight both point to buffers containing change
174787** records with nCol columns. This function "merges" the two records into
174788** a single records which is written to the buffer at *paOut. *paOut is
174789** then set to point to one byte after the last byte written before
174790** returning.
174791**
174792** The merging of records is done as follows: For each column, if the
174793** aRight record contains a value for the column, copy the value from
174794** their. Otherwise, if aLeft contains a value, copy it. If neither
174795** record contains a value for a given column, then neither does the
174796** output record.
174797*/
174798static void sessionMergeRecord(
174799  u8 **paOut,
174800  int nCol,
174801  u8 *aLeft,
174802  u8 *aRight
174803){
174804  u8 *a1 = aLeft;                 /* Cursor used to iterate through aLeft */
174805  u8 *a2 = aRight;                /* Cursor used to iterate through aRight */
174806  u8 *aOut = *paOut;              /* Output cursor */
174807  int iCol;                       /* Used to iterate from 0 to nCol */
174808
174809  for(iCol=0; iCol<nCol; iCol++){
174810    int n1 = sessionSerialLen(a1);
174811    int n2 = sessionSerialLen(a2);
174812    if( *a2 ){
174813      memcpy(aOut, a2, n2);
174814      aOut += n2;
174815    }else{
174816      memcpy(aOut, a1, n1);
174817      aOut += n1;
174818    }
174819    a1 += n1;
174820    a2 += n2;
174821  }
174822
174823  *paOut = aOut;
174824}
174825
174826/*
174827** This is a helper function used by sessionMergeUpdate().
174828**
174829** When this function is called, both *paOne and *paTwo point to a value
174830** within a change record. Before it returns, both have been advanced so
174831** as to point to the next value in the record.
174832**
174833** If, when this function is called, *paTwo points to a valid value (i.e.
174834** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
174835** pointer is returned and *pnVal is set to the number of bytes in the
174836** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
174837** set to the number of bytes in the value at *paOne. If *paOne points
174838** to the "no value" placeholder, *pnVal is set to 1. In other words:
174839**
174840**   if( *paTwo is valid ) return *paTwo;
174841**   return *paOne;
174842**
174843*/
174844static u8 *sessionMergeValue(
174845  u8 **paOne,                     /* IN/OUT: Left-hand buffer pointer */
174846  u8 **paTwo,                     /* IN/OUT: Right-hand buffer pointer */
174847  int *pnVal                      /* OUT: Bytes in returned value */
174848){
174849  u8 *a1 = *paOne;
174850  u8 *a2 = *paTwo;
174851  u8 *pRet = 0;
174852  int n1;
174853
174854  assert( a1 );
174855  if( a2 ){
174856    int n2 = sessionSerialLen(a2);
174857    if( *a2 ){
174858      *pnVal = n2;
174859      pRet = a2;
174860    }
174861    *paTwo = &a2[n2];
174862  }
174863
174864  n1 = sessionSerialLen(a1);
174865  if( pRet==0 ){
174866    *pnVal = n1;
174867    pRet = a1;
174868  }
174869  *paOne = &a1[n1];
174870
174871  return pRet;
174872}
174873
174874/*
174875** This function is used by changeset_concat() to merge two UPDATE changes
174876** on the same row.
174877*/
174878static int sessionMergeUpdate(
174879  u8 **paOut,                     /* IN/OUT: Pointer to output buffer */
174880  SessionTable *pTab,             /* Table change pertains to */
174881  int bPatchset,                  /* True if records are patchset records */
174882  u8 *aOldRecord1,                /* old.* record for first change */
174883  u8 *aOldRecord2,                /* old.* record for second change */
174884  u8 *aNewRecord1,                /* new.* record for first change */
174885  u8 *aNewRecord2                 /* new.* record for second change */
174886){
174887  u8 *aOld1 = aOldRecord1;
174888  u8 *aOld2 = aOldRecord2;
174889  u8 *aNew1 = aNewRecord1;
174890  u8 *aNew2 = aNewRecord2;
174891
174892  u8 *aOut = *paOut;
174893  int i;
174894
174895  if( bPatchset==0 ){
174896    int bRequired = 0;
174897
174898    assert( aOldRecord1 && aNewRecord1 );
174899
174900    /* Write the old.* vector first. */
174901    for(i=0; i<pTab->nCol; i++){
174902      int nOld;
174903      u8 *aOld;
174904      int nNew;
174905      u8 *aNew;
174906
174907      aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
174908      aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
174909      if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
174910        if( pTab->abPK[i]==0 ) bRequired = 1;
174911        memcpy(aOut, aOld, nOld);
174912        aOut += nOld;
174913      }else{
174914        *(aOut++) = '\0';
174915      }
174916    }
174917
174918    if( !bRequired ) return 0;
174919  }
174920
174921  /* Write the new.* vector */
174922  aOld1 = aOldRecord1;
174923  aOld2 = aOldRecord2;
174924  aNew1 = aNewRecord1;
174925  aNew2 = aNewRecord2;
174926  for(i=0; i<pTab->nCol; i++){
174927    int nOld;
174928    u8 *aOld;
174929    int nNew;
174930    u8 *aNew;
174931
174932    aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
174933    aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
174934    if( bPatchset==0
174935     && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
174936    ){
174937      *(aOut++) = '\0';
174938    }else{
174939      memcpy(aOut, aNew, nNew);
174940      aOut += nNew;
174941    }
174942  }
174943
174944  *paOut = aOut;
174945  return 1;
174946}
174947
174948/*
174949** This function is only called from within a pre-update-hook callback.
174950** It determines if the current pre-update-hook change affects the same row
174951** as the change stored in argument pChange. If so, it returns true. Otherwise
174952** if the pre-update-hook does not affect the same row as pChange, it returns
174953** false.
174954*/
174955static int sessionPreupdateEqual(
174956  sqlite3_session *pSession,      /* Session object that owns SessionTable */
174957  SessionTable *pTab,             /* Table associated with change */
174958  SessionChange *pChange,         /* Change to compare to */
174959  int op                          /* Current pre-update operation */
174960){
174961  int iCol;                       /* Used to iterate through columns */
174962  u8 *a = pChange->aRecord;       /* Cursor used to scan change record */
174963
174964  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
174965  for(iCol=0; iCol<pTab->nCol; iCol++){
174966    if( !pTab->abPK[iCol] ){
174967      a += sessionSerialLen(a);
174968    }else{
174969      sqlite3_value *pVal;        /* Value returned by preupdate_new/old */
174970      int rc;                     /* Error code from preupdate_new/old */
174971      int eType = *a++;           /* Type of value from change record */
174972
174973      /* The following calls to preupdate_new() and preupdate_old() can not
174974      ** fail. This is because they cache their return values, and by the
174975      ** time control flows to here they have already been called once from
174976      ** within sessionPreupdateHash(). The first two asserts below verify
174977      ** this (that the method has already been called). */
174978      if( op==SQLITE_INSERT ){
174979        /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
174980        rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
174981      }else{
174982        /* assert( db->pPreUpdate->pUnpacked ); */
174983        rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
174984      }
174985      assert( rc==SQLITE_OK );
174986      if( sqlite3_value_type(pVal)!=eType ) return 0;
174987
174988      /* A SessionChange object never has a NULL value in a PK column */
174989      assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
174990           || eType==SQLITE_BLOB    || eType==SQLITE_TEXT
174991      );
174992
174993      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
174994        i64 iVal = sessionGetI64(a);
174995        a += 8;
174996        if( eType==SQLITE_INTEGER ){
174997          if( sqlite3_value_int64(pVal)!=iVal ) return 0;
174998        }else{
174999          double rVal;
175000          assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
175001          memcpy(&rVal, &iVal, 8);
175002          if( sqlite3_value_double(pVal)!=rVal ) return 0;
175003        }
175004      }else{
175005        int n;
175006        const u8 *z;
175007        a += sessionVarintGet(a, &n);
175008        if( sqlite3_value_bytes(pVal)!=n ) return 0;
175009        if( eType==SQLITE_TEXT ){
175010          z = sqlite3_value_text(pVal);
175011        }else{
175012          z = sqlite3_value_blob(pVal);
175013        }
175014        if( memcmp(a, z, n) ) return 0;
175015        a += n;
175016        break;
175017      }
175018    }
175019  }
175020
175021  return 1;
175022}
175023
175024/*
175025** If required, grow the hash table used to store changes on table pTab
175026** (part of the session pSession). If a fatal OOM error occurs, set the
175027** session object to failed and return SQLITE_ERROR. Otherwise, return
175028** SQLITE_OK.
175029**
175030** It is possible that a non-fatal OOM error occurs in this function. In
175031** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
175032** Growing the hash table in this case is a performance optimization only,
175033** it is not required for correct operation.
175034*/
175035static int sessionGrowHash(int bPatchset, SessionTable *pTab){
175036  if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
175037    int i;
175038    SessionChange **apNew;
175039    int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
175040
175041    apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
175042    if( apNew==0 ){
175043      if( pTab->nChange==0 ){
175044        return SQLITE_ERROR;
175045      }
175046      return SQLITE_OK;
175047    }
175048    memset(apNew, 0, sizeof(SessionChange *) * nNew);
175049
175050    for(i=0; i<pTab->nChange; i++){
175051      SessionChange *p;
175052      SessionChange *pNext;
175053      for(p=pTab->apChange[i]; p; p=pNext){
175054        int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
175055        int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
175056        pNext = p->pNext;
175057        p->pNext = apNew[iHash];
175058        apNew[iHash] = p;
175059      }
175060    }
175061
175062    sqlite3_free(pTab->apChange);
175063    pTab->nChange = nNew;
175064    pTab->apChange = apNew;
175065  }
175066
175067  return SQLITE_OK;
175068}
175069
175070/*
175071** This function queries the database for the names of the columns of table
175072** zThis, in schema zDb. It is expected that the table has nCol columns. If
175073** not, SQLITE_SCHEMA is returned and none of the output variables are
175074** populated.
175075**
175076** Otherwise, if they are not NULL, variable *pnCol is set to the number
175077** of columns in the database table and variable *pzTab is set to point to a
175078** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
175079** point to an array of pointers to column names. And *pabPK (again, if not
175080** NULL) is set to point to an array of booleans - true if the corresponding
175081** column is part of the primary key.
175082**
175083** For example, if the table is declared as:
175084**
175085**     CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
175086**
175087** Then the four output variables are populated as follows:
175088**
175089**     *pnCol  = 4
175090**     *pzTab  = "tbl1"
175091**     *pazCol = {"w", "x", "y", "z"}
175092**     *pabPK  = {1, 0, 0, 1}
175093**
175094** All returned buffers are part of the same single allocation, which must
175095** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
175096** pointer *pazCol should be freed to release all memory. Otherwise, pointer
175097** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
175098*/
175099static int sessionTableInfo(
175100  sqlite3 *db,                    /* Database connection */
175101  const char *zDb,                /* Name of attached database (e.g. "main") */
175102  const char *zThis,              /* Table name */
175103  int *pnCol,                     /* OUT: number of columns */
175104  const char **pzTab,             /* OUT: Copy of zThis */
175105  const char ***pazCol,           /* OUT: Array of column names for table */
175106  u8 **pabPK                      /* OUT: Array of booleans - true for PK col */
175107){
175108  char *zPragma;
175109  sqlite3_stmt *pStmt;
175110  int rc;
175111  int nByte;
175112  int nDbCol = 0;
175113  int nThis;
175114  int i;
175115  u8 *pAlloc = 0;
175116  char **azCol = 0;
175117  u8 *abPK = 0;
175118
175119  assert( pazCol && pabPK );
175120
175121  nThis = sqlite3Strlen30(zThis);
175122  zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
175123  if( !zPragma ) return SQLITE_NOMEM;
175124
175125  rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
175126  sqlite3_free(zPragma);
175127  if( rc!=SQLITE_OK ) return rc;
175128
175129  nByte = nThis + 1;
175130  while( SQLITE_ROW==sqlite3_step(pStmt) ){
175131    nByte += sqlite3_column_bytes(pStmt, 1);
175132    nDbCol++;
175133  }
175134  rc = sqlite3_reset(pStmt);
175135
175136  if( rc==SQLITE_OK ){
175137    nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
175138    pAlloc = sqlite3_malloc(nByte);
175139    if( pAlloc==0 ){
175140      rc = SQLITE_NOMEM;
175141    }
175142  }
175143  if( rc==SQLITE_OK ){
175144    azCol = (char **)pAlloc;
175145    pAlloc = (u8 *)&azCol[nDbCol];
175146    abPK = (u8 *)pAlloc;
175147    pAlloc = &abPK[nDbCol];
175148    if( pzTab ){
175149      memcpy(pAlloc, zThis, nThis+1);
175150      *pzTab = (char *)pAlloc;
175151      pAlloc += nThis+1;
175152    }
175153
175154    i = 0;
175155    while( SQLITE_ROW==sqlite3_step(pStmt) ){
175156      int nName = sqlite3_column_bytes(pStmt, 1);
175157      const unsigned char *zName = sqlite3_column_text(pStmt, 1);
175158      if( zName==0 ) break;
175159      memcpy(pAlloc, zName, nName+1);
175160      azCol[i] = (char *)pAlloc;
175161      pAlloc += nName+1;
175162      abPK[i] = sqlite3_column_int(pStmt, 5);
175163      i++;
175164    }
175165    rc = sqlite3_reset(pStmt);
175166
175167  }
175168
175169  /* If successful, populate the output variables. Otherwise, zero them and
175170  ** free any allocation made. An error code will be returned in this case.
175171  */
175172  if( rc==SQLITE_OK ){
175173    *pazCol = (const char **)azCol;
175174    *pabPK = abPK;
175175    *pnCol = nDbCol;
175176  }else{
175177    *pazCol = 0;
175178    *pabPK = 0;
175179    *pnCol = 0;
175180    if( pzTab ) *pzTab = 0;
175181    sqlite3_free(azCol);
175182  }
175183  sqlite3_finalize(pStmt);
175184  return rc;
175185}
175186
175187/*
175188** This function is only called from within a pre-update handler for a
175189** write to table pTab, part of session pSession. If this is the first
175190** write to this table, initalize the SessionTable.nCol, azCol[] and
175191** abPK[] arrays accordingly.
175192**
175193** If an error occurs, an error code is stored in sqlite3_session.rc and
175194** non-zero returned. Or, if no error occurs but the table has no primary
175195** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
175196** indicate that updates on this table should be ignored. SessionTable.abPK
175197** is set to NULL in this case.
175198*/
175199static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
175200  if( pTab->nCol==0 ){
175201    u8 *abPK;
175202    assert( pTab->azCol==0 || pTab->abPK==0 );
175203    pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
175204        pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
175205    );
175206    if( pSession->rc==SQLITE_OK ){
175207      int i;
175208      for(i=0; i<pTab->nCol; i++){
175209        if( abPK[i] ){
175210          pTab->abPK = abPK;
175211          break;
175212        }
175213      }
175214    }
175215  }
175216  return (pSession->rc || pTab->abPK==0);
175217}
175218
175219/*
175220** This function is only called from with a pre-update-hook reporting a
175221** change on table pTab (attached to session pSession). The type of change
175222** (UPDATE, INSERT, DELETE) is specified by the first argument.
175223**
175224** Unless one is already present or an error occurs, an entry is added
175225** to the changed-rows hash table associated with table pTab.
175226*/
175227static void sessionPreupdateOneChange(
175228  int op,                         /* One of SQLITE_UPDATE, INSERT, DELETE */
175229  sqlite3_session *pSession,      /* Session object pTab is attached to */
175230  SessionTable *pTab              /* Table that change applies to */
175231){
175232  int iHash;
175233  int bNull = 0;
175234  int rc = SQLITE_OK;
175235
175236  if( pSession->rc ) return;
175237
175238  /* Load table details if required */
175239  if( sessionInitTable(pSession, pTab) ) return;
175240
175241  /* Check the number of columns in this xPreUpdate call matches the
175242  ** number of columns in the table.  */
175243  if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
175244    pSession->rc = SQLITE_SCHEMA;
175245    return;
175246  }
175247
175248  /* Grow the hash table if required */
175249  if( sessionGrowHash(0, pTab) ){
175250    pSession->rc = SQLITE_NOMEM;
175251    return;
175252  }
175253
175254  /* Calculate the hash-key for this change. If the primary key of the row
175255  ** includes a NULL value, exit early. Such changes are ignored by the
175256  ** session module. */
175257  rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
175258  if( rc!=SQLITE_OK ) goto error_out;
175259
175260  if( bNull==0 ){
175261    /* Search the hash table for an existing record for this row. */
175262    SessionChange *pC;
175263    for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
175264      if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
175265    }
175266
175267    if( pC==0 ){
175268      /* Create a new change object containing all the old values (if
175269      ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
175270      ** values (if this is an INSERT). */
175271      SessionChange *pChange; /* New change object */
175272      int nByte;              /* Number of bytes to allocate */
175273      int i;                  /* Used to iterate through columns */
175274
175275      assert( rc==SQLITE_OK );
175276      pTab->nEntry++;
175277
175278      /* Figure out how large an allocation is required */
175279      nByte = sizeof(SessionChange);
175280      for(i=0; i<pTab->nCol; i++){
175281        sqlite3_value *p = 0;
175282        if( op!=SQLITE_INSERT ){
175283          TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
175284          assert( trc==SQLITE_OK );
175285        }else if( pTab->abPK[i] ){
175286          TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
175287          assert( trc==SQLITE_OK );
175288        }
175289
175290        /* This may fail if SQLite value p contains a utf-16 string that must
175291        ** be converted to utf-8 and an OOM error occurs while doing so. */
175292        rc = sessionSerializeValue(0, p, &nByte);
175293        if( rc!=SQLITE_OK ) goto error_out;
175294      }
175295
175296      /* Allocate the change object */
175297      pChange = (SessionChange *)sqlite3_malloc(nByte);
175298      if( !pChange ){
175299        rc = SQLITE_NOMEM;
175300        goto error_out;
175301      }else{
175302        memset(pChange, 0, sizeof(SessionChange));
175303        pChange->aRecord = (u8 *)&pChange[1];
175304      }
175305
175306      /* Populate the change object. None of the preupdate_old(),
175307      ** preupdate_new() or SerializeValue() calls below may fail as all
175308      ** required values and encodings have already been cached in memory.
175309      ** It is not possible for an OOM to occur in this block. */
175310      nByte = 0;
175311      for(i=0; i<pTab->nCol; i++){
175312        sqlite3_value *p = 0;
175313        if( op!=SQLITE_INSERT ){
175314          pSession->hook.xOld(pSession->hook.pCtx, i, &p);
175315        }else if( pTab->abPK[i] ){
175316          pSession->hook.xNew(pSession->hook.pCtx, i, &p);
175317        }
175318        sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
175319      }
175320
175321      /* Add the change to the hash-table */
175322      if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
175323        pChange->bIndirect = 1;
175324      }
175325      pChange->nRecord = nByte;
175326      pChange->op = op;
175327      pChange->pNext = pTab->apChange[iHash];
175328      pTab->apChange[iHash] = pChange;
175329
175330    }else if( pC->bIndirect ){
175331      /* If the existing change is considered "indirect", but this current
175332      ** change is "direct", mark the change object as direct. */
175333      if( pSession->hook.xDepth(pSession->hook.pCtx)==0
175334       && pSession->bIndirect==0
175335      ){
175336        pC->bIndirect = 0;
175337      }
175338    }
175339  }
175340
175341  /* If an error has occurred, mark the session object as failed. */
175342 error_out:
175343  if( rc!=SQLITE_OK ){
175344    pSession->rc = rc;
175345  }
175346}
175347
175348static int sessionFindTable(
175349  sqlite3_session *pSession,
175350  const char *zName,
175351  SessionTable **ppTab
175352){
175353  int rc = SQLITE_OK;
175354  int nName = sqlite3Strlen30(zName);
175355  SessionTable *pRet;
175356
175357  /* Search for an existing table */
175358  for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
175359    if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
175360  }
175361
175362  if( pRet==0 && pSession->bAutoAttach ){
175363    /* If there is a table-filter configured, invoke it. If it returns 0,
175364    ** do not automatically add the new table. */
175365    if( pSession->xTableFilter==0
175366     || pSession->xTableFilter(pSession->pFilterCtx, zName)
175367    ){
175368      rc = sqlite3session_attach(pSession, zName);
175369      if( rc==SQLITE_OK ){
175370        for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
175371        assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
175372      }
175373    }
175374  }
175375
175376  assert( rc==SQLITE_OK || pRet==0 );
175377  *ppTab = pRet;
175378  return rc;
175379}
175380
175381/*
175382** The 'pre-update' hook registered by this module with SQLite databases.
175383*/
175384static void xPreUpdate(
175385  void *pCtx,                     /* Copy of third arg to preupdate_hook() */
175386  sqlite3 *db,                    /* Database handle */
175387  int op,                         /* SQLITE_UPDATE, DELETE or INSERT */
175388  char const *zDb,                /* Database name */
175389  char const *zName,              /* Table name */
175390  sqlite3_int64 iKey1,            /* Rowid of row about to be deleted/updated */
175391  sqlite3_int64 iKey2             /* New rowid value (for a rowid UPDATE) */
175392){
175393  sqlite3_session *pSession;
175394  int nDb = sqlite3Strlen30(zDb);
175395
175396  assert( sqlite3_mutex_held(db->mutex) );
175397
175398  for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
175399    SessionTable *pTab;
175400
175401    /* If this session is attached to a different database ("main", "temp"
175402    ** etc.), or if it is not currently enabled, there is nothing to do. Skip
175403    ** to the next session object attached to this database. */
175404    if( pSession->bEnable==0 ) continue;
175405    if( pSession->rc ) continue;
175406    if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
175407
175408    pSession->rc = sessionFindTable(pSession, zName, &pTab);
175409    if( pTab ){
175410      assert( pSession->rc==SQLITE_OK );
175411      sessionPreupdateOneChange(op, pSession, pTab);
175412      if( op==SQLITE_UPDATE ){
175413        sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
175414      }
175415    }
175416  }
175417}
175418
175419/*
175420** The pre-update hook implementations.
175421*/
175422static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
175423  return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
175424}
175425static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
175426  return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
175427}
175428static int sessionPreupdateCount(void *pCtx){
175429  return sqlite3_preupdate_count((sqlite3*)pCtx);
175430}
175431static int sessionPreupdateDepth(void *pCtx){
175432  return sqlite3_preupdate_depth((sqlite3*)pCtx);
175433}
175434
175435/*
175436** Install the pre-update hooks on the session object passed as the only
175437** argument.
175438*/
175439static void sessionPreupdateHooks(
175440  sqlite3_session *pSession
175441){
175442  pSession->hook.pCtx = (void*)pSession->db;
175443  pSession->hook.xOld = sessionPreupdateOld;
175444  pSession->hook.xNew = sessionPreupdateNew;
175445  pSession->hook.xCount = sessionPreupdateCount;
175446  pSession->hook.xDepth = sessionPreupdateDepth;
175447}
175448
175449typedef struct SessionDiffCtx SessionDiffCtx;
175450struct SessionDiffCtx {
175451  sqlite3_stmt *pStmt;
175452  int nOldOff;
175453};
175454
175455/*
175456** The diff hook implementations.
175457*/
175458static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
175459  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
175460  *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
175461  return SQLITE_OK;
175462}
175463static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
175464  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
175465  *ppVal = sqlite3_column_value(p->pStmt, iVal);
175466   return SQLITE_OK;
175467}
175468static int sessionDiffCount(void *pCtx){
175469  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
175470  return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
175471}
175472static int sessionDiffDepth(void *pCtx){
175473  return 0;
175474}
175475
175476/*
175477** Install the diff hooks on the session object passed as the only
175478** argument.
175479*/
175480static void sessionDiffHooks(
175481  sqlite3_session *pSession,
175482  SessionDiffCtx *pDiffCtx
175483){
175484  pSession->hook.pCtx = (void*)pDiffCtx;
175485  pSession->hook.xOld = sessionDiffOld;
175486  pSession->hook.xNew = sessionDiffNew;
175487  pSession->hook.xCount = sessionDiffCount;
175488  pSession->hook.xDepth = sessionDiffDepth;
175489}
175490
175491static char *sessionExprComparePK(
175492  int nCol,
175493  const char *zDb1, const char *zDb2,
175494  const char *zTab,
175495  const char **azCol, u8 *abPK
175496){
175497  int i;
175498  const char *zSep = "";
175499  char *zRet = 0;
175500
175501  for(i=0; i<nCol; i++){
175502    if( abPK[i] ){
175503      zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
175504          zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
175505      );
175506      zSep = " AND ";
175507      if( zRet==0 ) break;
175508    }
175509  }
175510
175511  return zRet;
175512}
175513
175514static char *sessionExprCompareOther(
175515  int nCol,
175516  const char *zDb1, const char *zDb2,
175517  const char *zTab,
175518  const char **azCol, u8 *abPK
175519){
175520  int i;
175521  const char *zSep = "";
175522  char *zRet = 0;
175523  int bHave = 0;
175524
175525  for(i=0; i<nCol; i++){
175526    if( abPK[i]==0 ){
175527      bHave = 1;
175528      zRet = sqlite3_mprintf(
175529          "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
175530          zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
175531      );
175532      zSep = " OR ";
175533      if( zRet==0 ) break;
175534    }
175535  }
175536
175537  if( bHave==0 ){
175538    assert( zRet==0 );
175539    zRet = sqlite3_mprintf("0");
175540  }
175541
175542  return zRet;
175543}
175544
175545static char *sessionSelectFindNew(
175546  int nCol,
175547  const char *zDb1,      /* Pick rows in this db only */
175548  const char *zDb2,      /* But not in this one */
175549  const char *zTbl,      /* Table name */
175550  const char *zExpr
175551){
175552  char *zRet = sqlite3_mprintf(
175553      "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
175554      "  SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
175555      ")",
175556      zDb1, zTbl, zDb2, zTbl, zExpr
175557  );
175558  return zRet;
175559}
175560
175561static int sessionDiffFindNew(
175562  int op,
175563  sqlite3_session *pSession,
175564  SessionTable *pTab,
175565  const char *zDb1,
175566  const char *zDb2,
175567  char *zExpr
175568){
175569  int rc = SQLITE_OK;
175570  char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
175571
175572  if( zStmt==0 ){
175573    rc = SQLITE_NOMEM;
175574  }else{
175575    sqlite3_stmt *pStmt;
175576    rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
175577    if( rc==SQLITE_OK ){
175578      SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
175579      pDiffCtx->pStmt = pStmt;
175580      pDiffCtx->nOldOff = 0;
175581      while( SQLITE_ROW==sqlite3_step(pStmt) ){
175582        sessionPreupdateOneChange(op, pSession, pTab);
175583      }
175584      rc = sqlite3_finalize(pStmt);
175585    }
175586    sqlite3_free(zStmt);
175587  }
175588
175589  return rc;
175590}
175591
175592static int sessionDiffFindModified(
175593  sqlite3_session *pSession,
175594  SessionTable *pTab,
175595  const char *zFrom,
175596  const char *zExpr
175597){
175598  int rc = SQLITE_OK;
175599
175600  char *zExpr2 = sessionExprCompareOther(pTab->nCol,
175601      pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
175602  );
175603  if( zExpr2==0 ){
175604    rc = SQLITE_NOMEM;
175605  }else{
175606    char *zStmt = sqlite3_mprintf(
175607        "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
175608        pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
175609    );
175610    if( zStmt==0 ){
175611      rc = SQLITE_NOMEM;
175612    }else{
175613      sqlite3_stmt *pStmt;
175614      rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
175615
175616      if( rc==SQLITE_OK ){
175617        SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
175618        pDiffCtx->pStmt = pStmt;
175619        pDiffCtx->nOldOff = pTab->nCol;
175620        while( SQLITE_ROW==sqlite3_step(pStmt) ){
175621          sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
175622        }
175623        rc = sqlite3_finalize(pStmt);
175624      }
175625      sqlite3_free(zStmt);
175626    }
175627  }
175628
175629  return rc;
175630}
175631
175632SQLITE_API int sqlite3session_diff(
175633  sqlite3_session *pSession,
175634  const char *zFrom,
175635  const char *zTbl,
175636  char **pzErrMsg
175637){
175638  const char *zDb = pSession->zDb;
175639  int rc = pSession->rc;
175640  SessionDiffCtx d;
175641
175642  memset(&d, 0, sizeof(d));
175643  sessionDiffHooks(pSession, &d);
175644
175645  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
175646  if( pzErrMsg ) *pzErrMsg = 0;
175647  if( rc==SQLITE_OK ){
175648    char *zExpr = 0;
175649    sqlite3 *db = pSession->db;
175650    SessionTable *pTo;            /* Table zTbl */
175651
175652    /* Locate and if necessary initialize the target table object */
175653    rc = sessionFindTable(pSession, zTbl, &pTo);
175654    if( pTo==0 ) goto diff_out;
175655    if( sessionInitTable(pSession, pTo) ){
175656      rc = pSession->rc;
175657      goto diff_out;
175658    }
175659
175660    /* Check the table schemas match */
175661    if( rc==SQLITE_OK ){
175662      int bHasPk = 0;
175663      int bMismatch = 0;
175664      int nCol;                   /* Columns in zFrom.zTbl */
175665      u8 *abPK;
175666      const char **azCol = 0;
175667      rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
175668      if( rc==SQLITE_OK ){
175669        if( pTo->nCol!=nCol ){
175670          bMismatch = 1;
175671        }else{
175672          int i;
175673          for(i=0; i<nCol; i++){
175674            if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
175675            if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
175676            if( abPK[i] ) bHasPk = 1;
175677          }
175678        }
175679
175680      }
175681      sqlite3_free((char*)azCol);
175682      if( bMismatch ){
175683        *pzErrMsg = sqlite3_mprintf("table schemas do not match");
175684        rc = SQLITE_SCHEMA;
175685      }
175686      if( bHasPk==0 ){
175687        /* Ignore tables with no primary keys */
175688        goto diff_out;
175689      }
175690    }
175691
175692    if( rc==SQLITE_OK ){
175693      zExpr = sessionExprComparePK(pTo->nCol,
175694          zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
175695      );
175696    }
175697
175698    /* Find new rows */
175699    if( rc==SQLITE_OK ){
175700      rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
175701    }
175702
175703    /* Find old rows */
175704    if( rc==SQLITE_OK ){
175705      rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
175706    }
175707
175708    /* Find modified rows */
175709    if( rc==SQLITE_OK ){
175710      rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
175711    }
175712
175713    sqlite3_free(zExpr);
175714  }
175715
175716 diff_out:
175717  sessionPreupdateHooks(pSession);
175718  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
175719  return rc;
175720}
175721
175722/*
175723** Create a session object. This session object will record changes to
175724** database zDb attached to connection db.
175725*/
175726SQLITE_API int sqlite3session_create(
175727  sqlite3 *db,                    /* Database handle */
175728  const char *zDb,                /* Name of db (e.g. "main") */
175729  sqlite3_session **ppSession     /* OUT: New session object */
175730){
175731  sqlite3_session *pNew;          /* Newly allocated session object */
175732  sqlite3_session *pOld;          /* Session object already attached to db */
175733  int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
175734
175735  /* Zero the output value in case an error occurs. */
175736  *ppSession = 0;
175737
175738  /* Allocate and populate the new session object. */
175739  pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
175740  if( !pNew ) return SQLITE_NOMEM;
175741  memset(pNew, 0, sizeof(sqlite3_session));
175742  pNew->db = db;
175743  pNew->zDb = (char *)&pNew[1];
175744  pNew->bEnable = 1;
175745  memcpy(pNew->zDb, zDb, nDb+1);
175746  sessionPreupdateHooks(pNew);
175747
175748  /* Add the new session object to the linked list of session objects
175749  ** attached to database handle $db. Do this under the cover of the db
175750  ** handle mutex.  */
175751  sqlite3_mutex_enter(sqlite3_db_mutex(db));
175752  pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
175753  pNew->pNext = pOld;
175754  sqlite3_mutex_leave(sqlite3_db_mutex(db));
175755
175756  *ppSession = pNew;
175757  return SQLITE_OK;
175758}
175759
175760/*
175761** Free the list of table objects passed as the first argument. The contents
175762** of the changed-rows hash tables are also deleted.
175763*/
175764static void sessionDeleteTable(SessionTable *pList){
175765  SessionTable *pNext;
175766  SessionTable *pTab;
175767
175768  for(pTab=pList; pTab; pTab=pNext){
175769    int i;
175770    pNext = pTab->pNext;
175771    for(i=0; i<pTab->nChange; i++){
175772      SessionChange *p;
175773      SessionChange *pNextChange;
175774      for(p=pTab->apChange[i]; p; p=pNextChange){
175775        pNextChange = p->pNext;
175776        sqlite3_free(p);
175777      }
175778    }
175779    sqlite3_free((char*)pTab->azCol);  /* cast works around VC++ bug */
175780    sqlite3_free(pTab->apChange);
175781    sqlite3_free(pTab);
175782  }
175783}
175784
175785/*
175786** Delete a session object previously allocated using sqlite3session_create().
175787*/
175788SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
175789  sqlite3 *db = pSession->db;
175790  sqlite3_session *pHead;
175791  sqlite3_session **pp;
175792
175793  /* Unlink the session from the linked list of sessions attached to the
175794  ** database handle. Hold the db mutex while doing so.  */
175795  sqlite3_mutex_enter(sqlite3_db_mutex(db));
175796  pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
175797  for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
175798    if( (*pp)==pSession ){
175799      *pp = (*pp)->pNext;
175800      if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
175801      break;
175802    }
175803  }
175804  sqlite3_mutex_leave(sqlite3_db_mutex(db));
175805
175806  /* Delete all attached table objects. And the contents of their
175807  ** associated hash-tables. */
175808  sessionDeleteTable(pSession->pTable);
175809
175810  /* Free the session object itself. */
175811  sqlite3_free(pSession);
175812}
175813
175814/*
175815** Set a table filter on a Session Object.
175816*/
175817SQLITE_API void sqlite3session_table_filter(
175818  sqlite3_session *pSession,
175819  int(*xFilter)(void*, const char*),
175820  void *pCtx                      /* First argument passed to xFilter */
175821){
175822  pSession->bAutoAttach = 1;
175823  pSession->pFilterCtx = pCtx;
175824  pSession->xTableFilter = xFilter;
175825}
175826
175827/*
175828** Attach a table to a session. All subsequent changes made to the table
175829** while the session object is enabled will be recorded.
175830**
175831** Only tables that have a PRIMARY KEY defined may be attached. It does
175832** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
175833** or not.
175834*/
175835SQLITE_API int sqlite3session_attach(
175836  sqlite3_session *pSession,      /* Session object */
175837  const char *zName               /* Table name */
175838){
175839  int rc = SQLITE_OK;
175840  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
175841
175842  if( !zName ){
175843    pSession->bAutoAttach = 1;
175844  }else{
175845    SessionTable *pTab;           /* New table object (if required) */
175846    int nName;                    /* Number of bytes in string zName */
175847
175848    /* First search for an existing entry. If one is found, this call is
175849    ** a no-op. Return early. */
175850    nName = sqlite3Strlen30(zName);
175851    for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
175852      if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
175853    }
175854
175855    if( !pTab ){
175856      /* Allocate new SessionTable object. */
175857      pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
175858      if( !pTab ){
175859        rc = SQLITE_NOMEM;
175860      }else{
175861        /* Populate the new SessionTable object and link it into the list.
175862        ** The new object must be linked onto the end of the list, not
175863        ** simply added to the start of it in order to ensure that tables
175864        ** appear in the correct order when a changeset or patchset is
175865        ** eventually generated. */
175866        SessionTable **ppTab;
175867        memset(pTab, 0, sizeof(SessionTable));
175868        pTab->zName = (char *)&pTab[1];
175869        memcpy(pTab->zName, zName, nName+1);
175870        for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
175871        *ppTab = pTab;
175872      }
175873    }
175874  }
175875
175876  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
175877  return rc;
175878}
175879
175880/*
175881** Ensure that there is room in the buffer to append nByte bytes of data.
175882** If not, use sqlite3_realloc() to grow the buffer so that there is.
175883**
175884** If successful, return zero. Otherwise, if an OOM condition is encountered,
175885** set *pRc to SQLITE_NOMEM and return non-zero.
175886*/
175887static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
175888  if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
175889    u8 *aNew;
175890    int nNew = p->nAlloc ? p->nAlloc : 128;
175891    do {
175892      nNew = nNew*2;
175893    }while( nNew<(p->nBuf+nByte) );
175894
175895    aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
175896    if( 0==aNew ){
175897      *pRc = SQLITE_NOMEM;
175898    }else{
175899      p->aBuf = aNew;
175900      p->nAlloc = nNew;
175901    }
175902  }
175903  return (*pRc!=SQLITE_OK);
175904}
175905
175906/*
175907** Append the value passed as the second argument to the buffer passed
175908** as the first.
175909**
175910** This function is a no-op if *pRc is non-zero when it is called.
175911** Otherwise, if an error occurs, *pRc is set to an SQLite error code
175912** before returning.
175913*/
175914static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
175915  int rc = *pRc;
175916  if( rc==SQLITE_OK ){
175917    int nByte = 0;
175918    rc = sessionSerializeValue(0, pVal, &nByte);
175919    sessionBufferGrow(p, nByte, &rc);
175920    if( rc==SQLITE_OK ){
175921      rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
175922      p->nBuf += nByte;
175923    }else{
175924      *pRc = rc;
175925    }
175926  }
175927}
175928
175929/*
175930** This function is a no-op if *pRc is other than SQLITE_OK when it is
175931** called. Otherwise, append a single byte to the buffer.
175932**
175933** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
175934** returning.
175935*/
175936static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
175937  if( 0==sessionBufferGrow(p, 1, pRc) ){
175938    p->aBuf[p->nBuf++] = v;
175939  }
175940}
175941
175942/*
175943** This function is a no-op if *pRc is other than SQLITE_OK when it is
175944** called. Otherwise, append a single varint to the buffer.
175945**
175946** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
175947** returning.
175948*/
175949static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
175950  if( 0==sessionBufferGrow(p, 9, pRc) ){
175951    p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
175952  }
175953}
175954
175955/*
175956** This function is a no-op if *pRc is other than SQLITE_OK when it is
175957** called. Otherwise, append a blob of data to the buffer.
175958**
175959** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
175960** returning.
175961*/
175962static void sessionAppendBlob(
175963  SessionBuffer *p,
175964  const u8 *aBlob,
175965  int nBlob,
175966  int *pRc
175967){
175968  if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
175969    memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
175970    p->nBuf += nBlob;
175971  }
175972}
175973
175974/*
175975** This function is a no-op if *pRc is other than SQLITE_OK when it is
175976** called. Otherwise, append a string to the buffer. All bytes in the string
175977** up to (but not including) the nul-terminator are written to the buffer.
175978**
175979** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
175980** returning.
175981*/
175982static void sessionAppendStr(
175983  SessionBuffer *p,
175984  const char *zStr,
175985  int *pRc
175986){
175987  int nStr = sqlite3Strlen30(zStr);
175988  if( 0==sessionBufferGrow(p, nStr, pRc) ){
175989    memcpy(&p->aBuf[p->nBuf], zStr, nStr);
175990    p->nBuf += nStr;
175991  }
175992}
175993
175994/*
175995** This function is a no-op if *pRc is other than SQLITE_OK when it is
175996** called. Otherwise, append the string representation of integer iVal
175997** to the buffer. No nul-terminator is written.
175998**
175999** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
176000** returning.
176001*/
176002static void sessionAppendInteger(
176003  SessionBuffer *p,               /* Buffer to append to */
176004  int iVal,                       /* Value to write the string rep. of */
176005  int *pRc                        /* IN/OUT: Error code */
176006){
176007  char aBuf[24];
176008  sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
176009  sessionAppendStr(p, aBuf, pRc);
176010}
176011
176012/*
176013** This function is a no-op if *pRc is other than SQLITE_OK when it is
176014** called. Otherwise, append the string zStr enclosed in quotes (") and
176015** with any embedded quote characters escaped to the buffer. No
176016** nul-terminator byte is written.
176017**
176018** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
176019** returning.
176020*/
176021static void sessionAppendIdent(
176022  SessionBuffer *p,               /* Buffer to a append to */
176023  const char *zStr,               /* String to quote, escape and append */
176024  int *pRc                        /* IN/OUT: Error code */
176025){
176026  int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
176027  if( 0==sessionBufferGrow(p, nStr, pRc) ){
176028    char *zOut = (char *)&p->aBuf[p->nBuf];
176029    const char *zIn = zStr;
176030    *zOut++ = '"';
176031    while( *zIn ){
176032      if( *zIn=='"' ) *zOut++ = '"';
176033      *zOut++ = *(zIn++);
176034    }
176035    *zOut++ = '"';
176036    p->nBuf = (int)((u8 *)zOut - p->aBuf);
176037  }
176038}
176039
176040/*
176041** This function is a no-op if *pRc is other than SQLITE_OK when it is
176042** called. Otherwse, it appends the serialized version of the value stored
176043** in column iCol of the row that SQL statement pStmt currently points
176044** to to the buffer.
176045*/
176046static void sessionAppendCol(
176047  SessionBuffer *p,               /* Buffer to append to */
176048  sqlite3_stmt *pStmt,            /* Handle pointing to row containing value */
176049  int iCol,                       /* Column to read value from */
176050  int *pRc                        /* IN/OUT: Error code */
176051){
176052  if( *pRc==SQLITE_OK ){
176053    int eType = sqlite3_column_type(pStmt, iCol);
176054    sessionAppendByte(p, (u8)eType, pRc);
176055    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
176056      sqlite3_int64 i;
176057      u8 aBuf[8];
176058      if( eType==SQLITE_INTEGER ){
176059        i = sqlite3_column_int64(pStmt, iCol);
176060      }else{
176061        double r = sqlite3_column_double(pStmt, iCol);
176062        memcpy(&i, &r, 8);
176063      }
176064      sessionPutI64(aBuf, i);
176065      sessionAppendBlob(p, aBuf, 8, pRc);
176066    }
176067    if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
176068      u8 *z;
176069      int nByte;
176070      if( eType==SQLITE_BLOB ){
176071        z = (u8 *)sqlite3_column_blob(pStmt, iCol);
176072      }else{
176073        z = (u8 *)sqlite3_column_text(pStmt, iCol);
176074      }
176075      nByte = sqlite3_column_bytes(pStmt, iCol);
176076      if( z || (eType==SQLITE_BLOB && nByte==0) ){
176077        sessionAppendVarint(p, nByte, pRc);
176078        sessionAppendBlob(p, z, nByte, pRc);
176079      }else{
176080        *pRc = SQLITE_NOMEM;
176081      }
176082    }
176083  }
176084}
176085
176086/*
176087**
176088** This function appends an update change to the buffer (see the comments
176089** under "CHANGESET FORMAT" at the top of the file). An update change
176090** consists of:
176091**
176092**   1 byte:  SQLITE_UPDATE (0x17)
176093**   n bytes: old.* record (see RECORD FORMAT)
176094**   m bytes: new.* record (see RECORD FORMAT)
176095**
176096** The SessionChange object passed as the third argument contains the
176097** values that were stored in the row when the session began (the old.*
176098** values). The statement handle passed as the second argument points
176099** at the current version of the row (the new.* values).
176100**
176101** If all of the old.* values are equal to their corresponding new.* value
176102** (i.e. nothing has changed), then no data at all is appended to the buffer.
176103**
176104** Otherwise, the old.* record contains all primary key values and the
176105** original values of any fields that have been modified. The new.* record
176106** contains the new values of only those fields that have been modified.
176107*/
176108static int sessionAppendUpdate(
176109  SessionBuffer *pBuf,            /* Buffer to append to */
176110  int bPatchset,                  /* True for "patchset", 0 for "changeset" */
176111  sqlite3_stmt *pStmt,            /* Statement handle pointing at new row */
176112  SessionChange *p,               /* Object containing old values */
176113  u8 *abPK                        /* Boolean array - true for PK columns */
176114){
176115  int rc = SQLITE_OK;
176116  SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
176117  int bNoop = 1;                /* Set to zero if any values are modified */
176118  int nRewind = pBuf->nBuf;     /* Set to zero if any values are modified */
176119  int i;                        /* Used to iterate through columns */
176120  u8 *pCsr = p->aRecord;        /* Used to iterate through old.* values */
176121
176122  sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
176123  sessionAppendByte(pBuf, p->bIndirect, &rc);
176124  for(i=0; i<sqlite3_column_count(pStmt); i++){
176125    int bChanged = 0;
176126    int nAdvance;
176127    int eType = *pCsr;
176128    switch( eType ){
176129      case SQLITE_NULL:
176130        nAdvance = 1;
176131        if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
176132          bChanged = 1;
176133        }
176134        break;
176135
176136      case SQLITE_FLOAT:
176137      case SQLITE_INTEGER: {
176138        nAdvance = 9;
176139        if( eType==sqlite3_column_type(pStmt, i) ){
176140          sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
176141          if( eType==SQLITE_INTEGER ){
176142            if( iVal==sqlite3_column_int64(pStmt, i) ) break;
176143          }else{
176144            double dVal;
176145            memcpy(&dVal, &iVal, 8);
176146            if( dVal==sqlite3_column_double(pStmt, i) ) break;
176147          }
176148        }
176149        bChanged = 1;
176150        break;
176151      }
176152
176153      default: {
176154        int n;
176155        int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
176156        assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
176157        nAdvance = nHdr + n;
176158        if( eType==sqlite3_column_type(pStmt, i)
176159         && n==sqlite3_column_bytes(pStmt, i)
176160         && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
176161        ){
176162          break;
176163        }
176164        bChanged = 1;
176165      }
176166    }
176167
176168    /* If at least one field has been modified, this is not a no-op. */
176169    if( bChanged ) bNoop = 0;
176170
176171    /* Add a field to the old.* record. This is omitted if this modules is
176172    ** currently generating a patchset. */
176173    if( bPatchset==0 ){
176174      if( bChanged || abPK[i] ){
176175        sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
176176      }else{
176177        sessionAppendByte(pBuf, 0, &rc);
176178      }
176179    }
176180
176181    /* Add a field to the new.* record. Or the only record if currently
176182    ** generating a patchset.  */
176183    if( bChanged || (bPatchset && abPK[i]) ){
176184      sessionAppendCol(&buf2, pStmt, i, &rc);
176185    }else{
176186      sessionAppendByte(&buf2, 0, &rc);
176187    }
176188
176189    pCsr += nAdvance;
176190  }
176191
176192  if( bNoop ){
176193    pBuf->nBuf = nRewind;
176194  }else{
176195    sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
176196  }
176197  sqlite3_free(buf2.aBuf);
176198
176199  return rc;
176200}
176201
176202/*
176203** Append a DELETE change to the buffer passed as the first argument. Use
176204** the changeset format if argument bPatchset is zero, or the patchset
176205** format otherwise.
176206*/
176207static int sessionAppendDelete(
176208  SessionBuffer *pBuf,            /* Buffer to append to */
176209  int bPatchset,                  /* True for "patchset", 0 for "changeset" */
176210  SessionChange *p,               /* Object containing old values */
176211  int nCol,                       /* Number of columns in table */
176212  u8 *abPK                        /* Boolean array - true for PK columns */
176213){
176214  int rc = SQLITE_OK;
176215
176216  sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
176217  sessionAppendByte(pBuf, p->bIndirect, &rc);
176218
176219  if( bPatchset==0 ){
176220    sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
176221  }else{
176222    int i;
176223    u8 *a = p->aRecord;
176224    for(i=0; i<nCol; i++){
176225      u8 *pStart = a;
176226      int eType = *a++;
176227
176228      switch( eType ){
176229        case 0:
176230        case SQLITE_NULL:
176231          assert( abPK[i]==0 );
176232          break;
176233
176234        case SQLITE_FLOAT:
176235        case SQLITE_INTEGER:
176236          a += 8;
176237          break;
176238
176239        default: {
176240          int n;
176241          a += sessionVarintGet(a, &n);
176242          a += n;
176243          break;
176244        }
176245      }
176246      if( abPK[i] ){
176247        sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
176248      }
176249    }
176250    assert( (a - p->aRecord)==p->nRecord );
176251  }
176252
176253  return rc;
176254}
176255
176256/*
176257** Formulate and prepare a SELECT statement to retrieve a row from table
176258** zTab in database zDb based on its primary key. i.e.
176259**
176260**   SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
176261*/
176262static int sessionSelectStmt(
176263  sqlite3 *db,                    /* Database handle */
176264  const char *zDb,                /* Database name */
176265  const char *zTab,               /* Table name */
176266  int nCol,                       /* Number of columns in table */
176267  const char **azCol,             /* Names of table columns */
176268  u8 *abPK,                       /* PRIMARY KEY  array */
176269  sqlite3_stmt **ppStmt           /* OUT: Prepared SELECT statement */
176270){
176271  int rc = SQLITE_OK;
176272  int i;
176273  const char *zSep = "";
176274  SessionBuffer buf = {0, 0, 0};
176275
176276  sessionAppendStr(&buf, "SELECT * FROM ", &rc);
176277  sessionAppendIdent(&buf, zDb, &rc);
176278  sessionAppendStr(&buf, ".", &rc);
176279  sessionAppendIdent(&buf, zTab, &rc);
176280  sessionAppendStr(&buf, " WHERE ", &rc);
176281  for(i=0; i<nCol; i++){
176282    if( abPK[i] ){
176283      sessionAppendStr(&buf, zSep, &rc);
176284      sessionAppendIdent(&buf, azCol[i], &rc);
176285      sessionAppendStr(&buf, " = ?", &rc);
176286      sessionAppendInteger(&buf, i+1, &rc);
176287      zSep = " AND ";
176288    }
176289  }
176290  if( rc==SQLITE_OK ){
176291    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
176292  }
176293  sqlite3_free(buf.aBuf);
176294  return rc;
176295}
176296
176297/*
176298** Bind the PRIMARY KEY values from the change passed in argument pChange
176299** to the SELECT statement passed as the first argument. The SELECT statement
176300** is as prepared by function sessionSelectStmt().
176301**
176302** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
176303** error code (e.g. SQLITE_NOMEM) otherwise.
176304*/
176305static int sessionSelectBind(
176306  sqlite3_stmt *pSelect,          /* SELECT from sessionSelectStmt() */
176307  int nCol,                       /* Number of columns in table */
176308  u8 *abPK,                       /* PRIMARY KEY array */
176309  SessionChange *pChange          /* Change structure */
176310){
176311  int i;
176312  int rc = SQLITE_OK;
176313  u8 *a = pChange->aRecord;
176314
176315  for(i=0; i<nCol && rc==SQLITE_OK; i++){
176316    int eType = *a++;
176317
176318    switch( eType ){
176319      case 0:
176320      case SQLITE_NULL:
176321        assert( abPK[i]==0 );
176322        break;
176323
176324      case SQLITE_INTEGER: {
176325        if( abPK[i] ){
176326          i64 iVal = sessionGetI64(a);
176327          rc = sqlite3_bind_int64(pSelect, i+1, iVal);
176328        }
176329        a += 8;
176330        break;
176331      }
176332
176333      case SQLITE_FLOAT: {
176334        if( abPK[i] ){
176335          double rVal;
176336          i64 iVal = sessionGetI64(a);
176337          memcpy(&rVal, &iVal, 8);
176338          rc = sqlite3_bind_double(pSelect, i+1, rVal);
176339        }
176340        a += 8;
176341        break;
176342      }
176343
176344      case SQLITE_TEXT: {
176345        int n;
176346        a += sessionVarintGet(a, &n);
176347        if( abPK[i] ){
176348          rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
176349        }
176350        a += n;
176351        break;
176352      }
176353
176354      default: {
176355        int n;
176356        assert( eType==SQLITE_BLOB );
176357        a += sessionVarintGet(a, &n);
176358        if( abPK[i] ){
176359          rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
176360        }
176361        a += n;
176362        break;
176363      }
176364    }
176365  }
176366
176367  return rc;
176368}
176369
176370/*
176371** This function is a no-op if *pRc is set to other than SQLITE_OK when it
176372** is called. Otherwise, append a serialized table header (part of the binary
176373** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
176374** SQLite error code before returning.
176375*/
176376static void sessionAppendTableHdr(
176377  SessionBuffer *pBuf,            /* Append header to this buffer */
176378  int bPatchset,                  /* Use the patchset format if true */
176379  SessionTable *pTab,             /* Table object to append header for */
176380  int *pRc                        /* IN/OUT: Error code */
176381){
176382  /* Write a table header */
176383  sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
176384  sessionAppendVarint(pBuf, pTab->nCol, pRc);
176385  sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
176386  sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
176387}
176388
176389/*
176390** Generate either a changeset (if argument bPatchset is zero) or a patchset
176391** (if it is non-zero) based on the current contents of the session object
176392** passed as the first argument.
176393**
176394** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
176395** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
176396** occurs, an SQLite error code is returned and both output variables set
176397** to 0.
176398*/
176399static int sessionGenerateChangeset(
176400  sqlite3_session *pSession,      /* Session object */
176401  int bPatchset,                  /* True for patchset, false for changeset */
176402  int (*xOutput)(void *pOut, const void *pData, int nData),
176403  void *pOut,                     /* First argument for xOutput */
176404  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
176405  void **ppChangeset              /* OUT: Buffer containing changeset */
176406){
176407  sqlite3 *db = pSession->db;     /* Source database handle */
176408  SessionTable *pTab;             /* Used to iterate through attached tables */
176409  SessionBuffer buf = {0,0,0};    /* Buffer in which to accumlate changeset */
176410  int rc;                         /* Return code */
176411
176412  assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
176413
176414  /* Zero the output variables in case an error occurs. If this session
176415  ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
176416  ** this call will be a no-op.  */
176417  if( xOutput==0 ){
176418    *pnChangeset = 0;
176419    *ppChangeset = 0;
176420  }
176421
176422  if( pSession->rc ) return pSession->rc;
176423  rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
176424  if( rc!=SQLITE_OK ) return rc;
176425
176426  sqlite3_mutex_enter(sqlite3_db_mutex(db));
176427
176428  for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
176429    if( pTab->nEntry ){
176430      const char *zName = pTab->zName;
176431      int nCol;                   /* Number of columns in table */
176432      u8 *abPK;                   /* Primary key array */
176433      const char **azCol = 0;     /* Table columns */
176434      int i;                      /* Used to iterate through hash buckets */
176435      sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */
176436      int nRewind = buf.nBuf;     /* Initial size of write buffer */
176437      int nNoop;                  /* Size of buffer after writing tbl header */
176438
176439      /* Check the table schema is still Ok. */
176440      rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
176441      if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
176442        rc = SQLITE_SCHEMA;
176443      }
176444
176445      /* Write a table header */
176446      sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
176447
176448      /* Build and compile a statement to execute: */
176449      if( rc==SQLITE_OK ){
176450        rc = sessionSelectStmt(
176451            db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
176452      }
176453
176454      nNoop = buf.nBuf;
176455      for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
176456        SessionChange *p;         /* Used to iterate through changes */
176457
176458        for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
176459          rc = sessionSelectBind(pSel, nCol, abPK, p);
176460          if( rc!=SQLITE_OK ) continue;
176461          if( sqlite3_step(pSel)==SQLITE_ROW ){
176462            if( p->op==SQLITE_INSERT ){
176463              int iCol;
176464              sessionAppendByte(&buf, SQLITE_INSERT, &rc);
176465              sessionAppendByte(&buf, p->bIndirect, &rc);
176466              for(iCol=0; iCol<nCol; iCol++){
176467                sessionAppendCol(&buf, pSel, iCol, &rc);
176468              }
176469            }else{
176470              rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
176471            }
176472          }else if( p->op!=SQLITE_INSERT ){
176473            rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
176474          }
176475          if( rc==SQLITE_OK ){
176476            rc = sqlite3_reset(pSel);
176477          }
176478
176479          /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
176480          ** its contents to the xOutput() callback. */
176481          if( xOutput
176482           && rc==SQLITE_OK
176483           && buf.nBuf>nNoop
176484           && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
176485          ){
176486            rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
176487            nNoop = -1;
176488            buf.nBuf = 0;
176489          }
176490
176491        }
176492      }
176493
176494      sqlite3_finalize(pSel);
176495      if( buf.nBuf==nNoop ){
176496        buf.nBuf = nRewind;
176497      }
176498      sqlite3_free((char*)azCol);  /* cast works around VC++ bug */
176499    }
176500  }
176501
176502  if( rc==SQLITE_OK ){
176503    if( xOutput==0 ){
176504      *pnChangeset = buf.nBuf;
176505      *ppChangeset = buf.aBuf;
176506      buf.aBuf = 0;
176507    }else if( buf.nBuf>0 ){
176508      rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
176509    }
176510  }
176511
176512  sqlite3_free(buf.aBuf);
176513  sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
176514  sqlite3_mutex_leave(sqlite3_db_mutex(db));
176515  return rc;
176516}
176517
176518/*
176519** Obtain a changeset object containing all changes recorded by the
176520** session object passed as the first argument.
176521**
176522** It is the responsibility of the caller to eventually free the buffer
176523** using sqlite3_free().
176524*/
176525SQLITE_API int sqlite3session_changeset(
176526  sqlite3_session *pSession,      /* Session object */
176527  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
176528  void **ppChangeset              /* OUT: Buffer containing changeset */
176529){
176530  return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
176531}
176532
176533/*
176534** Streaming version of sqlite3session_changeset().
176535*/
176536SQLITE_API int sqlite3session_changeset_strm(
176537  sqlite3_session *pSession,
176538  int (*xOutput)(void *pOut, const void *pData, int nData),
176539  void *pOut
176540){
176541  return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
176542}
176543
176544/*
176545** Streaming version of sqlite3session_patchset().
176546*/
176547SQLITE_API int sqlite3session_patchset_strm(
176548  sqlite3_session *pSession,
176549  int (*xOutput)(void *pOut, const void *pData, int nData),
176550  void *pOut
176551){
176552  return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
176553}
176554
176555/*
176556** Obtain a patchset object containing all changes recorded by the
176557** session object passed as the first argument.
176558**
176559** It is the responsibility of the caller to eventually free the buffer
176560** using sqlite3_free().
176561*/
176562SQLITE_API int sqlite3session_patchset(
176563  sqlite3_session *pSession,      /* Session object */
176564  int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
176565  void **ppPatchset               /* OUT: Buffer containing changeset */
176566){
176567  return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
176568}
176569
176570/*
176571** Enable or disable the session object passed as the first argument.
176572*/
176573SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
176574  int ret;
176575  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
176576  if( bEnable>=0 ){
176577    pSession->bEnable = bEnable;
176578  }
176579  ret = pSession->bEnable;
176580  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
176581  return ret;
176582}
176583
176584/*
176585** Enable or disable the session object passed as the first argument.
176586*/
176587SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
176588  int ret;
176589  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
176590  if( bIndirect>=0 ){
176591    pSession->bIndirect = bIndirect;
176592  }
176593  ret = pSession->bIndirect;
176594  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
176595  return ret;
176596}
176597
176598/*
176599** Return true if there have been no changes to monitored tables recorded
176600** by the session object passed as the only argument.
176601*/
176602SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
176603  int ret = 0;
176604  SessionTable *pTab;
176605
176606  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
176607  for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
176608    ret = (pTab->nEntry>0);
176609  }
176610  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
176611
176612  return (ret==0);
176613}
176614
176615/*
176616** Do the work for either sqlite3changeset_start() or start_strm().
176617*/
176618static int sessionChangesetStart(
176619  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
176620  int (*xInput)(void *pIn, void *pData, int *pnData),
176621  void *pIn,
176622  int nChangeset,                 /* Size of buffer pChangeset in bytes */
176623  void *pChangeset                /* Pointer to buffer containing changeset */
176624){
176625  sqlite3_changeset_iter *pRet;   /* Iterator to return */
176626  int nByte;                      /* Number of bytes to allocate for iterator */
176627
176628  assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
176629
176630  /* Zero the output variable in case an error occurs. */
176631  *pp = 0;
176632
176633  /* Allocate and initialize the iterator structure. */
176634  nByte = sizeof(sqlite3_changeset_iter);
176635  pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
176636  if( !pRet ) return SQLITE_NOMEM;
176637  memset(pRet, 0, sizeof(sqlite3_changeset_iter));
176638  pRet->in.aData = (u8 *)pChangeset;
176639  pRet->in.nData = nChangeset;
176640  pRet->in.xInput = xInput;
176641  pRet->in.pIn = pIn;
176642  pRet->in.bEof = (xInput ? 0 : 1);
176643
176644  /* Populate the output variable and return success. */
176645  *pp = pRet;
176646  return SQLITE_OK;
176647}
176648
176649/*
176650** Create an iterator used to iterate through the contents of a changeset.
176651*/
176652SQLITE_API int sqlite3changeset_start(
176653  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
176654  int nChangeset,                 /* Size of buffer pChangeset in bytes */
176655  void *pChangeset                /* Pointer to buffer containing changeset */
176656){
176657  return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
176658}
176659
176660/*
176661** Streaming version of sqlite3changeset_start().
176662*/
176663SQLITE_API int sqlite3changeset_start_strm(
176664  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
176665  int (*xInput)(void *pIn, void *pData, int *pnData),
176666  void *pIn
176667){
176668  return sessionChangesetStart(pp, xInput, pIn, 0, 0);
176669}
176670
176671/*
176672** If the SessionInput object passed as the only argument is a streaming
176673** object and the buffer is full, discard some data to free up space.
176674*/
176675static void sessionDiscardData(SessionInput *pIn){
176676  if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
176677    int nMove = pIn->buf.nBuf - pIn->iNext;
176678    assert( nMove>=0 );
176679    if( nMove>0 ){
176680      memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
176681    }
176682    pIn->buf.nBuf -= pIn->iNext;
176683    pIn->iNext = 0;
176684    pIn->nData = pIn->buf.nBuf;
176685  }
176686}
176687
176688/*
176689** Ensure that there are at least nByte bytes available in the buffer. Or,
176690** if there are not nByte bytes remaining in the input, that all available
176691** data is in the buffer.
176692**
176693** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
176694*/
176695static int sessionInputBuffer(SessionInput *pIn, int nByte){
176696  int rc = SQLITE_OK;
176697  if( pIn->xInput ){
176698    while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
176699      int nNew = SESSIONS_STRM_CHUNK_SIZE;
176700
176701      if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
176702      if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
176703        rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
176704        if( nNew==0 ){
176705          pIn->bEof = 1;
176706        }else{
176707          pIn->buf.nBuf += nNew;
176708        }
176709      }
176710
176711      pIn->aData = pIn->buf.aBuf;
176712      pIn->nData = pIn->buf.nBuf;
176713    }
176714  }
176715  return rc;
176716}
176717
176718/*
176719** When this function is called, *ppRec points to the start of a record
176720** that contains nCol values. This function advances the pointer *ppRec
176721** until it points to the byte immediately following that record.
176722*/
176723static void sessionSkipRecord(
176724  u8 **ppRec,                     /* IN/OUT: Record pointer */
176725  int nCol                        /* Number of values in record */
176726){
176727  u8 *aRec = *ppRec;
176728  int i;
176729  for(i=0; i<nCol; i++){
176730    int eType = *aRec++;
176731    if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
176732      int nByte;
176733      aRec += sessionVarintGet((u8*)aRec, &nByte);
176734      aRec += nByte;
176735    }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
176736      aRec += 8;
176737    }
176738  }
176739
176740  *ppRec = aRec;
176741}
176742
176743/*
176744** This function sets the value of the sqlite3_value object passed as the
176745** first argument to a copy of the string or blob held in the aData[]
176746** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
176747** error occurs.
176748*/
176749static int sessionValueSetStr(
176750  sqlite3_value *pVal,            /* Set the value of this object */
176751  u8 *aData,                      /* Buffer containing string or blob data */
176752  int nData,                      /* Size of buffer aData[] in bytes */
176753  u8 enc                          /* String encoding (0 for blobs) */
176754){
176755  /* In theory this code could just pass SQLITE_TRANSIENT as the final
176756  ** argument to sqlite3ValueSetStr() and have the copy created
176757  ** automatically. But doing so makes it difficult to detect any OOM
176758  ** error. Hence the code to create the copy externally. */
176759  u8 *aCopy = sqlite3_malloc(nData+1);
176760  if( aCopy==0 ) return SQLITE_NOMEM;
176761  memcpy(aCopy, aData, nData);
176762  sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
176763  return SQLITE_OK;
176764}
176765
176766/*
176767** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
176768** for details.
176769**
176770** When this function is called, *paChange points to the start of the record
176771** to deserialize. Assuming no error occurs, *paChange is set to point to
176772** one byte after the end of the same record before this function returns.
176773** If the argument abPK is NULL, then the record contains nCol values. Or,
176774** if abPK is other than NULL, then the record contains only the PK fields
176775** (in other words, it is a patchset DELETE record).
176776**
176777** If successful, each element of the apOut[] array (allocated by the caller)
176778** is set to point to an sqlite3_value object containing the value read
176779** from the corresponding position in the record. If that value is not
176780** included in the record (i.e. because the record is part of an UPDATE change
176781** and the field was not modified), the corresponding element of apOut[] is
176782** set to NULL.
176783**
176784** It is the responsibility of the caller to free all sqlite_value structures
176785** using sqlite3_free().
176786**
176787** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
176788** The apOut[] array may have been partially populated in this case.
176789*/
176790static int sessionReadRecord(
176791  SessionInput *pIn,              /* Input data */
176792  int nCol,                       /* Number of values in record */
176793  u8 *abPK,                       /* Array of primary key flags, or NULL */
176794  sqlite3_value **apOut           /* Write values to this array */
176795){
176796  int i;                          /* Used to iterate through columns */
176797  int rc = SQLITE_OK;
176798
176799  for(i=0; i<nCol && rc==SQLITE_OK; i++){
176800    int eType = 0;                /* Type of value (SQLITE_NULL, TEXT etc.) */
176801    if( abPK && abPK[i]==0 ) continue;
176802    rc = sessionInputBuffer(pIn, 9);
176803    if( rc==SQLITE_OK ){
176804      eType = pIn->aData[pIn->iNext++];
176805    }
176806
176807    assert( apOut[i]==0 );
176808    if( eType ){
176809      apOut[i] = sqlite3ValueNew(0);
176810      if( !apOut[i] ) rc = SQLITE_NOMEM;
176811    }
176812
176813    if( rc==SQLITE_OK ){
176814      u8 *aVal = &pIn->aData[pIn->iNext];
176815      if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
176816        int nByte;
176817        pIn->iNext += sessionVarintGet(aVal, &nByte);
176818        rc = sessionInputBuffer(pIn, nByte);
176819        if( rc==SQLITE_OK ){
176820          u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
176821          rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
176822        }
176823        pIn->iNext += nByte;
176824      }
176825      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
176826        sqlite3_int64 v = sessionGetI64(aVal);
176827        if( eType==SQLITE_INTEGER ){
176828          sqlite3VdbeMemSetInt64(apOut[i], v);
176829        }else{
176830          double d;
176831          memcpy(&d, &v, 8);
176832          sqlite3VdbeMemSetDouble(apOut[i], d);
176833        }
176834        pIn->iNext += 8;
176835      }
176836    }
176837  }
176838
176839  return rc;
176840}
176841
176842/*
176843** The input pointer currently points to the second byte of a table-header.
176844** Specifically, to the following:
176845**
176846**   + number of columns in table (varint)
176847**   + array of PK flags (1 byte per column),
176848**   + table name (nul terminated).
176849**
176850** This function ensures that all of the above is present in the input
176851** buffer (i.e. that it can be accessed without any calls to xInput()).
176852** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
176853** The input pointer is not moved.
176854*/
176855static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
176856  int rc = SQLITE_OK;
176857  int nCol = 0;
176858  int nRead = 0;
176859
176860  rc = sessionInputBuffer(pIn, 9);
176861  if( rc==SQLITE_OK ){
176862    nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
176863    rc = sessionInputBuffer(pIn, nRead+nCol+100);
176864    nRead += nCol;
176865  }
176866
176867  while( rc==SQLITE_OK ){
176868    while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
176869      nRead++;
176870    }
176871    if( (pIn->iNext + nRead)<pIn->nData ) break;
176872    rc = sessionInputBuffer(pIn, nRead + 100);
176873  }
176874  *pnByte = nRead+1;
176875  return rc;
176876}
176877
176878/*
176879** The input pointer currently points to the first byte of the first field
176880** of a record consisting of nCol columns. This function ensures the entire
176881** record is buffered. It does not move the input pointer.
176882**
176883** If successful, SQLITE_OK is returned and *pnByte is set to the size of
176884** the record in bytes. Otherwise, an SQLite error code is returned. The
176885** final value of *pnByte is undefined in this case.
176886*/
176887static int sessionChangesetBufferRecord(
176888  SessionInput *pIn,              /* Input data */
176889  int nCol,                       /* Number of columns in record */
176890  int *pnByte                     /* OUT: Size of record in bytes */
176891){
176892  int rc = SQLITE_OK;
176893  int nByte = 0;
176894  int i;
176895  for(i=0; rc==SQLITE_OK && i<nCol; i++){
176896    int eType;
176897    rc = sessionInputBuffer(pIn, nByte + 10);
176898    if( rc==SQLITE_OK ){
176899      eType = pIn->aData[pIn->iNext + nByte++];
176900      if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
176901        int n;
176902        nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
176903        nByte += n;
176904        rc = sessionInputBuffer(pIn, nByte);
176905      }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
176906        nByte += 8;
176907      }
176908    }
176909  }
176910  *pnByte = nByte;
176911  return rc;
176912}
176913
176914/*
176915** The input pointer currently points to the second byte of a table-header.
176916** Specifically, to the following:
176917**
176918**   + number of columns in table (varint)
176919**   + array of PK flags (1 byte per column),
176920**   + table name (nul terminated).
176921**
176922** This function decodes the table-header and populates the p->nCol,
176923** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
176924** also allocated or resized according to the new value of p->nCol. The
176925** input pointer is left pointing to the byte following the table header.
176926**
176927** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
176928** is returned and the final values of the various fields enumerated above
176929** are undefined.
176930*/
176931static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
176932  int rc;
176933  int nCopy;
176934  assert( p->rc==SQLITE_OK );
176935
176936  rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
176937  if( rc==SQLITE_OK ){
176938    int nByte;
176939    int nVarint;
176940    nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
176941    nCopy -= nVarint;
176942    p->in.iNext += nVarint;
176943    nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
176944    p->tblhdr.nBuf = 0;
176945    sessionBufferGrow(&p->tblhdr, nByte, &rc);
176946  }
176947
176948  if( rc==SQLITE_OK ){
176949    int iPK = sizeof(sqlite3_value*)*p->nCol*2;
176950    memset(p->tblhdr.aBuf, 0, iPK);
176951    memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
176952    p->in.iNext += nCopy;
176953  }
176954
176955  p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
176956  p->abPK = (u8*)&p->apValue[p->nCol*2];
176957  p->zTab = (char*)&p->abPK[p->nCol];
176958  return (p->rc = rc);
176959}
176960
176961/*
176962** Advance the changeset iterator to the next change.
176963**
176964** If both paRec and pnRec are NULL, then this function works like the public
176965** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
176966** sqlite3changeset_new() and old() APIs may be used to query for values.
176967**
176968** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
176969** record is written to *paRec before returning and the number of bytes in
176970** the record to *pnRec.
176971**
176972** Either way, this function returns SQLITE_ROW if the iterator is
176973** successfully advanced to the next change in the changeset, an SQLite
176974** error code if an error occurs, or SQLITE_DONE if there are no further
176975** changes in the changeset.
176976*/
176977static int sessionChangesetNext(
176978  sqlite3_changeset_iter *p,      /* Changeset iterator */
176979  u8 **paRec,                     /* If non-NULL, store record pointer here */
176980  int *pnRec                      /* If non-NULL, store size of record here */
176981){
176982  int i;
176983  u8 op;
176984
176985  assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
176986
176987  /* If the iterator is in the error-state, return immediately. */
176988  if( p->rc!=SQLITE_OK ) return p->rc;
176989
176990  /* Free the current contents of p->apValue[], if any. */
176991  if( p->apValue ){
176992    for(i=0; i<p->nCol*2; i++){
176993      sqlite3ValueFree(p->apValue[i]);
176994    }
176995    memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
176996  }
176997
176998  /* Make sure the buffer contains at least 10 bytes of input data, or all
176999  ** remaining data if there are less than 10 bytes available. This is
177000  ** sufficient either for the 'T' or 'P' byte and the varint that follows
177001  ** it, or for the two single byte values otherwise. */
177002  p->rc = sessionInputBuffer(&p->in, 2);
177003  if( p->rc!=SQLITE_OK ) return p->rc;
177004
177005  /* If the iterator is already at the end of the changeset, return DONE. */
177006  if( p->in.iNext>=p->in.nData ){
177007    return SQLITE_DONE;
177008  }
177009
177010  sessionDiscardData(&p->in);
177011  p->in.iCurrent = p->in.iNext;
177012
177013  op = p->in.aData[p->in.iNext++];
177014  if( op=='T' || op=='P' ){
177015    p->bPatchset = (op=='P');
177016    if( sessionChangesetReadTblhdr(p) ) return p->rc;
177017    if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
177018    p->in.iCurrent = p->in.iNext;
177019    op = p->in.aData[p->in.iNext++];
177020  }
177021
177022  p->op = op;
177023  p->bIndirect = p->in.aData[p->in.iNext++];
177024  if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
177025    return (p->rc = SQLITE_CORRUPT_BKPT);
177026  }
177027
177028  if( paRec ){
177029    int nVal;                     /* Number of values to buffer */
177030    if( p->bPatchset==0 && op==SQLITE_UPDATE ){
177031      nVal = p->nCol * 2;
177032    }else if( p->bPatchset && op==SQLITE_DELETE ){
177033      nVal = 0;
177034      for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
177035    }else{
177036      nVal = p->nCol;
177037    }
177038    p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
177039    if( p->rc!=SQLITE_OK ) return p->rc;
177040    *paRec = &p->in.aData[p->in.iNext];
177041    p->in.iNext += *pnRec;
177042  }else{
177043
177044    /* If this is an UPDATE or DELETE, read the old.* record. */
177045    if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
177046      u8 *abPK = p->bPatchset ? p->abPK : 0;
177047      p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
177048      if( p->rc!=SQLITE_OK ) return p->rc;
177049    }
177050
177051    /* If this is an INSERT or UPDATE, read the new.* record. */
177052    if( p->op!=SQLITE_DELETE ){
177053      p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
177054      if( p->rc!=SQLITE_OK ) return p->rc;
177055    }
177056
177057    if( p->bPatchset && p->op==SQLITE_UPDATE ){
177058      /* If this is an UPDATE that is part of a patchset, then all PK and
177059      ** modified fields are present in the new.* record. The old.* record
177060      ** is currently completely empty. This block shifts the PK fields from
177061      ** new.* to old.*, to accommodate the code that reads these arrays.  */
177062      for(i=0; i<p->nCol; i++){
177063        assert( p->apValue[i]==0 );
177064        assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
177065        if( p->abPK[i] ){
177066          p->apValue[i] = p->apValue[i+p->nCol];
177067          p->apValue[i+p->nCol] = 0;
177068        }
177069      }
177070    }
177071  }
177072
177073  return SQLITE_ROW;
177074}
177075
177076/*
177077** Advance an iterator created by sqlite3changeset_start() to the next
177078** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
177079** or SQLITE_CORRUPT.
177080**
177081** This function may not be called on iterators passed to a conflict handler
177082** callback by changeset_apply().
177083*/
177084SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
177085  return sessionChangesetNext(p, 0, 0);
177086}
177087
177088/*
177089** The following function extracts information on the current change
177090** from a changeset iterator. It may only be called after changeset_next()
177091** has returned SQLITE_ROW.
177092*/
177093SQLITE_API int sqlite3changeset_op(
177094  sqlite3_changeset_iter *pIter,  /* Iterator handle */
177095  const char **pzTab,             /* OUT: Pointer to table name */
177096  int *pnCol,                     /* OUT: Number of columns in table */
177097  int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
177098  int *pbIndirect                 /* OUT: True if change is indirect */
177099){
177100  *pOp = pIter->op;
177101  *pnCol = pIter->nCol;
177102  *pzTab = pIter->zTab;
177103  if( pbIndirect ) *pbIndirect = pIter->bIndirect;
177104  return SQLITE_OK;
177105}
177106
177107/*
177108** Return information regarding the PRIMARY KEY and number of columns in
177109** the database table affected by the change that pIter currently points
177110** to. This function may only be called after changeset_next() returns
177111** SQLITE_ROW.
177112*/
177113SQLITE_API int sqlite3changeset_pk(
177114  sqlite3_changeset_iter *pIter,  /* Iterator object */
177115  unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
177116  int *pnCol                      /* OUT: Number of entries in output array */
177117){
177118  *pabPK = pIter->abPK;
177119  if( pnCol ) *pnCol = pIter->nCol;
177120  return SQLITE_OK;
177121}
177122
177123/*
177124** This function may only be called while the iterator is pointing to an
177125** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
177126** Otherwise, SQLITE_MISUSE is returned.
177127**
177128** It sets *ppValue to point to an sqlite3_value structure containing the
177129** iVal'th value in the old.* record. Or, if that particular value is not
177130** included in the record (because the change is an UPDATE and the field
177131** was not modified and is not a PK column), set *ppValue to NULL.
177132**
177133** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
177134** not modified. Otherwise, SQLITE_OK.
177135*/
177136SQLITE_API int sqlite3changeset_old(
177137  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
177138  int iVal,                       /* Index of old.* value to retrieve */
177139  sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
177140){
177141  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
177142    return SQLITE_MISUSE;
177143  }
177144  if( iVal<0 || iVal>=pIter->nCol ){
177145    return SQLITE_RANGE;
177146  }
177147  *ppValue = pIter->apValue[iVal];
177148  return SQLITE_OK;
177149}
177150
177151/*
177152** This function may only be called while the iterator is pointing to an
177153** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
177154** Otherwise, SQLITE_MISUSE is returned.
177155**
177156** It sets *ppValue to point to an sqlite3_value structure containing the
177157** iVal'th value in the new.* record. Or, if that particular value is not
177158** included in the record (because the change is an UPDATE and the field
177159** was not modified), set *ppValue to NULL.
177160**
177161** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
177162** not modified. Otherwise, SQLITE_OK.
177163*/
177164SQLITE_API int sqlite3changeset_new(
177165  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
177166  int iVal,                       /* Index of new.* value to retrieve */
177167  sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
177168){
177169  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
177170    return SQLITE_MISUSE;
177171  }
177172  if( iVal<0 || iVal>=pIter->nCol ){
177173    return SQLITE_RANGE;
177174  }
177175  *ppValue = pIter->apValue[pIter->nCol+iVal];
177176  return SQLITE_OK;
177177}
177178
177179/*
177180** The following two macros are used internally. They are similar to the
177181** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
177182** they omit all error checking and return a pointer to the requested value.
177183*/
177184#define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
177185#define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
177186
177187/*
177188** This function may only be called with a changeset iterator that has been
177189** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
177190** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
177191**
177192** If successful, *ppValue is set to point to an sqlite3_value structure
177193** containing the iVal'th value of the conflicting record.
177194**
177195** If value iVal is out-of-range or some other error occurs, an SQLite error
177196** code is returned. Otherwise, SQLITE_OK.
177197*/
177198SQLITE_API int sqlite3changeset_conflict(
177199  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
177200  int iVal,                       /* Index of conflict record value to fetch */
177201  sqlite3_value **ppValue         /* OUT: Value from conflicting row */
177202){
177203  if( !pIter->pConflict ){
177204    return SQLITE_MISUSE;
177205  }
177206  if( iVal<0 || iVal>=pIter->nCol ){
177207    return SQLITE_RANGE;
177208  }
177209  *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
177210  return SQLITE_OK;
177211}
177212
177213/*
177214** This function may only be called with an iterator passed to an
177215** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
177216** it sets the output variable to the total number of known foreign key
177217** violations in the destination database and returns SQLITE_OK.
177218**
177219** In all other cases this function returns SQLITE_MISUSE.
177220*/
177221SQLITE_API int sqlite3changeset_fk_conflicts(
177222  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
177223  int *pnOut                      /* OUT: Number of FK violations */
177224){
177225  if( pIter->pConflict || pIter->apValue ){
177226    return SQLITE_MISUSE;
177227  }
177228  *pnOut = pIter->nCol;
177229  return SQLITE_OK;
177230}
177231
177232
177233/*
177234** Finalize an iterator allocated with sqlite3changeset_start().
177235**
177236** This function may not be called on iterators passed to a conflict handler
177237** callback by changeset_apply().
177238*/
177239SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
177240  int rc = SQLITE_OK;
177241  if( p ){
177242    int i;                        /* Used to iterate through p->apValue[] */
177243    rc = p->rc;
177244    if( p->apValue ){
177245      for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
177246    }
177247    sqlite3_free(p->tblhdr.aBuf);
177248    sqlite3_free(p->in.buf.aBuf);
177249    sqlite3_free(p);
177250  }
177251  return rc;
177252}
177253
177254static int sessionChangesetInvert(
177255  SessionInput *pInput,           /* Input changeset */
177256  int (*xOutput)(void *pOut, const void *pData, int nData),
177257  void *pOut,
177258  int *pnInverted,                /* OUT: Number of bytes in output changeset */
177259  void **ppInverted               /* OUT: Inverse of pChangeset */
177260){
177261  int rc = SQLITE_OK;             /* Return value */
177262  SessionBuffer sOut;             /* Output buffer */
177263  int nCol = 0;                   /* Number of cols in current table */
177264  u8 *abPK = 0;                   /* PK array for current table */
177265  sqlite3_value **apVal = 0;      /* Space for values for UPDATE inversion */
177266  SessionBuffer sPK = {0, 0, 0};  /* PK array for current table */
177267
177268  /* Initialize the output buffer */
177269  memset(&sOut, 0, sizeof(SessionBuffer));
177270
177271  /* Zero the output variables in case an error occurs. */
177272  if( ppInverted ){
177273    *ppInverted = 0;
177274    *pnInverted = 0;
177275  }
177276
177277  while( 1 ){
177278    u8 eType;
177279
177280    /* Test for EOF. */
177281    if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
177282    if( pInput->iNext>=pInput->nData ) break;
177283    eType = pInput->aData[pInput->iNext];
177284
177285    switch( eType ){
177286      case 'T': {
177287        /* A 'table' record consists of:
177288        **
177289        **   * A constant 'T' character,
177290        **   * Number of columns in said table (a varint),
177291        **   * An array of nCol bytes (sPK),
177292        **   * A nul-terminated table name.
177293        */
177294        int nByte;
177295        int nVar;
177296        pInput->iNext++;
177297        if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
177298          goto finished_invert;
177299        }
177300        nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
177301        sPK.nBuf = 0;
177302        sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
177303        sessionAppendByte(&sOut, eType, &rc);
177304        sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
177305        if( rc ) goto finished_invert;
177306
177307        pInput->iNext += nByte;
177308        sqlite3_free(apVal);
177309        apVal = 0;
177310        abPK = sPK.aBuf;
177311        break;
177312      }
177313
177314      case SQLITE_INSERT:
177315      case SQLITE_DELETE: {
177316        int nByte;
177317        int bIndirect = pInput->aData[pInput->iNext+1];
177318        int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
177319        pInput->iNext += 2;
177320        assert( rc==SQLITE_OK );
177321        rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
177322        sessionAppendByte(&sOut, eType2, &rc);
177323        sessionAppendByte(&sOut, bIndirect, &rc);
177324        sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
177325        pInput->iNext += nByte;
177326        if( rc ) goto finished_invert;
177327        break;
177328      }
177329
177330      case SQLITE_UPDATE: {
177331        int iCol;
177332
177333        if( 0==apVal ){
177334          apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
177335          if( 0==apVal ){
177336            rc = SQLITE_NOMEM;
177337            goto finished_invert;
177338          }
177339          memset(apVal, 0, sizeof(apVal[0])*nCol*2);
177340        }
177341
177342        /* Write the header for the new UPDATE change. Same as the original. */
177343        sessionAppendByte(&sOut, eType, &rc);
177344        sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
177345
177346        /* Read the old.* and new.* records for the update change. */
177347        pInput->iNext += 2;
177348        rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
177349        if( rc==SQLITE_OK ){
177350          rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
177351        }
177352
177353        /* Write the new old.* record. Consists of the PK columns from the
177354        ** original old.* record, and the other values from the original
177355        ** new.* record. */
177356        for(iCol=0; iCol<nCol; iCol++){
177357          sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
177358          sessionAppendValue(&sOut, pVal, &rc);
177359        }
177360
177361        /* Write the new new.* record. Consists of a copy of all values
177362        ** from the original old.* record, except for the PK columns, which
177363        ** are set to "undefined". */
177364        for(iCol=0; iCol<nCol; iCol++){
177365          sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
177366          sessionAppendValue(&sOut, pVal, &rc);
177367        }
177368
177369        for(iCol=0; iCol<nCol*2; iCol++){
177370          sqlite3ValueFree(apVal[iCol]);
177371        }
177372        memset(apVal, 0, sizeof(apVal[0])*nCol*2);
177373        if( rc!=SQLITE_OK ){
177374          goto finished_invert;
177375        }
177376
177377        break;
177378      }
177379
177380      default:
177381        rc = SQLITE_CORRUPT_BKPT;
177382        goto finished_invert;
177383    }
177384
177385    assert( rc==SQLITE_OK );
177386    if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
177387      rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
177388      sOut.nBuf = 0;
177389      if( rc!=SQLITE_OK ) goto finished_invert;
177390    }
177391  }
177392
177393  assert( rc==SQLITE_OK );
177394  if( pnInverted ){
177395    *pnInverted = sOut.nBuf;
177396    *ppInverted = sOut.aBuf;
177397    sOut.aBuf = 0;
177398  }else if( sOut.nBuf>0 ){
177399    rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
177400  }
177401
177402 finished_invert:
177403  sqlite3_free(sOut.aBuf);
177404  sqlite3_free(apVal);
177405  sqlite3_free(sPK.aBuf);
177406  return rc;
177407}
177408
177409
177410/*
177411** Invert a changeset object.
177412*/
177413SQLITE_API int sqlite3changeset_invert(
177414  int nChangeset,                 /* Number of bytes in input */
177415  const void *pChangeset,         /* Input changeset */
177416  int *pnInverted,                /* OUT: Number of bytes in output changeset */
177417  void **ppInverted               /* OUT: Inverse of pChangeset */
177418){
177419  SessionInput sInput;
177420
177421  /* Set up the input stream */
177422  memset(&sInput, 0, sizeof(SessionInput));
177423  sInput.nData = nChangeset;
177424  sInput.aData = (u8*)pChangeset;
177425
177426  return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
177427}
177428
177429/*
177430** Streaming version of sqlite3changeset_invert().
177431*/
177432SQLITE_API int sqlite3changeset_invert_strm(
177433  int (*xInput)(void *pIn, void *pData, int *pnData),
177434  void *pIn,
177435  int (*xOutput)(void *pOut, const void *pData, int nData),
177436  void *pOut
177437){
177438  SessionInput sInput;
177439  int rc;
177440
177441  /* Set up the input stream */
177442  memset(&sInput, 0, sizeof(SessionInput));
177443  sInput.xInput = xInput;
177444  sInput.pIn = pIn;
177445
177446  rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
177447  sqlite3_free(sInput.buf.aBuf);
177448  return rc;
177449}
177450
177451typedef struct SessionApplyCtx SessionApplyCtx;
177452struct SessionApplyCtx {
177453  sqlite3 *db;
177454  sqlite3_stmt *pDelete;          /* DELETE statement */
177455  sqlite3_stmt *pUpdate;          /* UPDATE statement */
177456  sqlite3_stmt *pInsert;          /* INSERT statement */
177457  sqlite3_stmt *pSelect;          /* SELECT statement */
177458  int nCol;                       /* Size of azCol[] and abPK[] arrays */
177459  const char **azCol;             /* Array of column names */
177460  u8 *abPK;                       /* Boolean array - true if column is in PK */
177461
177462  int bDeferConstraints;          /* True to defer constraints */
177463  SessionBuffer constraints;      /* Deferred constraints are stored here */
177464};
177465
177466/*
177467** Formulate a statement to DELETE a row from database db. Assuming a table
177468** structure like this:
177469**
177470**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
177471**
177472** The DELETE statement looks like this:
177473**
177474**     DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
177475**
177476** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
177477** matching b and d values, or 1 otherwise. The second case comes up if the
177478** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
177479**
177480** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
177481** pointing to the prepared version of the SQL statement.
177482*/
177483static int sessionDeleteRow(
177484  sqlite3 *db,                    /* Database handle */
177485  const char *zTab,               /* Table name */
177486  SessionApplyCtx *p              /* Session changeset-apply context */
177487){
177488  int i;
177489  const char *zSep = "";
177490  int rc = SQLITE_OK;
177491  SessionBuffer buf = {0, 0, 0};
177492  int nPk = 0;
177493
177494  sessionAppendStr(&buf, "DELETE FROM ", &rc);
177495  sessionAppendIdent(&buf, zTab, &rc);
177496  sessionAppendStr(&buf, " WHERE ", &rc);
177497
177498  for(i=0; i<p->nCol; i++){
177499    if( p->abPK[i] ){
177500      nPk++;
177501      sessionAppendStr(&buf, zSep, &rc);
177502      sessionAppendIdent(&buf, p->azCol[i], &rc);
177503      sessionAppendStr(&buf, " = ?", &rc);
177504      sessionAppendInteger(&buf, i+1, &rc);
177505      zSep = " AND ";
177506    }
177507  }
177508
177509  if( nPk<p->nCol ){
177510    sessionAppendStr(&buf, " AND (?", &rc);
177511    sessionAppendInteger(&buf, p->nCol+1, &rc);
177512    sessionAppendStr(&buf, " OR ", &rc);
177513
177514    zSep = "";
177515    for(i=0; i<p->nCol; i++){
177516      if( !p->abPK[i] ){
177517        sessionAppendStr(&buf, zSep, &rc);
177518        sessionAppendIdent(&buf, p->azCol[i], &rc);
177519        sessionAppendStr(&buf, " IS ?", &rc);
177520        sessionAppendInteger(&buf, i+1, &rc);
177521        zSep = "AND ";
177522      }
177523    }
177524    sessionAppendStr(&buf, ")", &rc);
177525  }
177526
177527  if( rc==SQLITE_OK ){
177528    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
177529  }
177530  sqlite3_free(buf.aBuf);
177531
177532  return rc;
177533}
177534
177535/*
177536** Formulate and prepare a statement to UPDATE a row from database db.
177537** Assuming a table structure like this:
177538**
177539**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
177540**
177541** The UPDATE statement looks like this:
177542**
177543**     UPDATE x SET
177544**     a = CASE WHEN ?2  THEN ?3  ELSE a END,
177545**     b = CASE WHEN ?5  THEN ?6  ELSE b END,
177546**     c = CASE WHEN ?8  THEN ?9  ELSE c END,
177547**     d = CASE WHEN ?11 THEN ?12 ELSE d END
177548**     WHERE a = ?1 AND c = ?7 AND (?13 OR
177549**       (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
177550**     )
177551**
177552** For each column in the table, there are three variables to bind:
177553**
177554**     ?(i*3+1)    The old.* value of the column, if any.
177555**     ?(i*3+2)    A boolean flag indicating that the value is being modified.
177556**     ?(i*3+3)    The new.* value of the column, if any.
177557**
177558** Also, a boolean flag that, if set to true, causes the statement to update
177559** a row even if the non-PK values do not match. This is required if the
177560** conflict-handler is invoked with CHANGESET_DATA and returns
177561** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
177562**
177563** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
177564** pointing to the prepared version of the SQL statement.
177565*/
177566static int sessionUpdateRow(
177567  sqlite3 *db,                    /* Database handle */
177568  const char *zTab,               /* Table name */
177569  SessionApplyCtx *p              /* Session changeset-apply context */
177570){
177571  int rc = SQLITE_OK;
177572  int i;
177573  const char *zSep = "";
177574  SessionBuffer buf = {0, 0, 0};
177575
177576  /* Append "UPDATE tbl SET " */
177577  sessionAppendStr(&buf, "UPDATE ", &rc);
177578  sessionAppendIdent(&buf, zTab, &rc);
177579  sessionAppendStr(&buf, " SET ", &rc);
177580
177581  /* Append the assignments */
177582  for(i=0; i<p->nCol; i++){
177583    sessionAppendStr(&buf, zSep, &rc);
177584    sessionAppendIdent(&buf, p->azCol[i], &rc);
177585    sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
177586    sessionAppendInteger(&buf, i*3+2, &rc);
177587    sessionAppendStr(&buf, " THEN ?", &rc);
177588    sessionAppendInteger(&buf, i*3+3, &rc);
177589    sessionAppendStr(&buf, " ELSE ", &rc);
177590    sessionAppendIdent(&buf, p->azCol[i], &rc);
177591    sessionAppendStr(&buf, " END", &rc);
177592    zSep = ", ";
177593  }
177594
177595  /* Append the PK part of the WHERE clause */
177596  sessionAppendStr(&buf, " WHERE ", &rc);
177597  for(i=0; i<p->nCol; i++){
177598    if( p->abPK[i] ){
177599      sessionAppendIdent(&buf, p->azCol[i], &rc);
177600      sessionAppendStr(&buf, " = ?", &rc);
177601      sessionAppendInteger(&buf, i*3+1, &rc);
177602      sessionAppendStr(&buf, " AND ", &rc);
177603    }
177604  }
177605
177606  /* Append the non-PK part of the WHERE clause */
177607  sessionAppendStr(&buf, " (?", &rc);
177608  sessionAppendInteger(&buf, p->nCol*3+1, &rc);
177609  sessionAppendStr(&buf, " OR 1", &rc);
177610  for(i=0; i<p->nCol; i++){
177611    if( !p->abPK[i] ){
177612      sessionAppendStr(&buf, " AND (?", &rc);
177613      sessionAppendInteger(&buf, i*3+2, &rc);
177614      sessionAppendStr(&buf, "=0 OR ", &rc);
177615      sessionAppendIdent(&buf, p->azCol[i], &rc);
177616      sessionAppendStr(&buf, " IS ?", &rc);
177617      sessionAppendInteger(&buf, i*3+1, &rc);
177618      sessionAppendStr(&buf, ")", &rc);
177619    }
177620  }
177621  sessionAppendStr(&buf, ")", &rc);
177622
177623  if( rc==SQLITE_OK ){
177624    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
177625  }
177626  sqlite3_free(buf.aBuf);
177627
177628  return rc;
177629}
177630
177631/*
177632** Formulate and prepare an SQL statement to query table zTab by primary
177633** key. Assuming the following table structure:
177634**
177635**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
177636**
177637** The SELECT statement looks like this:
177638**
177639**     SELECT * FROM x WHERE a = ?1 AND c = ?3
177640**
177641** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
177642** pointing to the prepared version of the SQL statement.
177643*/
177644static int sessionSelectRow(
177645  sqlite3 *db,                    /* Database handle */
177646  const char *zTab,               /* Table name */
177647  SessionApplyCtx *p              /* Session changeset-apply context */
177648){
177649  return sessionSelectStmt(
177650      db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
177651}
177652
177653/*
177654** Formulate and prepare an INSERT statement to add a record to table zTab.
177655** For example:
177656**
177657**     INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
177658**
177659** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
177660** pointing to the prepared version of the SQL statement.
177661*/
177662static int sessionInsertRow(
177663  sqlite3 *db,                    /* Database handle */
177664  const char *zTab,               /* Table name */
177665  SessionApplyCtx *p              /* Session changeset-apply context */
177666){
177667  int rc = SQLITE_OK;
177668  int i;
177669  SessionBuffer buf = {0, 0, 0};
177670
177671  sessionAppendStr(&buf, "INSERT INTO main.", &rc);
177672  sessionAppendIdent(&buf, zTab, &rc);
177673  sessionAppendStr(&buf, "(", &rc);
177674  for(i=0; i<p->nCol; i++){
177675    if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
177676    sessionAppendIdent(&buf, p->azCol[i], &rc);
177677  }
177678
177679  sessionAppendStr(&buf, ") VALUES(?", &rc);
177680  for(i=1; i<p->nCol; i++){
177681    sessionAppendStr(&buf, ", ?", &rc);
177682  }
177683  sessionAppendStr(&buf, ")", &rc);
177684
177685  if( rc==SQLITE_OK ){
177686    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
177687  }
177688  sqlite3_free(buf.aBuf);
177689  return rc;
177690}
177691
177692/*
177693** A wrapper around sqlite3_bind_value() that detects an extra problem.
177694** See comments in the body of this function for details.
177695*/
177696static int sessionBindValue(
177697  sqlite3_stmt *pStmt,            /* Statement to bind value to */
177698  int i,                          /* Parameter number to bind to */
177699  sqlite3_value *pVal             /* Value to bind */
177700){
177701  int eType = sqlite3_value_type(pVal);
177702  /* COVERAGE: The (pVal->z==0) branch is never true using current versions
177703  ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
177704  ** the (pVal->z) variable remains as it was or the type of the value is
177705  ** set to SQLITE_NULL.  */
177706  if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
177707    /* This condition occurs when an earlier OOM in a call to
177708    ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
177709    ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
177710    return SQLITE_NOMEM;
177711  }
177712  return sqlite3_bind_value(pStmt, i, pVal);
177713}
177714
177715/*
177716** Iterator pIter must point to an SQLITE_INSERT entry. This function
177717** transfers new.* values from the current iterator entry to statement
177718** pStmt. The table being inserted into has nCol columns.
177719**
177720** New.* value $i from the iterator is bound to variable ($i+1) of
177721** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
177722** are transfered to the statement. Otherwise, if abPK is not NULL, it points
177723** to an array nCol elements in size. In this case only those values for
177724** which abPK[$i] is true are read from the iterator and bound to the
177725** statement.
177726**
177727** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
177728*/
177729static int sessionBindRow(
177730  sqlite3_changeset_iter *pIter,  /* Iterator to read values from */
177731  int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
177732  int nCol,                       /* Number of columns */
177733  u8 *abPK,                       /* If not NULL, bind only if true */
177734  sqlite3_stmt *pStmt             /* Bind values to this statement */
177735){
177736  int i;
177737  int rc = SQLITE_OK;
177738
177739  /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
177740  ** argument iterator points to a suitable entry. Make sure that xValue
177741  ** is one of these to guarantee that it is safe to ignore the return
177742  ** in the code below. */
177743  assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
177744
177745  for(i=0; rc==SQLITE_OK && i<nCol; i++){
177746    if( !abPK || abPK[i] ){
177747      sqlite3_value *pVal;
177748      (void)xValue(pIter, i, &pVal);
177749      rc = sessionBindValue(pStmt, i+1, pVal);
177750    }
177751  }
177752  return rc;
177753}
177754
177755/*
177756** SQL statement pSelect is as generated by the sessionSelectRow() function.
177757** This function binds the primary key values from the change that changeset
177758** iterator pIter points to to the SELECT and attempts to seek to the table
177759** entry. If a row is found, the SELECT statement left pointing at the row
177760** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
177761** has occured, the statement is reset and SQLITE_OK is returned. If an
177762** error occurs, the statement is reset and an SQLite error code is returned.
177763**
177764** If this function returns SQLITE_ROW, the caller must eventually reset()
177765** statement pSelect. If any other value is returned, the statement does
177766** not require a reset().
177767**
177768** If the iterator currently points to an INSERT record, bind values from the
177769** new.* record to the SELECT statement. Or, if it points to a DELETE or
177770** UPDATE, bind values from the old.* record.
177771*/
177772static int sessionSeekToRow(
177773  sqlite3 *db,                    /* Database handle */
177774  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
177775  u8 *abPK,                       /* Primary key flags array */
177776  sqlite3_stmt *pSelect           /* SELECT statement from sessionSelectRow() */
177777){
177778  int rc;                         /* Return code */
177779  int nCol;                       /* Number of columns in table */
177780  int op;                         /* Changset operation (SQLITE_UPDATE etc.) */
177781  const char *zDummy;             /* Unused */
177782
177783  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
177784  rc = sessionBindRow(pIter,
177785      op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
177786      nCol, abPK, pSelect
177787  );
177788
177789  if( rc==SQLITE_OK ){
177790    rc = sqlite3_step(pSelect);
177791    if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
177792  }
177793
177794  return rc;
177795}
177796
177797/*
177798** Invoke the conflict handler for the change that the changeset iterator
177799** currently points to.
177800**
177801** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
177802** If argument pbReplace is NULL, then the type of conflict handler invoked
177803** depends solely on eType, as follows:
177804**
177805**    eType value                 Value passed to xConflict
177806**    -------------------------------------------------
177807**    CHANGESET_DATA              CHANGESET_NOTFOUND
177808**    CHANGESET_CONFLICT          CHANGESET_CONSTRAINT
177809**
177810** Or, if pbReplace is not NULL, then an attempt is made to find an existing
177811** record with the same primary key as the record about to be deleted, updated
177812** or inserted. If such a record can be found, it is available to the conflict
177813** handler as the "conflicting" record. In this case the type of conflict
177814** handler invoked is as follows:
177815**
177816**    eType value         PK Record found?   Value passed to xConflict
177817**    ----------------------------------------------------------------
177818**    CHANGESET_DATA      Yes                CHANGESET_DATA
177819**    CHANGESET_DATA      No                 CHANGESET_NOTFOUND
177820**    CHANGESET_CONFLICT  Yes                CHANGESET_CONFLICT
177821**    CHANGESET_CONFLICT  No                 CHANGESET_CONSTRAINT
177822**
177823** If pbReplace is not NULL, and a record with a matching PK is found, and
177824** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
177825** is set to non-zero before returning SQLITE_OK.
177826**
177827** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
177828** returned. Or, if the conflict handler returns an invalid value,
177829** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
177830** this function returns SQLITE_OK.
177831*/
177832static int sessionConflictHandler(
177833  int eType,                      /* Either CHANGESET_DATA or CONFLICT */
177834  SessionApplyCtx *p,             /* changeset_apply() context */
177835  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
177836  int(*xConflict)(void *, int, sqlite3_changeset_iter*),
177837  void *pCtx,                     /* First argument for conflict handler */
177838  int *pbReplace                  /* OUT: Set to true if PK row is found */
177839){
177840  int res = 0;                    /* Value returned by conflict handler */
177841  int rc;
177842  int nCol;
177843  int op;
177844  const char *zDummy;
177845
177846  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
177847
177848  assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
177849  assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
177850  assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
177851
177852  /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
177853  if( pbReplace ){
177854    rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
177855  }else{
177856    rc = SQLITE_OK;
177857  }
177858
177859  if( rc==SQLITE_ROW ){
177860    /* There exists another row with the new.* primary key. */
177861    pIter->pConflict = p->pSelect;
177862    res = xConflict(pCtx, eType, pIter);
177863    pIter->pConflict = 0;
177864    rc = sqlite3_reset(p->pSelect);
177865  }else if( rc==SQLITE_OK ){
177866    if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
177867      /* Instead of invoking the conflict handler, append the change blob
177868      ** to the SessionApplyCtx.constraints buffer. */
177869      u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
177870      int nBlob = pIter->in.iNext - pIter->in.iCurrent;
177871      sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
177872      res = SQLITE_CHANGESET_OMIT;
177873    }else{
177874      /* No other row with the new.* primary key. */
177875      res = xConflict(pCtx, eType+1, pIter);
177876      if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
177877    }
177878  }
177879
177880  if( rc==SQLITE_OK ){
177881    switch( res ){
177882      case SQLITE_CHANGESET_REPLACE:
177883        assert( pbReplace );
177884        *pbReplace = 1;
177885        break;
177886
177887      case SQLITE_CHANGESET_OMIT:
177888        break;
177889
177890      case SQLITE_CHANGESET_ABORT:
177891        rc = SQLITE_ABORT;
177892        break;
177893
177894      default:
177895        rc = SQLITE_MISUSE;
177896        break;
177897    }
177898  }
177899
177900  return rc;
177901}
177902
177903/*
177904** Attempt to apply the change that the iterator passed as the first argument
177905** currently points to to the database. If a conflict is encountered, invoke
177906** the conflict handler callback.
177907**
177908** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
177909** one is encountered, update or delete the row with the matching primary key
177910** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
177911** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
177912** to true before returning. In this case the caller will invoke this function
177913** again, this time with pbRetry set to NULL.
177914**
177915** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
177916** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
177917** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
177918** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
177919** before retrying. In this case the caller attempts to remove the conflicting
177920** row before invoking this function again, this time with pbReplace set
177921** to NULL.
177922**
177923** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
177924** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
177925** returned.
177926*/
177927static int sessionApplyOneOp(
177928  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
177929  SessionApplyCtx *p,             /* changeset_apply() context */
177930  int(*xConflict)(void *, int, sqlite3_changeset_iter *),
177931  void *pCtx,                     /* First argument for the conflict handler */
177932  int *pbReplace,                 /* OUT: True to remove PK row and retry */
177933  int *pbRetry                    /* OUT: True to retry. */
177934){
177935  const char *zDummy;
177936  int op;
177937  int nCol;
177938  int rc = SQLITE_OK;
177939
177940  assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
177941  assert( p->azCol && p->abPK );
177942  assert( !pbReplace || *pbReplace==0 );
177943
177944  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
177945
177946  if( op==SQLITE_DELETE ){
177947
177948    /* Bind values to the DELETE statement. If conflict handling is required,
177949    ** bind values for all columns and set bound variable (nCol+1) to true.
177950    ** Or, if conflict handling is not required, bind just the PK column
177951    ** values and, if it exists, set (nCol+1) to false. Conflict handling
177952    ** is not required if:
177953    **
177954    **   * this is a patchset, or
177955    **   * (pbRetry==0), or
177956    **   * all columns of the table are PK columns (in this case there is
177957    **     no (nCol+1) variable to bind to).
177958    */
177959    u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
177960    rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
177961    if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
177962      rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
177963    }
177964    if( rc!=SQLITE_OK ) return rc;
177965
177966    sqlite3_step(p->pDelete);
177967    rc = sqlite3_reset(p->pDelete);
177968    if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
177969      rc = sessionConflictHandler(
177970          SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
177971      );
177972    }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
177973      rc = sessionConflictHandler(
177974          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
177975      );
177976    }
177977
177978  }else if( op==SQLITE_UPDATE ){
177979    int i;
177980
177981    /* Bind values to the UPDATE statement. */
177982    for(i=0; rc==SQLITE_OK && i<nCol; i++){
177983      sqlite3_value *pOld = sessionChangesetOld(pIter, i);
177984      sqlite3_value *pNew = sessionChangesetNew(pIter, i);
177985
177986      sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
177987      if( pOld ){
177988        rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
177989      }
177990      if( rc==SQLITE_OK && pNew ){
177991        rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
177992      }
177993    }
177994    if( rc==SQLITE_OK ){
177995      sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
177996    }
177997    if( rc!=SQLITE_OK ) return rc;
177998
177999    /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
178000    ** the result will be SQLITE_OK with 0 rows modified. */
178001    sqlite3_step(p->pUpdate);
178002    rc = sqlite3_reset(p->pUpdate);
178003
178004    if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
178005      /* A NOTFOUND or DATA error. Search the table to see if it contains
178006      ** a row with a matching primary key. If so, this is a DATA conflict.
178007      ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
178008
178009      rc = sessionConflictHandler(
178010          SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
178011      );
178012
178013    }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
178014      /* This is always a CONSTRAINT conflict. */
178015      rc = sessionConflictHandler(
178016          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
178017      );
178018    }
178019
178020  }else{
178021    assert( op==SQLITE_INSERT );
178022    rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
178023    if( rc!=SQLITE_OK ) return rc;
178024
178025    sqlite3_step(p->pInsert);
178026    rc = sqlite3_reset(p->pInsert);
178027    if( (rc&0xff)==SQLITE_CONSTRAINT ){
178028      rc = sessionConflictHandler(
178029          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
178030      );
178031    }
178032  }
178033
178034  return rc;
178035}
178036
178037/*
178038** Attempt to apply the change that the iterator passed as the first argument
178039** currently points to to the database. If a conflict is encountered, invoke
178040** the conflict handler callback.
178041**
178042** The difference between this function and sessionApplyOne() is that this
178043** function handles the case where the conflict-handler is invoked and
178044** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
178045** retried in some manner.
178046*/
178047static int sessionApplyOneWithRetry(
178048  sqlite3 *db,                    /* Apply change to "main" db of this handle */
178049  sqlite3_changeset_iter *pIter,  /* Changeset iterator to read change from */
178050  SessionApplyCtx *pApply,        /* Apply context */
178051  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
178052  void *pCtx                      /* First argument passed to xConflict */
178053){
178054  int bReplace = 0;
178055  int bRetry = 0;
178056  int rc;
178057
178058  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
178059  assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
178060
178061  /* If the bRetry flag is set, the change has not been applied due to an
178062  ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
178063  ** a row with the correct PK is present in the db, but one or more other
178064  ** fields do not contain the expected values) and the conflict handler
178065  ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
178066  ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
178067  ** the SQLITE_CHANGESET_DATA problem.  */
178068  if( bRetry ){
178069    assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
178070    rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
178071  }
178072
178073  /* If the bReplace flag is set, the change is an INSERT that has not
178074  ** been performed because the database already contains a row with the
178075  ** specified primary key and the conflict handler returned
178076  ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
178077  ** before reattempting the INSERT.  */
178078  else if( bReplace ){
178079    assert( pIter->op==SQLITE_INSERT );
178080    rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
178081    if( rc==SQLITE_OK ){
178082      rc = sessionBindRow(pIter,
178083          sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
178084      sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
178085    }
178086    if( rc==SQLITE_OK ){
178087      sqlite3_step(pApply->pDelete);
178088      rc = sqlite3_reset(pApply->pDelete);
178089    }
178090    if( rc==SQLITE_OK ){
178091      rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
178092    }
178093    if( rc==SQLITE_OK ){
178094      rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
178095    }
178096  }
178097
178098  return rc;
178099}
178100
178101/*
178102** Retry the changes accumulated in the pApply->constraints buffer.
178103*/
178104static int sessionRetryConstraints(
178105  sqlite3 *db,
178106  int bPatchset,
178107  const char *zTab,
178108  SessionApplyCtx *pApply,
178109  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
178110  void *pCtx                      /* First argument passed to xConflict */
178111){
178112  int rc = SQLITE_OK;
178113
178114  while( pApply->constraints.nBuf ){
178115    sqlite3_changeset_iter *pIter2 = 0;
178116    SessionBuffer cons = pApply->constraints;
178117    memset(&pApply->constraints, 0, sizeof(SessionBuffer));
178118
178119    rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
178120    if( rc==SQLITE_OK ){
178121      int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
178122      int rc2;
178123      pIter2->bPatchset = bPatchset;
178124      pIter2->zTab = (char*)zTab;
178125      pIter2->nCol = pApply->nCol;
178126      pIter2->abPK = pApply->abPK;
178127      sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
178128      pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
178129      if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
178130
178131      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
178132        rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
178133      }
178134
178135      rc2 = sqlite3changeset_finalize(pIter2);
178136      if( rc==SQLITE_OK ) rc = rc2;
178137    }
178138    assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
178139
178140    sqlite3_free(cons.aBuf);
178141    if( rc!=SQLITE_OK ) break;
178142    if( pApply->constraints.nBuf>=cons.nBuf ){
178143      /* No progress was made on the last round. */
178144      pApply->bDeferConstraints = 0;
178145    }
178146  }
178147
178148  return rc;
178149}
178150
178151/*
178152** Argument pIter is a changeset iterator that has been initialized, but
178153** not yet passed to sqlite3changeset_next(). This function applies the
178154** changeset to the main database attached to handle "db". The supplied
178155** conflict handler callback is invoked to resolve any conflicts encountered
178156** while applying the change.
178157*/
178158static int sessionChangesetApply(
178159  sqlite3 *db,                    /* Apply change to "main" db of this handle */
178160  sqlite3_changeset_iter *pIter,  /* Changeset to apply */
178161  int(*xFilter)(
178162    void *pCtx,                   /* Copy of sixth arg to _apply() */
178163    const char *zTab              /* Table name */
178164  ),
178165  int(*xConflict)(
178166    void *pCtx,                   /* Copy of fifth arg to _apply() */
178167    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
178168    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
178169  ),
178170  void *pCtx                      /* First argument passed to xConflict */
178171){
178172  int schemaMismatch = 0;
178173  int rc;                         /* Return code */
178174  const char *zTab = 0;           /* Name of current table */
178175  int nTab = 0;                   /* Result of sqlite3Strlen30(zTab) */
178176  SessionApplyCtx sApply;         /* changeset_apply() context object */
178177  int bPatchset;
178178
178179  assert( xConflict!=0 );
178180
178181  pIter->in.bNoDiscard = 1;
178182  memset(&sApply, 0, sizeof(sApply));
178183  sqlite3_mutex_enter(sqlite3_db_mutex(db));
178184  rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
178185  if( rc==SQLITE_OK ){
178186    rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
178187  }
178188  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
178189    int nCol;
178190    int op;
178191    const char *zNew;
178192
178193    sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
178194
178195    if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
178196      u8 *abPK;
178197
178198      rc = sessionRetryConstraints(
178199          db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
178200      );
178201      if( rc!=SQLITE_OK ) break;
178202
178203      sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
178204      sqlite3_finalize(sApply.pDelete);
178205      sqlite3_finalize(sApply.pUpdate);
178206      sqlite3_finalize(sApply.pInsert);
178207      sqlite3_finalize(sApply.pSelect);
178208      memset(&sApply, 0, sizeof(sApply));
178209      sApply.db = db;
178210      sApply.bDeferConstraints = 1;
178211
178212      /* If an xFilter() callback was specified, invoke it now. If the
178213      ** xFilter callback returns zero, skip this table. If it returns
178214      ** non-zero, proceed. */
178215      schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
178216      if( schemaMismatch ){
178217        zTab = sqlite3_mprintf("%s", zNew);
178218        if( zTab==0 ){
178219          rc = SQLITE_NOMEM;
178220          break;
178221        }
178222        nTab = (int)strlen(zTab);
178223        sApply.azCol = (const char **)zTab;
178224      }else{
178225        int nMinCol = 0;
178226        int i;
178227
178228        sqlite3changeset_pk(pIter, &abPK, 0);
178229        rc = sessionTableInfo(
178230            db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
178231        );
178232        if( rc!=SQLITE_OK ) break;
178233        for(i=0; i<sApply.nCol; i++){
178234          if( sApply.abPK[i] ) nMinCol = i+1;
178235        }
178236
178237        if( sApply.nCol==0 ){
178238          schemaMismatch = 1;
178239          sqlite3_log(SQLITE_SCHEMA,
178240              "sqlite3changeset_apply(): no such table: %s", zTab
178241          );
178242        }
178243        else if( sApply.nCol<nCol ){
178244          schemaMismatch = 1;
178245          sqlite3_log(SQLITE_SCHEMA,
178246              "sqlite3changeset_apply(): table %s has %d columns, "
178247              "expected %d or more",
178248              zTab, sApply.nCol, nCol
178249          );
178250        }
178251        else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
178252          schemaMismatch = 1;
178253          sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
178254              "primary key mismatch for table %s", zTab
178255          );
178256        }
178257        else{
178258          sApply.nCol = nCol;
178259          if((rc = sessionSelectRow(db, zTab, &sApply))
178260          || (rc = sessionUpdateRow(db, zTab, &sApply))
178261          || (rc = sessionDeleteRow(db, zTab, &sApply))
178262          || (rc = sessionInsertRow(db, zTab, &sApply))
178263          ){
178264            break;
178265          }
178266        }
178267        nTab = sqlite3Strlen30(zTab);
178268      }
178269    }
178270
178271    /* If there is a schema mismatch on the current table, proceed to the
178272    ** next change. A log message has already been issued. */
178273    if( schemaMismatch ) continue;
178274
178275    rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
178276  }
178277
178278  bPatchset = pIter->bPatchset;
178279  if( rc==SQLITE_OK ){
178280    rc = sqlite3changeset_finalize(pIter);
178281  }else{
178282    sqlite3changeset_finalize(pIter);
178283  }
178284
178285  if( rc==SQLITE_OK ){
178286    rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
178287  }
178288
178289  if( rc==SQLITE_OK ){
178290    int nFk, notUsed;
178291    sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
178292    if( nFk!=0 ){
178293      int res = SQLITE_CHANGESET_ABORT;
178294      sqlite3_changeset_iter sIter;
178295      memset(&sIter, 0, sizeof(sIter));
178296      sIter.nCol = nFk;
178297      res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
178298      if( res!=SQLITE_CHANGESET_OMIT ){
178299        rc = SQLITE_CONSTRAINT;
178300      }
178301    }
178302  }
178303  sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
178304
178305  if( rc==SQLITE_OK ){
178306    rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
178307  }else{
178308    sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
178309    sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
178310  }
178311
178312  sqlite3_finalize(sApply.pInsert);
178313  sqlite3_finalize(sApply.pDelete);
178314  sqlite3_finalize(sApply.pUpdate);
178315  sqlite3_finalize(sApply.pSelect);
178316  sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
178317  sqlite3_free((char*)sApply.constraints.aBuf);
178318  sqlite3_mutex_leave(sqlite3_db_mutex(db));
178319  return rc;
178320}
178321
178322/*
178323** Apply the changeset passed via pChangeset/nChangeset to the main database
178324** attached to handle "db". Invoke the supplied conflict handler callback
178325** to resolve any conflicts encountered while applying the change.
178326*/
178327SQLITE_API int sqlite3changeset_apply(
178328  sqlite3 *db,                    /* Apply change to "main" db of this handle */
178329  int nChangeset,                 /* Size of changeset in bytes */
178330  void *pChangeset,               /* Changeset blob */
178331  int(*xFilter)(
178332    void *pCtx,                   /* Copy of sixth arg to _apply() */
178333    const char *zTab              /* Table name */
178334  ),
178335  int(*xConflict)(
178336    void *pCtx,                   /* Copy of fifth arg to _apply() */
178337    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
178338    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
178339  ),
178340  void *pCtx                      /* First argument passed to xConflict */
178341){
178342  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
178343  int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
178344  if( rc==SQLITE_OK ){
178345    rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
178346  }
178347  return rc;
178348}
178349
178350/*
178351** Apply the changeset passed via xInput/pIn to the main database
178352** attached to handle "db". Invoke the supplied conflict handler callback
178353** to resolve any conflicts encountered while applying the change.
178354*/
178355SQLITE_API int sqlite3changeset_apply_strm(
178356  sqlite3 *db,                    /* Apply change to "main" db of this handle */
178357  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
178358  void *pIn,                                          /* First arg for xInput */
178359  int(*xFilter)(
178360    void *pCtx,                   /* Copy of sixth arg to _apply() */
178361    const char *zTab              /* Table name */
178362  ),
178363  int(*xConflict)(
178364    void *pCtx,                   /* Copy of sixth arg to _apply() */
178365    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
178366    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
178367  ),
178368  void *pCtx                      /* First argument passed to xConflict */
178369){
178370  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
178371  int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
178372  if( rc==SQLITE_OK ){
178373    rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
178374  }
178375  return rc;
178376}
178377
178378/*
178379** sqlite3_changegroup handle.
178380*/
178381struct sqlite3_changegroup {
178382  int rc;                         /* Error code */
178383  int bPatch;                     /* True to accumulate patchsets */
178384  SessionTable *pList;            /* List of tables in current patch */
178385};
178386
178387/*
178388** This function is called to merge two changes to the same row together as
178389** part of an sqlite3changeset_concat() operation. A new change object is
178390** allocated and a pointer to it stored in *ppNew.
178391*/
178392static int sessionChangeMerge(
178393  SessionTable *pTab,             /* Table structure */
178394  int bPatchset,                  /* True for patchsets */
178395  SessionChange *pExist,          /* Existing change */
178396  int op2,                        /* Second change operation */
178397  int bIndirect,                  /* True if second change is indirect */
178398  u8 *aRec,                       /* Second change record */
178399  int nRec,                       /* Number of bytes in aRec */
178400  SessionChange **ppNew           /* OUT: Merged change */
178401){
178402  SessionChange *pNew = 0;
178403
178404  if( !pExist ){
178405    pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
178406    if( !pNew ){
178407      return SQLITE_NOMEM;
178408    }
178409    memset(pNew, 0, sizeof(SessionChange));
178410    pNew->op = op2;
178411    pNew->bIndirect = bIndirect;
178412    pNew->nRecord = nRec;
178413    pNew->aRecord = (u8*)&pNew[1];
178414    memcpy(pNew->aRecord, aRec, nRec);
178415  }else{
178416    int op1 = pExist->op;
178417
178418    /*
178419    **   op1=INSERT, op2=INSERT      ->      Unsupported. Discard op2.
178420    **   op1=INSERT, op2=UPDATE      ->      INSERT.
178421    **   op1=INSERT, op2=DELETE      ->      (none)
178422    **
178423    **   op1=UPDATE, op2=INSERT      ->      Unsupported. Discard op2.
178424    **   op1=UPDATE, op2=UPDATE      ->      UPDATE.
178425    **   op1=UPDATE, op2=DELETE      ->      DELETE.
178426    **
178427    **   op1=DELETE, op2=INSERT      ->      UPDATE.
178428    **   op1=DELETE, op2=UPDATE      ->      Unsupported. Discard op2.
178429    **   op1=DELETE, op2=DELETE      ->      Unsupported. Discard op2.
178430    */
178431    if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
178432     || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
178433     || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
178434     || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
178435    ){
178436      pNew = pExist;
178437    }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
178438      sqlite3_free(pExist);
178439      assert( pNew==0 );
178440    }else{
178441      u8 *aExist = pExist->aRecord;
178442      int nByte;
178443      u8 *aCsr;
178444
178445      /* Allocate a new SessionChange object. Ensure that the aRecord[]
178446      ** buffer of the new object is large enough to hold any record that
178447      ** may be generated by combining the input records.  */
178448      nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
178449      pNew = (SessionChange *)sqlite3_malloc(nByte);
178450      if( !pNew ){
178451        sqlite3_free(pExist);
178452        return SQLITE_NOMEM;
178453      }
178454      memset(pNew, 0, sizeof(SessionChange));
178455      pNew->bIndirect = (bIndirect && pExist->bIndirect);
178456      aCsr = pNew->aRecord = (u8 *)&pNew[1];
178457
178458      if( op1==SQLITE_INSERT ){             /* INSERT + UPDATE */
178459        u8 *a1 = aRec;
178460        assert( op2==SQLITE_UPDATE );
178461        pNew->op = SQLITE_INSERT;
178462        if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
178463        sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
178464      }else if( op1==SQLITE_DELETE ){       /* DELETE + INSERT */
178465        assert( op2==SQLITE_INSERT );
178466        pNew->op = SQLITE_UPDATE;
178467        if( bPatchset ){
178468          memcpy(aCsr, aRec, nRec);
178469          aCsr += nRec;
178470        }else{
178471          if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
178472            sqlite3_free(pNew);
178473            pNew = 0;
178474          }
178475        }
178476      }else if( op2==SQLITE_UPDATE ){       /* UPDATE + UPDATE */
178477        u8 *a1 = aExist;
178478        u8 *a2 = aRec;
178479        assert( op1==SQLITE_UPDATE );
178480        if( bPatchset==0 ){
178481          sessionSkipRecord(&a1, pTab->nCol);
178482          sessionSkipRecord(&a2, pTab->nCol);
178483        }
178484        pNew->op = SQLITE_UPDATE;
178485        if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
178486          sqlite3_free(pNew);
178487          pNew = 0;
178488        }
178489      }else{                                /* UPDATE + DELETE */
178490        assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
178491        pNew->op = SQLITE_DELETE;
178492        if( bPatchset ){
178493          memcpy(aCsr, aRec, nRec);
178494          aCsr += nRec;
178495        }else{
178496          sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
178497        }
178498      }
178499
178500      if( pNew ){
178501        pNew->nRecord = (int)(aCsr - pNew->aRecord);
178502      }
178503      sqlite3_free(pExist);
178504    }
178505  }
178506
178507  *ppNew = pNew;
178508  return SQLITE_OK;
178509}
178510
178511/*
178512** Add all changes in the changeset traversed by the iterator passed as
178513** the first argument to the changegroup hash tables.
178514*/
178515static int sessionChangesetToHash(
178516  sqlite3_changeset_iter *pIter,   /* Iterator to read from */
178517  sqlite3_changegroup *pGrp        /* Changegroup object to add changeset to */
178518){
178519  u8 *aRec;
178520  int nRec;
178521  int rc = SQLITE_OK;
178522  SessionTable *pTab = 0;
178523
178524
178525  while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
178526    const char *zNew;
178527    int nCol;
178528    int op;
178529    int iHash;
178530    int bIndirect;
178531    SessionChange *pChange;
178532    SessionChange *pExist = 0;
178533    SessionChange **pp;
178534
178535    if( pGrp->pList==0 ){
178536      pGrp->bPatch = pIter->bPatchset;
178537    }else if( pIter->bPatchset!=pGrp->bPatch ){
178538      rc = SQLITE_ERROR;
178539      break;
178540    }
178541
178542    sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
178543    if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
178544      /* Search the list for a matching table */
178545      int nNew = (int)strlen(zNew);
178546      u8 *abPK;
178547
178548      sqlite3changeset_pk(pIter, &abPK, 0);
178549      for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
178550        if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
178551      }
178552      if( !pTab ){
178553        SessionTable **ppTab;
178554
178555        pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
178556        if( !pTab ){
178557          rc = SQLITE_NOMEM;
178558          break;
178559        }
178560        memset(pTab, 0, sizeof(SessionTable));
178561        pTab->nCol = nCol;
178562        pTab->abPK = (u8*)&pTab[1];
178563        memcpy(pTab->abPK, abPK, nCol);
178564        pTab->zName = (char*)&pTab->abPK[nCol];
178565        memcpy(pTab->zName, zNew, nNew+1);
178566
178567        /* The new object must be linked on to the end of the list, not
178568        ** simply added to the start of it. This is to ensure that the
178569        ** tables within the output of sqlite3changegroup_output() are in
178570        ** the right order.  */
178571        for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
178572        *ppTab = pTab;
178573      }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
178574        rc = SQLITE_SCHEMA;
178575        break;
178576      }
178577    }
178578
178579    if( sessionGrowHash(pIter->bPatchset, pTab) ){
178580      rc = SQLITE_NOMEM;
178581      break;
178582    }
178583    iHash = sessionChangeHash(
178584        pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
178585    );
178586
178587    /* Search for existing entry. If found, remove it from the hash table.
178588    ** Code below may link it back in.
178589    */
178590    for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
178591      int bPkOnly1 = 0;
178592      int bPkOnly2 = 0;
178593      if( pIter->bPatchset ){
178594        bPkOnly1 = (*pp)->op==SQLITE_DELETE;
178595        bPkOnly2 = op==SQLITE_DELETE;
178596      }
178597      if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
178598        pExist = *pp;
178599        *pp = (*pp)->pNext;
178600        pTab->nEntry--;
178601        break;
178602      }
178603    }
178604
178605    rc = sessionChangeMerge(pTab,
178606        pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
178607    );
178608    if( rc ) break;
178609    if( pChange ){
178610      pChange->pNext = pTab->apChange[iHash];
178611      pTab->apChange[iHash] = pChange;
178612      pTab->nEntry++;
178613    }
178614  }
178615
178616  if( rc==SQLITE_OK ) rc = pIter->rc;
178617  return rc;
178618}
178619
178620/*
178621** Serialize a changeset (or patchset) based on all changesets (or patchsets)
178622** added to the changegroup object passed as the first argument.
178623**
178624** If xOutput is not NULL, then the changeset/patchset is returned to the
178625** user via one or more calls to xOutput, as with the other streaming
178626** interfaces.
178627**
178628** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
178629** buffer containing the output changeset before this function returns. In
178630** this case (*pnOut) is set to the size of the output buffer in bytes. It
178631** is the responsibility of the caller to free the output buffer using
178632** sqlite3_free() when it is no longer required.
178633**
178634** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
178635** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
178636** are both set to 0 before returning.
178637*/
178638static int sessionChangegroupOutput(
178639  sqlite3_changegroup *pGrp,
178640  int (*xOutput)(void *pOut, const void *pData, int nData),
178641  void *pOut,
178642  int *pnOut,
178643  void **ppOut
178644){
178645  int rc = SQLITE_OK;
178646  SessionBuffer buf = {0, 0, 0};
178647  SessionTable *pTab;
178648  assert( xOutput==0 || (ppOut==0 && pnOut==0) );
178649
178650  /* Create the serialized output changeset based on the contents of the
178651  ** hash tables attached to the SessionTable objects in list p->pList.
178652  */
178653  for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
178654    int i;
178655    if( pTab->nEntry==0 ) continue;
178656
178657    sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
178658    for(i=0; i<pTab->nChange; i++){
178659      SessionChange *p;
178660      for(p=pTab->apChange[i]; p; p=p->pNext){
178661        sessionAppendByte(&buf, p->op, &rc);
178662        sessionAppendByte(&buf, p->bIndirect, &rc);
178663        sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
178664      }
178665    }
178666
178667    if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
178668      rc = xOutput(pOut, buf.aBuf, buf.nBuf);
178669      buf.nBuf = 0;
178670    }
178671  }
178672
178673  if( rc==SQLITE_OK ){
178674    if( xOutput ){
178675      if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
178676    }else{
178677      *ppOut = buf.aBuf;
178678      *pnOut = buf.nBuf;
178679      buf.aBuf = 0;
178680    }
178681  }
178682  sqlite3_free(buf.aBuf);
178683
178684  return rc;
178685}
178686
178687/*
178688** Allocate a new, empty, sqlite3_changegroup.
178689*/
178690SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
178691  int rc = SQLITE_OK;             /* Return code */
178692  sqlite3_changegroup *p;         /* New object */
178693  p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
178694  if( p==0 ){
178695    rc = SQLITE_NOMEM;
178696  }else{
178697    memset(p, 0, sizeof(sqlite3_changegroup));
178698  }
178699  *pp = p;
178700  return rc;
178701}
178702
178703/*
178704** Add the changeset currently stored in buffer pData, size nData bytes,
178705** to changeset-group p.
178706*/
178707SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
178708  sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
178709  int rc;                         /* Return code */
178710
178711  rc = sqlite3changeset_start(&pIter, nData, pData);
178712  if( rc==SQLITE_OK ){
178713    rc = sessionChangesetToHash(pIter, pGrp);
178714  }
178715  sqlite3changeset_finalize(pIter);
178716  return rc;
178717}
178718
178719/*
178720** Obtain a buffer containing a changeset representing the concatenation
178721** of all changesets added to the group so far.
178722*/
178723SQLITE_API int sqlite3changegroup_output(
178724    sqlite3_changegroup *pGrp,
178725    int *pnData,
178726    void **ppData
178727){
178728  return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
178729}
178730
178731/*
178732** Streaming versions of changegroup_add().
178733*/
178734SQLITE_API int sqlite3changegroup_add_strm(
178735  sqlite3_changegroup *pGrp,
178736  int (*xInput)(void *pIn, void *pData, int *pnData),
178737  void *pIn
178738){
178739  sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
178740  int rc;                         /* Return code */
178741
178742  rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
178743  if( rc==SQLITE_OK ){
178744    rc = sessionChangesetToHash(pIter, pGrp);
178745  }
178746  sqlite3changeset_finalize(pIter);
178747  return rc;
178748}
178749
178750/*
178751** Streaming versions of changegroup_output().
178752*/
178753SQLITE_API int sqlite3changegroup_output_strm(
178754  sqlite3_changegroup *pGrp,
178755  int (*xOutput)(void *pOut, const void *pData, int nData),
178756  void *pOut
178757){
178758  return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
178759}
178760
178761/*
178762** Delete a changegroup object.
178763*/
178764SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
178765  if( pGrp ){
178766    sessionDeleteTable(pGrp->pList);
178767    sqlite3_free(pGrp);
178768  }
178769}
178770
178771/*
178772** Combine two changesets together.
178773*/
178774SQLITE_API int sqlite3changeset_concat(
178775  int nLeft,                      /* Number of bytes in lhs input */
178776  void *pLeft,                    /* Lhs input changeset */
178777  int nRight                      /* Number of bytes in rhs input */,
178778  void *pRight,                   /* Rhs input changeset */
178779  int *pnOut,                     /* OUT: Number of bytes in output changeset */
178780  void **ppOut                    /* OUT: changeset (left <concat> right) */
178781){
178782  sqlite3_changegroup *pGrp;
178783  int rc;
178784
178785  rc = sqlite3changegroup_new(&pGrp);
178786  if( rc==SQLITE_OK ){
178787    rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
178788  }
178789  if( rc==SQLITE_OK ){
178790    rc = sqlite3changegroup_add(pGrp, nRight, pRight);
178791  }
178792  if( rc==SQLITE_OK ){
178793    rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
178794  }
178795  sqlite3changegroup_delete(pGrp);
178796
178797  return rc;
178798}
178799
178800/*
178801** Streaming version of sqlite3changeset_concat().
178802*/
178803SQLITE_API int sqlite3changeset_concat_strm(
178804  int (*xInputA)(void *pIn, void *pData, int *pnData),
178805  void *pInA,
178806  int (*xInputB)(void *pIn, void *pData, int *pnData),
178807  void *pInB,
178808  int (*xOutput)(void *pOut, const void *pData, int nData),
178809  void *pOut
178810){
178811  sqlite3_changegroup *pGrp;
178812  int rc;
178813
178814  rc = sqlite3changegroup_new(&pGrp);
178815  if( rc==SQLITE_OK ){
178816    rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
178817  }
178818  if( rc==SQLITE_OK ){
178819    rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
178820  }
178821  if( rc==SQLITE_OK ){
178822    rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
178823  }
178824  sqlite3changegroup_delete(pGrp);
178825
178826  return rc;
178827}
178828
178829#endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
178830
178831/************** End of sqlite3session.c **************************************/
178832/************** Begin file json1.c *******************************************/
178833/*
178834** 2015-08-12
178835**
178836** The author disclaims copyright to this source code.  In place of
178837** a legal notice, here is a blessing:
178838**
178839**    May you do good and not evil.
178840**    May you find forgiveness for yourself and forgive others.
178841**    May you share freely, never taking more than you give.
178842**
178843******************************************************************************
178844**
178845** This SQLite extension implements JSON functions.  The interface is
178846** modeled after MySQL JSON functions:
178847**
178848**     https://dev.mysql.com/doc/refman/5.7/en/json.html
178849**
178850** For the time being, all JSON is stored as pure text.  (We might add
178851** a JSONB type in the future which stores a binary encoding of JSON in
178852** a BLOB, but there is no support for JSONB in the current implementation.
178853** This implementation parses JSON text at 250 MB/s, so it is hard to see
178854** how JSONB might improve on that.)
178855*/
178856#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
178857#if !defined(SQLITEINT_H)
178858/* #include "sqlite3ext.h" */
178859#endif
178860SQLITE_EXTENSION_INIT1
178861/* #include <assert.h> */
178862/* #include <string.h> */
178863/* #include <stdlib.h> */
178864/* #include <stdarg.h> */
178865
178866/* Mark a function parameter as unused, to suppress nuisance compiler
178867** warnings. */
178868#ifndef UNUSED_PARAM
178869# define UNUSED_PARAM(X)  (void)(X)
178870#endif
178871
178872#ifndef LARGEST_INT64
178873# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
178874# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
178875#endif
178876
178877/*
178878** Versions of isspace(), isalnum() and isdigit() to which it is safe
178879** to pass signed char values.
178880*/
178881#ifdef sqlite3Isdigit
178882   /* Use the SQLite core versions if this routine is part of the
178883   ** SQLite amalgamation */
178884#  define safe_isdigit(x)  sqlite3Isdigit(x)
178885#  define safe_isalnum(x)  sqlite3Isalnum(x)
178886#  define safe_isxdigit(x) sqlite3Isxdigit(x)
178887#else
178888   /* Use the standard library for separate compilation */
178889#include <ctype.h>  /* amalgamator: keep */
178890#  define safe_isdigit(x)  isdigit((unsigned char)(x))
178891#  define safe_isalnum(x)  isalnum((unsigned char)(x))
178892#  define safe_isxdigit(x) isxdigit((unsigned char)(x))
178893#endif
178894
178895/*
178896** Growing our own isspace() routine this way is twice as fast as
178897** the library isspace() function, resulting in a 7% overall performance
178898** increase for the parser.  (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
178899*/
178900static const char jsonIsSpace[] = {
178901  0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,
178902  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178903  1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178904  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178905  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178906  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178907  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178908  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178909  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178910  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178911  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178912  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178913  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178914  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178915  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178916  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
178917};
178918#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
178919
178920#ifndef SQLITE_AMALGAMATION
178921  /* Unsigned integer types.  These are already defined in the sqliteInt.h,
178922  ** but the definitions need to be repeated for separate compilation. */
178923  typedef sqlite3_uint64 u64;
178924  typedef unsigned int u32;
178925  typedef unsigned char u8;
178926#endif
178927
178928/* Objects */
178929typedef struct JsonString JsonString;
178930typedef struct JsonNode JsonNode;
178931typedef struct JsonParse JsonParse;
178932
178933/* An instance of this object represents a JSON string
178934** under construction.  Really, this is a generic string accumulator
178935** that can be and is used to create strings other than JSON.
178936*/
178937struct JsonString {
178938  sqlite3_context *pCtx;   /* Function context - put error messages here */
178939  char *zBuf;              /* Append JSON content here */
178940  u64 nAlloc;              /* Bytes of storage available in zBuf[] */
178941  u64 nUsed;               /* Bytes of zBuf[] currently used */
178942  u8 bStatic;              /* True if zBuf is static space */
178943  u8 bErr;                 /* True if an error has been encountered */
178944  char zSpace[100];        /* Initial static space */
178945};
178946
178947/* JSON type values
178948*/
178949#define JSON_NULL     0
178950#define JSON_TRUE     1
178951#define JSON_FALSE    2
178952#define JSON_INT      3
178953#define JSON_REAL     4
178954#define JSON_STRING   5
178955#define JSON_ARRAY    6
178956#define JSON_OBJECT   7
178957
178958/* The "subtype" set for JSON values */
178959#define JSON_SUBTYPE  74    /* Ascii for "J" */
178960
178961/*
178962** Names of the various JSON types:
178963*/
178964static const char * const jsonType[] = {
178965  "null", "true", "false", "integer", "real", "text", "array", "object"
178966};
178967
178968/* Bit values for the JsonNode.jnFlag field
178969*/
178970#define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */
178971#define JNODE_ESCAPE  0x02         /* Content is text with \ escapes */
178972#define JNODE_REMOVE  0x04         /* Do not output */
178973#define JNODE_REPLACE 0x08         /* Replace with JsonNode.u.iReplace */
178974#define JNODE_PATCH   0x10         /* Patch with JsonNode.u.pPatch */
178975#define JNODE_APPEND  0x20         /* More ARRAY/OBJECT entries at u.iAppend */
178976#define JNODE_LABEL   0x40         /* Is a label of an object */
178977
178978
178979/* A single node of parsed JSON
178980*/
178981struct JsonNode {
178982  u8 eType;              /* One of the JSON_ type values */
178983  u8 jnFlags;            /* JNODE flags */
178984  u32 n;                 /* Bytes of content, or number of sub-nodes */
178985  union {
178986    const char *zJContent; /* Content for INT, REAL, and STRING */
178987    u32 iAppend;           /* More terms for ARRAY and OBJECT */
178988    u32 iKey;              /* Key for ARRAY objects in json_tree() */
178989    u32 iReplace;          /* Replacement content for JNODE_REPLACE */
178990    JsonNode *pPatch;      /* Node chain of patch for JNODE_PATCH */
178991  } u;
178992};
178993
178994/* A completely parsed JSON string
178995*/
178996struct JsonParse {
178997  u32 nNode;         /* Number of slots of aNode[] used */
178998  u32 nAlloc;        /* Number of slots of aNode[] allocated */
178999  JsonNode *aNode;   /* Array of nodes containing the parse */
179000  const char *zJson; /* Original JSON string */
179001  u32 *aUp;          /* Index of parent of each node */
179002  u8 oom;            /* Set to true if out of memory */
179003  u8 nErr;           /* Number of errors seen */
179004};
179005
179006/**************************************************************************
179007** Utility routines for dealing with JsonString objects
179008**************************************************************************/
179009
179010/* Set the JsonString object to an empty string
179011*/
179012static void jsonZero(JsonString *p){
179013  p->zBuf = p->zSpace;
179014  p->nAlloc = sizeof(p->zSpace);
179015  p->nUsed = 0;
179016  p->bStatic = 1;
179017}
179018
179019/* Initialize the JsonString object
179020*/
179021static void jsonInit(JsonString *p, sqlite3_context *pCtx){
179022  p->pCtx = pCtx;
179023  p->bErr = 0;
179024  jsonZero(p);
179025}
179026
179027
179028/* Free all allocated memory and reset the JsonString object back to its
179029** initial state.
179030*/
179031static void jsonReset(JsonString *p){
179032  if( !p->bStatic ) sqlite3_free(p->zBuf);
179033  jsonZero(p);
179034}
179035
179036
179037/* Report an out-of-memory (OOM) condition
179038*/
179039static void jsonOom(JsonString *p){
179040  p->bErr = 1;
179041  sqlite3_result_error_nomem(p->pCtx);
179042  jsonReset(p);
179043}
179044
179045/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
179046** Return zero on success.  Return non-zero on an OOM error
179047*/
179048static int jsonGrow(JsonString *p, u32 N){
179049  u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
179050  char *zNew;
179051  if( p->bStatic ){
179052    if( p->bErr ) return 1;
179053    zNew = sqlite3_malloc64(nTotal);
179054    if( zNew==0 ){
179055      jsonOom(p);
179056      return SQLITE_NOMEM;
179057    }
179058    memcpy(zNew, p->zBuf, (size_t)p->nUsed);
179059    p->zBuf = zNew;
179060    p->bStatic = 0;
179061  }else{
179062    zNew = sqlite3_realloc64(p->zBuf, nTotal);
179063    if( zNew==0 ){
179064      jsonOom(p);
179065      return SQLITE_NOMEM;
179066    }
179067    p->zBuf = zNew;
179068  }
179069  p->nAlloc = nTotal;
179070  return SQLITE_OK;
179071}
179072
179073/* Append N bytes from zIn onto the end of the JsonString string.
179074*/
179075static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
179076  if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
179077  memcpy(p->zBuf+p->nUsed, zIn, N);
179078  p->nUsed += N;
179079}
179080
179081/* Append formatted text (not to exceed N bytes) to the JsonString.
179082*/
179083static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
179084  va_list ap;
179085  if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
179086  va_start(ap, zFormat);
179087  sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
179088  va_end(ap);
179089  p->nUsed += (int)strlen(p->zBuf+p->nUsed);
179090}
179091
179092/* Append a single character
179093*/
179094static void jsonAppendChar(JsonString *p, char c){
179095  if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
179096  p->zBuf[p->nUsed++] = c;
179097}
179098
179099/* Append a comma separator to the output buffer, if the previous
179100** character is not '[' or '{'.
179101*/
179102static void jsonAppendSeparator(JsonString *p){
179103  char c;
179104  if( p->nUsed==0 ) return;
179105  c = p->zBuf[p->nUsed-1];
179106  if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
179107}
179108
179109/* Append the N-byte string in zIn to the end of the JsonString string
179110** under construction.  Enclose the string in "..." and escape
179111** any double-quotes or backslash characters contained within the
179112** string.
179113*/
179114static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
179115  u32 i;
179116  if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
179117  p->zBuf[p->nUsed++] = '"';
179118  for(i=0; i<N; i++){
179119    unsigned char c = ((unsigned const char*)zIn)[i];
179120    if( c=='"' || c=='\\' ){
179121      json_simple_escape:
179122      if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
179123      p->zBuf[p->nUsed++] = '\\';
179124    }else if( c<=0x1f ){
179125      static const char aSpecial[] = {
179126         0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
179127         0, 0, 0, 0, 0, 0, 0, 0,   0,   0,   0, 0,   0,   0, 0, 0
179128      };
179129      assert( sizeof(aSpecial)==32 );
179130      assert( aSpecial['\b']=='b' );
179131      assert( aSpecial['\f']=='f' );
179132      assert( aSpecial['\n']=='n' );
179133      assert( aSpecial['\r']=='r' );
179134      assert( aSpecial['\t']=='t' );
179135      if( aSpecial[c] ){
179136        c = aSpecial[c];
179137        goto json_simple_escape;
179138      }
179139      if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
179140      p->zBuf[p->nUsed++] = '\\';
179141      p->zBuf[p->nUsed++] = 'u';
179142      p->zBuf[p->nUsed++] = '0';
179143      p->zBuf[p->nUsed++] = '0';
179144      p->zBuf[p->nUsed++] = '0' + (c>>4);
179145      c = "0123456789abcdef"[c&0xf];
179146    }
179147    p->zBuf[p->nUsed++] = c;
179148  }
179149  p->zBuf[p->nUsed++] = '"';
179150  assert( p->nUsed<p->nAlloc );
179151}
179152
179153/*
179154** Append a function parameter value to the JSON string under
179155** construction.
179156*/
179157static void jsonAppendValue(
179158  JsonString *p,                 /* Append to this JSON string */
179159  sqlite3_value *pValue          /* Value to append */
179160){
179161  switch( sqlite3_value_type(pValue) ){
179162    case SQLITE_NULL: {
179163      jsonAppendRaw(p, "null", 4);
179164      break;
179165    }
179166    case SQLITE_INTEGER:
179167    case SQLITE_FLOAT: {
179168      const char *z = (const char*)sqlite3_value_text(pValue);
179169      u32 n = (u32)sqlite3_value_bytes(pValue);
179170      jsonAppendRaw(p, z, n);
179171      break;
179172    }
179173    case SQLITE_TEXT: {
179174      const char *z = (const char*)sqlite3_value_text(pValue);
179175      u32 n = (u32)sqlite3_value_bytes(pValue);
179176      if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
179177        jsonAppendRaw(p, z, n);
179178      }else{
179179        jsonAppendString(p, z, n);
179180      }
179181      break;
179182    }
179183    default: {
179184      if( p->bErr==0 ){
179185        sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
179186        p->bErr = 2;
179187        jsonReset(p);
179188      }
179189      break;
179190    }
179191  }
179192}
179193
179194
179195/* Make the JSON in p the result of the SQL function.
179196*/
179197static void jsonResult(JsonString *p){
179198  if( p->bErr==0 ){
179199    sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
179200                          p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
179201                          SQLITE_UTF8);
179202    jsonZero(p);
179203  }
179204  assert( p->bStatic );
179205}
179206
179207/**************************************************************************
179208** Utility routines for dealing with JsonNode and JsonParse objects
179209**************************************************************************/
179210
179211/*
179212** Return the number of consecutive JsonNode slots need to represent
179213** the parsed JSON at pNode.  The minimum answer is 1.  For ARRAY and
179214** OBJECT types, the number might be larger.
179215**
179216** Appended elements are not counted.  The value returned is the number
179217** by which the JsonNode counter should increment in order to go to the
179218** next peer value.
179219*/
179220static u32 jsonNodeSize(JsonNode *pNode){
179221  return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
179222}
179223
179224/*
179225** Reclaim all memory allocated by a JsonParse object.  But do not
179226** delete the JsonParse object itself.
179227*/
179228static void jsonParseReset(JsonParse *pParse){
179229  sqlite3_free(pParse->aNode);
179230  pParse->aNode = 0;
179231  pParse->nNode = 0;
179232  pParse->nAlloc = 0;
179233  sqlite3_free(pParse->aUp);
179234  pParse->aUp = 0;
179235}
179236
179237/*
179238** Convert the JsonNode pNode into a pure JSON string and
179239** append to pOut.  Subsubstructure is also included.  Return
179240** the number of JsonNode objects that are encoded.
179241*/
179242static void jsonRenderNode(
179243  JsonNode *pNode,               /* The node to render */
179244  JsonString *pOut,              /* Write JSON here */
179245  sqlite3_value **aReplace       /* Replacement values */
179246){
179247  if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
179248    if( pNode->jnFlags & JNODE_REPLACE ){
179249      jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
179250      return;
179251    }
179252    pNode = pNode->u.pPatch;
179253  }
179254  switch( pNode->eType ){
179255    default: {
179256      assert( pNode->eType==JSON_NULL );
179257      jsonAppendRaw(pOut, "null", 4);
179258      break;
179259    }
179260    case JSON_TRUE: {
179261      jsonAppendRaw(pOut, "true", 4);
179262      break;
179263    }
179264    case JSON_FALSE: {
179265      jsonAppendRaw(pOut, "false", 5);
179266      break;
179267    }
179268    case JSON_STRING: {
179269      if( pNode->jnFlags & JNODE_RAW ){
179270        jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
179271        break;
179272      }
179273      /* Fall through into the next case */
179274    }
179275    case JSON_REAL:
179276    case JSON_INT: {
179277      jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
179278      break;
179279    }
179280    case JSON_ARRAY: {
179281      u32 j = 1;
179282      jsonAppendChar(pOut, '[');
179283      for(;;){
179284        while( j<=pNode->n ){
179285          if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
179286            jsonAppendSeparator(pOut);
179287            jsonRenderNode(&pNode[j], pOut, aReplace);
179288          }
179289          j += jsonNodeSize(&pNode[j]);
179290        }
179291        if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
179292        pNode = &pNode[pNode->u.iAppend];
179293        j = 1;
179294      }
179295      jsonAppendChar(pOut, ']');
179296      break;
179297    }
179298    case JSON_OBJECT: {
179299      u32 j = 1;
179300      jsonAppendChar(pOut, '{');
179301      for(;;){
179302        while( j<=pNode->n ){
179303          if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
179304            jsonAppendSeparator(pOut);
179305            jsonRenderNode(&pNode[j], pOut, aReplace);
179306            jsonAppendChar(pOut, ':');
179307            jsonRenderNode(&pNode[j+1], pOut, aReplace);
179308          }
179309          j += 1 + jsonNodeSize(&pNode[j+1]);
179310        }
179311        if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
179312        pNode = &pNode[pNode->u.iAppend];
179313        j = 1;
179314      }
179315      jsonAppendChar(pOut, '}');
179316      break;
179317    }
179318  }
179319}
179320
179321/*
179322** Return a JsonNode and all its descendents as a JSON string.
179323*/
179324static void jsonReturnJson(
179325  JsonNode *pNode,            /* Node to return */
179326  sqlite3_context *pCtx,      /* Return value for this function */
179327  sqlite3_value **aReplace    /* Array of replacement values */
179328){
179329  JsonString s;
179330  jsonInit(&s, pCtx);
179331  jsonRenderNode(pNode, &s, aReplace);
179332  jsonResult(&s);
179333  sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
179334}
179335
179336/*
179337** Make the JsonNode the return value of the function.
179338*/
179339static void jsonReturn(
179340  JsonNode *pNode,            /* Node to return */
179341  sqlite3_context *pCtx,      /* Return value for this function */
179342  sqlite3_value **aReplace    /* Array of replacement values */
179343){
179344  switch( pNode->eType ){
179345    default: {
179346      assert( pNode->eType==JSON_NULL );
179347      sqlite3_result_null(pCtx);
179348      break;
179349    }
179350    case JSON_TRUE: {
179351      sqlite3_result_int(pCtx, 1);
179352      break;
179353    }
179354    case JSON_FALSE: {
179355      sqlite3_result_int(pCtx, 0);
179356      break;
179357    }
179358    case JSON_INT: {
179359      sqlite3_int64 i = 0;
179360      const char *z = pNode->u.zJContent;
179361      if( z[0]=='-' ){ z++; }
179362      while( z[0]>='0' && z[0]<='9' ){
179363        unsigned v = *(z++) - '0';
179364        if( i>=LARGEST_INT64/10 ){
179365          if( i>LARGEST_INT64/10 ) goto int_as_real;
179366          if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
179367          if( v==9 ) goto int_as_real;
179368          if( v==8 ){
179369            if( pNode->u.zJContent[0]=='-' ){
179370              sqlite3_result_int64(pCtx, SMALLEST_INT64);
179371              goto int_done;
179372            }else{
179373              goto int_as_real;
179374            }
179375          }
179376        }
179377        i = i*10 + v;
179378      }
179379      if( pNode->u.zJContent[0]=='-' ){ i = -i; }
179380      sqlite3_result_int64(pCtx, i);
179381      int_done:
179382      break;
179383      int_as_real: /* fall through to real */;
179384    }
179385    case JSON_REAL: {
179386      double r;
179387#ifdef SQLITE_AMALGAMATION
179388      const char *z = pNode->u.zJContent;
179389      sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
179390#else
179391      r = strtod(pNode->u.zJContent, 0);
179392#endif
179393      sqlite3_result_double(pCtx, r);
179394      break;
179395    }
179396    case JSON_STRING: {
179397#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
179398      ** json_insert() and json_replace() and those routines do not
179399      ** call jsonReturn() */
179400      if( pNode->jnFlags & JNODE_RAW ){
179401        sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
179402                            SQLITE_TRANSIENT);
179403      }else
179404#endif
179405      assert( (pNode->jnFlags & JNODE_RAW)==0 );
179406      if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
179407        /* JSON formatted without any backslash-escapes */
179408        sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
179409                            SQLITE_TRANSIENT);
179410      }else{
179411        /* Translate JSON formatted string into raw text */
179412        u32 i;
179413        u32 n = pNode->n;
179414        const char *z = pNode->u.zJContent;
179415        char *zOut;
179416        u32 j;
179417        zOut = sqlite3_malloc( n+1 );
179418        if( zOut==0 ){
179419          sqlite3_result_error_nomem(pCtx);
179420          break;
179421        }
179422        for(i=1, j=0; i<n-1; i++){
179423          char c = z[i];
179424          if( c!='\\' ){
179425            zOut[j++] = c;
179426          }else{
179427            c = z[++i];
179428            if( c=='u' ){
179429              u32 v = 0, k;
179430              for(k=0; k<4; i++, k++){
179431                assert( i<n-2 );
179432                c = z[i+1];
179433                assert( safe_isxdigit(c) );
179434                if( c<='9' ) v = v*16 + c - '0';
179435                else if( c<='F' ) v = v*16 + c - 'A' + 10;
179436                else v = v*16 + c - 'a' + 10;
179437              }
179438              if( v==0 ) break;
179439              if( v<=0x7f ){
179440                zOut[j++] = (char)v;
179441              }else if( v<=0x7ff ){
179442                zOut[j++] = (char)(0xc0 | (v>>6));
179443                zOut[j++] = 0x80 | (v&0x3f);
179444              }else{
179445                zOut[j++] = (char)(0xe0 | (v>>12));
179446                zOut[j++] = 0x80 | ((v>>6)&0x3f);
179447                zOut[j++] = 0x80 | (v&0x3f);
179448              }
179449            }else{
179450              if( c=='b' ){
179451                c = '\b';
179452              }else if( c=='f' ){
179453                c = '\f';
179454              }else if( c=='n' ){
179455                c = '\n';
179456              }else if( c=='r' ){
179457                c = '\r';
179458              }else if( c=='t' ){
179459                c = '\t';
179460              }
179461              zOut[j++] = c;
179462            }
179463          }
179464        }
179465        zOut[j] = 0;
179466        sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
179467      }
179468      break;
179469    }
179470    case JSON_ARRAY:
179471    case JSON_OBJECT: {
179472      jsonReturnJson(pNode, pCtx, aReplace);
179473      break;
179474    }
179475  }
179476}
179477
179478/* Forward reference */
179479static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
179480
179481/*
179482** A macro to hint to the compiler that a function should not be
179483** inlined.
179484*/
179485#if defined(__GNUC__)
179486#  define JSON_NOINLINE  __attribute__((noinline))
179487#elif defined(_MSC_VER) && _MSC_VER>=1310
179488#  define JSON_NOINLINE  __declspec(noinline)
179489#else
179490#  define JSON_NOINLINE
179491#endif
179492
179493
179494static JSON_NOINLINE int jsonParseAddNodeExpand(
179495  JsonParse *pParse,        /* Append the node to this object */
179496  u32 eType,                /* Node type */
179497  u32 n,                    /* Content size or sub-node count */
179498  const char *zContent      /* Content */
179499){
179500  u32 nNew;
179501  JsonNode *pNew;
179502  assert( pParse->nNode>=pParse->nAlloc );
179503  if( pParse->oom ) return -1;
179504  nNew = pParse->nAlloc*2 + 10;
179505  pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
179506  if( pNew==0 ){
179507    pParse->oom = 1;
179508    return -1;
179509  }
179510  pParse->nAlloc = nNew;
179511  pParse->aNode = pNew;
179512  assert( pParse->nNode<pParse->nAlloc );
179513  return jsonParseAddNode(pParse, eType, n, zContent);
179514}
179515
179516/*
179517** Create a new JsonNode instance based on the arguments and append that
179518** instance to the JsonParse.  Return the index in pParse->aNode[] of the
179519** new node, or -1 if a memory allocation fails.
179520*/
179521static int jsonParseAddNode(
179522  JsonParse *pParse,        /* Append the node to this object */
179523  u32 eType,                /* Node type */
179524  u32 n,                    /* Content size or sub-node count */
179525  const char *zContent      /* Content */
179526){
179527  JsonNode *p;
179528  if( pParse->nNode>=pParse->nAlloc ){
179529    return jsonParseAddNodeExpand(pParse, eType, n, zContent);
179530  }
179531  p = &pParse->aNode[pParse->nNode];
179532  p->eType = (u8)eType;
179533  p->jnFlags = 0;
179534  p->n = n;
179535  p->u.zJContent = zContent;
179536  return pParse->nNode++;
179537}
179538
179539/*
179540** Return true if z[] begins with 4 (or more) hexadecimal digits
179541*/
179542static int jsonIs4Hex(const char *z){
179543  int i;
179544  for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
179545  return 1;
179546}
179547
179548/*
179549** Parse a single JSON value which begins at pParse->zJson[i].  Return the
179550** index of the first character past the end of the value parsed.
179551**
179552** Return negative for a syntax error.  Special cases:  return -2 if the
179553** first non-whitespace character is '}' and return -3 if the first
179554** non-whitespace character is ']'.
179555*/
179556static int jsonParseValue(JsonParse *pParse, u32 i){
179557  char c;
179558  u32 j;
179559  int iThis;
179560  int x;
179561  JsonNode *pNode;
179562  while( safe_isspace(pParse->zJson[i]) ){ i++; }
179563  if( (c = pParse->zJson[i])=='{' ){
179564    /* Parse object */
179565    iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
179566    if( iThis<0 ) return -1;
179567    for(j=i+1;;j++){
179568      while( safe_isspace(pParse->zJson[j]) ){ j++; }
179569      x = jsonParseValue(pParse, j);
179570      if( x<0 ){
179571        if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
179572        return -1;
179573      }
179574      if( pParse->oom ) return -1;
179575      pNode = &pParse->aNode[pParse->nNode-1];
179576      if( pNode->eType!=JSON_STRING ) return -1;
179577      pNode->jnFlags |= JNODE_LABEL;
179578      j = x;
179579      while( safe_isspace(pParse->zJson[j]) ){ j++; }
179580      if( pParse->zJson[j]!=':' ) return -1;
179581      j++;
179582      x = jsonParseValue(pParse, j);
179583      if( x<0 ) return -1;
179584      j = x;
179585      while( safe_isspace(pParse->zJson[j]) ){ j++; }
179586      c = pParse->zJson[j];
179587      if( c==',' ) continue;
179588      if( c!='}' ) return -1;
179589      break;
179590    }
179591    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
179592    return j+1;
179593  }else if( c=='[' ){
179594    /* Parse array */
179595    iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
179596    if( iThis<0 ) return -1;
179597    for(j=i+1;;j++){
179598      while( safe_isspace(pParse->zJson[j]) ){ j++; }
179599      x = jsonParseValue(pParse, j);
179600      if( x<0 ){
179601        if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
179602        return -1;
179603      }
179604      j = x;
179605      while( safe_isspace(pParse->zJson[j]) ){ j++; }
179606      c = pParse->zJson[j];
179607      if( c==',' ) continue;
179608      if( c!=']' ) return -1;
179609      break;
179610    }
179611    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
179612    return j+1;
179613  }else if( c=='"' ){
179614    /* Parse string */
179615    u8 jnFlags = 0;
179616    j = i+1;
179617    for(;;){
179618      c = pParse->zJson[j];
179619      if( c==0 ) return -1;
179620      if( c=='\\' ){
179621        c = pParse->zJson[++j];
179622        if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
179623           || c=='n' || c=='r' || c=='t'
179624           || (c=='u' && jsonIs4Hex(pParse->zJson+j+1)) ){
179625          jnFlags = JNODE_ESCAPE;
179626        }else{
179627          return -1;
179628        }
179629      }else if( c=='"' ){
179630        break;
179631      }
179632      j++;
179633    }
179634    jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
179635    if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
179636    return j+1;
179637  }else if( c=='n'
179638         && strncmp(pParse->zJson+i,"null",4)==0
179639         && !safe_isalnum(pParse->zJson[i+4]) ){
179640    jsonParseAddNode(pParse, JSON_NULL, 0, 0);
179641    return i+4;
179642  }else if( c=='t'
179643         && strncmp(pParse->zJson+i,"true",4)==0
179644         && !safe_isalnum(pParse->zJson[i+4]) ){
179645    jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
179646    return i+4;
179647  }else if( c=='f'
179648         && strncmp(pParse->zJson+i,"false",5)==0
179649         && !safe_isalnum(pParse->zJson[i+5]) ){
179650    jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
179651    return i+5;
179652  }else if( c=='-' || (c>='0' && c<='9') ){
179653    /* Parse number */
179654    u8 seenDP = 0;
179655    u8 seenE = 0;
179656    j = i+1;
179657    for(;; j++){
179658      c = pParse->zJson[j];
179659      if( c>='0' && c<='9' ) continue;
179660      if( c=='.' ){
179661        if( pParse->zJson[j-1]=='-' ) return -1;
179662        if( seenDP ) return -1;
179663        seenDP = 1;
179664        continue;
179665      }
179666      if( c=='e' || c=='E' ){
179667        if( pParse->zJson[j-1]<'0' ) return -1;
179668        if( seenE ) return -1;
179669        seenDP = seenE = 1;
179670        c = pParse->zJson[j+1];
179671        if( c=='+' || c=='-' ){
179672          j++;
179673          c = pParse->zJson[j+1];
179674        }
179675        if( c<'0' || c>'9' ) return -1;
179676        continue;
179677      }
179678      break;
179679    }
179680    if( pParse->zJson[j-1]<'0' ) return -1;
179681    jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
179682                        j - i, &pParse->zJson[i]);
179683    return j;
179684  }else if( c=='}' ){
179685    return -2;  /* End of {...} */
179686  }else if( c==']' ){
179687    return -3;  /* End of [...] */
179688  }else if( c==0 ){
179689    return 0;   /* End of file */
179690  }else{
179691    return -1;  /* Syntax error */
179692  }
179693}
179694
179695/*
179696** Parse a complete JSON string.  Return 0 on success or non-zero if there
179697** are any errors.  If an error occurs, free all memory associated with
179698** pParse.
179699**
179700** pParse is uninitialized when this routine is called.
179701*/
179702static int jsonParse(
179703  JsonParse *pParse,           /* Initialize and fill this JsonParse object */
179704  sqlite3_context *pCtx,       /* Report errors here */
179705  const char *zJson            /* Input JSON text to be parsed */
179706){
179707  int i;
179708  memset(pParse, 0, sizeof(*pParse));
179709  if( zJson==0 ) return 1;
179710  pParse->zJson = zJson;
179711  i = jsonParseValue(pParse, 0);
179712  if( pParse->oom ) i = -1;
179713  if( i>0 ){
179714    while( safe_isspace(zJson[i]) ) i++;
179715    if( zJson[i] ) i = -1;
179716  }
179717  if( i<=0 ){
179718    if( pCtx!=0 ){
179719      if( pParse->oom ){
179720        sqlite3_result_error_nomem(pCtx);
179721      }else{
179722        sqlite3_result_error(pCtx, "malformed JSON", -1);
179723      }
179724    }
179725    jsonParseReset(pParse);
179726    return 1;
179727  }
179728  return 0;
179729}
179730
179731/* Mark node i of pParse as being a child of iParent.  Call recursively
179732** to fill in all the descendants of node i.
179733*/
179734static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
179735  JsonNode *pNode = &pParse->aNode[i];
179736  u32 j;
179737  pParse->aUp[i] = iParent;
179738  switch( pNode->eType ){
179739    case JSON_ARRAY: {
179740      for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
179741        jsonParseFillInParentage(pParse, i+j, i);
179742      }
179743      break;
179744    }
179745    case JSON_OBJECT: {
179746      for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
179747        pParse->aUp[i+j] = i;
179748        jsonParseFillInParentage(pParse, i+j+1, i);
179749      }
179750      break;
179751    }
179752    default: {
179753      break;
179754    }
179755  }
179756}
179757
179758/*
179759** Compute the parentage of all nodes in a completed parse.
179760*/
179761static int jsonParseFindParents(JsonParse *pParse){
179762  u32 *aUp;
179763  assert( pParse->aUp==0 );
179764  aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
179765  if( aUp==0 ){
179766    pParse->oom = 1;
179767    return SQLITE_NOMEM;
179768  }
179769  jsonParseFillInParentage(pParse, 0, 0);
179770  return SQLITE_OK;
179771}
179772
179773/*
179774** Compare the OBJECT label at pNode against zKey,nKey.  Return true on
179775** a match.
179776*/
179777static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
179778  if( pNode->jnFlags & JNODE_RAW ){
179779    if( pNode->n!=nKey ) return 0;
179780    return strncmp(pNode->u.zJContent, zKey, nKey)==0;
179781  }else{
179782    if( pNode->n!=nKey+2 ) return 0;
179783    return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
179784  }
179785}
179786
179787/* forward declaration */
179788static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
179789
179790/*
179791** Search along zPath to find the node specified.  Return a pointer
179792** to that node, or NULL if zPath is malformed or if there is no such
179793** node.
179794**
179795** If pApnd!=0, then try to append new nodes to complete zPath if it is
179796** possible to do so and if no existing node corresponds to zPath.  If
179797** new nodes are appended *pApnd is set to 1.
179798*/
179799static JsonNode *jsonLookupStep(
179800  JsonParse *pParse,      /* The JSON to search */
179801  u32 iRoot,              /* Begin the search at this node */
179802  const char *zPath,      /* The path to search */
179803  int *pApnd,             /* Append nodes to complete path if not NULL */
179804  const char **pzErr      /* Make *pzErr point to any syntax error in zPath */
179805){
179806  u32 i, j, nKey;
179807  const char *zKey;
179808  JsonNode *pRoot = &pParse->aNode[iRoot];
179809  if( zPath[0]==0 ) return pRoot;
179810  if( zPath[0]=='.' ){
179811    if( pRoot->eType!=JSON_OBJECT ) return 0;
179812    zPath++;
179813    if( zPath[0]=='"' ){
179814      zKey = zPath + 1;
179815      for(i=1; zPath[i] && zPath[i]!='"'; i++){}
179816      nKey = i-1;
179817      if( zPath[i] ){
179818        i++;
179819      }else{
179820        *pzErr = zPath;
179821        return 0;
179822      }
179823    }else{
179824      zKey = zPath;
179825      for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
179826      nKey = i;
179827    }
179828    if( nKey==0 ){
179829      *pzErr = zPath;
179830      return 0;
179831    }
179832    j = 1;
179833    for(;;){
179834      while( j<=pRoot->n ){
179835        if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
179836          return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
179837        }
179838        j++;
179839        j += jsonNodeSize(&pRoot[j]);
179840      }
179841      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
179842      iRoot += pRoot->u.iAppend;
179843      pRoot = &pParse->aNode[iRoot];
179844      j = 1;
179845    }
179846    if( pApnd ){
179847      u32 iStart, iLabel;
179848      JsonNode *pNode;
179849      iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
179850      iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
179851      zPath += i;
179852      pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
179853      if( pParse->oom ) return 0;
179854      if( pNode ){
179855        pRoot = &pParse->aNode[iRoot];
179856        pRoot->u.iAppend = iStart - iRoot;
179857        pRoot->jnFlags |= JNODE_APPEND;
179858        pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
179859      }
179860      return pNode;
179861    }
179862  }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
179863    if( pRoot->eType!=JSON_ARRAY ) return 0;
179864    i = 0;
179865    j = 1;
179866    while( safe_isdigit(zPath[j]) ){
179867      i = i*10 + zPath[j] - '0';
179868      j++;
179869    }
179870    if( zPath[j]!=']' ){
179871      *pzErr = zPath;
179872      return 0;
179873    }
179874    zPath += j + 1;
179875    j = 1;
179876    for(;;){
179877      while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
179878        if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
179879        j += jsonNodeSize(&pRoot[j]);
179880      }
179881      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
179882      iRoot += pRoot->u.iAppend;
179883      pRoot = &pParse->aNode[iRoot];
179884      j = 1;
179885    }
179886    if( j<=pRoot->n ){
179887      return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
179888    }
179889    if( i==0 && pApnd ){
179890      u32 iStart;
179891      JsonNode *pNode;
179892      iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
179893      pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
179894      if( pParse->oom ) return 0;
179895      if( pNode ){
179896        pRoot = &pParse->aNode[iRoot];
179897        pRoot->u.iAppend = iStart - iRoot;
179898        pRoot->jnFlags |= JNODE_APPEND;
179899      }
179900      return pNode;
179901    }
179902  }else{
179903    *pzErr = zPath;
179904  }
179905  return 0;
179906}
179907
179908/*
179909** Append content to pParse that will complete zPath.  Return a pointer
179910** to the inserted node, or return NULL if the append fails.
179911*/
179912static JsonNode *jsonLookupAppend(
179913  JsonParse *pParse,     /* Append content to the JSON parse */
179914  const char *zPath,     /* Description of content to append */
179915  int *pApnd,            /* Set this flag to 1 */
179916  const char **pzErr     /* Make this point to any syntax error */
179917){
179918  *pApnd = 1;
179919  if( zPath[0]==0 ){
179920    jsonParseAddNode(pParse, JSON_NULL, 0, 0);
179921    return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
179922  }
179923  if( zPath[0]=='.' ){
179924    jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
179925  }else if( strncmp(zPath,"[0]",3)==0 ){
179926    jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
179927  }else{
179928    return 0;
179929  }
179930  if( pParse->oom ) return 0;
179931  return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
179932}
179933
179934/*
179935** Return the text of a syntax error message on a JSON path.  Space is
179936** obtained from sqlite3_malloc().
179937*/
179938static char *jsonPathSyntaxError(const char *zErr){
179939  return sqlite3_mprintf("JSON path error near '%q'", zErr);
179940}
179941
179942/*
179943** Do a node lookup using zPath.  Return a pointer to the node on success.
179944** Return NULL if not found or if there is an error.
179945**
179946** On an error, write an error message into pCtx and increment the
179947** pParse->nErr counter.
179948**
179949** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
179950** nodes are appended.
179951*/
179952static JsonNode *jsonLookup(
179953  JsonParse *pParse,      /* The JSON to search */
179954  const char *zPath,      /* The path to search */
179955  int *pApnd,             /* Append nodes to complete path if not NULL */
179956  sqlite3_context *pCtx   /* Report errors here, if not NULL */
179957){
179958  const char *zErr = 0;
179959  JsonNode *pNode = 0;
179960  char *zMsg;
179961
179962  if( zPath==0 ) return 0;
179963  if( zPath[0]!='$' ){
179964    zErr = zPath;
179965    goto lookup_err;
179966  }
179967  zPath++;
179968  pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
179969  if( zErr==0 ) return pNode;
179970
179971lookup_err:
179972  pParse->nErr++;
179973  assert( zErr!=0 && pCtx!=0 );
179974  zMsg = jsonPathSyntaxError(zErr);
179975  if( zMsg ){
179976    sqlite3_result_error(pCtx, zMsg, -1);
179977    sqlite3_free(zMsg);
179978  }else{
179979    sqlite3_result_error_nomem(pCtx);
179980  }
179981  return 0;
179982}
179983
179984
179985/*
179986** Report the wrong number of arguments for json_insert(), json_replace()
179987** or json_set().
179988*/
179989static void jsonWrongNumArgs(
179990  sqlite3_context *pCtx,
179991  const char *zFuncName
179992){
179993  char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
179994                               zFuncName);
179995  sqlite3_result_error(pCtx, zMsg, -1);
179996  sqlite3_free(zMsg);
179997}
179998
179999/*
180000** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
180001*/
180002static void jsonRemoveAllNulls(JsonNode *pNode){
180003  int i, n;
180004  assert( pNode->eType==JSON_OBJECT );
180005  n = pNode->n;
180006  for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
180007    switch( pNode[i].eType ){
180008      case JSON_NULL:
180009        pNode[i].jnFlags |= JNODE_REMOVE;
180010        break;
180011      case JSON_OBJECT:
180012        jsonRemoveAllNulls(&pNode[i]);
180013        break;
180014    }
180015  }
180016}
180017
180018
180019/****************************************************************************
180020** SQL functions used for testing and debugging
180021****************************************************************************/
180022
180023#ifdef SQLITE_DEBUG
180024/*
180025** The json_parse(JSON) function returns a string which describes
180026** a parse of the JSON provided.  Or it returns NULL if JSON is not
180027** well-formed.
180028*/
180029static void jsonParseFunc(
180030  sqlite3_context *ctx,
180031  int argc,
180032  sqlite3_value **argv
180033){
180034  JsonString s;       /* Output string - not real JSON */
180035  JsonParse x;        /* The parse */
180036  u32 i;
180037
180038  assert( argc==1 );
180039  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
180040  jsonParseFindParents(&x);
180041  jsonInit(&s, ctx);
180042  for(i=0; i<x.nNode; i++){
180043    const char *zType;
180044    if( x.aNode[i].jnFlags & JNODE_LABEL ){
180045      assert( x.aNode[i].eType==JSON_STRING );
180046      zType = "label";
180047    }else{
180048      zType = jsonType[x.aNode[i].eType];
180049    }
180050    jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
180051               i, zType, x.aNode[i].n, x.aUp[i]);
180052    if( x.aNode[i].u.zJContent!=0 ){
180053      jsonAppendRaw(&s, " ", 1);
180054      jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
180055    }
180056    jsonAppendRaw(&s, "\n", 1);
180057  }
180058  jsonParseReset(&x);
180059  jsonResult(&s);
180060}
180061
180062/*
180063** The json_test1(JSON) function return true (1) if the input is JSON
180064** text generated by another json function.  It returns (0) if the input
180065** is not known to be JSON.
180066*/
180067static void jsonTest1Func(
180068  sqlite3_context *ctx,
180069  int argc,
180070  sqlite3_value **argv
180071){
180072  UNUSED_PARAM(argc);
180073  sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
180074}
180075#endif /* SQLITE_DEBUG */
180076
180077/****************************************************************************
180078** Scalar SQL function implementations
180079****************************************************************************/
180080
180081/*
180082** Implementation of the json_QUOTE(VALUE) function.  Return a JSON value
180083** corresponding to the SQL value input.  Mostly this means putting
180084** double-quotes around strings and returning the unquoted string "null"
180085** when given a NULL input.
180086*/
180087static void jsonQuoteFunc(
180088  sqlite3_context *ctx,
180089  int argc,
180090  sqlite3_value **argv
180091){
180092  JsonString jx;
180093  UNUSED_PARAM(argc);
180094
180095  jsonInit(&jx, ctx);
180096  jsonAppendValue(&jx, argv[0]);
180097  jsonResult(&jx);
180098  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
180099}
180100
180101/*
180102** Implementation of the json_array(VALUE,...) function.  Return a JSON
180103** array that contains all values given in arguments.  Or if any argument
180104** is a BLOB, throw an error.
180105*/
180106static void jsonArrayFunc(
180107  sqlite3_context *ctx,
180108  int argc,
180109  sqlite3_value **argv
180110){
180111  int i;
180112  JsonString jx;
180113
180114  jsonInit(&jx, ctx);
180115  jsonAppendChar(&jx, '[');
180116  for(i=0; i<argc; i++){
180117    jsonAppendSeparator(&jx);
180118    jsonAppendValue(&jx, argv[i]);
180119  }
180120  jsonAppendChar(&jx, ']');
180121  jsonResult(&jx);
180122  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
180123}
180124
180125
180126/*
180127** json_array_length(JSON)
180128** json_array_length(JSON, PATH)
180129**
180130** Return the number of elements in the top-level JSON array.
180131** Return 0 if the input is not a well-formed JSON array.
180132*/
180133static void jsonArrayLengthFunc(
180134  sqlite3_context *ctx,
180135  int argc,
180136  sqlite3_value **argv
180137){
180138  JsonParse x;          /* The parse */
180139  sqlite3_int64 n = 0;
180140  u32 i;
180141  JsonNode *pNode;
180142
180143  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
180144  assert( x.nNode );
180145  if( argc==2 ){
180146    const char *zPath = (const char*)sqlite3_value_text(argv[1]);
180147    pNode = jsonLookup(&x, zPath, 0, ctx);
180148  }else{
180149    pNode = x.aNode;
180150  }
180151  if( pNode==0 ){
180152    x.nErr = 1;
180153  }else if( pNode->eType==JSON_ARRAY ){
180154    assert( (pNode->jnFlags & JNODE_APPEND)==0 );
180155    for(i=1; i<=pNode->n; n++){
180156      i += jsonNodeSize(&pNode[i]);
180157    }
180158  }
180159  if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
180160  jsonParseReset(&x);
180161}
180162
180163/*
180164** json_extract(JSON, PATH, ...)
180165**
180166** Return the element described by PATH.  Return NULL if there is no
180167** PATH element.  If there are multiple PATHs, then return a JSON array
180168** with the result from each path.  Throw an error if the JSON or any PATH
180169** is malformed.
180170*/
180171static void jsonExtractFunc(
180172  sqlite3_context *ctx,
180173  int argc,
180174  sqlite3_value **argv
180175){
180176  JsonParse x;          /* The parse */
180177  JsonNode *pNode;
180178  const char *zPath;
180179  JsonString jx;
180180  int i;
180181
180182  if( argc<2 ) return;
180183  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
180184  jsonInit(&jx, ctx);
180185  jsonAppendChar(&jx, '[');
180186  for(i=1; i<argc; i++){
180187    zPath = (const char*)sqlite3_value_text(argv[i]);
180188    pNode = jsonLookup(&x, zPath, 0, ctx);
180189    if( x.nErr ) break;
180190    if( argc>2 ){
180191      jsonAppendSeparator(&jx);
180192      if( pNode ){
180193        jsonRenderNode(pNode, &jx, 0);
180194      }else{
180195        jsonAppendRaw(&jx, "null", 4);
180196      }
180197    }else if( pNode ){
180198      jsonReturn(pNode, ctx, 0);
180199    }
180200  }
180201  if( argc>2 && i==argc ){
180202    jsonAppendChar(&jx, ']');
180203    jsonResult(&jx);
180204    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
180205  }
180206  jsonReset(&jx);
180207  jsonParseReset(&x);
180208}
180209
180210/* This is the RFC 7396 MergePatch algorithm.
180211*/
180212static JsonNode *jsonMergePatch(
180213  JsonParse *pParse,   /* The JSON parser that contains the TARGET */
180214  int iTarget,         /* Node of the TARGET in pParse */
180215  JsonNode *pPatch     /* The PATCH */
180216){
180217  u32 i, j;
180218  u32 iRoot;
180219  JsonNode *pTarget;
180220  if( pPatch->eType!=JSON_OBJECT ){
180221    return pPatch;
180222  }
180223  assert( iTarget>=0 && iTarget<pParse->nNode );
180224  pTarget = &pParse->aNode[iTarget];
180225  assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
180226  if( pTarget->eType!=JSON_OBJECT ){
180227    jsonRemoveAllNulls(pPatch);
180228    return pPatch;
180229  }
180230  iRoot = iTarget;
180231  for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
180232    u32 nKey;
180233    const char *zKey;
180234    assert( pPatch[i].eType==JSON_STRING );
180235    assert( pPatch[i].jnFlags & JNODE_LABEL );
180236    nKey = pPatch[i].n;
180237    zKey = pPatch[i].u.zJContent;
180238    assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
180239    for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
180240      assert( pTarget[j].eType==JSON_STRING );
180241      assert( pTarget[j].jnFlags & JNODE_LABEL );
180242      assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
180243      if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
180244        if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
180245        if( pPatch[i+1].eType==JSON_NULL ){
180246          pTarget[j+1].jnFlags |= JNODE_REMOVE;
180247        }else{
180248          JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
180249          if( pNew==0 ) return 0;
180250          pTarget = &pParse->aNode[iTarget];
180251          if( pNew!=&pTarget[j+1] ){
180252            pTarget[j+1].u.pPatch = pNew;
180253            pTarget[j+1].jnFlags |= JNODE_PATCH;
180254          }
180255        }
180256        break;
180257      }
180258    }
180259    if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
180260      int iStart, iPatch;
180261      iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
180262      jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
180263      iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
180264      if( pParse->oom ) return 0;
180265      jsonRemoveAllNulls(pPatch);
180266      pTarget = &pParse->aNode[iTarget];
180267      pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
180268      pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
180269      iRoot = iStart;
180270      pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
180271      pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
180272    }
180273  }
180274  return pTarget;
180275}
180276
180277/*
180278** Implementation of the json_mergepatch(JSON1,JSON2) function.  Return a JSON
180279** object that is the result of running the RFC 7396 MergePatch() algorithm
180280** on the two arguments.
180281*/
180282static void jsonPatchFunc(
180283  sqlite3_context *ctx,
180284  int argc,
180285  sqlite3_value **argv
180286){
180287  JsonParse x;     /* The JSON that is being patched */
180288  JsonParse y;     /* The patch */
180289  JsonNode *pResult;   /* The result of the merge */
180290
180291  UNUSED_PARAM(argc);
180292  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
180293  if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
180294    jsonParseReset(&x);
180295    return;
180296  }
180297  pResult = jsonMergePatch(&x, 0, y.aNode);
180298  assert( pResult!=0 || x.oom );
180299  if( pResult ){
180300    jsonReturnJson(pResult, ctx, 0);
180301  }else{
180302    sqlite3_result_error_nomem(ctx);
180303  }
180304  jsonParseReset(&x);
180305  jsonParseReset(&y);
180306}
180307
180308
180309/*
180310** Implementation of the json_object(NAME,VALUE,...) function.  Return a JSON
180311** object that contains all name/value given in arguments.  Or if any name
180312** is not a string or if any value is a BLOB, throw an error.
180313*/
180314static void jsonObjectFunc(
180315  sqlite3_context *ctx,
180316  int argc,
180317  sqlite3_value **argv
180318){
180319  int i;
180320  JsonString jx;
180321  const char *z;
180322  u32 n;
180323
180324  if( argc&1 ){
180325    sqlite3_result_error(ctx, "json_object() requires an even number "
180326                                  "of arguments", -1);
180327    return;
180328  }
180329  jsonInit(&jx, ctx);
180330  jsonAppendChar(&jx, '{');
180331  for(i=0; i<argc; i+=2){
180332    if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
180333      sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
180334      jsonReset(&jx);
180335      return;
180336    }
180337    jsonAppendSeparator(&jx);
180338    z = (const char*)sqlite3_value_text(argv[i]);
180339    n = (u32)sqlite3_value_bytes(argv[i]);
180340    jsonAppendString(&jx, z, n);
180341    jsonAppendChar(&jx, ':');
180342    jsonAppendValue(&jx, argv[i+1]);
180343  }
180344  jsonAppendChar(&jx, '}');
180345  jsonResult(&jx);
180346  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
180347}
180348
180349
180350/*
180351** json_remove(JSON, PATH, ...)
180352**
180353** Remove the named elements from JSON and return the result.  malformed
180354** JSON or PATH arguments result in an error.
180355*/
180356static void jsonRemoveFunc(
180357  sqlite3_context *ctx,
180358  int argc,
180359  sqlite3_value **argv
180360){
180361  JsonParse x;          /* The parse */
180362  JsonNode *pNode;
180363  const char *zPath;
180364  u32 i;
180365
180366  if( argc<1 ) return;
180367  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
180368  assert( x.nNode );
180369  for(i=1; i<(u32)argc; i++){
180370    zPath = (const char*)sqlite3_value_text(argv[i]);
180371    if( zPath==0 ) goto remove_done;
180372    pNode = jsonLookup(&x, zPath, 0, ctx);
180373    if( x.nErr ) goto remove_done;
180374    if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
180375  }
180376  if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
180377    jsonReturnJson(x.aNode, ctx, 0);
180378  }
180379remove_done:
180380  jsonParseReset(&x);
180381}
180382
180383/*
180384** json_replace(JSON, PATH, VALUE, ...)
180385**
180386** Replace the value at PATH with VALUE.  If PATH does not already exist,
180387** this routine is a no-op.  If JSON or PATH is malformed, throw an error.
180388*/
180389static void jsonReplaceFunc(
180390  sqlite3_context *ctx,
180391  int argc,
180392  sqlite3_value **argv
180393){
180394  JsonParse x;          /* The parse */
180395  JsonNode *pNode;
180396  const char *zPath;
180397  u32 i;
180398
180399  if( argc<1 ) return;
180400  if( (argc&1)==0 ) {
180401    jsonWrongNumArgs(ctx, "replace");
180402    return;
180403  }
180404  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
180405  assert( x.nNode );
180406  for(i=1; i<(u32)argc; i+=2){
180407    zPath = (const char*)sqlite3_value_text(argv[i]);
180408    pNode = jsonLookup(&x, zPath, 0, ctx);
180409    if( x.nErr ) goto replace_err;
180410    if( pNode ){
180411      pNode->jnFlags |= (u8)JNODE_REPLACE;
180412      pNode->u.iReplace = i + 1;
180413    }
180414  }
180415  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
180416    sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
180417  }else{
180418    jsonReturnJson(x.aNode, ctx, argv);
180419  }
180420replace_err:
180421  jsonParseReset(&x);
180422}
180423
180424/*
180425** json_set(JSON, PATH, VALUE, ...)
180426**
180427** Set the value at PATH to VALUE.  Create the PATH if it does not already
180428** exist.  Overwrite existing values that do exist.
180429** If JSON or PATH is malformed, throw an error.
180430**
180431** json_insert(JSON, PATH, VALUE, ...)
180432**
180433** Create PATH and initialize it to VALUE.  If PATH already exists, this
180434** routine is a no-op.  If JSON or PATH is malformed, throw an error.
180435*/
180436static void jsonSetFunc(
180437  sqlite3_context *ctx,
180438  int argc,
180439  sqlite3_value **argv
180440){
180441  JsonParse x;          /* The parse */
180442  JsonNode *pNode;
180443  const char *zPath;
180444  u32 i;
180445  int bApnd;
180446  int bIsSet = *(int*)sqlite3_user_data(ctx);
180447
180448  if( argc<1 ) return;
180449  if( (argc&1)==0 ) {
180450    jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
180451    return;
180452  }
180453  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
180454  assert( x.nNode );
180455  for(i=1; i<(u32)argc; i+=2){
180456    zPath = (const char*)sqlite3_value_text(argv[i]);
180457    bApnd = 0;
180458    pNode = jsonLookup(&x, zPath, &bApnd, ctx);
180459    if( x.oom ){
180460      sqlite3_result_error_nomem(ctx);
180461      goto jsonSetDone;
180462    }else if( x.nErr ){
180463      goto jsonSetDone;
180464    }else if( pNode && (bApnd || bIsSet) ){
180465      pNode->jnFlags |= (u8)JNODE_REPLACE;
180466      pNode->u.iReplace = i + 1;
180467    }
180468  }
180469  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
180470    sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
180471  }else{
180472    jsonReturnJson(x.aNode, ctx, argv);
180473  }
180474jsonSetDone:
180475  jsonParseReset(&x);
180476}
180477
180478/*
180479** json_type(JSON)
180480** json_type(JSON, PATH)
180481**
180482** Return the top-level "type" of a JSON string.  Throw an error if
180483** either the JSON or PATH inputs are not well-formed.
180484*/
180485static void jsonTypeFunc(
180486  sqlite3_context *ctx,
180487  int argc,
180488  sqlite3_value **argv
180489){
180490  JsonParse x;          /* The parse */
180491  const char *zPath;
180492  JsonNode *pNode;
180493
180494  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
180495  assert( x.nNode );
180496  if( argc==2 ){
180497    zPath = (const char*)sqlite3_value_text(argv[1]);
180498    pNode = jsonLookup(&x, zPath, 0, ctx);
180499  }else{
180500    pNode = x.aNode;
180501  }
180502  if( pNode ){
180503    sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
180504  }
180505  jsonParseReset(&x);
180506}
180507
180508/*
180509** json_valid(JSON)
180510**
180511** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
180512** Return 0 otherwise.
180513*/
180514static void jsonValidFunc(
180515  sqlite3_context *ctx,
180516  int argc,
180517  sqlite3_value **argv
180518){
180519  JsonParse x;          /* The parse */
180520  int rc = 0;
180521
180522  UNUSED_PARAM(argc);
180523  if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
180524    rc = 1;
180525  }
180526  jsonParseReset(&x);
180527  sqlite3_result_int(ctx, rc);
180528}
180529
180530
180531/****************************************************************************
180532** Aggregate SQL function implementations
180533****************************************************************************/
180534/*
180535** json_group_array(VALUE)
180536**
180537** Return a JSON array composed of all values in the aggregate.
180538*/
180539static void jsonArrayStep(
180540  sqlite3_context *ctx,
180541  int argc,
180542  sqlite3_value **argv
180543){
180544  JsonString *pStr;
180545  UNUSED_PARAM(argc);
180546  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
180547  if( pStr ){
180548    if( pStr->zBuf==0 ){
180549      jsonInit(pStr, ctx);
180550      jsonAppendChar(pStr, '[');
180551    }else{
180552      jsonAppendChar(pStr, ',');
180553      pStr->pCtx = ctx;
180554    }
180555    jsonAppendValue(pStr, argv[0]);
180556  }
180557}
180558static void jsonArrayFinal(sqlite3_context *ctx){
180559  JsonString *pStr;
180560  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
180561  if( pStr ){
180562    pStr->pCtx = ctx;
180563    jsonAppendChar(pStr, ']');
180564    if( pStr->bErr ){
180565      if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
180566      assert( pStr->bStatic );
180567    }else{
180568      sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
180569                          pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
180570      pStr->bStatic = 1;
180571    }
180572  }else{
180573    sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
180574  }
180575  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
180576}
180577
180578/*
180579** json_group_obj(NAME,VALUE)
180580**
180581** Return a JSON object composed of all names and values in the aggregate.
180582*/
180583static void jsonObjectStep(
180584  sqlite3_context *ctx,
180585  int argc,
180586  sqlite3_value **argv
180587){
180588  JsonString *pStr;
180589  const char *z;
180590  u32 n;
180591  UNUSED_PARAM(argc);
180592  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
180593  if( pStr ){
180594    if( pStr->zBuf==0 ){
180595      jsonInit(pStr, ctx);
180596      jsonAppendChar(pStr, '{');
180597    }else{
180598      jsonAppendChar(pStr, ',');
180599      pStr->pCtx = ctx;
180600    }
180601    z = (const char*)sqlite3_value_text(argv[0]);
180602    n = (u32)sqlite3_value_bytes(argv[0]);
180603    jsonAppendString(pStr, z, n);
180604    jsonAppendChar(pStr, ':');
180605    jsonAppendValue(pStr, argv[1]);
180606  }
180607}
180608static void jsonObjectFinal(sqlite3_context *ctx){
180609  JsonString *pStr;
180610  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
180611  if( pStr ){
180612    jsonAppendChar(pStr, '}');
180613    if( pStr->bErr ){
180614      if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
180615      assert( pStr->bStatic );
180616    }else{
180617      sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
180618                          pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
180619      pStr->bStatic = 1;
180620    }
180621  }else{
180622    sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
180623  }
180624  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
180625}
180626
180627
180628#ifndef SQLITE_OMIT_VIRTUALTABLE
180629/****************************************************************************
180630** The json_each virtual table
180631****************************************************************************/
180632typedef struct JsonEachCursor JsonEachCursor;
180633struct JsonEachCursor {
180634  sqlite3_vtab_cursor base;  /* Base class - must be first */
180635  u32 iRowid;                /* The rowid */
180636  u32 iBegin;                /* The first node of the scan */
180637  u32 i;                     /* Index in sParse.aNode[] of current row */
180638  u32 iEnd;                  /* EOF when i equals or exceeds this value */
180639  u8 eType;                  /* Type of top-level element */
180640  u8 bRecursive;             /* True for json_tree().  False for json_each() */
180641  char *zJson;               /* Input JSON */
180642  char *zRoot;               /* Path by which to filter zJson */
180643  JsonParse sParse;          /* Parse of the input JSON */
180644};
180645
180646/* Constructor for the json_each virtual table */
180647static int jsonEachConnect(
180648  sqlite3 *db,
180649  void *pAux,
180650  int argc, const char *const*argv,
180651  sqlite3_vtab **ppVtab,
180652  char **pzErr
180653){
180654  sqlite3_vtab *pNew;
180655  int rc;
180656
180657/* Column numbers */
180658#define JEACH_KEY     0
180659#define JEACH_VALUE   1
180660#define JEACH_TYPE    2
180661#define JEACH_ATOM    3
180662#define JEACH_ID      4
180663#define JEACH_PARENT  5
180664#define JEACH_FULLKEY 6
180665#define JEACH_PATH    7
180666#define JEACH_JSON    8
180667#define JEACH_ROOT    9
180668
180669  UNUSED_PARAM(pzErr);
180670  UNUSED_PARAM(argv);
180671  UNUSED_PARAM(argc);
180672  UNUSED_PARAM(pAux);
180673  rc = sqlite3_declare_vtab(db,
180674     "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
180675                    "json HIDDEN,root HIDDEN)");
180676  if( rc==SQLITE_OK ){
180677    pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
180678    if( pNew==0 ) return SQLITE_NOMEM;
180679    memset(pNew, 0, sizeof(*pNew));
180680  }
180681  return rc;
180682}
180683
180684/* destructor for json_each virtual table */
180685static int jsonEachDisconnect(sqlite3_vtab *pVtab){
180686  sqlite3_free(pVtab);
180687  return SQLITE_OK;
180688}
180689
180690/* constructor for a JsonEachCursor object for json_each(). */
180691static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
180692  JsonEachCursor *pCur;
180693
180694  UNUSED_PARAM(p);
180695  pCur = sqlite3_malloc( sizeof(*pCur) );
180696  if( pCur==0 ) return SQLITE_NOMEM;
180697  memset(pCur, 0, sizeof(*pCur));
180698  *ppCursor = &pCur->base;
180699  return SQLITE_OK;
180700}
180701
180702/* constructor for a JsonEachCursor object for json_tree(). */
180703static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
180704  int rc = jsonEachOpenEach(p, ppCursor);
180705  if( rc==SQLITE_OK ){
180706    JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
180707    pCur->bRecursive = 1;
180708  }
180709  return rc;
180710}
180711
180712/* Reset a JsonEachCursor back to its original state.  Free any memory
180713** held. */
180714static void jsonEachCursorReset(JsonEachCursor *p){
180715  sqlite3_free(p->zJson);
180716  sqlite3_free(p->zRoot);
180717  jsonParseReset(&p->sParse);
180718  p->iRowid = 0;
180719  p->i = 0;
180720  p->iEnd = 0;
180721  p->eType = 0;
180722  p->zJson = 0;
180723  p->zRoot = 0;
180724}
180725
180726/* Destructor for a jsonEachCursor object */
180727static int jsonEachClose(sqlite3_vtab_cursor *cur){
180728  JsonEachCursor *p = (JsonEachCursor*)cur;
180729  jsonEachCursorReset(p);
180730  sqlite3_free(cur);
180731  return SQLITE_OK;
180732}
180733
180734/* Return TRUE if the jsonEachCursor object has been advanced off the end
180735** of the JSON object */
180736static int jsonEachEof(sqlite3_vtab_cursor *cur){
180737  JsonEachCursor *p = (JsonEachCursor*)cur;
180738  return p->i >= p->iEnd;
180739}
180740
180741/* Advance the cursor to the next element for json_tree() */
180742static int jsonEachNext(sqlite3_vtab_cursor *cur){
180743  JsonEachCursor *p = (JsonEachCursor*)cur;
180744  if( p->bRecursive ){
180745    if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
180746    p->i++;
180747    p->iRowid++;
180748    if( p->i<p->iEnd ){
180749      u32 iUp = p->sParse.aUp[p->i];
180750      JsonNode *pUp = &p->sParse.aNode[iUp];
180751      p->eType = pUp->eType;
180752      if( pUp->eType==JSON_ARRAY ){
180753        if( iUp==p->i-1 ){
180754          pUp->u.iKey = 0;
180755        }else{
180756          pUp->u.iKey++;
180757        }
180758      }
180759    }
180760  }else{
180761    switch( p->eType ){
180762      case JSON_ARRAY: {
180763        p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
180764        p->iRowid++;
180765        break;
180766      }
180767      case JSON_OBJECT: {
180768        p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
180769        p->iRowid++;
180770        break;
180771      }
180772      default: {
180773        p->i = p->iEnd;
180774        break;
180775      }
180776    }
180777  }
180778  return SQLITE_OK;
180779}
180780
180781/* Append the name of the path for element i to pStr
180782*/
180783static void jsonEachComputePath(
180784  JsonEachCursor *p,       /* The cursor */
180785  JsonString *pStr,        /* Write the path here */
180786  u32 i                    /* Path to this element */
180787){
180788  JsonNode *pNode, *pUp;
180789  u32 iUp;
180790  if( i==0 ){
180791    jsonAppendChar(pStr, '$');
180792    return;
180793  }
180794  iUp = p->sParse.aUp[i];
180795  jsonEachComputePath(p, pStr, iUp);
180796  pNode = &p->sParse.aNode[i];
180797  pUp = &p->sParse.aNode[iUp];
180798  if( pUp->eType==JSON_ARRAY ){
180799    jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
180800  }else{
180801    assert( pUp->eType==JSON_OBJECT );
180802    if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
180803    assert( pNode->eType==JSON_STRING );
180804    assert( pNode->jnFlags & JNODE_LABEL );
180805    jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
180806  }
180807}
180808
180809/* Return the value of a column */
180810static int jsonEachColumn(
180811  sqlite3_vtab_cursor *cur,   /* The cursor */
180812  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
180813  int i                       /* Which column to return */
180814){
180815  JsonEachCursor *p = (JsonEachCursor*)cur;
180816  JsonNode *pThis = &p->sParse.aNode[p->i];
180817  switch( i ){
180818    case JEACH_KEY: {
180819      if( p->i==0 ) break;
180820      if( p->eType==JSON_OBJECT ){
180821        jsonReturn(pThis, ctx, 0);
180822      }else if( p->eType==JSON_ARRAY ){
180823        u32 iKey;
180824        if( p->bRecursive ){
180825          if( p->iRowid==0 ) break;
180826          iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
180827        }else{
180828          iKey = p->iRowid;
180829        }
180830        sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
180831      }
180832      break;
180833    }
180834    case JEACH_VALUE: {
180835      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
180836      jsonReturn(pThis, ctx, 0);
180837      break;
180838    }
180839    case JEACH_TYPE: {
180840      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
180841      sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
180842      break;
180843    }
180844    case JEACH_ATOM: {
180845      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
180846      if( pThis->eType>=JSON_ARRAY ) break;
180847      jsonReturn(pThis, ctx, 0);
180848      break;
180849    }
180850    case JEACH_ID: {
180851      sqlite3_result_int64(ctx,
180852         (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
180853      break;
180854    }
180855    case JEACH_PARENT: {
180856      if( p->i>p->iBegin && p->bRecursive ){
180857        sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
180858      }
180859      break;
180860    }
180861    case JEACH_FULLKEY: {
180862      JsonString x;
180863      jsonInit(&x, ctx);
180864      if( p->bRecursive ){
180865        jsonEachComputePath(p, &x, p->i);
180866      }else{
180867        if( p->zRoot ){
180868          jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
180869        }else{
180870          jsonAppendChar(&x, '$');
180871        }
180872        if( p->eType==JSON_ARRAY ){
180873          jsonPrintf(30, &x, "[%d]", p->iRowid);
180874        }else{
180875          jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
180876        }
180877      }
180878      jsonResult(&x);
180879      break;
180880    }
180881    case JEACH_PATH: {
180882      if( p->bRecursive ){
180883        JsonString x;
180884        jsonInit(&x, ctx);
180885        jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
180886        jsonResult(&x);
180887        break;
180888      }
180889      /* For json_each() path and root are the same so fall through
180890      ** into the root case */
180891    }
180892    default: {
180893      const char *zRoot = p->zRoot;
180894      if( zRoot==0 ) zRoot = "$";
180895      sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
180896      break;
180897    }
180898    case JEACH_JSON: {
180899      assert( i==JEACH_JSON );
180900      sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
180901      break;
180902    }
180903  }
180904  return SQLITE_OK;
180905}
180906
180907/* Return the current rowid value */
180908static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
180909  JsonEachCursor *p = (JsonEachCursor*)cur;
180910  *pRowid = p->iRowid;
180911  return SQLITE_OK;
180912}
180913
180914/* The query strategy is to look for an equality constraint on the json
180915** column.  Without such a constraint, the table cannot operate.  idxNum is
180916** 1 if the constraint is found, 3 if the constraint and zRoot are found,
180917** and 0 otherwise.
180918*/
180919static int jsonEachBestIndex(
180920  sqlite3_vtab *tab,
180921  sqlite3_index_info *pIdxInfo
180922){
180923  int i;
180924  int jsonIdx = -1;
180925  int rootIdx = -1;
180926  const struct sqlite3_index_constraint *pConstraint;
180927
180928  UNUSED_PARAM(tab);
180929  pConstraint = pIdxInfo->aConstraint;
180930  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
180931    if( pConstraint->usable==0 ) continue;
180932    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
180933    switch( pConstraint->iColumn ){
180934      case JEACH_JSON:   jsonIdx = i;    break;
180935      case JEACH_ROOT:   rootIdx = i;    break;
180936      default:           /* no-op */     break;
180937    }
180938  }
180939  if( jsonIdx<0 ){
180940    pIdxInfo->idxNum = 0;
180941    pIdxInfo->estimatedCost = 1e99;
180942  }else{
180943    pIdxInfo->estimatedCost = 1.0;
180944    pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
180945    pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
180946    if( rootIdx<0 ){
180947      pIdxInfo->idxNum = 1;
180948    }else{
180949      pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
180950      pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
180951      pIdxInfo->idxNum = 3;
180952    }
180953  }
180954  return SQLITE_OK;
180955}
180956
180957/* Start a search on a new JSON string */
180958static int jsonEachFilter(
180959  sqlite3_vtab_cursor *cur,
180960  int idxNum, const char *idxStr,
180961  int argc, sqlite3_value **argv
180962){
180963  JsonEachCursor *p = (JsonEachCursor*)cur;
180964  const char *z;
180965  const char *zRoot = 0;
180966  sqlite3_int64 n;
180967
180968  UNUSED_PARAM(idxStr);
180969  UNUSED_PARAM(argc);
180970  jsonEachCursorReset(p);
180971  if( idxNum==0 ) return SQLITE_OK;
180972  z = (const char*)sqlite3_value_text(argv[0]);
180973  if( z==0 ) return SQLITE_OK;
180974  n = sqlite3_value_bytes(argv[0]);
180975  p->zJson = sqlite3_malloc64( n+1 );
180976  if( p->zJson==0 ) return SQLITE_NOMEM;
180977  memcpy(p->zJson, z, (size_t)n+1);
180978  if( jsonParse(&p->sParse, 0, p->zJson) ){
180979    int rc = SQLITE_NOMEM;
180980    if( p->sParse.oom==0 ){
180981      sqlite3_free(cur->pVtab->zErrMsg);
180982      cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
180983      if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
180984    }
180985    jsonEachCursorReset(p);
180986    return rc;
180987  }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
180988    jsonEachCursorReset(p);
180989    return SQLITE_NOMEM;
180990  }else{
180991    JsonNode *pNode = 0;
180992    if( idxNum==3 ){
180993      const char *zErr = 0;
180994      zRoot = (const char*)sqlite3_value_text(argv[1]);
180995      if( zRoot==0 ) return SQLITE_OK;
180996      n = sqlite3_value_bytes(argv[1]);
180997      p->zRoot = sqlite3_malloc64( n+1 );
180998      if( p->zRoot==0 ) return SQLITE_NOMEM;
180999      memcpy(p->zRoot, zRoot, (size_t)n+1);
181000      if( zRoot[0]!='$' ){
181001        zErr = zRoot;
181002      }else{
181003        pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
181004      }
181005      if( zErr ){
181006        sqlite3_free(cur->pVtab->zErrMsg);
181007        cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
181008        jsonEachCursorReset(p);
181009        return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
181010      }else if( pNode==0 ){
181011        return SQLITE_OK;
181012      }
181013    }else{
181014      pNode = p->sParse.aNode;
181015    }
181016    p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
181017    p->eType = pNode->eType;
181018    if( p->eType>=JSON_ARRAY ){
181019      pNode->u.iKey = 0;
181020      p->iEnd = p->i + pNode->n + 1;
181021      if( p->bRecursive ){
181022        p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
181023        if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
181024          p->i--;
181025        }
181026      }else{
181027        p->i++;
181028      }
181029    }else{
181030      p->iEnd = p->i+1;
181031    }
181032  }
181033  return SQLITE_OK;
181034}
181035
181036/* The methods of the json_each virtual table */
181037static sqlite3_module jsonEachModule = {
181038  0,                         /* iVersion */
181039  0,                         /* xCreate */
181040  jsonEachConnect,           /* xConnect */
181041  jsonEachBestIndex,         /* xBestIndex */
181042  jsonEachDisconnect,        /* xDisconnect */
181043  0,                         /* xDestroy */
181044  jsonEachOpenEach,          /* xOpen - open a cursor */
181045  jsonEachClose,             /* xClose - close a cursor */
181046  jsonEachFilter,            /* xFilter - configure scan constraints */
181047  jsonEachNext,              /* xNext - advance a cursor */
181048  jsonEachEof,               /* xEof - check for end of scan */
181049  jsonEachColumn,            /* xColumn - read data */
181050  jsonEachRowid,             /* xRowid - read data */
181051  0,                         /* xUpdate */
181052  0,                         /* xBegin */
181053  0,                         /* xSync */
181054  0,                         /* xCommit */
181055  0,                         /* xRollback */
181056  0,                         /* xFindMethod */
181057  0,                         /* xRename */
181058  0,                         /* xSavepoint */
181059  0,                         /* xRelease */
181060  0                          /* xRollbackTo */
181061};
181062
181063/* The methods of the json_tree virtual table. */
181064static sqlite3_module jsonTreeModule = {
181065  0,                         /* iVersion */
181066  0,                         /* xCreate */
181067  jsonEachConnect,           /* xConnect */
181068  jsonEachBestIndex,         /* xBestIndex */
181069  jsonEachDisconnect,        /* xDisconnect */
181070  0,                         /* xDestroy */
181071  jsonEachOpenTree,          /* xOpen - open a cursor */
181072  jsonEachClose,             /* xClose - close a cursor */
181073  jsonEachFilter,            /* xFilter - configure scan constraints */
181074  jsonEachNext,              /* xNext - advance a cursor */
181075  jsonEachEof,               /* xEof - check for end of scan */
181076  jsonEachColumn,            /* xColumn - read data */
181077  jsonEachRowid,             /* xRowid - read data */
181078  0,                         /* xUpdate */
181079  0,                         /* xBegin */
181080  0,                         /* xSync */
181081  0,                         /* xCommit */
181082  0,                         /* xRollback */
181083  0,                         /* xFindMethod */
181084  0,                         /* xRename */
181085  0,                         /* xSavepoint */
181086  0,                         /* xRelease */
181087  0                          /* xRollbackTo */
181088};
181089#endif /* SQLITE_OMIT_VIRTUALTABLE */
181090
181091/****************************************************************************
181092** The following routines are the only publically visible identifiers in this
181093** file.  Call the following routines in order to register the various SQL
181094** functions and the virtual table implemented by this file.
181095****************************************************************************/
181096
181097SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
181098  int rc = SQLITE_OK;
181099  unsigned int i;
181100  static const struct {
181101     const char *zName;
181102     int nArg;
181103     int flag;
181104     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
181105  } aFunc[] = {
181106    { "json",                 1, 0,   jsonRemoveFunc        },
181107    { "json_array",          -1, 0,   jsonArrayFunc         },
181108    { "json_array_length",    1, 0,   jsonArrayLengthFunc   },
181109    { "json_array_length",    2, 0,   jsonArrayLengthFunc   },
181110    { "json_extract",        -1, 0,   jsonExtractFunc       },
181111    { "json_insert",         -1, 0,   jsonSetFunc           },
181112    { "json_object",         -1, 0,   jsonObjectFunc        },
181113    { "json_patch",           2, 0,   jsonPatchFunc         },
181114    { "json_quote",           1, 0,   jsonQuoteFunc         },
181115    { "json_remove",         -1, 0,   jsonRemoveFunc        },
181116    { "json_replace",        -1, 0,   jsonReplaceFunc       },
181117    { "json_set",            -1, 1,   jsonSetFunc           },
181118    { "json_type",            1, 0,   jsonTypeFunc          },
181119    { "json_type",            2, 0,   jsonTypeFunc          },
181120    { "json_valid",           1, 0,   jsonValidFunc         },
181121
181122#if SQLITE_DEBUG
181123    /* DEBUG and TESTING functions */
181124    { "json_parse",           1, 0,   jsonParseFunc         },
181125    { "json_test1",           1, 0,   jsonTest1Func         },
181126#endif
181127  };
181128  static const struct {
181129     const char *zName;
181130     int nArg;
181131     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
181132     void (*xFinal)(sqlite3_context*);
181133  } aAgg[] = {
181134    { "json_group_array",     1,   jsonArrayStep,   jsonArrayFinal  },
181135    { "json_group_object",    2,   jsonObjectStep,  jsonObjectFinal },
181136  };
181137#ifndef SQLITE_OMIT_VIRTUALTABLE
181138  static const struct {
181139     const char *zName;
181140     sqlite3_module *pModule;
181141  } aMod[] = {
181142    { "json_each",            &jsonEachModule               },
181143    { "json_tree",            &jsonTreeModule               },
181144  };
181145#endif
181146  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
181147    rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
181148                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
181149                                 (void*)&aFunc[i].flag,
181150                                 aFunc[i].xFunc, 0, 0);
181151  }
181152  for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
181153    rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
181154                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
181155                                 0, aAgg[i].xStep, aAgg[i].xFinal);
181156  }
181157#ifndef SQLITE_OMIT_VIRTUALTABLE
181158  for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
181159    rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
181160  }
181161#endif
181162  return rc;
181163}
181164
181165
181166#ifndef SQLITE_CORE
181167#ifdef _WIN32
181168__declspec(dllexport)
181169#endif
181170SQLITE_API int sqlite3_json_init(
181171  sqlite3 *db,
181172  char **pzErrMsg,
181173  const sqlite3_api_routines *pApi
181174){
181175  SQLITE_EXTENSION_INIT2(pApi);
181176  (void)pzErrMsg;  /* Unused parameter */
181177  return sqlite3Json1Init(db);
181178}
181179#endif
181180#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
181181
181182/************** End of json1.c ***********************************************/
181183/************** Begin file fts5.c ********************************************/
181184
181185
181186#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
181187
181188#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
181189# define NDEBUG 1
181190#endif
181191#if defined(NDEBUG) && defined(SQLITE_DEBUG)
181192# undef NDEBUG
181193#endif
181194
181195/*
181196** 2014 May 31
181197**
181198** The author disclaims copyright to this source code.  In place of
181199** a legal notice, here is a blessing:
181200**
181201**    May you do good and not evil.
181202**    May you find forgiveness for yourself and forgive others.
181203**    May you share freely, never taking more than you give.
181204**
181205******************************************************************************
181206**
181207** Interfaces to extend FTS5. Using the interfaces defined in this file,
181208** FTS5 may be extended with:
181209**
181210**     * custom tokenizers, and
181211**     * custom auxiliary functions.
181212*/
181213
181214
181215#ifndef _FTS5_H
181216#define _FTS5_H
181217
181218/* #include "sqlite3.h" */
181219
181220#if 0
181221extern "C" {
181222#endif
181223
181224/*************************************************************************
181225** CUSTOM AUXILIARY FUNCTIONS
181226**
181227** Virtual table implementations may overload SQL functions by implementing
181228** the sqlite3_module.xFindFunction() method.
181229*/
181230
181231typedef struct Fts5ExtensionApi Fts5ExtensionApi;
181232typedef struct Fts5Context Fts5Context;
181233typedef struct Fts5PhraseIter Fts5PhraseIter;
181234
181235typedef void (*fts5_extension_function)(
181236  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
181237  Fts5Context *pFts,              /* First arg to pass to pApi functions */
181238  sqlite3_context *pCtx,          /* Context for returning result/error */
181239  int nVal,                       /* Number of values in apVal[] array */
181240  sqlite3_value **apVal           /* Array of trailing arguments */
181241);
181242
181243struct Fts5PhraseIter {
181244  const unsigned char *a;
181245  const unsigned char *b;
181246};
181247
181248/*
181249** EXTENSION API FUNCTIONS
181250**
181251** xUserData(pFts):
181252**   Return a copy of the context pointer the extension function was
181253**   registered with.
181254**
181255** xColumnTotalSize(pFts, iCol, pnToken):
181256**   If parameter iCol is less than zero, set output variable *pnToken
181257**   to the total number of tokens in the FTS5 table. Or, if iCol is
181258**   non-negative but less than the number of columns in the table, return
181259**   the total number of tokens in column iCol, considering all rows in
181260**   the FTS5 table.
181261**
181262**   If parameter iCol is greater than or equal to the number of columns
181263**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
181264**   an OOM condition or IO error), an appropriate SQLite error code is
181265**   returned.
181266**
181267** xColumnCount(pFts):
181268**   Return the number of columns in the table.
181269**
181270** xColumnSize(pFts, iCol, pnToken):
181271**   If parameter iCol is less than zero, set output variable *pnToken
181272**   to the total number of tokens in the current row. Or, if iCol is
181273**   non-negative but less than the number of columns in the table, set
181274**   *pnToken to the number of tokens in column iCol of the current row.
181275**
181276**   If parameter iCol is greater than or equal to the number of columns
181277**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
181278**   an OOM condition or IO error), an appropriate SQLite error code is
181279**   returned.
181280**
181281**   This function may be quite inefficient if used with an FTS5 table
181282**   created with the "columnsize=0" option.
181283**
181284** xColumnText:
181285**   This function attempts to retrieve the text of column iCol of the
181286**   current document. If successful, (*pz) is set to point to a buffer
181287**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
181288**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
181289**   if an error occurs, an SQLite error code is returned and the final values
181290**   of (*pz) and (*pn) are undefined.
181291**
181292** xPhraseCount:
181293**   Returns the number of phrases in the current query expression.
181294**
181295** xPhraseSize:
181296**   Returns the number of tokens in phrase iPhrase of the query. Phrases
181297**   are numbered starting from zero.
181298**
181299** xInstCount:
181300**   Set *pnInst to the total number of occurrences of all phrases within
181301**   the query within the current row. Return SQLITE_OK if successful, or
181302**   an error code (i.e. SQLITE_NOMEM) if an error occurs.
181303**
181304**   This API can be quite slow if used with an FTS5 table created with the
181305**   "detail=none" or "detail=column" option. If the FTS5 table is created
181306**   with either "detail=none" or "detail=column" and "content=" option
181307**   (i.e. if it is a contentless table), then this API always returns 0.
181308**
181309** xInst:
181310**   Query for the details of phrase match iIdx within the current row.
181311**   Phrase matches are numbered starting from zero, so the iIdx argument
181312**   should be greater than or equal to zero and smaller than the value
181313**   output by xInstCount().
181314**
181315**   Usually, output parameter *piPhrase is set to the phrase number, *piCol
181316**   to the column in which it occurs and *piOff the token offset of the
181317**   first token of the phrase. The exception is if the table was created
181318**   with the offsets=0 option specified. In this case *piOff is always
181319**   set to -1.
181320**
181321**   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
181322**   if an error occurs.
181323**
181324**   This API can be quite slow if used with an FTS5 table created with the
181325**   "detail=none" or "detail=column" option.
181326**
181327** xRowid:
181328**   Returns the rowid of the current row.
181329**
181330** xTokenize:
181331**   Tokenize text using the tokenizer belonging to the FTS5 table.
181332**
181333** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
181334**   This API function is used to query the FTS table for phrase iPhrase
181335**   of the current query. Specifically, a query equivalent to:
181336**
181337**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
181338**
181339**   with $p set to a phrase equivalent to the phrase iPhrase of the
181340**   current query is executed. Any column filter that applies to
181341**   phrase iPhrase of the current query is included in $p. For each
181342**   row visited, the callback function passed as the fourth argument
181343**   is invoked. The context and API objects passed to the callback
181344**   function may be used to access the properties of each matched row.
181345**   Invoking Api.xUserData() returns a copy of the pointer passed as
181346**   the third argument to pUserData.
181347**
181348**   If the callback function returns any value other than SQLITE_OK, the
181349**   query is abandoned and the xQueryPhrase function returns immediately.
181350**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
181351**   Otherwise, the error code is propagated upwards.
181352**
181353**   If the query runs to completion without incident, SQLITE_OK is returned.
181354**   Or, if some error occurs before the query completes or is aborted by
181355**   the callback, an SQLite error code is returned.
181356**
181357**
181358** xSetAuxdata(pFts5, pAux, xDelete)
181359**
181360**   Save the pointer passed as the second argument as the extension functions
181361**   "auxiliary data". The pointer may then be retrieved by the current or any
181362**   future invocation of the same fts5 extension function made as part of
181363**   of the same MATCH query using the xGetAuxdata() API.
181364**
181365**   Each extension function is allocated a single auxiliary data slot for
181366**   each FTS query (MATCH expression). If the extension function is invoked
181367**   more than once for a single FTS query, then all invocations share a
181368**   single auxiliary data context.
181369**
181370**   If there is already an auxiliary data pointer when this function is
181371**   invoked, then it is replaced by the new pointer. If an xDelete callback
181372**   was specified along with the original pointer, it is invoked at this
181373**   point.
181374**
181375**   The xDelete callback, if one is specified, is also invoked on the
181376**   auxiliary data pointer after the FTS5 query has finished.
181377**
181378**   If an error (e.g. an OOM condition) occurs within this function, an
181379**   the auxiliary data is set to NULL and an error code returned. If the
181380**   xDelete parameter was not NULL, it is invoked on the auxiliary data
181381**   pointer before returning.
181382**
181383**
181384** xGetAuxdata(pFts5, bClear)
181385**
181386**   Returns the current auxiliary data pointer for the fts5 extension
181387**   function. See the xSetAuxdata() method for details.
181388**
181389**   If the bClear argument is non-zero, then the auxiliary data is cleared
181390**   (set to NULL) before this function returns. In this case the xDelete,
181391**   if any, is not invoked.
181392**
181393**
181394** xRowCount(pFts5, pnRow)
181395**
181396**   This function is used to retrieve the total number of rows in the table.
181397**   In other words, the same value that would be returned by:
181398**
181399**        SELECT count(*) FROM ftstable;
181400**
181401** xPhraseFirst()
181402**   This function is used, along with type Fts5PhraseIter and the xPhraseNext
181403**   method, to iterate through all instances of a single query phrase within
181404**   the current row. This is the same information as is accessible via the
181405**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
181406**   to use, this API may be faster under some circumstances. To iterate
181407**   through instances of phrase iPhrase, use the following code:
181408**
181409**       Fts5PhraseIter iter;
181410**       int iCol, iOff;
181411**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
181412**           iCol>=0;
181413**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
181414**       ){
181415**         // An instance of phrase iPhrase at offset iOff of column iCol
181416**       }
181417**
181418**   The Fts5PhraseIter structure is defined above. Applications should not
181419**   modify this structure directly - it should only be used as shown above
181420**   with the xPhraseFirst() and xPhraseNext() API methods (and by
181421**   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
181422**
181423**   This API can be quite slow if used with an FTS5 table created with the
181424**   "detail=none" or "detail=column" option. If the FTS5 table is created
181425**   with either "detail=none" or "detail=column" and "content=" option
181426**   (i.e. if it is a contentless table), then this API always iterates
181427**   through an empty set (all calls to xPhraseFirst() set iCol to -1).
181428**
181429** xPhraseNext()
181430**   See xPhraseFirst above.
181431**
181432** xPhraseFirstColumn()
181433**   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
181434**   and xPhraseNext() APIs described above. The difference is that instead
181435**   of iterating through all instances of a phrase in the current row, these
181436**   APIs are used to iterate through the set of columns in the current row
181437**   that contain one or more instances of a specified phrase. For example:
181438**
181439**       Fts5PhraseIter iter;
181440**       int iCol;
181441**       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
181442**           iCol>=0;
181443**           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
181444**       ){
181445**         // Column iCol contains at least one instance of phrase iPhrase
181446**       }
181447**
181448**   This API can be quite slow if used with an FTS5 table created with the
181449**   "detail=none" option. If the FTS5 table is created with either
181450**   "detail=none" "content=" option (i.e. if it is a contentless table),
181451**   then this API always iterates through an empty set (all calls to
181452**   xPhraseFirstColumn() set iCol to -1).
181453**
181454**   The information accessed using this API and its companion
181455**   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
181456**   (or xInst/xInstCount). The chief advantage of this API is that it is
181457**   significantly more efficient than those alternatives when used with
181458**   "detail=column" tables.
181459**
181460** xPhraseNextColumn()
181461**   See xPhraseFirstColumn above.
181462*/
181463struct Fts5ExtensionApi {
181464  int iVersion;                   /* Currently always set to 3 */
181465
181466  void *(*xUserData)(Fts5Context*);
181467
181468  int (*xColumnCount)(Fts5Context*);
181469  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
181470  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
181471
181472  int (*xTokenize)(Fts5Context*,
181473    const char *pText, int nText, /* Text to tokenize */
181474    void *pCtx,                   /* Context passed to xToken() */
181475    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
181476  );
181477
181478  int (*xPhraseCount)(Fts5Context*);
181479  int (*xPhraseSize)(Fts5Context*, int iPhrase);
181480
181481  int (*xInstCount)(Fts5Context*, int *pnInst);
181482  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
181483
181484  sqlite3_int64 (*xRowid)(Fts5Context*);
181485  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
181486  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
181487
181488  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
181489    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
181490  );
181491  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
181492  void *(*xGetAuxdata)(Fts5Context*, int bClear);
181493
181494  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
181495  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
181496
181497  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
181498  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
181499};
181500
181501/*
181502** CUSTOM AUXILIARY FUNCTIONS
181503*************************************************************************/
181504
181505/*************************************************************************
181506** CUSTOM TOKENIZERS
181507**
181508** Applications may also register custom tokenizer types. A tokenizer
181509** is registered by providing fts5 with a populated instance of the
181510** following structure. All structure methods must be defined, setting
181511** any member of the fts5_tokenizer struct to NULL leads to undefined
181512** behaviour. The structure methods are expected to function as follows:
181513**
181514** xCreate:
181515**   This function is used to allocate and initialize a tokenizer instance.
181516**   A tokenizer instance is required to actually tokenize text.
181517**
181518**   The first argument passed to this function is a copy of the (void*)
181519**   pointer provided by the application when the fts5_tokenizer object
181520**   was registered with FTS5 (the third argument to xCreateTokenizer()).
181521**   The second and third arguments are an array of nul-terminated strings
181522**   containing the tokenizer arguments, if any, specified following the
181523**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
181524**   to create the FTS5 table.
181525**
181526**   The final argument is an output variable. If successful, (*ppOut)
181527**   should be set to point to the new tokenizer handle and SQLITE_OK
181528**   returned. If an error occurs, some value other than SQLITE_OK should
181529**   be returned. In this case, fts5 assumes that the final value of *ppOut
181530**   is undefined.
181531**
181532** xDelete:
181533**   This function is invoked to delete a tokenizer handle previously
181534**   allocated using xCreate(). Fts5 guarantees that this function will
181535**   be invoked exactly once for each successful call to xCreate().
181536**
181537** xTokenize:
181538**   This function is expected to tokenize the nText byte string indicated
181539**   by argument pText. pText may or may not be nul-terminated. The first
181540**   argument passed to this function is a pointer to an Fts5Tokenizer object
181541**   returned by an earlier call to xCreate().
181542**
181543**   The second argument indicates the reason that FTS5 is requesting
181544**   tokenization of the supplied text. This is always one of the following
181545**   four values:
181546**
181547**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
181548**            or removed from the FTS table. The tokenizer is being invoked to
181549**            determine the set of tokens to add to (or delete from) the
181550**            FTS index.
181551**
181552**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
181553**            against the FTS index. The tokenizer is being called to tokenize
181554**            a bareword or quoted string specified as part of the query.
181555**
181556**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
181557**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
181558**            followed by a "*" character, indicating that the last token
181559**            returned by the tokenizer will be treated as a token prefix.
181560**
181561**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
181562**            satisfy an fts5_api.xTokenize() request made by an auxiliary
181563**            function. Or an fts5_api.xColumnSize() request made by the same
181564**            on a columnsize=0 database.
181565**   </ul>
181566**
181567**   For each token in the input string, the supplied callback xToken() must
181568**   be invoked. The first argument to it should be a copy of the pointer
181569**   passed as the second argument to xTokenize(). The third and fourth
181570**   arguments are a pointer to a buffer containing the token text, and the
181571**   size of the token in bytes. The 4th and 5th arguments are the byte offsets
181572**   of the first byte of and first byte immediately following the text from
181573**   which the token is derived within the input.
181574**
181575**   The second argument passed to the xToken() callback ("tflags") should
181576**   normally be set to 0. The exception is if the tokenizer supports
181577**   synonyms. In this case see the discussion below for details.
181578**
181579**   FTS5 assumes the xToken() callback is invoked for each token in the
181580**   order that they occur within the input text.
181581**
181582**   If an xToken() callback returns any value other than SQLITE_OK, then
181583**   the tokenization should be abandoned and the xTokenize() method should
181584**   immediately return a copy of the xToken() return value. Or, if the
181585**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
181586**   if an error occurs with the xTokenize() implementation itself, it
181587**   may abandon the tokenization and return any error code other than
181588**   SQLITE_OK or SQLITE_DONE.
181589**
181590** SYNONYM SUPPORT
181591**
181592**   Custom tokenizers may also support synonyms. Consider a case in which a
181593**   user wishes to query for a phrase such as "first place". Using the
181594**   built-in tokenizers, the FTS5 query 'first + place' will match instances
181595**   of "first place" within the document set, but not alternative forms
181596**   such as "1st place". In some applications, it would be better to match
181597**   all instances of "first place" or "1st place" regardless of which form
181598**   the user specified in the MATCH query text.
181599**
181600**   There are several ways to approach this in FTS5:
181601**
181602**   <ol><li> By mapping all synonyms to a single token. In this case, the
181603**            In the above example, this means that the tokenizer returns the
181604**            same token for inputs "first" and "1st". Say that token is in
181605**            fact "first", so that when the user inserts the document "I won
181606**            1st place" entries are added to the index for tokens "i", "won",
181607**            "first" and "place". If the user then queries for '1st + place',
181608**            the tokenizer substitutes "first" for "1st" and the query works
181609**            as expected.
181610**
181611**       <li> By adding multiple synonyms for a single term to the FTS index.
181612**            In this case, when tokenizing query text, the tokenizer may
181613**            provide multiple synonyms for a single term within the document.
181614**            FTS5 then queries the index for each synonym individually. For
181615**            example, faced with the query:
181616**
181617**   <codeblock>
181618**     ... MATCH 'first place'</codeblock>
181619**
181620**            the tokenizer offers both "1st" and "first" as synonyms for the
181621**            first token in the MATCH query and FTS5 effectively runs a query
181622**            similar to:
181623**
181624**   <codeblock>
181625**     ... MATCH '(first OR 1st) place'</codeblock>
181626**
181627**            except that, for the purposes of auxiliary functions, the query
181628**            still appears to contain just two phrases - "(first OR 1st)"
181629**            being treated as a single phrase.
181630**
181631**       <li> By adding multiple synonyms for a single term to the FTS index.
181632**            Using this method, when tokenizing document text, the tokenizer
181633**            provides multiple synonyms for each token. So that when a
181634**            document such as "I won first place" is tokenized, entries are
181635**            added to the FTS index for "i", "won", "first", "1st" and
181636**            "place".
181637**
181638**            This way, even if the tokenizer does not provide synonyms
181639**            when tokenizing query text (it should not - to do would be
181640**            inefficient), it doesn't matter if the user queries for
181641**            'first + place' or '1st + place', as there are entires in the
181642**            FTS index corresponding to both forms of the first token.
181643**   </ol>
181644**
181645**   Whether it is parsing document or query text, any call to xToken that
181646**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
181647**   is considered to supply a synonym for the previous token. For example,
181648**   when parsing the document "I won first place", a tokenizer that supports
181649**   synonyms would call xToken() 5 times, as follows:
181650**
181651**   <codeblock>
181652**       xToken(pCtx, 0, "i",                      1,  0,  1);
181653**       xToken(pCtx, 0, "won",                    3,  2,  5);
181654**       xToken(pCtx, 0, "first",                  5,  6, 11);
181655**       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
181656**       xToken(pCtx, 0, "place",                  5, 12, 17);
181657**</codeblock>
181658**
181659**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
181660**   xToken() is called. Multiple synonyms may be specified for a single token
181661**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
181662**   There is no limit to the number of synonyms that may be provided for a
181663**   single token.
181664**
181665**   In many cases, method (1) above is the best approach. It does not add
181666**   extra data to the FTS index or require FTS5 to query for multiple terms,
181667**   so it is efficient in terms of disk space and query speed. However, it
181668**   does not support prefix queries very well. If, as suggested above, the
181669**   token "first" is subsituted for "1st" by the tokenizer, then the query:
181670**
181671**   <codeblock>
181672**     ... MATCH '1s*'</codeblock>
181673**
181674**   will not match documents that contain the token "1st" (as the tokenizer
181675**   will probably not map "1s" to any prefix of "first").
181676**
181677**   For full prefix support, method (3) may be preferred. In this case,
181678**   because the index contains entries for both "first" and "1st", prefix
181679**   queries such as 'fi*' or '1s*' will match correctly. However, because
181680**   extra entries are added to the FTS index, this method uses more space
181681**   within the database.
181682**
181683**   Method (2) offers a midpoint between (1) and (3). Using this method,
181684**   a query such as '1s*' will match documents that contain the literal
181685**   token "1st", but not "first" (assuming the tokenizer is not able to
181686**   provide synonyms for prefixes). However, a non-prefix query like '1st'
181687**   will match against "1st" and "first". This method does not require
181688**   extra disk space, as no extra entries are added to the FTS index.
181689**   On the other hand, it may require more CPU cycles to run MATCH queries,
181690**   as separate queries of the FTS index are required for each synonym.
181691**
181692**   When using methods (2) or (3), it is important that the tokenizer only
181693**   provide synonyms when tokenizing document text (method (2)) or query
181694**   text (method (3)), not both. Doing so will not cause any errors, but is
181695**   inefficient.
181696*/
181697typedef struct Fts5Tokenizer Fts5Tokenizer;
181698typedef struct fts5_tokenizer fts5_tokenizer;
181699struct fts5_tokenizer {
181700  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
181701  void (*xDelete)(Fts5Tokenizer*);
181702  int (*xTokenize)(Fts5Tokenizer*,
181703      void *pCtx,
181704      int flags,            /* Mask of FTS5_TOKENIZE_* flags */
181705      const char *pText, int nText,
181706      int (*xToken)(
181707        void *pCtx,         /* Copy of 2nd argument to xTokenize() */
181708        int tflags,         /* Mask of FTS5_TOKEN_* flags */
181709        const char *pToken, /* Pointer to buffer containing token */
181710        int nToken,         /* Size of token in bytes */
181711        int iStart,         /* Byte offset of token within input text */
181712        int iEnd            /* Byte offset of end of token within input text */
181713      )
181714  );
181715};
181716
181717/* Flags that may be passed as the third argument to xTokenize() */
181718#define FTS5_TOKENIZE_QUERY     0x0001
181719#define FTS5_TOKENIZE_PREFIX    0x0002
181720#define FTS5_TOKENIZE_DOCUMENT  0x0004
181721#define FTS5_TOKENIZE_AUX       0x0008
181722
181723/* Flags that may be passed by the tokenizer implementation back to FTS5
181724** as the third argument to the supplied xToken callback. */
181725#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
181726
181727/*
181728** END OF CUSTOM TOKENIZERS
181729*************************************************************************/
181730
181731/*************************************************************************
181732** FTS5 EXTENSION REGISTRATION API
181733*/
181734typedef struct fts5_api fts5_api;
181735struct fts5_api {
181736  int iVersion;                   /* Currently always set to 2 */
181737
181738  /* Create a new tokenizer */
181739  int (*xCreateTokenizer)(
181740    fts5_api *pApi,
181741    const char *zName,
181742    void *pContext,
181743    fts5_tokenizer *pTokenizer,
181744    void (*xDestroy)(void*)
181745  );
181746
181747  /* Find an existing tokenizer */
181748  int (*xFindTokenizer)(
181749    fts5_api *pApi,
181750    const char *zName,
181751    void **ppContext,
181752    fts5_tokenizer *pTokenizer
181753  );
181754
181755  /* Create a new auxiliary function */
181756  int (*xCreateFunction)(
181757    fts5_api *pApi,
181758    const char *zName,
181759    void *pContext,
181760    fts5_extension_function xFunction,
181761    void (*xDestroy)(void*)
181762  );
181763};
181764
181765/*
181766** END OF REGISTRATION API
181767*************************************************************************/
181768
181769#if 0
181770}  /* end of the 'extern "C"' block */
181771#endif
181772
181773#endif /* _FTS5_H */
181774
181775/*
181776** 2014 May 31
181777**
181778** The author disclaims copyright to this source code.  In place of
181779** a legal notice, here is a blessing:
181780**
181781**    May you do good and not evil.
181782**    May you find forgiveness for yourself and forgive others.
181783**    May you share freely, never taking more than you give.
181784**
181785******************************************************************************
181786**
181787*/
181788#ifndef _FTS5INT_H
181789#define _FTS5INT_H
181790
181791/* #include "fts5.h" */
181792/* #include "sqlite3ext.h" */
181793SQLITE_EXTENSION_INIT1
181794
181795/* #include <string.h> */
181796/* #include <assert.h> */
181797
181798#ifndef SQLITE_AMALGAMATION
181799
181800typedef unsigned char  u8;
181801typedef unsigned int   u32;
181802typedef unsigned short u16;
181803typedef short i16;
181804typedef sqlite3_int64 i64;
181805typedef sqlite3_uint64 u64;
181806
181807#ifndef ArraySize
181808# define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
181809#endif
181810
181811#define testcase(x)
181812#define ALWAYS(x) 1
181813#define NEVER(x) 0
181814
181815#define MIN(x,y) (((x) < (y)) ? (x) : (y))
181816#define MAX(x,y) (((x) > (y)) ? (x) : (y))
181817
181818/*
181819** Constants for the largest and smallest possible 64-bit signed integers.
181820*/
181821# define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
181822# define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
181823
181824#endif
181825
181826/* Truncate very long tokens to this many bytes. Hard limit is
181827** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
181828** field that occurs at the start of each leaf page (see fts5_index.c). */
181829#define FTS5_MAX_TOKEN_SIZE 32768
181830
181831/*
181832** Maximum number of prefix indexes on single FTS5 table. This must be
181833** less than 32. If it is set to anything large than that, an #error
181834** directive in fts5_index.c will cause the build to fail.
181835*/
181836#define FTS5_MAX_PREFIX_INDEXES 31
181837
181838#define FTS5_DEFAULT_NEARDIST 10
181839#define FTS5_DEFAULT_RANK     "bm25"
181840
181841/* Name of rank and rowid columns */
181842#define FTS5_RANK_NAME "rank"
181843#define FTS5_ROWID_NAME "rowid"
181844
181845#ifdef SQLITE_DEBUG
181846# define FTS5_CORRUPT sqlite3Fts5Corrupt()
181847static int sqlite3Fts5Corrupt(void);
181848#else
181849# define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
181850#endif
181851
181852/*
181853** The assert_nc() macro is similar to the assert() macro, except that it
181854** is used for assert() conditions that are true only if it can be
181855** guranteed that the database is not corrupt.
181856*/
181857#ifdef SQLITE_DEBUG
181858SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
181859# define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
181860#else
181861# define assert_nc(x) assert(x)
181862#endif
181863
181864/* Mark a function parameter as unused, to suppress nuisance compiler
181865** warnings. */
181866#ifndef UNUSED_PARAM
181867# define UNUSED_PARAM(X)  (void)(X)
181868#endif
181869
181870#ifndef UNUSED_PARAM2
181871# define UNUSED_PARAM2(X, Y)  (void)(X), (void)(Y)
181872#endif
181873
181874typedef struct Fts5Global Fts5Global;
181875typedef struct Fts5Colset Fts5Colset;
181876
181877/* If a NEAR() clump or phrase may only match a specific set of columns,
181878** then an object of the following type is used to record the set of columns.
181879** Each entry in the aiCol[] array is a column that may be matched.
181880**
181881** This object is used by fts5_expr.c and fts5_index.c.
181882*/
181883struct Fts5Colset {
181884  int nCol;
181885  int aiCol[1];
181886};
181887
181888
181889
181890/**************************************************************************
181891** Interface to code in fts5_config.c. fts5_config.c contains contains code
181892** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
181893*/
181894
181895typedef struct Fts5Config Fts5Config;
181896
181897/*
181898** An instance of the following structure encodes all information that can
181899** be gleaned from the CREATE VIRTUAL TABLE statement.
181900**
181901** And all information loaded from the %_config table.
181902**
181903** nAutomerge:
181904**   The minimum number of segments that an auto-merge operation should
181905**   attempt to merge together. A value of 1 sets the object to use the
181906**   compile time default. Zero disables auto-merge altogether.
181907**
181908** zContent:
181909**
181910** zContentRowid:
181911**   The value of the content_rowid= option, if one was specified. Or
181912**   the string "rowid" otherwise. This text is not quoted - if it is
181913**   used as part of an SQL statement it needs to be quoted appropriately.
181914**
181915** zContentExprlist:
181916**
181917** pzErrmsg:
181918**   This exists in order to allow the fts5_index.c module to return a
181919**   decent error message if it encounters a file-format version it does
181920**   not understand.
181921**
181922** bColumnsize:
181923**   True if the %_docsize table is created.
181924**
181925** bPrefixIndex:
181926**   This is only used for debugging. If set to false, any prefix indexes
181927**   are ignored. This value is configured using:
181928**
181929**       INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
181930**
181931*/
181932struct Fts5Config {
181933  sqlite3 *db;                    /* Database handle */
181934  char *zDb;                      /* Database holding FTS index (e.g. "main") */
181935  char *zName;                    /* Name of FTS index */
181936  int nCol;                       /* Number of columns */
181937  char **azCol;                   /* Column names */
181938  u8 *abUnindexed;                /* True for unindexed columns */
181939  int nPrefix;                    /* Number of prefix indexes */
181940  int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */
181941  int eContent;                   /* An FTS5_CONTENT value */
181942  char *zContent;                 /* content table */
181943  char *zContentRowid;            /* "content_rowid=" option value */
181944  int bColumnsize;                /* "columnsize=" option value (dflt==1) */
181945  int eDetail;                    /* FTS5_DETAIL_XXX value */
181946  char *zContentExprlist;
181947  Fts5Tokenizer *pTok;
181948  fts5_tokenizer *pTokApi;
181949
181950  /* Values loaded from the %_config table */
181951  int iCookie;                    /* Incremented when %_config is modified */
181952  int pgsz;                       /* Approximate page size used in %_data */
181953  int nAutomerge;                 /* 'automerge' setting */
181954  int nCrisisMerge;               /* Maximum allowed segments per level */
181955  int nUsermerge;                 /* 'usermerge' setting */
181956  int nHashSize;                  /* Bytes of memory for in-memory hash */
181957  char *zRank;                    /* Name of rank function */
181958  char *zRankArgs;                /* Arguments to rank function */
181959
181960  /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
181961  char **pzErrmsg;
181962
181963#ifdef SQLITE_DEBUG
181964  int bPrefixIndex;               /* True to use prefix-indexes */
181965#endif
181966};
181967
181968/* Current expected value of %_config table 'version' field */
181969#define FTS5_CURRENT_VERSION 4
181970
181971#define FTS5_CONTENT_NORMAL   0
181972#define FTS5_CONTENT_NONE     1
181973#define FTS5_CONTENT_EXTERNAL 2
181974
181975#define FTS5_DETAIL_FULL    0
181976#define FTS5_DETAIL_NONE    1
181977#define FTS5_DETAIL_COLUMNS 2
181978
181979
181980
181981static int sqlite3Fts5ConfigParse(
181982    Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
181983);
181984static void sqlite3Fts5ConfigFree(Fts5Config*);
181985
181986static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
181987
181988static int sqlite3Fts5Tokenize(
181989  Fts5Config *pConfig,            /* FTS5 Configuration object */
181990  int flags,                      /* FTS5_TOKENIZE_* flags */
181991  const char *pText, int nText,   /* Text to tokenize */
181992  void *pCtx,                     /* Context passed to xToken() */
181993  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
181994);
181995
181996static void sqlite3Fts5Dequote(char *z);
181997
181998/* Load the contents of the %_config table */
181999static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
182000
182001/* Set the value of a single config attribute */
182002static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
182003
182004static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
182005
182006/*
182007** End of interface to code in fts5_config.c.
182008**************************************************************************/
182009
182010/**************************************************************************
182011** Interface to code in fts5_buffer.c.
182012*/
182013
182014/*
182015** Buffer object for the incremental building of string data.
182016*/
182017typedef struct Fts5Buffer Fts5Buffer;
182018struct Fts5Buffer {
182019  u8 *p;
182020  int n;
182021  int nSpace;
182022};
182023
182024static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
182025static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
182026static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
182027static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
182028static void sqlite3Fts5BufferFree(Fts5Buffer*);
182029static void sqlite3Fts5BufferZero(Fts5Buffer*);
182030static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
182031static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
182032
182033static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
182034
182035#define fts5BufferZero(x)             sqlite3Fts5BufferZero(x)
182036#define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
182037#define fts5BufferFree(a)             sqlite3Fts5BufferFree(a)
182038#define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
182039#define fts5BufferSet(a,b,c,d)        sqlite3Fts5BufferSet(a,b,c,d)
182040
182041#define fts5BufferGrow(pRc,pBuf,nn) ( \
182042  (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
182043    sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
182044)
182045
182046/* Write and decode big-endian 32-bit integer values */
182047static void sqlite3Fts5Put32(u8*, int);
182048static int sqlite3Fts5Get32(const u8*);
182049
182050#define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
182051#define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
182052
182053typedef struct Fts5PoslistReader Fts5PoslistReader;
182054struct Fts5PoslistReader {
182055  /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
182056  const u8 *a;                    /* Position list to iterate through */
182057  int n;                          /* Size of buffer at a[] in bytes */
182058  int i;                          /* Current offset in a[] */
182059
182060  u8 bFlag;                       /* For client use (any custom purpose) */
182061
182062  /* Output variables */
182063  u8 bEof;                        /* Set to true at EOF */
182064  i64 iPos;                       /* (iCol<<32) + iPos */
182065};
182066static int sqlite3Fts5PoslistReaderInit(
182067  const u8 *a, int n,             /* Poslist buffer to iterate through */
182068  Fts5PoslistReader *pIter        /* Iterator object to initialize */
182069);
182070static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
182071
182072typedef struct Fts5PoslistWriter Fts5PoslistWriter;
182073struct Fts5PoslistWriter {
182074  i64 iPrev;
182075};
182076static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
182077static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
182078
182079static int sqlite3Fts5PoslistNext64(
182080  const u8 *a, int n,             /* Buffer containing poslist */
182081  int *pi,                        /* IN/OUT: Offset within a[] */
182082  i64 *piOff                      /* IN/OUT: Current offset */
182083);
182084
182085/* Malloc utility */
182086static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
182087static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
182088
182089/* Character set tests (like isspace(), isalpha() etc.) */
182090static int sqlite3Fts5IsBareword(char t);
182091
182092
182093/* Bucket of terms object used by the integrity-check in offsets=0 mode. */
182094typedef struct Fts5Termset Fts5Termset;
182095static int sqlite3Fts5TermsetNew(Fts5Termset**);
182096static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
182097static void sqlite3Fts5TermsetFree(Fts5Termset*);
182098
182099/*
182100** End of interface to code in fts5_buffer.c.
182101**************************************************************************/
182102
182103/**************************************************************************
182104** Interface to code in fts5_index.c. fts5_index.c contains contains code
182105** to access the data stored in the %_data table.
182106*/
182107
182108typedef struct Fts5Index Fts5Index;
182109typedef struct Fts5IndexIter Fts5IndexIter;
182110
182111struct Fts5IndexIter {
182112  i64 iRowid;
182113  const u8 *pData;
182114  int nData;
182115  u8 bEof;
182116};
182117
182118#define sqlite3Fts5IterEof(x) ((x)->bEof)
182119
182120/*
182121** Values used as part of the flags argument passed to IndexQuery().
182122*/
182123#define FTS5INDEX_QUERY_PREFIX     0x0001   /* Prefix query */
182124#define FTS5INDEX_QUERY_DESC       0x0002   /* Docs in descending rowid order */
182125#define FTS5INDEX_QUERY_TEST_NOIDX 0x0004   /* Do not use prefix index */
182126#define FTS5INDEX_QUERY_SCAN       0x0008   /* Scan query (fts5vocab) */
182127
182128/* The following are used internally by the fts5_index.c module. They are
182129** defined here only to make it easier to avoid clashes with the flags
182130** above. */
182131#define FTS5INDEX_QUERY_SKIPEMPTY  0x0010
182132#define FTS5INDEX_QUERY_NOOUTPUT   0x0020
182133
182134/*
182135** Create/destroy an Fts5Index object.
182136*/
182137static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
182138static int sqlite3Fts5IndexClose(Fts5Index *p);
182139
182140/*
182141** Return a simple checksum value based on the arguments.
182142*/
182143static u64 sqlite3Fts5IndexEntryCksum(
182144  i64 iRowid,
182145  int iCol,
182146  int iPos,
182147  int iIdx,
182148  const char *pTerm,
182149  int nTerm
182150);
182151
182152/*
182153** Argument p points to a buffer containing utf-8 text that is n bytes in
182154** size. Return the number of bytes in the nChar character prefix of the
182155** buffer, or 0 if there are less than nChar characters in total.
182156*/
182157static int sqlite3Fts5IndexCharlenToBytelen(
182158  const char *p,
182159  int nByte,
182160  int nChar
182161);
182162
182163/*
182164** Open a new iterator to iterate though all rowids that match the
182165** specified token or token prefix.
182166*/
182167static int sqlite3Fts5IndexQuery(
182168  Fts5Index *p,                   /* FTS index to query */
182169  const char *pToken, int nToken, /* Token (or prefix) to query for */
182170  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
182171  Fts5Colset *pColset,            /* Match these columns only */
182172  Fts5IndexIter **ppIter          /* OUT: New iterator object */
182173);
182174
182175/*
182176** The various operations on open token or token prefix iterators opened
182177** using sqlite3Fts5IndexQuery().
182178*/
182179static int sqlite3Fts5IterNext(Fts5IndexIter*);
182180static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
182181
182182/*
182183** Close an iterator opened by sqlite3Fts5IndexQuery().
182184*/
182185static void sqlite3Fts5IterClose(Fts5IndexIter*);
182186
182187/*
182188** This interface is used by the fts5vocab module.
182189*/
182190static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
182191static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
182192
182193
182194/*
182195** Insert or remove data to or from the index. Each time a document is
182196** added to or removed from the index, this function is called one or more
182197** times.
182198**
182199** For an insert, it must be called once for each token in the new document.
182200** If the operation is a delete, it must be called (at least) once for each
182201** unique token in the document with an iCol value less than zero. The iPos
182202** argument is ignored for a delete.
182203*/
182204static int sqlite3Fts5IndexWrite(
182205  Fts5Index *p,                   /* Index to write to */
182206  int iCol,                       /* Column token appears in (-ve -> delete) */
182207  int iPos,                       /* Position of token within column */
182208  const char *pToken, int nToken  /* Token to add or remove to or from index */
182209);
182210
182211/*
182212** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
182213** document iDocid.
182214*/
182215static int sqlite3Fts5IndexBeginWrite(
182216  Fts5Index *p,                   /* Index to write to */
182217  int bDelete,                    /* True if current operation is a delete */
182218  i64 iDocid                      /* Docid to add or remove data from */
182219);
182220
182221/*
182222** Flush any data stored in the in-memory hash tables to the database.
182223** If the bCommit flag is true, also close any open blob handles.
182224*/
182225static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit);
182226
182227/*
182228** Discard any data stored in the in-memory hash tables. Do not write it
182229** to the database. Additionally, assume that the contents of the %_data
182230** table may have changed on disk. So any in-memory caches of %_data
182231** records must be invalidated.
182232*/
182233static int sqlite3Fts5IndexRollback(Fts5Index *p);
182234
182235/*
182236** Get or set the "averages" values.
182237*/
182238static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
182239static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
182240
182241/*
182242** Functions called by the storage module as part of integrity-check.
182243*/
182244static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
182245
182246/*
182247** Called during virtual module initialization to register UDF
182248** fts5_decode() with SQLite
182249*/
182250static int sqlite3Fts5IndexInit(sqlite3*);
182251
182252static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
182253
182254/*
182255** Return the total number of entries read from the %_data table by
182256** this connection since it was created.
182257*/
182258static int sqlite3Fts5IndexReads(Fts5Index *p);
182259
182260static int sqlite3Fts5IndexReinit(Fts5Index *p);
182261static int sqlite3Fts5IndexOptimize(Fts5Index *p);
182262static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
182263static int sqlite3Fts5IndexReset(Fts5Index *p);
182264
182265static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
182266
182267/*
182268** End of interface to code in fts5_index.c.
182269**************************************************************************/
182270
182271/**************************************************************************
182272** Interface to code in fts5_varint.c.
182273*/
182274static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
182275static int sqlite3Fts5GetVarintLen(u32 iVal);
182276static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
182277static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
182278
182279#define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
182280#define fts5GetVarint    sqlite3Fts5GetVarint
182281
182282#define fts5FastGetVarint32(a, iOff, nVal) {      \
182283  nVal = (a)[iOff++];                             \
182284  if( nVal & 0x80 ){                              \
182285    iOff--;                                       \
182286    iOff += fts5GetVarint32(&(a)[iOff], nVal);    \
182287  }                                               \
182288}
182289
182290
182291/*
182292** End of interface to code in fts5_varint.c.
182293**************************************************************************/
182294
182295
182296/**************************************************************************
182297** Interface to code in fts5.c.
182298*/
182299
182300static int sqlite3Fts5GetTokenizer(
182301  Fts5Global*,
182302  const char **azArg,
182303  int nArg,
182304  Fts5Tokenizer**,
182305  fts5_tokenizer**,
182306  char **pzErr
182307);
182308
182309static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
182310
182311/*
182312** End of interface to code in fts5.c.
182313**************************************************************************/
182314
182315/**************************************************************************
182316** Interface to code in fts5_hash.c.
182317*/
182318typedef struct Fts5Hash Fts5Hash;
182319
182320/*
182321** Create a hash table, free a hash table.
182322*/
182323static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
182324static void sqlite3Fts5HashFree(Fts5Hash*);
182325
182326static int sqlite3Fts5HashWrite(
182327  Fts5Hash*,
182328  i64 iRowid,                     /* Rowid for this entry */
182329  int iCol,                       /* Column token appears in (-ve -> delete) */
182330  int iPos,                       /* Position of token within column */
182331  char bByte,
182332  const char *pToken, int nToken  /* Token to add or remove to or from index */
182333);
182334
182335/*
182336** Empty (but do not delete) a hash table.
182337*/
182338static void sqlite3Fts5HashClear(Fts5Hash*);
182339
182340static int sqlite3Fts5HashQuery(
182341  Fts5Hash*,                      /* Hash table to query */
182342  const char *pTerm, int nTerm,   /* Query term */
182343  const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
182344  int *pnDoclist                  /* OUT: Size of doclist in bytes */
182345);
182346
182347static int sqlite3Fts5HashScanInit(
182348  Fts5Hash*,                      /* Hash table to query */
182349  const char *pTerm, int nTerm    /* Query prefix */
182350);
182351static void sqlite3Fts5HashScanNext(Fts5Hash*);
182352static int sqlite3Fts5HashScanEof(Fts5Hash*);
182353static void sqlite3Fts5HashScanEntry(Fts5Hash *,
182354  const char **pzTerm,            /* OUT: term (nul-terminated) */
182355  const u8 **ppDoclist,           /* OUT: pointer to doclist */
182356  int *pnDoclist                  /* OUT: size of doclist in bytes */
182357);
182358
182359
182360/*
182361** End of interface to code in fts5_hash.c.
182362**************************************************************************/
182363
182364/**************************************************************************
182365** Interface to code in fts5_storage.c. fts5_storage.c contains contains
182366** code to access the data stored in the %_content and %_docsize tables.
182367*/
182368
182369#define FTS5_STMT_SCAN_ASC  0     /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
182370#define FTS5_STMT_SCAN_DESC 1     /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
182371#define FTS5_STMT_LOOKUP    2     /* SELECT rowid, * FROM ... WHERE rowid=? */
182372
182373typedef struct Fts5Storage Fts5Storage;
182374
182375static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
182376static int sqlite3Fts5StorageClose(Fts5Storage *p);
182377static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
182378
182379static int sqlite3Fts5DropAll(Fts5Config*);
182380static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
182381
182382static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
182383static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
182384static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
182385
182386static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
182387
182388static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
182389static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
182390
182391static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
182392static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
182393static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
182394
182395static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit);
182396static int sqlite3Fts5StorageRollback(Fts5Storage *p);
182397
182398static int sqlite3Fts5StorageConfigValue(
182399    Fts5Storage *p, const char*, sqlite3_value*, int
182400);
182401
182402static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
182403static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
182404static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
182405static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
182406static int sqlite3Fts5StorageReset(Fts5Storage *p);
182407
182408/*
182409** End of interface to code in fts5_storage.c.
182410**************************************************************************/
182411
182412
182413/**************************************************************************
182414** Interface to code in fts5_expr.c.
182415*/
182416typedef struct Fts5Expr Fts5Expr;
182417typedef struct Fts5ExprNode Fts5ExprNode;
182418typedef struct Fts5Parse Fts5Parse;
182419typedef struct Fts5Token Fts5Token;
182420typedef struct Fts5ExprPhrase Fts5ExprPhrase;
182421typedef struct Fts5ExprNearset Fts5ExprNearset;
182422
182423struct Fts5Token {
182424  const char *p;                  /* Token text (not NULL terminated) */
182425  int n;                          /* Size of buffer p in bytes */
182426};
182427
182428/* Parse a MATCH expression. */
182429static int sqlite3Fts5ExprNew(
182430  Fts5Config *pConfig,
182431  const char *zExpr,
182432  Fts5Expr **ppNew,
182433  char **pzErr
182434);
182435
182436/*
182437** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
182438**     rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
182439**     rc = sqlite3Fts5ExprNext(pExpr)
182440** ){
182441**   // The document with rowid iRowid matches the expression!
182442**   i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
182443** }
182444*/
182445static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
182446static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
182447static int sqlite3Fts5ExprEof(Fts5Expr*);
182448static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
182449
182450static void sqlite3Fts5ExprFree(Fts5Expr*);
182451
182452/* Called during startup to register a UDF with SQLite */
182453static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
182454
182455static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
182456static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
182457static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
182458
182459typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
182460static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
182461static int sqlite3Fts5ExprPopulatePoslists(
182462    Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
182463);
182464static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
182465
182466static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
182467
182468static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
182469
182470/*******************************************
182471** The fts5_expr.c API above this point is used by the other hand-written
182472** C code in this module. The interfaces below this point are called by
182473** the parser code in fts5parse.y.  */
182474
182475static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
182476
182477static Fts5ExprNode *sqlite3Fts5ParseNode(
182478  Fts5Parse *pParse,
182479  int eType,
182480  Fts5ExprNode *pLeft,
182481  Fts5ExprNode *pRight,
182482  Fts5ExprNearset *pNear
182483);
182484
182485static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
182486  Fts5Parse *pParse,
182487  Fts5ExprNode *pLeft,
182488  Fts5ExprNode *pRight
182489);
182490
182491static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
182492  Fts5Parse *pParse,
182493  Fts5ExprPhrase *pPhrase,
182494  Fts5Token *pToken,
182495  int bPrefix
182496);
182497
182498static Fts5ExprNearset *sqlite3Fts5ParseNearset(
182499  Fts5Parse*,
182500  Fts5ExprNearset*,
182501  Fts5ExprPhrase*
182502);
182503
182504static Fts5Colset *sqlite3Fts5ParseColset(
182505  Fts5Parse*,
182506  Fts5Colset*,
182507  Fts5Token *
182508);
182509
182510static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
182511static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
182512static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
182513
182514static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
182515static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*);
182516static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
182517static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
182518static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
182519
182520/*
182521** End of interface to code in fts5_expr.c.
182522**************************************************************************/
182523
182524
182525
182526/**************************************************************************
182527** Interface to code in fts5_aux.c.
182528*/
182529
182530static int sqlite3Fts5AuxInit(fts5_api*);
182531/*
182532** End of interface to code in fts5_aux.c.
182533**************************************************************************/
182534
182535/**************************************************************************
182536** Interface to code in fts5_tokenizer.c.
182537*/
182538
182539static int sqlite3Fts5TokenizerInit(fts5_api*);
182540/*
182541** End of interface to code in fts5_tokenizer.c.
182542**************************************************************************/
182543
182544/**************************************************************************
182545** Interface to code in fts5_vocab.c.
182546*/
182547
182548static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
182549
182550/*
182551** End of interface to code in fts5_vocab.c.
182552**************************************************************************/
182553
182554
182555/**************************************************************************
182556** Interface to automatically generated code in fts5_unicode2.c.
182557*/
182558static int sqlite3Fts5UnicodeIsalnum(int c);
182559static int sqlite3Fts5UnicodeIsdiacritic(int c);
182560static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
182561/*
182562** End of interface to code in fts5_unicode2.c.
182563**************************************************************************/
182564
182565#endif
182566
182567#define FTS5_OR                               1
182568#define FTS5_AND                              2
182569#define FTS5_NOT                              3
182570#define FTS5_TERM                             4
182571#define FTS5_COLON                            5
182572#define FTS5_LP                               6
182573#define FTS5_RP                               7
182574#define FTS5_MINUS                            8
182575#define FTS5_LCP                              9
182576#define FTS5_RCP                             10
182577#define FTS5_STRING                          11
182578#define FTS5_COMMA                           12
182579#define FTS5_PLUS                            13
182580#define FTS5_STAR                            14
182581
182582/*
182583** 2000-05-29
182584**
182585** The author disclaims copyright to this source code.  In place of
182586** a legal notice, here is a blessing:
182587**
182588**    May you do good and not evil.
182589**    May you find forgiveness for yourself and forgive others.
182590**    May you share freely, never taking more than you give.
182591**
182592*************************************************************************
182593** Driver template for the LEMON parser generator.
182594**
182595** The "lemon" program processes an LALR(1) input grammar file, then uses
182596** this template to construct a parser.  The "lemon" program inserts text
182597** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
182598** interstitial "-" characters) contained in this template is changed into
182599** the value of the %name directive from the grammar.  Otherwise, the content
182600** of this template is copied straight through into the generate parser
182601** source file.
182602**
182603** The following is the concatenation of all %include directives from the
182604** input grammar file:
182605*/
182606/* #include <stdio.h> */
182607/************ Begin %include sections from the grammar ************************/
182608
182609/* #include "fts5Int.h" */
182610/* #include "fts5parse.h" */
182611
182612/*
182613** Disable all error recovery processing in the parser push-down
182614** automaton.
182615*/
182616#define fts5YYNOERRORRECOVERY 1
182617
182618/*
182619** Make fts5yytestcase() the same as testcase()
182620*/
182621#define fts5yytestcase(X) testcase(X)
182622
182623/*
182624** Indicate that sqlite3ParserFree() will never be called with a null
182625** pointer.
182626*/
182627#define fts5YYPARSEFREENOTNULL 1
182628
182629/*
182630** Alternative datatype for the argument to the malloc() routine passed
182631** into sqlite3ParserAlloc().  The default is size_t.
182632*/
182633#define fts5YYMALLOCARGTYPE  u64
182634
182635/**************** End of %include directives **********************************/
182636/* These constants specify the various numeric values for terminal symbols
182637** in a format understandable to "makeheaders".  This section is blank unless
182638** "lemon" is run with the "-m" command-line option.
182639***************** Begin makeheaders token definitions *************************/
182640/**************** End makeheaders token definitions ***************************/
182641
182642/* The next sections is a series of control #defines.
182643** various aspects of the generated parser.
182644**    fts5YYCODETYPE         is the data type used to store the integer codes
182645**                       that represent terminal and non-terminal symbols.
182646**                       "unsigned char" is used if there are fewer than
182647**                       256 symbols.  Larger types otherwise.
182648**    fts5YYNOCODE           is a number of type fts5YYCODETYPE that is not used for
182649**                       any terminal or nonterminal symbol.
182650**    fts5YYFALLBACK         If defined, this indicates that one or more tokens
182651**                       (also known as: "terminal symbols") have fall-back
182652**                       values which should be used if the original symbol
182653**                       would not parse.  This permits keywords to sometimes
182654**                       be used as identifiers, for example.
182655**    fts5YYACTIONTYPE       is the data type used for "action codes" - numbers
182656**                       that indicate what to do in response to the next
182657**                       token.
182658**    sqlite3Fts5ParserFTS5TOKENTYPE     is the data type used for minor type for terminal
182659**                       symbols.  Background: A "minor type" is a semantic
182660**                       value associated with a terminal or non-terminal
182661**                       symbols.  For example, for an "ID" terminal symbol,
182662**                       the minor type might be the name of the identifier.
182663**                       Each non-terminal can have a different minor type.
182664**                       Terminal symbols all have the same minor type, though.
182665**                       This macros defines the minor type for terminal
182666**                       symbols.
182667**    fts5YYMINORTYPE        is the data type used for all minor types.
182668**                       This is typically a union of many types, one of
182669**                       which is sqlite3Fts5ParserFTS5TOKENTYPE.  The entry in the union
182670**                       for terminal symbols is called "fts5yy0".
182671**    fts5YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
182672**                       zero the stack is dynamically sized using realloc()
182673**    sqlite3Fts5ParserARG_SDECL     A static variable declaration for the %extra_argument
182674**    sqlite3Fts5ParserARG_PDECL     A parameter declaration for the %extra_argument
182675**    sqlite3Fts5ParserARG_STORE     Code to store %extra_argument into fts5yypParser
182676**    sqlite3Fts5ParserARG_FETCH     Code to extract %extra_argument from fts5yypParser
182677**    fts5YYERRORSYMBOL      is the code number of the error symbol.  If not
182678**                       defined, then do no error processing.
182679**    fts5YYNSTATE           the combined number of states.
182680**    fts5YYNRULE            the number of rules in the grammar
182681**    fts5YY_MAX_SHIFT       Maximum value for shift actions
182682**    fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
182683**    fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
182684**    fts5YY_MIN_REDUCE      Maximum value for reduce actions
182685**    fts5YY_ERROR_ACTION    The fts5yy_action[] code for syntax error
182686**    fts5YY_ACCEPT_ACTION   The fts5yy_action[] code for accept
182687**    fts5YY_NO_ACTION       The fts5yy_action[] code for no-op
182688*/
182689#ifndef INTERFACE
182690# define INTERFACE 1
182691#endif
182692/************* Begin control #defines *****************************************/
182693#define fts5YYCODETYPE unsigned char
182694#define fts5YYNOCODE 28
182695#define fts5YYACTIONTYPE unsigned char
182696#define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
182697typedef union {
182698  int fts5yyinit;
182699  sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
182700  int fts5yy4;
182701  Fts5Colset* fts5yy11;
182702  Fts5ExprNode* fts5yy24;
182703  Fts5ExprNearset* fts5yy46;
182704  Fts5ExprPhrase* fts5yy53;
182705} fts5YYMINORTYPE;
182706#ifndef fts5YYSTACKDEPTH
182707#define fts5YYSTACKDEPTH 100
182708#endif
182709#define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
182710#define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
182711#define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
182712#define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
182713#define fts5YYNSTATE             29
182714#define fts5YYNRULE              26
182715#define fts5YY_MAX_SHIFT         28
182716#define fts5YY_MIN_SHIFTREDUCE   45
182717#define fts5YY_MAX_SHIFTREDUCE   70
182718#define fts5YY_MIN_REDUCE        71
182719#define fts5YY_MAX_REDUCE        96
182720#define fts5YY_ERROR_ACTION      97
182721#define fts5YY_ACCEPT_ACTION     98
182722#define fts5YY_NO_ACTION         99
182723/************* End control #defines *******************************************/
182724
182725/* Define the fts5yytestcase() macro to be a no-op if is not already defined
182726** otherwise.
182727**
182728** Applications can choose to define fts5yytestcase() in the %include section
182729** to a macro that can assist in verifying code coverage.  For production
182730** code the fts5yytestcase() macro should be turned off.  But it is useful
182731** for testing.
182732*/
182733#ifndef fts5yytestcase
182734# define fts5yytestcase(X)
182735#endif
182736
182737
182738/* Next are the tables used to determine what action to take based on the
182739** current state and lookahead token.  These tables are used to implement
182740** functions that take a state number and lookahead value and return an
182741** action integer.
182742**
182743** Suppose the action integer is N.  Then the action is determined as
182744** follows
182745**
182746**   0 <= N <= fts5YY_MAX_SHIFT             Shift N.  That is, push the lookahead
182747**                                      token onto the stack and goto state N.
182748**
182749**   N between fts5YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
182750**     and fts5YY_MAX_SHIFTREDUCE           reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
182751**
182752**   N between fts5YY_MIN_REDUCE            Reduce by rule N-fts5YY_MIN_REDUCE
182753**     and fts5YY_MAX_REDUCE
182754**
182755**   N == fts5YY_ERROR_ACTION               A syntax error has occurred.
182756**
182757**   N == fts5YY_ACCEPT_ACTION              The parser accepts its input.
182758**
182759**   N == fts5YY_NO_ACTION                  No such action.  Denotes unused
182760**                                      slots in the fts5yy_action[] table.
182761**
182762** The action table is constructed as a single large table named fts5yy_action[].
182763** Given state S and lookahead X, the action is computed as either:
182764**
182765**    (A)   N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
182766**    (B)   N = fts5yy_default[S]
182767**
182768** The (A) formula is preferred.  The B formula is used instead if:
182769**    (1)  The fts5yy_shift_ofst[S]+X value is out of range, or
182770**    (2)  fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X, or
182771**    (3)  fts5yy_shift_ofst[S] equal fts5YY_SHIFT_USE_DFLT.
182772** (Implementation note: fts5YY_SHIFT_USE_DFLT is chosen so that
182773** fts5YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
182774** Hence only tests (1) and (2) need to be evaluated.)
182775**
182776** The formulas above are for computing the action when the lookahead is
182777** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
182778** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
182779** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
182780** fts5YY_SHIFT_USE_DFLT.
182781**
182782** The following are the tables generated in this section:
182783**
182784**  fts5yy_action[]        A single table containing all actions.
182785**  fts5yy_lookahead[]     A table containing the lookahead for each entry in
182786**                     fts5yy_action.  Used to detect hash collisions.
182787**  fts5yy_shift_ofst[]    For each state, the offset into fts5yy_action for
182788**                     shifting terminals.
182789**  fts5yy_reduce_ofst[]   For each state, the offset into fts5yy_action for
182790**                     shifting non-terminals after a reduce.
182791**  fts5yy_default[]       Default action for each state.
182792**
182793*********** Begin parsing tables **********************************************/
182794#define fts5YY_ACTTAB_COUNT (85)
182795static const fts5YYACTIONTYPE fts5yy_action[] = {
182796 /*     0 */    98,   16,   51,    5,   53,   27,   83,    7,   26,   15,
182797 /*    10 */    51,    5,   53,   27,   13,   69,   26,   48,   51,    5,
182798 /*    20 */    53,   27,   19,   11,   26,    9,   20,   51,    5,   53,
182799 /*    30 */    27,   13,   22,   26,   28,   51,    5,   53,   27,   68,
182800 /*    40 */     1,   26,   19,   11,   17,    9,   52,   10,   53,   27,
182801 /*    50 */    23,   24,   26,   54,    3,    4,    2,   26,    6,   21,
182802 /*    60 */    49,   71,    3,    4,    2,    7,   56,   59,   55,   59,
182803 /*    70 */     4,    2,   12,   69,   58,   60,   18,   67,   62,   69,
182804 /*    80 */    25,   66,    8,   14,    2,
182805};
182806static const fts5YYCODETYPE fts5yy_lookahead[] = {
182807 /*     0 */    16,   17,   18,   19,   20,   21,    5,    6,   24,   17,
182808 /*    10 */    18,   19,   20,   21,   11,   14,   24,   17,   18,   19,
182809 /*    20 */    20,   21,    8,    9,   24,   11,   17,   18,   19,   20,
182810 /*    30 */    21,   11,   12,   24,   17,   18,   19,   20,   21,   26,
182811 /*    40 */     6,   24,    8,    9,   22,   11,   18,   11,   20,   21,
182812 /*    50 */    24,   25,   24,   20,    1,    2,    3,   24,   23,   24,
182813 /*    60 */     7,    0,    1,    2,    3,    6,   10,   11,   10,   11,
182814 /*    70 */     2,    3,    9,   14,   11,   11,   22,   26,    7,   14,
182815 /*    80 */    13,   11,    5,   11,    3,
182816};
182817#define fts5YY_SHIFT_USE_DFLT (85)
182818#define fts5YY_SHIFT_COUNT    (28)
182819#define fts5YY_SHIFT_MIN      (0)
182820#define fts5YY_SHIFT_MAX      (81)
182821static const unsigned char fts5yy_shift_ofst[] = {
182822 /*     0 */    34,   34,   34,   34,   34,   14,   20,    3,   36,    1,
182823 /*    10 */    59,   64,   64,   65,   65,   53,   61,   56,   58,   63,
182824 /*    20 */    68,   67,   70,   67,   71,   72,   67,   77,   81,
182825};
182826#define fts5YY_REDUCE_USE_DFLT (-17)
182827#define fts5YY_REDUCE_COUNT (14)
182828#define fts5YY_REDUCE_MIN   (-16)
182829#define fts5YY_REDUCE_MAX   (54)
182830static const signed char fts5yy_reduce_ofst[] = {
182831 /*     0 */   -16,   -8,    0,    9,   17,   28,   26,   35,   33,   13,
182832 /*    10 */    13,   22,   54,   13,   51,
182833};
182834static const fts5YYACTIONTYPE fts5yy_default[] = {
182835 /*     0 */    97,   97,   97,   97,   97,   76,   91,   97,   97,   96,
182836 /*    10 */    96,   97,   97,   96,   96,   97,   97,   97,   97,   97,
182837 /*    20 */    73,   89,   97,   90,   97,   97,   87,   97,   72,
182838};
182839/********** End of lemon-generated parsing tables *****************************/
182840
182841/* The next table maps tokens (terminal symbols) into fallback tokens.
182842** If a construct like the following:
182843**
182844**      %fallback ID X Y Z.
182845**
182846** appears in the grammar, then ID becomes a fallback token for X, Y,
182847** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
182848** but it does not parse, the type of the token is changed to ID and
182849** the parse is retried before an error is thrown.
182850**
182851** This feature can be used, for example, to cause some keywords in a language
182852** to revert to identifiers if they keyword does not apply in the context where
182853** it appears.
182854*/
182855#ifdef fts5YYFALLBACK
182856static const fts5YYCODETYPE fts5yyFallback[] = {
182857};
182858#endif /* fts5YYFALLBACK */
182859
182860/* The following structure represents a single element of the
182861** parser's stack.  Information stored includes:
182862**
182863**   +  The state number for the parser at this level of the stack.
182864**
182865**   +  The value of the token stored at this level of the stack.
182866**      (In other words, the "major" token.)
182867**
182868**   +  The semantic value stored at this level of the stack.  This is
182869**      the information used by the action routines in the grammar.
182870**      It is sometimes called the "minor" token.
182871**
182872** After the "shift" half of a SHIFTREDUCE action, the stateno field
182873** actually contains the reduce action for the second half of the
182874** SHIFTREDUCE.
182875*/
182876struct fts5yyStackEntry {
182877  fts5YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
182878  fts5YYCODETYPE major;      /* The major token value.  This is the code
182879                         ** number for the token at this stack level */
182880  fts5YYMINORTYPE minor;     /* The user-supplied minor token value.  This
182881                         ** is the value of the token  */
182882};
182883typedef struct fts5yyStackEntry fts5yyStackEntry;
182884
182885/* The state of the parser is completely contained in an instance of
182886** the following structure */
182887struct fts5yyParser {
182888  fts5yyStackEntry *fts5yytos;          /* Pointer to top element of the stack */
182889#ifdef fts5YYTRACKMAXSTACKDEPTH
182890  int fts5yyhwm;                    /* High-water mark of the stack */
182891#endif
182892#ifndef fts5YYNOERRORRECOVERY
182893  int fts5yyerrcnt;                 /* Shifts left before out of the error */
182894#endif
182895  sqlite3Fts5ParserARG_SDECL                /* A place to hold %extra_argument */
182896#if fts5YYSTACKDEPTH<=0
182897  int fts5yystksz;                  /* Current side of the stack */
182898  fts5yyStackEntry *fts5yystack;        /* The parser's stack */
182899  fts5yyStackEntry fts5yystk0;          /* First stack entry */
182900#else
182901  fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH];  /* The parser's stack */
182902#endif
182903};
182904typedef struct fts5yyParser fts5yyParser;
182905
182906#ifndef NDEBUG
182907/* #include <stdio.h> */
182908static FILE *fts5yyTraceFILE = 0;
182909static char *fts5yyTracePrompt = 0;
182910#endif /* NDEBUG */
182911
182912#ifndef NDEBUG
182913/*
182914** Turn parser tracing on by giving a stream to which to write the trace
182915** and a prompt to preface each trace message.  Tracing is turned off
182916** by making either argument NULL
182917**
182918** Inputs:
182919** <ul>
182920** <li> A FILE* to which trace output should be written.
182921**      If NULL, then tracing is turned off.
182922** <li> A prefix string written at the beginning of every
182923**      line of trace output.  If NULL, then tracing is
182924**      turned off.
182925** </ul>
182926**
182927** Outputs:
182928** None.
182929*/
182930static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
182931  fts5yyTraceFILE = TraceFILE;
182932  fts5yyTracePrompt = zTracePrompt;
182933  if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
182934  else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
182935}
182936#endif /* NDEBUG */
182937
182938#ifndef NDEBUG
182939/* For tracing shifts, the names of all terminals and nonterminals
182940** are required.  The following table supplies these names */
182941static const char *const fts5yyTokenName[] = {
182942  "$",             "OR",            "AND",           "NOT",
182943  "TERM",          "COLON",         "LP",            "RP",
182944  "MINUS",         "LCP",           "RCP",           "STRING",
182945  "COMMA",         "PLUS",          "STAR",          "error",
182946  "input",         "expr",          "cnearset",      "exprlist",
182947  "nearset",       "colset",        "colsetlist",    "nearphrases",
182948  "phrase",        "neardist_opt",  "star_opt",
182949};
182950#endif /* NDEBUG */
182951
182952#ifndef NDEBUG
182953/* For tracing reduce actions, the names of all rules are required.
182954*/
182955static const char *const fts5yyRuleName[] = {
182956 /*   0 */ "input ::= expr",
182957 /*   1 */ "expr ::= expr AND expr",
182958 /*   2 */ "expr ::= expr OR expr",
182959 /*   3 */ "expr ::= expr NOT expr",
182960 /*   4 */ "expr ::= LP expr RP",
182961 /*   5 */ "expr ::= exprlist",
182962 /*   6 */ "exprlist ::= cnearset",
182963 /*   7 */ "exprlist ::= exprlist cnearset",
182964 /*   8 */ "cnearset ::= nearset",
182965 /*   9 */ "cnearset ::= colset COLON nearset",
182966 /*  10 */ "colset ::= MINUS LCP colsetlist RCP",
182967 /*  11 */ "colset ::= LCP colsetlist RCP",
182968 /*  12 */ "colset ::= STRING",
182969 /*  13 */ "colset ::= MINUS STRING",
182970 /*  14 */ "colsetlist ::= colsetlist STRING",
182971 /*  15 */ "colsetlist ::= STRING",
182972 /*  16 */ "nearset ::= phrase",
182973 /*  17 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
182974 /*  18 */ "nearphrases ::= phrase",
182975 /*  19 */ "nearphrases ::= nearphrases phrase",
182976 /*  20 */ "neardist_opt ::=",
182977 /*  21 */ "neardist_opt ::= COMMA STRING",
182978 /*  22 */ "phrase ::= phrase PLUS STRING star_opt",
182979 /*  23 */ "phrase ::= STRING star_opt",
182980 /*  24 */ "star_opt ::= STAR",
182981 /*  25 */ "star_opt ::=",
182982};
182983#endif /* NDEBUG */
182984
182985
182986#if fts5YYSTACKDEPTH<=0
182987/*
182988** Try to increase the size of the parser stack.  Return the number
182989** of errors.  Return 0 on success.
182990*/
182991static int fts5yyGrowStack(fts5yyParser *p){
182992  int newSize;
182993  int idx;
182994  fts5yyStackEntry *pNew;
182995
182996  newSize = p->fts5yystksz*2 + 100;
182997  idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
182998  if( p->fts5yystack==&p->fts5yystk0 ){
182999    pNew = malloc(newSize*sizeof(pNew[0]));
183000    if( pNew ) pNew[0] = p->fts5yystk0;
183001  }else{
183002    pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
183003  }
183004  if( pNew ){
183005    p->fts5yystack = pNew;
183006    p->fts5yytos = &p->fts5yystack[idx];
183007#ifndef NDEBUG
183008    if( fts5yyTraceFILE ){
183009      fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
183010              fts5yyTracePrompt, p->fts5yystksz, newSize);
183011    }
183012#endif
183013    p->fts5yystksz = newSize;
183014  }
183015  return pNew==0;
183016}
183017#endif
183018
183019/* Datatype of the argument to the memory allocated passed as the
183020** second argument to sqlite3Fts5ParserAlloc() below.  This can be changed by
183021** putting an appropriate #define in the %include section of the input
183022** grammar.
183023*/
183024#ifndef fts5YYMALLOCARGTYPE
183025# define fts5YYMALLOCARGTYPE size_t
183026#endif
183027
183028/* Initialize a new parser that has already been allocated.
183029*/
183030static void sqlite3Fts5ParserInit(void *fts5yypParser){
183031  fts5yyParser *pParser = (fts5yyParser*)fts5yypParser;
183032#ifdef fts5YYTRACKMAXSTACKDEPTH
183033  pParser->fts5yyhwm = 0;
183034#endif
183035#if fts5YYSTACKDEPTH<=0
183036  pParser->fts5yytos = NULL;
183037  pParser->fts5yystack = NULL;
183038  pParser->fts5yystksz = 0;
183039  if( fts5yyGrowStack(pParser) ){
183040    pParser->fts5yystack = &pParser->fts5yystk0;
183041    pParser->fts5yystksz = 1;
183042  }
183043#endif
183044#ifndef fts5YYNOERRORRECOVERY
183045  pParser->fts5yyerrcnt = -1;
183046#endif
183047  pParser->fts5yytos = pParser->fts5yystack;
183048  pParser->fts5yystack[0].stateno = 0;
183049  pParser->fts5yystack[0].major = 0;
183050}
183051
183052#ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
183053/*
183054** This function allocates a new parser.
183055** The only argument is a pointer to a function which works like
183056** malloc.
183057**
183058** Inputs:
183059** A pointer to the function used to allocate memory.
183060**
183061** Outputs:
183062** A pointer to a parser.  This pointer is used in subsequent calls
183063** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
183064*/
183065static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
183066  fts5yyParser *pParser;
183067  pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
183068  if( pParser ) sqlite3Fts5ParserInit(pParser);
183069  return pParser;
183070}
183071#endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
183072
183073
183074/* The following function deletes the "minor type" or semantic value
183075** associated with a symbol.  The symbol can be either a terminal
183076** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
183077** a pointer to the value to be deleted.  The code used to do the
183078** deletions is derived from the %destructor and/or %token_destructor
183079** directives of the input grammar.
183080*/
183081static void fts5yy_destructor(
183082  fts5yyParser *fts5yypParser,    /* The parser */
183083  fts5YYCODETYPE fts5yymajor,     /* Type code for object to destroy */
183084  fts5YYMINORTYPE *fts5yypminor   /* The object to be destroyed */
183085){
183086  sqlite3Fts5ParserARG_FETCH;
183087  switch( fts5yymajor ){
183088    /* Here is inserted the actions which take place when a
183089    ** terminal or non-terminal is destroyed.  This can happen
183090    ** when the symbol is popped from the stack during a
183091    ** reduce or during error processing or when a parser is
183092    ** being destroyed before it is finished parsing.
183093    **
183094    ** Note: during a reduce, the only symbols destroyed are those
183095    ** which appear on the RHS of the rule, but which are *not* used
183096    ** inside the C code.
183097    */
183098/********* Begin destructor definitions ***************************************/
183099    case 16: /* input */
183100{
183101 (void)pParse;
183102}
183103      break;
183104    case 17: /* expr */
183105    case 18: /* cnearset */
183106    case 19: /* exprlist */
183107{
183108 sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
183109}
183110      break;
183111    case 20: /* nearset */
183112    case 23: /* nearphrases */
183113{
183114 sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
183115}
183116      break;
183117    case 21: /* colset */
183118    case 22: /* colsetlist */
183119{
183120 sqlite3_free((fts5yypminor->fts5yy11));
183121}
183122      break;
183123    case 24: /* phrase */
183124{
183125 sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
183126}
183127      break;
183128/********* End destructor definitions *****************************************/
183129    default:  break;   /* If no destructor action specified: do nothing */
183130  }
183131}
183132
183133/*
183134** Pop the parser's stack once.
183135**
183136** If there is a destructor routine associated with the token which
183137** is popped from the stack, then call it.
183138*/
183139static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
183140  fts5yyStackEntry *fts5yytos;
183141  assert( pParser->fts5yytos!=0 );
183142  assert( pParser->fts5yytos > pParser->fts5yystack );
183143  fts5yytos = pParser->fts5yytos--;
183144#ifndef NDEBUG
183145  if( fts5yyTraceFILE ){
183146    fprintf(fts5yyTraceFILE,"%sPopping %s\n",
183147      fts5yyTracePrompt,
183148      fts5yyTokenName[fts5yytos->major]);
183149  }
183150#endif
183151  fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
183152}
183153
183154/*
183155** Clear all secondary memory allocations from the parser
183156*/
183157static void sqlite3Fts5ParserFinalize(void *p){
183158  fts5yyParser *pParser = (fts5yyParser*)p;
183159  while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
183160#if fts5YYSTACKDEPTH<=0
183161  if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
183162#endif
183163}
183164
183165#ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
183166/*
183167** Deallocate and destroy a parser.  Destructors are called for
183168** all stack elements before shutting the parser down.
183169**
183170** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
183171** is defined in a %include section of the input grammar) then it is
183172** assumed that the input pointer is never NULL.
183173*/
183174static void sqlite3Fts5ParserFree(
183175  void *p,                    /* The parser to be deleted */
183176  void (*freeProc)(void*)     /* Function used to reclaim memory */
183177){
183178#ifndef fts5YYPARSEFREENEVERNULL
183179  if( p==0 ) return;
183180#endif
183181  sqlite3Fts5ParserFinalize(p);
183182  (*freeProc)(p);
183183}
183184#endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
183185
183186/*
183187** Return the peak depth of the stack for a parser.
183188*/
183189#ifdef fts5YYTRACKMAXSTACKDEPTH
183190static int sqlite3Fts5ParserStackPeak(void *p){
183191  fts5yyParser *pParser = (fts5yyParser*)p;
183192  return pParser->fts5yyhwm;
183193}
183194#endif
183195
183196/*
183197** Find the appropriate action for a parser given the terminal
183198** look-ahead token iLookAhead.
183199*/
183200static unsigned int fts5yy_find_shift_action(
183201  fts5yyParser *pParser,        /* The parser */
183202  fts5YYCODETYPE iLookAhead     /* The look-ahead token */
183203){
183204  int i;
183205  int stateno = pParser->fts5yytos->stateno;
183206
183207  if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
183208  assert( stateno <= fts5YY_SHIFT_COUNT );
183209  do{
183210    i = fts5yy_shift_ofst[stateno];
183211    assert( iLookAhead!=fts5YYNOCODE );
183212    i += iLookAhead;
183213    if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
183214#ifdef fts5YYFALLBACK
183215      fts5YYCODETYPE iFallback;            /* Fallback token */
183216      if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
183217             && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
183218#ifndef NDEBUG
183219        if( fts5yyTraceFILE ){
183220          fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
183221             fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
183222        }
183223#endif
183224        assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
183225        iLookAhead = iFallback;
183226        continue;
183227      }
183228#endif
183229#ifdef fts5YYWILDCARD
183230      {
183231        int j = i - iLookAhead + fts5YYWILDCARD;
183232        if(
183233#if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
183234          j>=0 &&
183235#endif
183236#if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
183237          j<fts5YY_ACTTAB_COUNT &&
183238#endif
183239          fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
183240        ){
183241#ifndef NDEBUG
183242          if( fts5yyTraceFILE ){
183243            fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
183244               fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
183245               fts5yyTokenName[fts5YYWILDCARD]);
183246          }
183247#endif /* NDEBUG */
183248          return fts5yy_action[j];
183249        }
183250      }
183251#endif /* fts5YYWILDCARD */
183252      return fts5yy_default[stateno];
183253    }else{
183254      return fts5yy_action[i];
183255    }
183256  }while(1);
183257}
183258
183259/*
183260** Find the appropriate action for a parser given the non-terminal
183261** look-ahead token iLookAhead.
183262*/
183263static int fts5yy_find_reduce_action(
183264  int stateno,              /* Current state number */
183265  fts5YYCODETYPE iLookAhead     /* The look-ahead token */
183266){
183267  int i;
183268#ifdef fts5YYERRORSYMBOL
183269  if( stateno>fts5YY_REDUCE_COUNT ){
183270    return fts5yy_default[stateno];
183271  }
183272#else
183273  assert( stateno<=fts5YY_REDUCE_COUNT );
183274#endif
183275  i = fts5yy_reduce_ofst[stateno];
183276  assert( i!=fts5YY_REDUCE_USE_DFLT );
183277  assert( iLookAhead!=fts5YYNOCODE );
183278  i += iLookAhead;
183279#ifdef fts5YYERRORSYMBOL
183280  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
183281    return fts5yy_default[stateno];
183282  }
183283#else
183284  assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
183285  assert( fts5yy_lookahead[i]==iLookAhead );
183286#endif
183287  return fts5yy_action[i];
183288}
183289
183290/*
183291** The following routine is called if the stack overflows.
183292*/
183293static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
183294   sqlite3Fts5ParserARG_FETCH;
183295#ifndef NDEBUG
183296   if( fts5yyTraceFILE ){
183297     fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
183298   }
183299#endif
183300   while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
183301   /* Here code is inserted which will execute if the parser
183302   ** stack every overflows */
183303/******** Begin %stack_overflow code ******************************************/
183304
183305  sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
183306/******** End %stack_overflow code ********************************************/
183307   sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
183308}
183309
183310/*
183311** Print tracing information for a SHIFT action
183312*/
183313#ifndef NDEBUG
183314static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
183315  if( fts5yyTraceFILE ){
183316    if( fts5yyNewState<fts5YYNSTATE ){
183317      fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
183318         fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major],
183319         fts5yyNewState);
183320    }else{
183321      fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
183322         fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major]);
183323    }
183324  }
183325}
183326#else
183327# define fts5yyTraceShift(X,Y)
183328#endif
183329
183330/*
183331** Perform a shift action.
183332*/
183333static void fts5yy_shift(
183334  fts5yyParser *fts5yypParser,          /* The parser to be shifted */
183335  int fts5yyNewState,               /* The new state to shift in */
183336  int fts5yyMajor,                  /* The major token to shift in */
183337  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor        /* The minor token to shift in */
183338){
183339  fts5yyStackEntry *fts5yytos;
183340  fts5yypParser->fts5yytos++;
183341#ifdef fts5YYTRACKMAXSTACKDEPTH
183342  if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
183343    fts5yypParser->fts5yyhwm++;
183344    assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
183345  }
183346#endif
183347#if fts5YYSTACKDEPTH>0
183348  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH] ){
183349    fts5yypParser->fts5yytos--;
183350    fts5yyStackOverflow(fts5yypParser);
183351    return;
183352  }
183353#else
183354  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
183355    if( fts5yyGrowStack(fts5yypParser) ){
183356      fts5yypParser->fts5yytos--;
183357      fts5yyStackOverflow(fts5yypParser);
183358      return;
183359    }
183360  }
183361#endif
183362  if( fts5yyNewState > fts5YY_MAX_SHIFT ){
183363    fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
183364  }
183365  fts5yytos = fts5yypParser->fts5yytos;
183366  fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
183367  fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
183368  fts5yytos->minor.fts5yy0 = fts5yyMinor;
183369  fts5yyTraceShift(fts5yypParser, fts5yyNewState);
183370}
183371
183372/* The following table contains information about every rule that
183373** is used during the reduce.
183374*/
183375static const struct {
183376  fts5YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
183377  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
183378} fts5yyRuleInfo[] = {
183379  { 16, 1 },
183380  { 17, 3 },
183381  { 17, 3 },
183382  { 17, 3 },
183383  { 17, 3 },
183384  { 17, 1 },
183385  { 19, 1 },
183386  { 19, 2 },
183387  { 18, 1 },
183388  { 18, 3 },
183389  { 21, 4 },
183390  { 21, 3 },
183391  { 21, 1 },
183392  { 21, 2 },
183393  { 22, 2 },
183394  { 22, 1 },
183395  { 20, 1 },
183396  { 20, 5 },
183397  { 23, 1 },
183398  { 23, 2 },
183399  { 25, 0 },
183400  { 25, 2 },
183401  { 24, 4 },
183402  { 24, 2 },
183403  { 26, 1 },
183404  { 26, 0 },
183405};
183406
183407static void fts5yy_accept(fts5yyParser*);  /* Forward Declaration */
183408
183409/*
183410** Perform a reduce action and the shift that must immediately
183411** follow the reduce.
183412*/
183413static void fts5yy_reduce(
183414  fts5yyParser *fts5yypParser,         /* The parser */
183415  unsigned int fts5yyruleno        /* Number of the rule by which to reduce */
183416){
183417  int fts5yygoto;                     /* The next state */
183418  int fts5yyact;                      /* The next action */
183419  fts5yyStackEntry *fts5yymsp;            /* The top of the parser's stack */
183420  int fts5yysize;                     /* Amount to pop the stack */
183421  sqlite3Fts5ParserARG_FETCH;
183422  fts5yymsp = fts5yypParser->fts5yytos;
183423#ifndef NDEBUG
183424  if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
183425    fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
183426    fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
183427      fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno);
183428  }
183429#endif /* NDEBUG */
183430
183431  /* Check that the stack is large enough to grow by a single entry
183432  ** if the RHS of the rule is empty.  This ensures that there is room
183433  ** enough on the stack to push the LHS value */
183434  if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
183435#ifdef fts5YYTRACKMAXSTACKDEPTH
183436    if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
183437      fts5yypParser->fts5yyhwm++;
183438      assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
183439    }
183440#endif
183441#if fts5YYSTACKDEPTH>0
183442    if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1] ){
183443      fts5yyStackOverflow(fts5yypParser);
183444      return;
183445    }
183446#else
183447    if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
183448      if( fts5yyGrowStack(fts5yypParser) ){
183449        fts5yyStackOverflow(fts5yypParser);
183450        return;
183451      }
183452      fts5yymsp = fts5yypParser->fts5yytos;
183453    }
183454#endif
183455  }
183456
183457  switch( fts5yyruleno ){
183458  /* Beginning here are the reduction cases.  A typical example
183459  ** follows:
183460  **   case 0:
183461  **  #line <lineno> <grammarfile>
183462  **     { ... }           // User supplied code
183463  **  #line <lineno> <thisfile>
183464  **     break;
183465  */
183466/********** Begin reduce actions **********************************************/
183467        fts5YYMINORTYPE fts5yylhsminor;
183468      case 0: /* input ::= expr */
183469{ sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
183470        break;
183471      case 1: /* expr ::= expr AND expr */
183472{
183473  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
183474}
183475  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
183476        break;
183477      case 2: /* expr ::= expr OR expr */
183478{
183479  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
183480}
183481  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
183482        break;
183483      case 3: /* expr ::= expr NOT expr */
183484{
183485  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
183486}
183487  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
183488        break;
183489      case 4: /* expr ::= LP expr RP */
183490{fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
183491        break;
183492      case 5: /* expr ::= exprlist */
183493      case 6: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==6);
183494{fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
183495  fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
183496        break;
183497      case 7: /* exprlist ::= exprlist cnearset */
183498{
183499  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
183500}
183501  fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
183502        break;
183503      case 8: /* cnearset ::= nearset */
183504{
183505  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
183506}
183507  fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
183508        break;
183509      case 9: /* cnearset ::= colset COLON nearset */
183510{
183511  sqlite3Fts5ParseSetColset(pParse, fts5yymsp[0].minor.fts5yy46, fts5yymsp[-2].minor.fts5yy11);
183512  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
183513}
183514  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
183515        break;
183516      case 10: /* colset ::= MINUS LCP colsetlist RCP */
183517{
183518    fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
183519}
183520        break;
183521      case 11: /* colset ::= LCP colsetlist RCP */
183522{ fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
183523        break;
183524      case 12: /* colset ::= STRING */
183525{
183526  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
183527}
183528  fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
183529        break;
183530      case 13: /* colset ::= MINUS STRING */
183531{
183532  fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
183533  fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
183534}
183535        break;
183536      case 14: /* colsetlist ::= colsetlist STRING */
183537{
183538  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
183539  fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
183540        break;
183541      case 15: /* colsetlist ::= STRING */
183542{
183543  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
183544}
183545  fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
183546        break;
183547      case 16: /* nearset ::= phrase */
183548{ fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
183549  fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
183550        break;
183551      case 17: /* nearset ::= STRING LP nearphrases neardist_opt RP */
183552{
183553  sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
183554  sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
183555  fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
183556}
183557  fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
183558        break;
183559      case 18: /* nearphrases ::= phrase */
183560{
183561  fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
183562}
183563  fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
183564        break;
183565      case 19: /* nearphrases ::= nearphrases phrase */
183566{
183567  fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
183568}
183569  fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
183570        break;
183571      case 20: /* neardist_opt ::= */
183572{ fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
183573        break;
183574      case 21: /* neardist_opt ::= COMMA STRING */
183575{ fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
183576        break;
183577      case 22: /* phrase ::= phrase PLUS STRING star_opt */
183578{
183579  fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
183580}
183581  fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
183582        break;
183583      case 23: /* phrase ::= STRING star_opt */
183584{
183585  fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
183586}
183587  fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
183588        break;
183589      case 24: /* star_opt ::= STAR */
183590{ fts5yymsp[0].minor.fts5yy4 = 1; }
183591        break;
183592      case 25: /* star_opt ::= */
183593{ fts5yymsp[1].minor.fts5yy4 = 0; }
183594        break;
183595      default:
183596        break;
183597/********** End reduce actions ************************************************/
183598  };
183599  assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
183600  fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
183601  fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
183602  fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
183603  if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
183604    if( fts5yyact>fts5YY_MAX_SHIFT ){
183605      fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
183606    }
183607    fts5yymsp -= fts5yysize-1;
183608    fts5yypParser->fts5yytos = fts5yymsp;
183609    fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
183610    fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
183611    fts5yyTraceShift(fts5yypParser, fts5yyact);
183612  }else{
183613    assert( fts5yyact == fts5YY_ACCEPT_ACTION );
183614    fts5yypParser->fts5yytos -= fts5yysize;
183615    fts5yy_accept(fts5yypParser);
183616  }
183617}
183618
183619/*
183620** The following code executes when the parse fails
183621*/
183622#ifndef fts5YYNOERRORRECOVERY
183623static void fts5yy_parse_failed(
183624  fts5yyParser *fts5yypParser           /* The parser */
183625){
183626  sqlite3Fts5ParserARG_FETCH;
183627#ifndef NDEBUG
183628  if( fts5yyTraceFILE ){
183629    fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
183630  }
183631#endif
183632  while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
183633  /* Here code is inserted which will be executed whenever the
183634  ** parser fails */
183635/************ Begin %parse_failure code ***************************************/
183636/************ End %parse_failure code *****************************************/
183637  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
183638}
183639#endif /* fts5YYNOERRORRECOVERY */
183640
183641/*
183642** The following code executes when a syntax error first occurs.
183643*/
183644static void fts5yy_syntax_error(
183645  fts5yyParser *fts5yypParser,           /* The parser */
183646  int fts5yymajor,                   /* The major type of the error token */
183647  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor         /* The minor type of the error token */
183648){
183649  sqlite3Fts5ParserARG_FETCH;
183650#define FTS5TOKEN fts5yyminor
183651/************ Begin %syntax_error code ****************************************/
183652
183653  UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
183654  sqlite3Fts5ParseError(
183655    pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
183656  );
183657/************ End %syntax_error code ******************************************/
183658  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
183659}
183660
183661/*
183662** The following is executed when the parser accepts
183663*/
183664static void fts5yy_accept(
183665  fts5yyParser *fts5yypParser           /* The parser */
183666){
183667  sqlite3Fts5ParserARG_FETCH;
183668#ifndef NDEBUG
183669  if( fts5yyTraceFILE ){
183670    fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
183671  }
183672#endif
183673#ifndef fts5YYNOERRORRECOVERY
183674  fts5yypParser->fts5yyerrcnt = -1;
183675#endif
183676  assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
183677  /* Here code is inserted which will be executed whenever the
183678  ** parser accepts */
183679/*********** Begin %parse_accept code *****************************************/
183680/*********** End %parse_accept code *******************************************/
183681  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
183682}
183683
183684/* The main parser program.
183685** The first argument is a pointer to a structure obtained from
183686** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
183687** The second argument is the major token number.  The third is
183688** the minor token.  The fourth optional argument is whatever the
183689** user wants (and specified in the grammar) and is available for
183690** use by the action routines.
183691**
183692** Inputs:
183693** <ul>
183694** <li> A pointer to the parser (an opaque structure.)
183695** <li> The major token number.
183696** <li> The minor token number.
183697** <li> An option argument of a grammar-specified type.
183698** </ul>
183699**
183700** Outputs:
183701** None.
183702*/
183703static void sqlite3Fts5Parser(
183704  void *fts5yyp,                   /* The parser */
183705  int fts5yymajor,                 /* The major token code number */
183706  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor       /* The value for the token */
183707  sqlite3Fts5ParserARG_PDECL               /* Optional %extra_argument parameter */
183708){
183709  fts5YYMINORTYPE fts5yyminorunion;
183710  unsigned int fts5yyact;   /* The parser action. */
183711#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
183712  int fts5yyendofinput;     /* True if we are at the end of input */
183713#endif
183714#ifdef fts5YYERRORSYMBOL
183715  int fts5yyerrorhit = 0;   /* True if fts5yymajor has invoked an error */
183716#endif
183717  fts5yyParser *fts5yypParser;  /* The parser */
183718
183719  fts5yypParser = (fts5yyParser*)fts5yyp;
183720  assert( fts5yypParser->fts5yytos!=0 );
183721#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
183722  fts5yyendofinput = (fts5yymajor==0);
183723#endif
183724  sqlite3Fts5ParserARG_STORE;
183725
183726#ifndef NDEBUG
183727  if( fts5yyTraceFILE ){
183728    fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
183729  }
183730#endif
183731
183732  do{
183733    fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
183734    if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
183735      fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
183736#ifndef fts5YYNOERRORRECOVERY
183737      fts5yypParser->fts5yyerrcnt--;
183738#endif
183739      fts5yymajor = fts5YYNOCODE;
183740    }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
183741      fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
183742    }else{
183743      assert( fts5yyact == fts5YY_ERROR_ACTION );
183744      fts5yyminorunion.fts5yy0 = fts5yyminor;
183745#ifdef fts5YYERRORSYMBOL
183746      int fts5yymx;
183747#endif
183748#ifndef NDEBUG
183749      if( fts5yyTraceFILE ){
183750        fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
183751      }
183752#endif
183753#ifdef fts5YYERRORSYMBOL
183754      /* A syntax error has occurred.
183755      ** The response to an error depends upon whether or not the
183756      ** grammar defines an error token "ERROR".
183757      **
183758      ** This is what we do if the grammar does define ERROR:
183759      **
183760      **  * Call the %syntax_error function.
183761      **
183762      **  * Begin popping the stack until we enter a state where
183763      **    it is legal to shift the error symbol, then shift
183764      **    the error symbol.
183765      **
183766      **  * Set the error count to three.
183767      **
183768      **  * Begin accepting and shifting new tokens.  No new error
183769      **    processing will occur until three tokens have been
183770      **    shifted successfully.
183771      **
183772      */
183773      if( fts5yypParser->fts5yyerrcnt<0 ){
183774        fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
183775      }
183776      fts5yymx = fts5yypParser->fts5yytos->major;
183777      if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
183778#ifndef NDEBUG
183779        if( fts5yyTraceFILE ){
183780          fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
183781             fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
183782        }
183783#endif
183784        fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
183785        fts5yymajor = fts5YYNOCODE;
183786      }else{
183787        while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
183788            && fts5yymx != fts5YYERRORSYMBOL
183789            && (fts5yyact = fts5yy_find_reduce_action(
183790                        fts5yypParser->fts5yytos->stateno,
183791                        fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
183792        ){
183793          fts5yy_pop_parser_stack(fts5yypParser);
183794        }
183795        if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
183796          fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
183797          fts5yy_parse_failed(fts5yypParser);
183798#ifndef fts5YYNOERRORRECOVERY
183799          fts5yypParser->fts5yyerrcnt = -1;
183800#endif
183801          fts5yymajor = fts5YYNOCODE;
183802        }else if( fts5yymx!=fts5YYERRORSYMBOL ){
183803          fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
183804        }
183805      }
183806      fts5yypParser->fts5yyerrcnt = 3;
183807      fts5yyerrorhit = 1;
183808#elif defined(fts5YYNOERRORRECOVERY)
183809      /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
183810      ** do any kind of error recovery.  Instead, simply invoke the syntax
183811      ** error routine and continue going as if nothing had happened.
183812      **
183813      ** Applications can set this macro (for example inside %include) if
183814      ** they intend to abandon the parse upon the first syntax error seen.
183815      */
183816      fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
183817      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
183818      fts5yymajor = fts5YYNOCODE;
183819
183820#else  /* fts5YYERRORSYMBOL is not defined */
183821      /* This is what we do if the grammar does not define ERROR:
183822      **
183823      **  * Report an error message, and throw away the input token.
183824      **
183825      **  * If the input token is $, then fail the parse.
183826      **
183827      ** As before, subsequent error messages are suppressed until
183828      ** three input tokens have been successfully shifted.
183829      */
183830      if( fts5yypParser->fts5yyerrcnt<=0 ){
183831        fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
183832      }
183833      fts5yypParser->fts5yyerrcnt = 3;
183834      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
183835      if( fts5yyendofinput ){
183836        fts5yy_parse_failed(fts5yypParser);
183837#ifndef fts5YYNOERRORRECOVERY
183838        fts5yypParser->fts5yyerrcnt = -1;
183839#endif
183840      }
183841      fts5yymajor = fts5YYNOCODE;
183842#endif
183843    }
183844  }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
183845#ifndef NDEBUG
183846  if( fts5yyTraceFILE ){
183847    fts5yyStackEntry *i;
183848    char cDiv = '[';
183849    fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
183850    for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
183851      fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
183852      cDiv = ' ';
183853    }
183854    fprintf(fts5yyTraceFILE,"]\n");
183855  }
183856#endif
183857  return;
183858}
183859
183860/*
183861** 2014 May 31
183862**
183863** The author disclaims copyright to this source code.  In place of
183864** a legal notice, here is a blessing:
183865**
183866**    May you do good and not evil.
183867**    May you find forgiveness for yourself and forgive others.
183868**    May you share freely, never taking more than you give.
183869**
183870******************************************************************************
183871*/
183872
183873
183874/* #include "fts5Int.h" */
183875#include <math.h>                 /* amalgamator: keep */
183876
183877/*
183878** Object used to iterate through all "coalesced phrase instances" in
183879** a single column of the current row. If the phrase instances in the
183880** column being considered do not overlap, this object simply iterates
183881** through them. Or, if they do overlap (share one or more tokens in
183882** common), each set of overlapping instances is treated as a single
183883** match. See documentation for the highlight() auxiliary function for
183884** details.
183885**
183886** Usage is:
183887**
183888**   for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
183889**      (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
183890**      rc = fts5CInstIterNext(&iter)
183891**   ){
183892**     printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
183893**   }
183894**
183895*/
183896typedef struct CInstIter CInstIter;
183897struct CInstIter {
183898  const Fts5ExtensionApi *pApi;   /* API offered by current FTS version */
183899  Fts5Context *pFts;              /* First arg to pass to pApi functions */
183900  int iCol;                       /* Column to search */
183901  int iInst;                      /* Next phrase instance index */
183902  int nInst;                      /* Total number of phrase instances */
183903
183904  /* Output variables */
183905  int iStart;                     /* First token in coalesced phrase instance */
183906  int iEnd;                       /* Last token in coalesced phrase instance */
183907};
183908
183909/*
183910** Advance the iterator to the next coalesced phrase instance. Return
183911** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
183912*/
183913static int fts5CInstIterNext(CInstIter *pIter){
183914  int rc = SQLITE_OK;
183915  pIter->iStart = -1;
183916  pIter->iEnd = -1;
183917
183918  while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
183919    int ip; int ic; int io;
183920    rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
183921    if( rc==SQLITE_OK ){
183922      if( ic==pIter->iCol ){
183923        int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
183924        if( pIter->iStart<0 ){
183925          pIter->iStart = io;
183926          pIter->iEnd = iEnd;
183927        }else if( io<=pIter->iEnd ){
183928          if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
183929        }else{
183930          break;
183931        }
183932      }
183933      pIter->iInst++;
183934    }
183935  }
183936
183937  return rc;
183938}
183939
183940/*
183941** Initialize the iterator object indicated by the final parameter to
183942** iterate through coalesced phrase instances in column iCol.
183943*/
183944static int fts5CInstIterInit(
183945  const Fts5ExtensionApi *pApi,
183946  Fts5Context *pFts,
183947  int iCol,
183948  CInstIter *pIter
183949){
183950  int rc;
183951
183952  memset(pIter, 0, sizeof(CInstIter));
183953  pIter->pApi = pApi;
183954  pIter->pFts = pFts;
183955  pIter->iCol = iCol;
183956  rc = pApi->xInstCount(pFts, &pIter->nInst);
183957
183958  if( rc==SQLITE_OK ){
183959    rc = fts5CInstIterNext(pIter);
183960  }
183961
183962  return rc;
183963}
183964
183965
183966
183967/*************************************************************************
183968** Start of highlight() implementation.
183969*/
183970typedef struct HighlightContext HighlightContext;
183971struct HighlightContext {
183972  CInstIter iter;                 /* Coalesced Instance Iterator */
183973  int iPos;                       /* Current token offset in zIn[] */
183974  int iRangeStart;                /* First token to include */
183975  int iRangeEnd;                  /* If non-zero, last token to include */
183976  const char *zOpen;              /* Opening highlight */
183977  const char *zClose;             /* Closing highlight */
183978  const char *zIn;                /* Input text */
183979  int nIn;                        /* Size of input text in bytes */
183980  int iOff;                       /* Current offset within zIn[] */
183981  char *zOut;                     /* Output value */
183982};
183983
183984/*
183985** Append text to the HighlightContext output string - p->zOut. Argument
183986** z points to a buffer containing n bytes of text to append. If n is
183987** negative, everything up until the first '\0' is appended to the output.
183988**
183989** If *pRc is set to any value other than SQLITE_OK when this function is
183990** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
183991** *pRc is set to an error code before returning.
183992*/
183993static void fts5HighlightAppend(
183994  int *pRc,
183995  HighlightContext *p,
183996  const char *z, int n
183997){
183998  if( *pRc==SQLITE_OK ){
183999    if( n<0 ) n = (int)strlen(z);
184000    p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
184001    if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
184002  }
184003}
184004
184005/*
184006** Tokenizer callback used by implementation of highlight() function.
184007*/
184008static int fts5HighlightCb(
184009  void *pContext,                 /* Pointer to HighlightContext object */
184010  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
184011  const char *pToken,             /* Buffer containing token */
184012  int nToken,                     /* Size of token in bytes */
184013  int iStartOff,                  /* Start offset of token */
184014  int iEndOff                     /* End offset of token */
184015){
184016  HighlightContext *p = (HighlightContext*)pContext;
184017  int rc = SQLITE_OK;
184018  int iPos;
184019
184020  UNUSED_PARAM2(pToken, nToken);
184021
184022  if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
184023  iPos = p->iPos++;
184024
184025  if( p->iRangeEnd>0 ){
184026    if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
184027    if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
184028  }
184029
184030  if( iPos==p->iter.iStart ){
184031    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
184032    fts5HighlightAppend(&rc, p, p->zOpen, -1);
184033    p->iOff = iStartOff;
184034  }
184035
184036  if( iPos==p->iter.iEnd ){
184037    if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
184038      fts5HighlightAppend(&rc, p, p->zOpen, -1);
184039    }
184040    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
184041    fts5HighlightAppend(&rc, p, p->zClose, -1);
184042    p->iOff = iEndOff;
184043    if( rc==SQLITE_OK ){
184044      rc = fts5CInstIterNext(&p->iter);
184045    }
184046  }
184047
184048  if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
184049    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
184050    p->iOff = iEndOff;
184051    if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
184052      fts5HighlightAppend(&rc, p, p->zClose, -1);
184053    }
184054  }
184055
184056  return rc;
184057}
184058
184059/*
184060** Implementation of highlight() function.
184061*/
184062static void fts5HighlightFunction(
184063  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
184064  Fts5Context *pFts,              /* First arg to pass to pApi functions */
184065  sqlite3_context *pCtx,          /* Context for returning result/error */
184066  int nVal,                       /* Number of values in apVal[] array */
184067  sqlite3_value **apVal           /* Array of trailing arguments */
184068){
184069  HighlightContext ctx;
184070  int rc;
184071  int iCol;
184072
184073  if( nVal!=3 ){
184074    const char *zErr = "wrong number of arguments to function highlight()";
184075    sqlite3_result_error(pCtx, zErr, -1);
184076    return;
184077  }
184078
184079  iCol = sqlite3_value_int(apVal[0]);
184080  memset(&ctx, 0, sizeof(HighlightContext));
184081  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
184082  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
184083  rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
184084
184085  if( ctx.zIn ){
184086    if( rc==SQLITE_OK ){
184087      rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
184088    }
184089
184090    if( rc==SQLITE_OK ){
184091      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
184092    }
184093    fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
184094
184095    if( rc==SQLITE_OK ){
184096      sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
184097    }
184098    sqlite3_free(ctx.zOut);
184099  }
184100  if( rc!=SQLITE_OK ){
184101    sqlite3_result_error_code(pCtx, rc);
184102  }
184103}
184104/*
184105** End of highlight() implementation.
184106**************************************************************************/
184107
184108/*
184109** Context object passed to the fts5SentenceFinderCb() function.
184110*/
184111typedef struct Fts5SFinder Fts5SFinder;
184112struct Fts5SFinder {
184113  int iPos;                       /* Current token position */
184114  int nFirstAlloc;                /* Allocated size of aFirst[] */
184115  int nFirst;                     /* Number of entries in aFirst[] */
184116  int *aFirst;                    /* Array of first token in each sentence */
184117  const char *zDoc;               /* Document being tokenized */
184118};
184119
184120/*
184121** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
184122** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
184123** error occurs.
184124*/
184125static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
184126  if( p->nFirstAlloc==p->nFirst ){
184127    int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
184128    int *aNew;
184129
184130    aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int));
184131    if( aNew==0 ) return SQLITE_NOMEM;
184132    p->aFirst = aNew;
184133    p->nFirstAlloc = nNew;
184134  }
184135  p->aFirst[p->nFirst++] = iAdd;
184136  return SQLITE_OK;
184137}
184138
184139/*
184140** This function is an xTokenize() callback used by the auxiliary snippet()
184141** function. Its job is to identify tokens that are the first in a sentence.
184142** For each such token, an entry is added to the SFinder.aFirst[] array.
184143*/
184144static int fts5SentenceFinderCb(
184145  void *pContext,                 /* Pointer to HighlightContext object */
184146  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
184147  const char *pToken,             /* Buffer containing token */
184148  int nToken,                     /* Size of token in bytes */
184149  int iStartOff,                  /* Start offset of token */
184150  int iEndOff                     /* End offset of token */
184151){
184152  int rc = SQLITE_OK;
184153
184154  UNUSED_PARAM2(pToken, nToken);
184155  UNUSED_PARAM(iEndOff);
184156
184157  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
184158    Fts5SFinder *p = (Fts5SFinder*)pContext;
184159    if( p->iPos>0 ){
184160      int i;
184161      char c = 0;
184162      for(i=iStartOff-1; i>=0; i--){
184163        c = p->zDoc[i];
184164        if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
184165      }
184166      if( i!=iStartOff-1 && (c=='.' || c==':') ){
184167        rc = fts5SentenceFinderAdd(p, p->iPos);
184168      }
184169    }else{
184170      rc = fts5SentenceFinderAdd(p, 0);
184171    }
184172    p->iPos++;
184173  }
184174  return rc;
184175}
184176
184177static int fts5SnippetScore(
184178  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
184179  Fts5Context *pFts,              /* First arg to pass to pApi functions */
184180  int nDocsize,                   /* Size of column in tokens */
184181  unsigned char *aSeen,           /* Array with one element per query phrase */
184182  int iCol,                       /* Column to score */
184183  int iPos,                       /* Starting offset to score */
184184  int nToken,                     /* Max tokens per snippet */
184185  int *pnScore,                   /* OUT: Score */
184186  int *piPos                      /* OUT: Adjusted offset */
184187){
184188  int rc;
184189  int i;
184190  int ip = 0;
184191  int ic = 0;
184192  int iOff = 0;
184193  int iFirst = -1;
184194  int nInst;
184195  int nScore = 0;
184196  int iLast = 0;
184197
184198  rc = pApi->xInstCount(pFts, &nInst);
184199  for(i=0; i<nInst && rc==SQLITE_OK; i++){
184200    rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
184201    if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){
184202      nScore += (aSeen[ip] ? 1 : 1000);
184203      aSeen[ip] = 1;
184204      if( iFirst<0 ) iFirst = iOff;
184205      iLast = iOff + pApi->xPhraseSize(pFts, ip);
184206    }
184207  }
184208
184209  *pnScore = nScore;
184210  if( piPos ){
184211    int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
184212    if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
184213    if( iAdj<0 ) iAdj = 0;
184214    *piPos = iAdj;
184215  }
184216
184217  return rc;
184218}
184219
184220/*
184221** Implementation of snippet() function.
184222*/
184223static void fts5SnippetFunction(
184224  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
184225  Fts5Context *pFts,              /* First arg to pass to pApi functions */
184226  sqlite3_context *pCtx,          /* Context for returning result/error */
184227  int nVal,                       /* Number of values in apVal[] array */
184228  sqlite3_value **apVal           /* Array of trailing arguments */
184229){
184230  HighlightContext ctx;
184231  int rc = SQLITE_OK;             /* Return code */
184232  int iCol;                       /* 1st argument to snippet() */
184233  const char *zEllips;            /* 4th argument to snippet() */
184234  int nToken;                     /* 5th argument to snippet() */
184235  int nInst = 0;                  /* Number of instance matches this row */
184236  int i;                          /* Used to iterate through instances */
184237  int nPhrase;                    /* Number of phrases in query */
184238  unsigned char *aSeen;           /* Array of "seen instance" flags */
184239  int iBestCol;                   /* Column containing best snippet */
184240  int iBestStart = 0;             /* First token of best snippet */
184241  int nBestScore = 0;             /* Score of best snippet */
184242  int nColSize = 0;               /* Total size of iBestCol in tokens */
184243  Fts5SFinder sFinder;            /* Used to find the beginnings of sentences */
184244  int nCol;
184245
184246  if( nVal!=5 ){
184247    const char *zErr = "wrong number of arguments to function snippet()";
184248    sqlite3_result_error(pCtx, zErr, -1);
184249    return;
184250  }
184251
184252  nCol = pApi->xColumnCount(pFts);
184253  memset(&ctx, 0, sizeof(HighlightContext));
184254  iCol = sqlite3_value_int(apVal[0]);
184255  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
184256  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
184257  zEllips = (const char*)sqlite3_value_text(apVal[3]);
184258  nToken = sqlite3_value_int(apVal[4]);
184259
184260  iBestCol = (iCol>=0 ? iCol : 0);
184261  nPhrase = pApi->xPhraseCount(pFts);
184262  aSeen = sqlite3_malloc(nPhrase);
184263  if( aSeen==0 ){
184264    rc = SQLITE_NOMEM;
184265  }
184266  if( rc==SQLITE_OK ){
184267    rc = pApi->xInstCount(pFts, &nInst);
184268  }
184269
184270  memset(&sFinder, 0, sizeof(Fts5SFinder));
184271  for(i=0; i<nCol; i++){
184272    if( iCol<0 || iCol==i ){
184273      int nDoc;
184274      int nDocsize;
184275      int ii;
184276      sFinder.iPos = 0;
184277      sFinder.nFirst = 0;
184278      rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
184279      if( rc!=SQLITE_OK ) break;
184280      rc = pApi->xTokenize(pFts,
184281          sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
184282      );
184283      if( rc!=SQLITE_OK ) break;
184284      rc = pApi->xColumnSize(pFts, i, &nDocsize);
184285      if( rc!=SQLITE_OK ) break;
184286
184287      for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
184288        int ip, ic, io;
184289        int iAdj;
184290        int nScore;
184291        int jj;
184292
184293        rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
184294        if( ic!=i || rc!=SQLITE_OK ) continue;
184295        memset(aSeen, 0, nPhrase);
184296        rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
184297            io, nToken, &nScore, &iAdj
184298        );
184299        if( rc==SQLITE_OK && nScore>nBestScore ){
184300          nBestScore = nScore;
184301          iBestCol = i;
184302          iBestStart = iAdj;
184303          nColSize = nDocsize;
184304        }
184305
184306        if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
184307          for(jj=0; jj<(sFinder.nFirst-1); jj++){
184308            if( sFinder.aFirst[jj+1]>io ) break;
184309          }
184310
184311          if( sFinder.aFirst[jj]<io ){
184312            memset(aSeen, 0, nPhrase);
184313            rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
184314              sFinder.aFirst[jj], nToken, &nScore, 0
184315            );
184316
184317            nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
184318            if( rc==SQLITE_OK && nScore>nBestScore ){
184319              nBestScore = nScore;
184320              iBestCol = i;
184321              iBestStart = sFinder.aFirst[jj];
184322              nColSize = nDocsize;
184323            }
184324          }
184325        }
184326      }
184327    }
184328  }
184329
184330  if( rc==SQLITE_OK ){
184331    rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
184332  }
184333  if( rc==SQLITE_OK && nColSize==0 ){
184334    rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
184335  }
184336  if( ctx.zIn ){
184337    if( rc==SQLITE_OK ){
184338      rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
184339    }
184340
184341    ctx.iRangeStart = iBestStart;
184342    ctx.iRangeEnd = iBestStart + nToken - 1;
184343
184344    if( iBestStart>0 ){
184345      fts5HighlightAppend(&rc, &ctx, zEllips, -1);
184346    }
184347
184348    /* Advance iterator ctx.iter so that it points to the first coalesced
184349    ** phrase instance at or following position iBestStart. */
184350    while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
184351      rc = fts5CInstIterNext(&ctx.iter);
184352    }
184353
184354    if( rc==SQLITE_OK ){
184355      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
184356    }
184357    if( ctx.iRangeEnd>=(nColSize-1) ){
184358      fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
184359    }else{
184360      fts5HighlightAppend(&rc, &ctx, zEllips, -1);
184361    }
184362  }
184363  if( rc==SQLITE_OK ){
184364    sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
184365  }else{
184366    sqlite3_result_error_code(pCtx, rc);
184367  }
184368  sqlite3_free(ctx.zOut);
184369  sqlite3_free(aSeen);
184370  sqlite3_free(sFinder.aFirst);
184371}
184372
184373/************************************************************************/
184374
184375/*
184376** The first time the bm25() function is called for a query, an instance
184377** of the following structure is allocated and populated.
184378*/
184379typedef struct Fts5Bm25Data Fts5Bm25Data;
184380struct Fts5Bm25Data {
184381  int nPhrase;                    /* Number of phrases in query */
184382  double avgdl;                   /* Average number of tokens in each row */
184383  double *aIDF;                   /* IDF for each phrase */
184384  double *aFreq;                  /* Array used to calculate phrase freq. */
184385};
184386
184387/*
184388** Callback used by fts5Bm25GetData() to count the number of rows in the
184389** table matched by each individual phrase within the query.
184390*/
184391static int fts5CountCb(
184392  const Fts5ExtensionApi *pApi,
184393  Fts5Context *pFts,
184394  void *pUserData                 /* Pointer to sqlite3_int64 variable */
184395){
184396  sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
184397  UNUSED_PARAM2(pApi, pFts);
184398  (*pn)++;
184399  return SQLITE_OK;
184400}
184401
184402/*
184403** Set *ppData to point to the Fts5Bm25Data object for the current query.
184404** If the object has not already been allocated, allocate and populate it
184405** now.
184406*/
184407static int fts5Bm25GetData(
184408  const Fts5ExtensionApi *pApi,
184409  Fts5Context *pFts,
184410  Fts5Bm25Data **ppData           /* OUT: bm25-data object for this query */
184411){
184412  int rc = SQLITE_OK;             /* Return code */
184413  Fts5Bm25Data *p;                /* Object to return */
184414
184415  p = pApi->xGetAuxdata(pFts, 0);
184416  if( p==0 ){
184417    int nPhrase;                  /* Number of phrases in query */
184418    sqlite3_int64 nRow = 0;       /* Number of rows in table */
184419    sqlite3_int64 nToken = 0;     /* Number of tokens in table */
184420    int nByte;                    /* Bytes of space to allocate */
184421    int i;
184422
184423    /* Allocate the Fts5Bm25Data object */
184424    nPhrase = pApi->xPhraseCount(pFts);
184425    nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
184426    p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
184427    if( p==0 ){
184428      rc = SQLITE_NOMEM;
184429    }else{
184430      memset(p, 0, nByte);
184431      p->nPhrase = nPhrase;
184432      p->aIDF = (double*)&p[1];
184433      p->aFreq = &p->aIDF[nPhrase];
184434    }
184435
184436    /* Calculate the average document length for this FTS5 table */
184437    if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
184438    if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
184439    if( rc==SQLITE_OK ) p->avgdl = (double)nToken  / (double)nRow;
184440
184441    /* Calculate an IDF for each phrase in the query */
184442    for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
184443      sqlite3_int64 nHit = 0;
184444      rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
184445      if( rc==SQLITE_OK ){
184446        /* Calculate the IDF (Inverse Document Frequency) for phrase i.
184447        ** This is done using the standard BM25 formula as found on wikipedia:
184448        **
184449        **   IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
184450        **
184451        ** where "N" is the total number of documents in the set and nHit
184452        ** is the number that contain at least one instance of the phrase
184453        ** under consideration.
184454        **
184455        ** The problem with this is that if (N < 2*nHit), the IDF is
184456        ** negative. Which is undesirable. So the mimimum allowable IDF is
184457        ** (1e-6) - roughly the same as a term that appears in just over
184458        ** half of set of 5,000,000 documents.  */
184459        double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
184460        if( idf<=0.0 ) idf = 1e-6;
184461        p->aIDF[i] = idf;
184462      }
184463    }
184464
184465    if( rc!=SQLITE_OK ){
184466      sqlite3_free(p);
184467    }else{
184468      rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
184469    }
184470    if( rc!=SQLITE_OK ) p = 0;
184471  }
184472  *ppData = p;
184473  return rc;
184474}
184475
184476/*
184477** Implementation of bm25() function.
184478*/
184479static void fts5Bm25Function(
184480  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
184481  Fts5Context *pFts,              /* First arg to pass to pApi functions */
184482  sqlite3_context *pCtx,          /* Context for returning result/error */
184483  int nVal,                       /* Number of values in apVal[] array */
184484  sqlite3_value **apVal           /* Array of trailing arguments */
184485){
184486  const double k1 = 1.2;          /* Constant "k1" from BM25 formula */
184487  const double b = 0.75;          /* Constant "b" from BM25 formula */
184488  int rc = SQLITE_OK;             /* Error code */
184489  double score = 0.0;             /* SQL function return value */
184490  Fts5Bm25Data *pData;            /* Values allocated/calculated once only */
184491  int i;                          /* Iterator variable */
184492  int nInst = 0;                  /* Value returned by xInstCount() */
184493  double D = 0.0;                 /* Total number of tokens in row */
184494  double *aFreq = 0;              /* Array of phrase freq. for current row */
184495
184496  /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
184497  ** for each phrase in the query for the current row. */
184498  rc = fts5Bm25GetData(pApi, pFts, &pData);
184499  if( rc==SQLITE_OK ){
184500    aFreq = pData->aFreq;
184501    memset(aFreq, 0, sizeof(double) * pData->nPhrase);
184502    rc = pApi->xInstCount(pFts, &nInst);
184503  }
184504  for(i=0; rc==SQLITE_OK && i<nInst; i++){
184505    int ip; int ic; int io;
184506    rc = pApi->xInst(pFts, i, &ip, &ic, &io);
184507    if( rc==SQLITE_OK ){
184508      double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
184509      aFreq[ip] += w;
184510    }
184511  }
184512
184513  /* Figure out the total size of the current row in tokens. */
184514  if( rc==SQLITE_OK ){
184515    int nTok;
184516    rc = pApi->xColumnSize(pFts, -1, &nTok);
184517    D = (double)nTok;
184518  }
184519
184520  /* Determine the BM25 score for the current row. */
184521  for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
184522    score += pData->aIDF[i] * (
184523      ( aFreq[i] * (k1 + 1.0) ) /
184524      ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
184525    );
184526  }
184527
184528  /* If no error has occurred, return the calculated score. Otherwise,
184529  ** throw an SQL exception.  */
184530  if( rc==SQLITE_OK ){
184531    sqlite3_result_double(pCtx, -1.0 * score);
184532  }else{
184533    sqlite3_result_error_code(pCtx, rc);
184534  }
184535}
184536
184537static int sqlite3Fts5AuxInit(fts5_api *pApi){
184538  struct Builtin {
184539    const char *zFunc;            /* Function name (nul-terminated) */
184540    void *pUserData;              /* User-data pointer */
184541    fts5_extension_function xFunc;/* Callback function */
184542    void (*xDestroy)(void*);      /* Destructor function */
184543  } aBuiltin [] = {
184544    { "snippet",   0, fts5SnippetFunction, 0 },
184545    { "highlight", 0, fts5HighlightFunction, 0 },
184546    { "bm25",      0, fts5Bm25Function,    0 },
184547  };
184548  int rc = SQLITE_OK;             /* Return code */
184549  int i;                          /* To iterate through builtin functions */
184550
184551  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
184552    rc = pApi->xCreateFunction(pApi,
184553        aBuiltin[i].zFunc,
184554        aBuiltin[i].pUserData,
184555        aBuiltin[i].xFunc,
184556        aBuiltin[i].xDestroy
184557    );
184558  }
184559
184560  return rc;
184561}
184562
184563
184564
184565/*
184566** 2014 May 31
184567**
184568** The author disclaims copyright to this source code.  In place of
184569** a legal notice, here is a blessing:
184570**
184571**    May you do good and not evil.
184572**    May you find forgiveness for yourself and forgive others.
184573**    May you share freely, never taking more than you give.
184574**
184575******************************************************************************
184576*/
184577
184578
184579
184580/* #include "fts5Int.h" */
184581
184582static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
184583  if( (u32)pBuf->nSpace<nByte ){
184584    u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
184585    u8 *pNew;
184586    while( nNew<nByte ){
184587      nNew = nNew * 2;
184588    }
184589    pNew = sqlite3_realloc(pBuf->p, nNew);
184590    if( pNew==0 ){
184591      *pRc = SQLITE_NOMEM;
184592      return 1;
184593    }else{
184594      pBuf->nSpace = nNew;
184595      pBuf->p = pNew;
184596    }
184597  }
184598  return 0;
184599}
184600
184601
184602/*
184603** Encode value iVal as an SQLite varint and append it to the buffer object
184604** pBuf. If an OOM error occurs, set the error code in p.
184605*/
184606static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
184607  if( fts5BufferGrow(pRc, pBuf, 9) ) return;
184608  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
184609}
184610
184611static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
184612  aBuf[0] = (iVal>>24) & 0x00FF;
184613  aBuf[1] = (iVal>>16) & 0x00FF;
184614  aBuf[2] = (iVal>> 8) & 0x00FF;
184615  aBuf[3] = (iVal>> 0) & 0x00FF;
184616}
184617
184618static int sqlite3Fts5Get32(const u8 *aBuf){
184619  return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
184620}
184621
184622/*
184623** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
184624** the error code in p. If an error has already occurred when this function
184625** is called, it is a no-op.
184626*/
184627static void sqlite3Fts5BufferAppendBlob(
184628  int *pRc,
184629  Fts5Buffer *pBuf,
184630  u32 nData,
184631  const u8 *pData
184632){
184633  assert_nc( *pRc || nData>=0 );
184634  if( fts5BufferGrow(pRc, pBuf, nData) ) return;
184635  memcpy(&pBuf->p[pBuf->n], pData, nData);
184636  pBuf->n += nData;
184637}
184638
184639/*
184640** Append the nul-terminated string zStr to the buffer pBuf. This function
184641** ensures that the byte following the buffer data is set to 0x00, even
184642** though this byte is not included in the pBuf->n count.
184643*/
184644static void sqlite3Fts5BufferAppendString(
184645  int *pRc,
184646  Fts5Buffer *pBuf,
184647  const char *zStr
184648){
184649  int nStr = (int)strlen(zStr);
184650  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
184651  pBuf->n--;
184652}
184653
184654/*
184655** Argument zFmt is a printf() style format string. This function performs
184656** the printf() style processing, then appends the results to buffer pBuf.
184657**
184658** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
184659** following the buffer data is set to 0x00, even though this byte is not
184660** included in the pBuf->n count.
184661*/
184662static void sqlite3Fts5BufferAppendPrintf(
184663  int *pRc,
184664  Fts5Buffer *pBuf,
184665  char *zFmt, ...
184666){
184667  if( *pRc==SQLITE_OK ){
184668    char *zTmp;
184669    va_list ap;
184670    va_start(ap, zFmt);
184671    zTmp = sqlite3_vmprintf(zFmt, ap);
184672    va_end(ap);
184673
184674    if( zTmp==0 ){
184675      *pRc = SQLITE_NOMEM;
184676    }else{
184677      sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
184678      sqlite3_free(zTmp);
184679    }
184680  }
184681}
184682
184683static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
184684  char *zRet = 0;
184685  if( *pRc==SQLITE_OK ){
184686    va_list ap;
184687    va_start(ap, zFmt);
184688    zRet = sqlite3_vmprintf(zFmt, ap);
184689    va_end(ap);
184690    if( zRet==0 ){
184691      *pRc = SQLITE_NOMEM;
184692    }
184693  }
184694  return zRet;
184695}
184696
184697
184698/*
184699** Free any buffer allocated by pBuf. Zero the structure before returning.
184700*/
184701static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
184702  sqlite3_free(pBuf->p);
184703  memset(pBuf, 0, sizeof(Fts5Buffer));
184704}
184705
184706/*
184707** Zero the contents of the buffer object. But do not free the associated
184708** memory allocation.
184709*/
184710static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
184711  pBuf->n = 0;
184712}
184713
184714/*
184715** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
184716** the error code in p. If an error has already occurred when this function
184717** is called, it is a no-op.
184718*/
184719static void sqlite3Fts5BufferSet(
184720  int *pRc,
184721  Fts5Buffer *pBuf,
184722  int nData,
184723  const u8 *pData
184724){
184725  pBuf->n = 0;
184726  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
184727}
184728
184729static int sqlite3Fts5PoslistNext64(
184730  const u8 *a, int n,             /* Buffer containing poslist */
184731  int *pi,                        /* IN/OUT: Offset within a[] */
184732  i64 *piOff                      /* IN/OUT: Current offset */
184733){
184734  int i = *pi;
184735  if( i>=n ){
184736    /* EOF */
184737    *piOff = -1;
184738    return 1;
184739  }else{
184740    i64 iOff = *piOff;
184741    int iVal;
184742    fts5FastGetVarint32(a, i, iVal);
184743    if( iVal==1 ){
184744      fts5FastGetVarint32(a, i, iVal);
184745      iOff = ((i64)iVal) << 32;
184746      fts5FastGetVarint32(a, i, iVal);
184747    }
184748    *piOff = iOff + (iVal-2);
184749    *pi = i;
184750    return 0;
184751  }
184752}
184753
184754
184755/*
184756** Advance the iterator object passed as the only argument. Return true
184757** if the iterator reaches EOF, or false otherwise.
184758*/
184759static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
184760  if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
184761    pIter->bEof = 1;
184762  }
184763  return pIter->bEof;
184764}
184765
184766static int sqlite3Fts5PoslistReaderInit(
184767  const u8 *a, int n,             /* Poslist buffer to iterate through */
184768  Fts5PoslistReader *pIter        /* Iterator object to initialize */
184769){
184770  memset(pIter, 0, sizeof(*pIter));
184771  pIter->a = a;
184772  pIter->n = n;
184773  sqlite3Fts5PoslistReaderNext(pIter);
184774  return pIter->bEof;
184775}
184776
184777/*
184778** Append position iPos to the position list being accumulated in buffer
184779** pBuf, which must be already be large enough to hold the new data.
184780** The previous position written to this list is *piPrev. *piPrev is set
184781** to iPos before returning.
184782*/
184783static void sqlite3Fts5PoslistSafeAppend(
184784  Fts5Buffer *pBuf,
184785  i64 *piPrev,
184786  i64 iPos
184787){
184788  static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
184789  if( (iPos & colmask) != (*piPrev & colmask) ){
184790    pBuf->p[pBuf->n++] = 1;
184791    pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
184792    *piPrev = (iPos & colmask);
184793  }
184794  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
184795  *piPrev = iPos;
184796}
184797
184798static int sqlite3Fts5PoslistWriterAppend(
184799  Fts5Buffer *pBuf,
184800  Fts5PoslistWriter *pWriter,
184801  i64 iPos
184802){
184803  int rc = 0;   /* Initialized only to suppress erroneous warning from Clang */
184804  if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
184805  sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
184806  return SQLITE_OK;
184807}
184808
184809static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
184810  void *pRet = 0;
184811  if( *pRc==SQLITE_OK ){
184812    pRet = sqlite3_malloc(nByte);
184813    if( pRet==0 && nByte>0 ){
184814      *pRc = SQLITE_NOMEM;
184815    }else{
184816      memset(pRet, 0, nByte);
184817    }
184818  }
184819  return pRet;
184820}
184821
184822/*
184823** Return a nul-terminated copy of the string indicated by pIn. If nIn
184824** is non-negative, then it is the length of the string in bytes. Otherwise,
184825** the length of the string is determined using strlen().
184826**
184827** It is the responsibility of the caller to eventually free the returned
184828** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
184829*/
184830static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
184831  char *zRet = 0;
184832  if( *pRc==SQLITE_OK ){
184833    if( nIn<0 ){
184834      nIn = (int)strlen(pIn);
184835    }
184836    zRet = (char*)sqlite3_malloc(nIn+1);
184837    if( zRet ){
184838      memcpy(zRet, pIn, nIn);
184839      zRet[nIn] = '\0';
184840    }else{
184841      *pRc = SQLITE_NOMEM;
184842    }
184843  }
184844  return zRet;
184845}
184846
184847
184848/*
184849** Return true if character 't' may be part of an FTS5 bareword, or false
184850** otherwise. Characters that may be part of barewords:
184851**
184852**   * All non-ASCII characters,
184853**   * The 52 upper and lower case ASCII characters, and
184854**   * The 10 integer ASCII characters.
184855**   * The underscore character "_" (0x5F).
184856**   * The unicode "subsitute" character (0x1A).
184857*/
184858static int sqlite3Fts5IsBareword(char t){
184859  u8 aBareword[128] = {
184860    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00 .. 0x0F */
184861    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 1, 0, 0, 0, 0, 0,   /* 0x10 .. 0x1F */
184862    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20 .. 0x2F */
184863    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30 .. 0x3F */
184864    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40 .. 0x4F */
184865    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 1,   /* 0x50 .. 0x5F */
184866    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60 .. 0x6F */
184867    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 0    /* 0x70 .. 0x7F */
184868  };
184869
184870  return (t & 0x80) || aBareword[(int)t];
184871}
184872
184873
184874/*************************************************************************
184875*/
184876typedef struct Fts5TermsetEntry Fts5TermsetEntry;
184877struct Fts5TermsetEntry {
184878  char *pTerm;
184879  int nTerm;
184880  int iIdx;                       /* Index (main or aPrefix[] entry) */
184881  Fts5TermsetEntry *pNext;
184882};
184883
184884struct Fts5Termset {
184885  Fts5TermsetEntry *apHash[512];
184886};
184887
184888static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
184889  int rc = SQLITE_OK;
184890  *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
184891  return rc;
184892}
184893
184894static int sqlite3Fts5TermsetAdd(
184895  Fts5Termset *p,
184896  int iIdx,
184897  const char *pTerm, int nTerm,
184898  int *pbPresent
184899){
184900  int rc = SQLITE_OK;
184901  *pbPresent = 0;
184902  if( p ){
184903    int i;
184904    u32 hash = 13;
184905    Fts5TermsetEntry *pEntry;
184906
184907    /* Calculate a hash value for this term. This is the same hash checksum
184908    ** used by the fts5_hash.c module. This is not important for correct
184909    ** operation of the module, but is necessary to ensure that some tests
184910    ** designed to produce hash table collisions really do work.  */
184911    for(i=nTerm-1; i>=0; i--){
184912      hash = (hash << 3) ^ hash ^ pTerm[i];
184913    }
184914    hash = (hash << 3) ^ hash ^ iIdx;
184915    hash = hash % ArraySize(p->apHash);
184916
184917    for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
184918      if( pEntry->iIdx==iIdx
184919          && pEntry->nTerm==nTerm
184920          && memcmp(pEntry->pTerm, pTerm, nTerm)==0
184921      ){
184922        *pbPresent = 1;
184923        break;
184924      }
184925    }
184926
184927    if( pEntry==0 ){
184928      pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
184929      if( pEntry ){
184930        pEntry->pTerm = (char*)&pEntry[1];
184931        pEntry->nTerm = nTerm;
184932        pEntry->iIdx = iIdx;
184933        memcpy(pEntry->pTerm, pTerm, nTerm);
184934        pEntry->pNext = p->apHash[hash];
184935        p->apHash[hash] = pEntry;
184936      }
184937    }
184938  }
184939
184940  return rc;
184941}
184942
184943static void sqlite3Fts5TermsetFree(Fts5Termset *p){
184944  if( p ){
184945    u32 i;
184946    for(i=0; i<ArraySize(p->apHash); i++){
184947      Fts5TermsetEntry *pEntry = p->apHash[i];
184948      while( pEntry ){
184949        Fts5TermsetEntry *pDel = pEntry;
184950        pEntry = pEntry->pNext;
184951        sqlite3_free(pDel);
184952      }
184953    }
184954    sqlite3_free(p);
184955  }
184956}
184957
184958/*
184959** 2014 Jun 09
184960**
184961** The author disclaims copyright to this source code.  In place of
184962** a legal notice, here is a blessing:
184963**
184964**    May you do good and not evil.
184965**    May you find forgiveness for yourself and forgive others.
184966**    May you share freely, never taking more than you give.
184967**
184968******************************************************************************
184969**
184970** This is an SQLite module implementing full-text search.
184971*/
184972
184973
184974/* #include "fts5Int.h" */
184975
184976#define FTS5_DEFAULT_PAGE_SIZE   4050
184977#define FTS5_DEFAULT_AUTOMERGE      4
184978#define FTS5_DEFAULT_USERMERGE      4
184979#define FTS5_DEFAULT_CRISISMERGE   16
184980#define FTS5_DEFAULT_HASHSIZE    (1024*1024)
184981
184982/* Maximum allowed page size */
184983#define FTS5_MAX_PAGE_SIZE (128*1024)
184984
184985static int fts5_iswhitespace(char x){
184986  return (x==' ');
184987}
184988
184989static int fts5_isopenquote(char x){
184990  return (x=='"' || x=='\'' || x=='[' || x=='`');
184991}
184992
184993/*
184994** Argument pIn points to a character that is part of a nul-terminated
184995** string. Return a pointer to the first character following *pIn in
184996** the string that is not a white-space character.
184997*/
184998static const char *fts5ConfigSkipWhitespace(const char *pIn){
184999  const char *p = pIn;
185000  if( p ){
185001    while( fts5_iswhitespace(*p) ){ p++; }
185002  }
185003  return p;
185004}
185005
185006/*
185007** Argument pIn points to a character that is part of a nul-terminated
185008** string. Return a pointer to the first character following *pIn in
185009** the string that is not a "bareword" character.
185010*/
185011static const char *fts5ConfigSkipBareword(const char *pIn){
185012  const char *p = pIn;
185013  while ( sqlite3Fts5IsBareword(*p) ) p++;
185014  if( p==pIn ) p = 0;
185015  return p;
185016}
185017
185018static int fts5_isdigit(char a){
185019  return (a>='0' && a<='9');
185020}
185021
185022
185023
185024static const char *fts5ConfigSkipLiteral(const char *pIn){
185025  const char *p = pIn;
185026  switch( *p ){
185027    case 'n': case 'N':
185028      if( sqlite3_strnicmp("null", p, 4)==0 ){
185029        p = &p[4];
185030      }else{
185031        p = 0;
185032      }
185033      break;
185034
185035    case 'x': case 'X':
185036      p++;
185037      if( *p=='\'' ){
185038        p++;
185039        while( (*p>='a' && *p<='f')
185040            || (*p>='A' && *p<='F')
185041            || (*p>='0' && *p<='9')
185042            ){
185043          p++;
185044        }
185045        if( *p=='\'' && 0==((p-pIn)%2) ){
185046          p++;
185047        }else{
185048          p = 0;
185049        }
185050      }else{
185051        p = 0;
185052      }
185053      break;
185054
185055    case '\'':
185056      p++;
185057      while( p ){
185058        if( *p=='\'' ){
185059          p++;
185060          if( *p!='\'' ) break;
185061        }
185062        p++;
185063        if( *p==0 ) p = 0;
185064      }
185065      break;
185066
185067    default:
185068      /* maybe a number */
185069      if( *p=='+' || *p=='-' ) p++;
185070      while( fts5_isdigit(*p) ) p++;
185071
185072      /* At this point, if the literal was an integer, the parse is
185073      ** finished. Or, if it is a floating point value, it may continue
185074      ** with either a decimal point or an 'E' character. */
185075      if( *p=='.' && fts5_isdigit(p[1]) ){
185076        p += 2;
185077        while( fts5_isdigit(*p) ) p++;
185078      }
185079      if( p==pIn ) p = 0;
185080
185081      break;
185082  }
185083
185084  return p;
185085}
185086
185087/*
185088** The first character of the string pointed to by argument z is guaranteed
185089** to be an open-quote character (see function fts5_isopenquote()).
185090**
185091** This function searches for the corresponding close-quote character within
185092** the string and, if found, dequotes the string in place and adds a new
185093** nul-terminator byte.
185094**
185095** If the close-quote is found, the value returned is the byte offset of
185096** the character immediately following it. Or, if the close-quote is not
185097** found, -1 is returned. If -1 is returned, the buffer is left in an
185098** undefined state.
185099*/
185100static int fts5Dequote(char *z){
185101  char q;
185102  int iIn = 1;
185103  int iOut = 0;
185104  q = z[0];
185105
185106  /* Set stack variable q to the close-quote character */
185107  assert( q=='[' || q=='\'' || q=='"' || q=='`' );
185108  if( q=='[' ) q = ']';
185109
185110  while( ALWAYS(z[iIn]) ){
185111    if( z[iIn]==q ){
185112      if( z[iIn+1]!=q ){
185113        /* Character iIn was the close quote. */
185114        iIn++;
185115        break;
185116      }else{
185117        /* Character iIn and iIn+1 form an escaped quote character. Skip
185118        ** the input cursor past both and copy a single quote character
185119        ** to the output buffer. */
185120        iIn += 2;
185121        z[iOut++] = q;
185122      }
185123    }else{
185124      z[iOut++] = z[iIn++];
185125    }
185126  }
185127
185128  z[iOut] = '\0';
185129  return iIn;
185130}
185131
185132/*
185133** Convert an SQL-style quoted string into a normal string by removing
185134** the quote characters.  The conversion is done in-place.  If the
185135** input does not begin with a quote character, then this routine
185136** is a no-op.
185137**
185138** Examples:
185139**
185140**     "abc"   becomes   abc
185141**     'xyz'   becomes   xyz
185142**     [pqr]   becomes   pqr
185143**     `mno`   becomes   mno
185144*/
185145static void sqlite3Fts5Dequote(char *z){
185146  char quote;                     /* Quote character (if any ) */
185147
185148  assert( 0==fts5_iswhitespace(z[0]) );
185149  quote = z[0];
185150  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
185151    fts5Dequote(z);
185152  }
185153}
185154
185155
185156struct Fts5Enum {
185157  const char *zName;
185158  int eVal;
185159};
185160typedef struct Fts5Enum Fts5Enum;
185161
185162static int fts5ConfigSetEnum(
185163  const Fts5Enum *aEnum,
185164  const char *zEnum,
185165  int *peVal
185166){
185167  int nEnum = (int)strlen(zEnum);
185168  int i;
185169  int iVal = -1;
185170
185171  for(i=0; aEnum[i].zName; i++){
185172    if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
185173      if( iVal>=0 ) return SQLITE_ERROR;
185174      iVal = aEnum[i].eVal;
185175    }
185176  }
185177
185178  *peVal = iVal;
185179  return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
185180}
185181
185182/*
185183** Parse a "special" CREATE VIRTUAL TABLE directive and update
185184** configuration object pConfig as appropriate.
185185**
185186** If successful, object pConfig is updated and SQLITE_OK returned. If
185187** an error occurs, an SQLite error code is returned and an error message
185188** may be left in *pzErr. It is the responsibility of the caller to
185189** eventually free any such error message using sqlite3_free().
185190*/
185191static int fts5ConfigParseSpecial(
185192  Fts5Global *pGlobal,
185193  Fts5Config *pConfig,            /* Configuration object to update */
185194  const char *zCmd,               /* Special command to parse */
185195  const char *zArg,               /* Argument to parse */
185196  char **pzErr                    /* OUT: Error message */
185197){
185198  int rc = SQLITE_OK;
185199  int nCmd = (int)strlen(zCmd);
185200  if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
185201    const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
185202    const char *p;
185203    int bFirst = 1;
185204    if( pConfig->aPrefix==0 ){
185205      pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
185206      if( rc ) return rc;
185207    }
185208
185209    p = zArg;
185210    while( 1 ){
185211      int nPre = 0;
185212
185213      while( p[0]==' ' ) p++;
185214      if( bFirst==0 && p[0]==',' ){
185215        p++;
185216        while( p[0]==' ' ) p++;
185217      }else if( p[0]=='\0' ){
185218        break;
185219      }
185220      if( p[0]<'0' || p[0]>'9' ){
185221        *pzErr = sqlite3_mprintf("malformed prefix=... directive");
185222        rc = SQLITE_ERROR;
185223        break;
185224      }
185225
185226      if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
185227        *pzErr = sqlite3_mprintf(
185228            "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
185229        );
185230        rc = SQLITE_ERROR;
185231        break;
185232      }
185233
185234      while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
185235        nPre = nPre*10 + (p[0] - '0');
185236        p++;
185237      }
185238
185239      if( nPre<=0 || nPre>=1000 ){
185240        *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
185241        rc = SQLITE_ERROR;
185242        break;
185243      }
185244
185245      pConfig->aPrefix[pConfig->nPrefix] = nPre;
185246      pConfig->nPrefix++;
185247      bFirst = 0;
185248    }
185249    assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
185250    return rc;
185251  }
185252
185253  if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
185254    const char *p = (const char*)zArg;
185255    int nArg = (int)strlen(zArg) + 1;
185256    char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
185257    char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
185258    char *pSpace = pDel;
185259
185260    if( azArg && pSpace ){
185261      if( pConfig->pTok ){
185262        *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
185263        rc = SQLITE_ERROR;
185264      }else{
185265        for(nArg=0; p && *p; nArg++){
185266          const char *p2 = fts5ConfigSkipWhitespace(p);
185267          if( *p2=='\'' ){
185268            p = fts5ConfigSkipLiteral(p2);
185269          }else{
185270            p = fts5ConfigSkipBareword(p2);
185271          }
185272          if( p ){
185273            memcpy(pSpace, p2, p-p2);
185274            azArg[nArg] = pSpace;
185275            sqlite3Fts5Dequote(pSpace);
185276            pSpace += (p - p2) + 1;
185277            p = fts5ConfigSkipWhitespace(p);
185278          }
185279        }
185280        if( p==0 ){
185281          *pzErr = sqlite3_mprintf("parse error in tokenize directive");
185282          rc = SQLITE_ERROR;
185283        }else{
185284          rc = sqlite3Fts5GetTokenizer(pGlobal,
185285              (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
185286              pzErr
185287          );
185288        }
185289      }
185290    }
185291
185292    sqlite3_free(azArg);
185293    sqlite3_free(pDel);
185294    return rc;
185295  }
185296
185297  if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
185298    if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
185299      *pzErr = sqlite3_mprintf("multiple content=... directives");
185300      rc = SQLITE_ERROR;
185301    }else{
185302      if( zArg[0] ){
185303        pConfig->eContent = FTS5_CONTENT_EXTERNAL;
185304        pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
185305      }else{
185306        pConfig->eContent = FTS5_CONTENT_NONE;
185307      }
185308    }
185309    return rc;
185310  }
185311
185312  if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
185313    if( pConfig->zContentRowid ){
185314      *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
185315      rc = SQLITE_ERROR;
185316    }else{
185317      pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
185318    }
185319    return rc;
185320  }
185321
185322  if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
185323    if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
185324      *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
185325      rc = SQLITE_ERROR;
185326    }else{
185327      pConfig->bColumnsize = (zArg[0]=='1');
185328    }
185329    return rc;
185330  }
185331
185332  if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
185333    const Fts5Enum aDetail[] = {
185334      { "none", FTS5_DETAIL_NONE },
185335      { "full", FTS5_DETAIL_FULL },
185336      { "columns", FTS5_DETAIL_COLUMNS },
185337      { 0, 0 }
185338    };
185339
185340    if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
185341      *pzErr = sqlite3_mprintf("malformed detail=... directive");
185342    }
185343    return rc;
185344  }
185345
185346  *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
185347  return SQLITE_ERROR;
185348}
185349
185350/*
185351** Allocate an instance of the default tokenizer ("simple") at
185352** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
185353** code if an error occurs.
185354*/
185355static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
185356  assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
185357  return sqlite3Fts5GetTokenizer(
185358      pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
185359  );
185360}
185361
185362/*
185363** Gobble up the first bareword or quoted word from the input buffer zIn.
185364** Return a pointer to the character immediately following the last in
185365** the gobbled word if successful, or a NULL pointer otherwise (failed
185366** to find close-quote character).
185367**
185368** Before returning, set pzOut to point to a new buffer containing a
185369** nul-terminated, dequoted copy of the gobbled word. If the word was
185370** quoted, *pbQuoted is also set to 1 before returning.
185371**
185372** If *pRc is other than SQLITE_OK when this function is called, it is
185373** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
185374** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
185375** set if a parse error (failed to find close quote) occurs.
185376*/
185377static const char *fts5ConfigGobbleWord(
185378  int *pRc,                       /* IN/OUT: Error code */
185379  const char *zIn,                /* Buffer to gobble string/bareword from */
185380  char **pzOut,                   /* OUT: malloc'd buffer containing str/bw */
185381  int *pbQuoted                   /* OUT: Set to true if dequoting required */
185382){
185383  const char *zRet = 0;
185384
185385  int nIn = (int)strlen(zIn);
185386  char *zOut = sqlite3_malloc(nIn+1);
185387
185388  assert( *pRc==SQLITE_OK );
185389  *pbQuoted = 0;
185390  *pzOut = 0;
185391
185392  if( zOut==0 ){
185393    *pRc = SQLITE_NOMEM;
185394  }else{
185395    memcpy(zOut, zIn, nIn+1);
185396    if( fts5_isopenquote(zOut[0]) ){
185397      int ii = fts5Dequote(zOut);
185398      zRet = &zIn[ii];
185399      *pbQuoted = 1;
185400    }else{
185401      zRet = fts5ConfigSkipBareword(zIn);
185402      if( zRet ){
185403        zOut[zRet-zIn] = '\0';
185404      }
185405    }
185406  }
185407
185408  if( zRet==0 ){
185409    sqlite3_free(zOut);
185410  }else{
185411    *pzOut = zOut;
185412  }
185413
185414  return zRet;
185415}
185416
185417static int fts5ConfigParseColumn(
185418  Fts5Config *p,
185419  char *zCol,
185420  char *zArg,
185421  char **pzErr
185422){
185423  int rc = SQLITE_OK;
185424  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
185425   || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
185426  ){
185427    *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
185428    rc = SQLITE_ERROR;
185429  }else if( zArg ){
185430    if( 0==sqlite3_stricmp(zArg, "unindexed") ){
185431      p->abUnindexed[p->nCol] = 1;
185432    }else{
185433      *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
185434      rc = SQLITE_ERROR;
185435    }
185436  }
185437
185438  p->azCol[p->nCol++] = zCol;
185439  return rc;
185440}
185441
185442/*
185443** Populate the Fts5Config.zContentExprlist string.
185444*/
185445static int fts5ConfigMakeExprlist(Fts5Config *p){
185446  int i;
185447  int rc = SQLITE_OK;
185448  Fts5Buffer buf = {0, 0, 0};
185449
185450  sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
185451  if( p->eContent!=FTS5_CONTENT_NONE ){
185452    for(i=0; i<p->nCol; i++){
185453      if( p->eContent==FTS5_CONTENT_EXTERNAL ){
185454        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
185455      }else{
185456        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
185457      }
185458    }
185459  }
185460
185461  assert( p->zContentExprlist==0 );
185462  p->zContentExprlist = (char*)buf.p;
185463  return rc;
185464}
185465
185466/*
185467** Arguments nArg/azArg contain the string arguments passed to the xCreate
185468** or xConnect method of the virtual table. This function attempts to
185469** allocate an instance of Fts5Config containing the results of parsing
185470** those arguments.
185471**
185472** If successful, SQLITE_OK is returned and *ppOut is set to point to the
185473** new Fts5Config object. If an error occurs, an SQLite error code is
185474** returned, *ppOut is set to NULL and an error message may be left in
185475** *pzErr. It is the responsibility of the caller to eventually free any
185476** such error message using sqlite3_free().
185477*/
185478static int sqlite3Fts5ConfigParse(
185479  Fts5Global *pGlobal,
185480  sqlite3 *db,
185481  int nArg,                       /* Number of arguments */
185482  const char **azArg,             /* Array of nArg CREATE VIRTUAL TABLE args */
185483  Fts5Config **ppOut,             /* OUT: Results of parse */
185484  char **pzErr                    /* OUT: Error message */
185485){
185486  int rc = SQLITE_OK;             /* Return code */
185487  Fts5Config *pRet;               /* New object to return */
185488  int i;
185489  int nByte;
185490
185491  *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
185492  if( pRet==0 ) return SQLITE_NOMEM;
185493  memset(pRet, 0, sizeof(Fts5Config));
185494  pRet->db = db;
185495  pRet->iCookie = -1;
185496
185497  nByte = nArg * (sizeof(char*) + sizeof(u8));
185498  pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
185499  pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
185500  pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
185501  pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
185502  pRet->bColumnsize = 1;
185503  pRet->eDetail = FTS5_DETAIL_FULL;
185504#ifdef SQLITE_DEBUG
185505  pRet->bPrefixIndex = 1;
185506#endif
185507  if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
185508    *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
185509    rc = SQLITE_ERROR;
185510  }
185511
185512  for(i=3; rc==SQLITE_OK && i<nArg; i++){
185513    const char *zOrig = azArg[i];
185514    const char *z;
185515    char *zOne = 0;
185516    char *zTwo = 0;
185517    int bOption = 0;
185518    int bMustBeCol = 0;
185519
185520    z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
185521    z = fts5ConfigSkipWhitespace(z);
185522    if( z && *z=='=' ){
185523      bOption = 1;
185524      z++;
185525      if( bMustBeCol ) z = 0;
185526    }
185527    z = fts5ConfigSkipWhitespace(z);
185528    if( z && z[0] ){
185529      int bDummy;
185530      z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
185531      if( z && z[0] ) z = 0;
185532    }
185533
185534    if( rc==SQLITE_OK ){
185535      if( z==0 ){
185536        *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
185537        rc = SQLITE_ERROR;
185538      }else{
185539        if( bOption ){
185540          rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
185541        }else{
185542          rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
185543          zOne = 0;
185544        }
185545      }
185546    }
185547
185548    sqlite3_free(zOne);
185549    sqlite3_free(zTwo);
185550  }
185551
185552  /* If a tokenizer= option was successfully parsed, the tokenizer has
185553  ** already been allocated. Otherwise, allocate an instance of the default
185554  ** tokenizer (unicode61) now.  */
185555  if( rc==SQLITE_OK && pRet->pTok==0 ){
185556    rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
185557  }
185558
185559  /* If no zContent option was specified, fill in the default values. */
185560  if( rc==SQLITE_OK && pRet->zContent==0 ){
185561    const char *zTail = 0;
185562    assert( pRet->eContent==FTS5_CONTENT_NORMAL
185563         || pRet->eContent==FTS5_CONTENT_NONE
185564    );
185565    if( pRet->eContent==FTS5_CONTENT_NORMAL ){
185566      zTail = "content";
185567    }else if( pRet->bColumnsize ){
185568      zTail = "docsize";
185569    }
185570
185571    if( zTail ){
185572      pRet->zContent = sqlite3Fts5Mprintf(
185573          &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
185574      );
185575    }
185576  }
185577
185578  if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
185579    pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
185580  }
185581
185582  /* Formulate the zContentExprlist text */
185583  if( rc==SQLITE_OK ){
185584    rc = fts5ConfigMakeExprlist(pRet);
185585  }
185586
185587  if( rc!=SQLITE_OK ){
185588    sqlite3Fts5ConfigFree(pRet);
185589    *ppOut = 0;
185590  }
185591  return rc;
185592}
185593
185594/*
185595** Free the configuration object passed as the only argument.
185596*/
185597static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
185598  if( pConfig ){
185599    int i;
185600    if( pConfig->pTok ){
185601      pConfig->pTokApi->xDelete(pConfig->pTok);
185602    }
185603    sqlite3_free(pConfig->zDb);
185604    sqlite3_free(pConfig->zName);
185605    for(i=0; i<pConfig->nCol; i++){
185606      sqlite3_free(pConfig->azCol[i]);
185607    }
185608    sqlite3_free(pConfig->azCol);
185609    sqlite3_free(pConfig->aPrefix);
185610    sqlite3_free(pConfig->zRank);
185611    sqlite3_free(pConfig->zRankArgs);
185612    sqlite3_free(pConfig->zContent);
185613    sqlite3_free(pConfig->zContentRowid);
185614    sqlite3_free(pConfig->zContentExprlist);
185615    sqlite3_free(pConfig);
185616  }
185617}
185618
185619/*
185620** Call sqlite3_declare_vtab() based on the contents of the configuration
185621** object passed as the only argument. Return SQLITE_OK if successful, or
185622** an SQLite error code if an error occurs.
185623*/
185624static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
185625  int i;
185626  int rc = SQLITE_OK;
185627  char *zSql;
185628
185629  zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
185630  for(i=0; zSql && i<pConfig->nCol; i++){
185631    const char *zSep = (i==0?"":", ");
185632    zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
185633  }
185634  zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
185635      zSql, pConfig->zName, FTS5_RANK_NAME
185636  );
185637
185638  assert( zSql || rc==SQLITE_NOMEM );
185639  if( zSql ){
185640    rc = sqlite3_declare_vtab(pConfig->db, zSql);
185641    sqlite3_free(zSql);
185642  }
185643
185644  return rc;
185645}
185646
185647/*
185648** Tokenize the text passed via the second and third arguments.
185649**
185650** The callback is invoked once for each token in the input text. The
185651** arguments passed to it are, in order:
185652**
185653**     void *pCtx          // Copy of 4th argument to sqlite3Fts5Tokenize()
185654**     const char *pToken  // Pointer to buffer containing token
185655**     int nToken          // Size of token in bytes
185656**     int iStart          // Byte offset of start of token within input text
185657**     int iEnd            // Byte offset of end of token within input text
185658**     int iPos            // Position of token in input (first token is 0)
185659**
185660** If the callback returns a non-zero value the tokenization is abandoned
185661** and no further callbacks are issued.
185662**
185663** This function returns SQLITE_OK if successful or an SQLite error code
185664** if an error occurs. If the tokenization was abandoned early because
185665** the callback returned SQLITE_DONE, this is not an error and this function
185666** still returns SQLITE_OK. Or, if the tokenization was abandoned early
185667** because the callback returned another non-zero value, it is assumed
185668** to be an SQLite error code and returned to the caller.
185669*/
185670static int sqlite3Fts5Tokenize(
185671  Fts5Config *pConfig,            /* FTS5 Configuration object */
185672  int flags,                      /* FTS5_TOKENIZE_* flags */
185673  const char *pText, int nText,   /* Text to tokenize */
185674  void *pCtx,                     /* Context passed to xToken() */
185675  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
185676){
185677  if( pText==0 ) return SQLITE_OK;
185678  return pConfig->pTokApi->xTokenize(
185679      pConfig->pTok, pCtx, flags, pText, nText, xToken
185680  );
185681}
185682
185683/*
185684** Argument pIn points to the first character in what is expected to be
185685** a comma-separated list of SQL literals followed by a ')' character.
185686** If it actually is this, return a pointer to the ')'. Otherwise, return
185687** NULL to indicate a parse error.
185688*/
185689static const char *fts5ConfigSkipArgs(const char *pIn){
185690  const char *p = pIn;
185691
185692  while( 1 ){
185693    p = fts5ConfigSkipWhitespace(p);
185694    p = fts5ConfigSkipLiteral(p);
185695    p = fts5ConfigSkipWhitespace(p);
185696    if( p==0 || *p==')' ) break;
185697    if( *p!=',' ){
185698      p = 0;
185699      break;
185700    }
185701    p++;
185702  }
185703
185704  return p;
185705}
185706
185707/*
185708** Parameter zIn contains a rank() function specification. The format of
185709** this is:
185710**
185711**   + Bareword (function name)
185712**   + Open parenthesis - "("
185713**   + Zero or more SQL literals in a comma separated list
185714**   + Close parenthesis - ")"
185715*/
185716static int sqlite3Fts5ConfigParseRank(
185717  const char *zIn,                /* Input string */
185718  char **pzRank,                  /* OUT: Rank function name */
185719  char **pzRankArgs               /* OUT: Rank function arguments */
185720){
185721  const char *p = zIn;
185722  const char *pRank;
185723  char *zRank = 0;
185724  char *zRankArgs = 0;
185725  int rc = SQLITE_OK;
185726
185727  *pzRank = 0;
185728  *pzRankArgs = 0;
185729
185730  if( p==0 ){
185731    rc = SQLITE_ERROR;
185732  }else{
185733    p = fts5ConfigSkipWhitespace(p);
185734    pRank = p;
185735    p = fts5ConfigSkipBareword(p);
185736
185737    if( p ){
185738      zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
185739      if( zRank ) memcpy(zRank, pRank, p-pRank);
185740    }else{
185741      rc = SQLITE_ERROR;
185742    }
185743
185744    if( rc==SQLITE_OK ){
185745      p = fts5ConfigSkipWhitespace(p);
185746      if( *p!='(' ) rc = SQLITE_ERROR;
185747      p++;
185748    }
185749    if( rc==SQLITE_OK ){
185750      const char *pArgs;
185751      p = fts5ConfigSkipWhitespace(p);
185752      pArgs = p;
185753      if( *p!=')' ){
185754        p = fts5ConfigSkipArgs(p);
185755        if( p==0 ){
185756          rc = SQLITE_ERROR;
185757        }else{
185758          zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
185759          if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
185760        }
185761      }
185762    }
185763  }
185764
185765  if( rc!=SQLITE_OK ){
185766    sqlite3_free(zRank);
185767    assert( zRankArgs==0 );
185768  }else{
185769    *pzRank = zRank;
185770    *pzRankArgs = zRankArgs;
185771  }
185772  return rc;
185773}
185774
185775static int sqlite3Fts5ConfigSetValue(
185776  Fts5Config *pConfig,
185777  const char *zKey,
185778  sqlite3_value *pVal,
185779  int *pbBadkey
185780){
185781  int rc = SQLITE_OK;
185782
185783  if( 0==sqlite3_stricmp(zKey, "pgsz") ){
185784    int pgsz = 0;
185785    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
185786      pgsz = sqlite3_value_int(pVal);
185787    }
185788    if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
185789      *pbBadkey = 1;
185790    }else{
185791      pConfig->pgsz = pgsz;
185792    }
185793  }
185794
185795  else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
185796    int nHashSize = -1;
185797    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
185798      nHashSize = sqlite3_value_int(pVal);
185799    }
185800    if( nHashSize<=0 ){
185801      *pbBadkey = 1;
185802    }else{
185803      pConfig->nHashSize = nHashSize;
185804    }
185805  }
185806
185807  else if( 0==sqlite3_stricmp(zKey, "automerge") ){
185808    int nAutomerge = -1;
185809    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
185810      nAutomerge = sqlite3_value_int(pVal);
185811    }
185812    if( nAutomerge<0 || nAutomerge>64 ){
185813      *pbBadkey = 1;
185814    }else{
185815      if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
185816      pConfig->nAutomerge = nAutomerge;
185817    }
185818  }
185819
185820  else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
185821    int nUsermerge = -1;
185822    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
185823      nUsermerge = sqlite3_value_int(pVal);
185824    }
185825    if( nUsermerge<2 || nUsermerge>16 ){
185826      *pbBadkey = 1;
185827    }else{
185828      pConfig->nUsermerge = nUsermerge;
185829    }
185830  }
185831
185832  else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
185833    int nCrisisMerge = -1;
185834    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
185835      nCrisisMerge = sqlite3_value_int(pVal);
185836    }
185837    if( nCrisisMerge<0 ){
185838      *pbBadkey = 1;
185839    }else{
185840      if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
185841      pConfig->nCrisisMerge = nCrisisMerge;
185842    }
185843  }
185844
185845  else if( 0==sqlite3_stricmp(zKey, "rank") ){
185846    const char *zIn = (const char*)sqlite3_value_text(pVal);
185847    char *zRank;
185848    char *zRankArgs;
185849    rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
185850    if( rc==SQLITE_OK ){
185851      sqlite3_free(pConfig->zRank);
185852      sqlite3_free(pConfig->zRankArgs);
185853      pConfig->zRank = zRank;
185854      pConfig->zRankArgs = zRankArgs;
185855    }else if( rc==SQLITE_ERROR ){
185856      rc = SQLITE_OK;
185857      *pbBadkey = 1;
185858    }
185859  }else{
185860    *pbBadkey = 1;
185861  }
185862  return rc;
185863}
185864
185865/*
185866** Load the contents of the %_config table into memory.
185867*/
185868static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
185869  const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
185870  char *zSql;
185871  sqlite3_stmt *p = 0;
185872  int rc = SQLITE_OK;
185873  int iVersion = 0;
185874
185875  /* Set default values */
185876  pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
185877  pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
185878  pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
185879  pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
185880  pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
185881
185882  zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
185883  if( zSql ){
185884    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
185885    sqlite3_free(zSql);
185886  }
185887
185888  assert( rc==SQLITE_OK || p==0 );
185889  if( rc==SQLITE_OK ){
185890    while( SQLITE_ROW==sqlite3_step(p) ){
185891      const char *zK = (const char*)sqlite3_column_text(p, 0);
185892      sqlite3_value *pVal = sqlite3_column_value(p, 1);
185893      if( 0==sqlite3_stricmp(zK, "version") ){
185894        iVersion = sqlite3_value_int(pVal);
185895      }else{
185896        int bDummy = 0;
185897        sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
185898      }
185899    }
185900    rc = sqlite3_finalize(p);
185901  }
185902
185903  if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
185904    rc = SQLITE_ERROR;
185905    if( pConfig->pzErrmsg ){
185906      assert( 0==*pConfig->pzErrmsg );
185907      *pConfig->pzErrmsg = sqlite3_mprintf(
185908          "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
185909          iVersion, FTS5_CURRENT_VERSION
185910      );
185911    }
185912  }
185913
185914  if( rc==SQLITE_OK ){
185915    pConfig->iCookie = iCookie;
185916  }
185917  return rc;
185918}
185919
185920/*
185921** 2014 May 31
185922**
185923** The author disclaims copyright to this source code.  In place of
185924** a legal notice, here is a blessing:
185925**
185926**    May you do good and not evil.
185927**    May you find forgiveness for yourself and forgive others.
185928**    May you share freely, never taking more than you give.
185929**
185930******************************************************************************
185931**
185932*/
185933
185934
185935
185936/* #include "fts5Int.h" */
185937/* #include "fts5parse.h" */
185938
185939/*
185940** All token types in the generated fts5parse.h file are greater than 0.
185941*/
185942#define FTS5_EOF 0
185943
185944#define FTS5_LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
185945
185946typedef struct Fts5ExprTerm Fts5ExprTerm;
185947
185948/*
185949** Functions generated by lemon from fts5parse.y.
185950*/
185951static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
185952static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
185953static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
185954#ifndef NDEBUG
185955/* #include <stdio.h> */
185956static void sqlite3Fts5ParserTrace(FILE*, char*);
185957#endif
185958
185959
185960struct Fts5Expr {
185961  Fts5Index *pIndex;
185962  Fts5Config *pConfig;
185963  Fts5ExprNode *pRoot;
185964  int bDesc;                      /* Iterate in descending rowid order */
185965  int nPhrase;                    /* Number of phrases in expression */
185966  Fts5ExprPhrase **apExprPhrase;  /* Pointers to phrase objects */
185967};
185968
185969/*
185970** eType:
185971**   Expression node type. Always one of:
185972**
185973**       FTS5_AND                 (nChild, apChild valid)
185974**       FTS5_OR                  (nChild, apChild valid)
185975**       FTS5_NOT                 (nChild, apChild valid)
185976**       FTS5_STRING              (pNear valid)
185977**       FTS5_TERM                (pNear valid)
185978*/
185979struct Fts5ExprNode {
185980  int eType;                      /* Node type */
185981  int bEof;                       /* True at EOF */
185982  int bNomatch;                   /* True if entry is not a match */
185983
185984  /* Next method for this node. */
185985  int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
185986
185987  i64 iRowid;                     /* Current rowid */
185988  Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */
185989
185990  /* Child nodes. For a NOT node, this array always contains 2 entries. For
185991  ** AND or OR nodes, it contains 2 or more entries.  */
185992  int nChild;                     /* Number of child nodes */
185993  Fts5ExprNode *apChild[1];       /* Array of child nodes */
185994};
185995
185996#define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
185997
185998/*
185999** Invoke the xNext method of an Fts5ExprNode object. This macro should be
186000** used as if it has the same signature as the xNext() methods themselves.
186001*/
186002#define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
186003
186004/*
186005** An instance of the following structure represents a single search term
186006** or term prefix.
186007*/
186008struct Fts5ExprTerm {
186009  int bPrefix;                    /* True for a prefix term */
186010  char *zTerm;                    /* nul-terminated term */
186011  Fts5IndexIter *pIter;           /* Iterator for this term */
186012  Fts5ExprTerm *pSynonym;         /* Pointer to first in list of synonyms */
186013};
186014
186015/*
186016** A phrase. One or more terms that must appear in a contiguous sequence
186017** within a document for it to match.
186018*/
186019struct Fts5ExprPhrase {
186020  Fts5ExprNode *pNode;            /* FTS5_STRING node this phrase is part of */
186021  Fts5Buffer poslist;             /* Current position list */
186022  int nTerm;                      /* Number of entries in aTerm[] */
186023  Fts5ExprTerm aTerm[1];          /* Terms that make up this phrase */
186024};
186025
186026/*
186027** One or more phrases that must appear within a certain token distance of
186028** each other within each matching document.
186029*/
186030struct Fts5ExprNearset {
186031  int nNear;                      /* NEAR parameter */
186032  Fts5Colset *pColset;            /* Columns to search (NULL -> all columns) */
186033  int nPhrase;                    /* Number of entries in aPhrase[] array */
186034  Fts5ExprPhrase *apPhrase[1];    /* Array of phrase pointers */
186035};
186036
186037
186038/*
186039** Parse context.
186040*/
186041struct Fts5Parse {
186042  Fts5Config *pConfig;
186043  char *zErr;
186044  int rc;
186045  int nPhrase;                    /* Size of apPhrase array */
186046  Fts5ExprPhrase **apPhrase;      /* Array of all phrases */
186047  Fts5ExprNode *pExpr;            /* Result of a successful parse */
186048};
186049
186050static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
186051  va_list ap;
186052  va_start(ap, zFmt);
186053  if( pParse->rc==SQLITE_OK ){
186054    pParse->zErr = sqlite3_vmprintf(zFmt, ap);
186055    pParse->rc = SQLITE_ERROR;
186056  }
186057  va_end(ap);
186058}
186059
186060static int fts5ExprIsspace(char t){
186061  return t==' ' || t=='\t' || t=='\n' || t=='\r';
186062}
186063
186064/*
186065** Read the first token from the nul-terminated string at *pz.
186066*/
186067static int fts5ExprGetToken(
186068  Fts5Parse *pParse,
186069  const char **pz,                /* IN/OUT: Pointer into buffer */
186070  Fts5Token *pToken
186071){
186072  const char *z = *pz;
186073  int tok;
186074
186075  /* Skip past any whitespace */
186076  while( fts5ExprIsspace(*z) ) z++;
186077
186078  pToken->p = z;
186079  pToken->n = 1;
186080  switch( *z ){
186081    case '(':  tok = FTS5_LP;    break;
186082    case ')':  tok = FTS5_RP;    break;
186083    case '{':  tok = FTS5_LCP;   break;
186084    case '}':  tok = FTS5_RCP;   break;
186085    case ':':  tok = FTS5_COLON; break;
186086    case ',':  tok = FTS5_COMMA; break;
186087    case '+':  tok = FTS5_PLUS;  break;
186088    case '*':  tok = FTS5_STAR;  break;
186089    case '-':  tok = FTS5_MINUS; break;
186090    case '\0': tok = FTS5_EOF;   break;
186091
186092    case '"': {
186093      const char *z2;
186094      tok = FTS5_STRING;
186095
186096      for(z2=&z[1]; 1; z2++){
186097        if( z2[0]=='"' ){
186098          z2++;
186099          if( z2[0]!='"' ) break;
186100        }
186101        if( z2[0]=='\0' ){
186102          sqlite3Fts5ParseError(pParse, "unterminated string");
186103          return FTS5_EOF;
186104        }
186105      }
186106      pToken->n = (z2 - z);
186107      break;
186108    }
186109
186110    default: {
186111      const char *z2;
186112      if( sqlite3Fts5IsBareword(z[0])==0 ){
186113        sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
186114        return FTS5_EOF;
186115      }
186116      tok = FTS5_STRING;
186117      for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
186118      pToken->n = (z2 - z);
186119      if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 )  tok = FTS5_OR;
186120      if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
186121      if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
186122      break;
186123    }
186124  }
186125
186126  *pz = &pToken->p[pToken->n];
186127  return tok;
186128}
186129
186130static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
186131static void fts5ParseFree(void *p){ sqlite3_free(p); }
186132
186133static int sqlite3Fts5ExprNew(
186134  Fts5Config *pConfig,            /* FTS5 Configuration */
186135  const char *zExpr,              /* Expression text */
186136  Fts5Expr **ppNew,
186137  char **pzErr
186138){
186139  Fts5Parse sParse;
186140  Fts5Token token;
186141  const char *z = zExpr;
186142  int t;                          /* Next token type */
186143  void *pEngine;
186144  Fts5Expr *pNew;
186145
186146  *ppNew = 0;
186147  *pzErr = 0;
186148  memset(&sParse, 0, sizeof(sParse));
186149  pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
186150  if( pEngine==0 ){ return SQLITE_NOMEM; }
186151  sParse.pConfig = pConfig;
186152
186153  do {
186154    t = fts5ExprGetToken(&sParse, &z, &token);
186155    sqlite3Fts5Parser(pEngine, t, token, &sParse);
186156  }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
186157  sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
186158
186159  assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
186160  if( sParse.rc==SQLITE_OK ){
186161    *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
186162    if( pNew==0 ){
186163      sParse.rc = SQLITE_NOMEM;
186164      sqlite3Fts5ParseNodeFree(sParse.pExpr);
186165    }else{
186166      if( !sParse.pExpr ){
186167        const int nByte = sizeof(Fts5ExprNode);
186168        pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
186169        if( pNew->pRoot ){
186170          pNew->pRoot->bEof = 1;
186171        }
186172      }else{
186173        pNew->pRoot = sParse.pExpr;
186174      }
186175      pNew->pIndex = 0;
186176      pNew->pConfig = pConfig;
186177      pNew->apExprPhrase = sParse.apPhrase;
186178      pNew->nPhrase = sParse.nPhrase;
186179      sParse.apPhrase = 0;
186180    }
186181  }else{
186182    sqlite3Fts5ParseNodeFree(sParse.pExpr);
186183  }
186184
186185  sqlite3_free(sParse.apPhrase);
186186  *pzErr = sParse.zErr;
186187  return sParse.rc;
186188}
186189
186190/*
186191** Free the expression node object passed as the only argument.
186192*/
186193static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
186194  if( p ){
186195    int i;
186196    for(i=0; i<p->nChild; i++){
186197      sqlite3Fts5ParseNodeFree(p->apChild[i]);
186198    }
186199    sqlite3Fts5ParseNearsetFree(p->pNear);
186200    sqlite3_free(p);
186201  }
186202}
186203
186204/*
186205** Free the expression object passed as the only argument.
186206*/
186207static void sqlite3Fts5ExprFree(Fts5Expr *p){
186208  if( p ){
186209    sqlite3Fts5ParseNodeFree(p->pRoot);
186210    sqlite3_free(p->apExprPhrase);
186211    sqlite3_free(p);
186212  }
186213}
186214
186215/*
186216** Argument pTerm must be a synonym iterator. Return the current rowid
186217** that it points to.
186218*/
186219static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
186220  i64 iRet = 0;
186221  int bRetValid = 0;
186222  Fts5ExprTerm *p;
186223
186224  assert( pTerm->pSynonym );
186225  assert( bDesc==0 || bDesc==1 );
186226  for(p=pTerm; p; p=p->pSynonym){
186227    if( 0==sqlite3Fts5IterEof(p->pIter) ){
186228      i64 iRowid = p->pIter->iRowid;
186229      if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
186230        iRet = iRowid;
186231        bRetValid = 1;
186232      }
186233    }
186234  }
186235
186236  if( pbEof && bRetValid==0 ) *pbEof = 1;
186237  return iRet;
186238}
186239
186240/*
186241** Argument pTerm must be a synonym iterator.
186242*/
186243static int fts5ExprSynonymList(
186244  Fts5ExprTerm *pTerm,
186245  i64 iRowid,
186246  Fts5Buffer *pBuf,               /* Use this buffer for space if required */
186247  u8 **pa, int *pn
186248){
186249  Fts5PoslistReader aStatic[4];
186250  Fts5PoslistReader *aIter = aStatic;
186251  int nIter = 0;
186252  int nAlloc = 4;
186253  int rc = SQLITE_OK;
186254  Fts5ExprTerm *p;
186255
186256  assert( pTerm->pSynonym );
186257  for(p=pTerm; p; p=p->pSynonym){
186258    Fts5IndexIter *pIter = p->pIter;
186259    if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
186260      if( pIter->nData==0 ) continue;
186261      if( nIter==nAlloc ){
186262        int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
186263        Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
186264        if( aNew==0 ){
186265          rc = SQLITE_NOMEM;
186266          goto synonym_poslist_out;
186267        }
186268        memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
186269        nAlloc = nAlloc*2;
186270        if( aIter!=aStatic ) sqlite3_free(aIter);
186271        aIter = aNew;
186272      }
186273      sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
186274      assert( aIter[nIter].bEof==0 );
186275      nIter++;
186276    }
186277  }
186278
186279  if( nIter==1 ){
186280    *pa = (u8*)aIter[0].a;
186281    *pn = aIter[0].n;
186282  }else{
186283    Fts5PoslistWriter writer = {0};
186284    i64 iPrev = -1;
186285    fts5BufferZero(pBuf);
186286    while( 1 ){
186287      int i;
186288      i64 iMin = FTS5_LARGEST_INT64;
186289      for(i=0; i<nIter; i++){
186290        if( aIter[i].bEof==0 ){
186291          if( aIter[i].iPos==iPrev ){
186292            if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
186293          }
186294          if( aIter[i].iPos<iMin ){
186295            iMin = aIter[i].iPos;
186296          }
186297        }
186298      }
186299      if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
186300      rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
186301      iPrev = iMin;
186302    }
186303    if( rc==SQLITE_OK ){
186304      *pa = pBuf->p;
186305      *pn = pBuf->n;
186306    }
186307  }
186308
186309 synonym_poslist_out:
186310  if( aIter!=aStatic ) sqlite3_free(aIter);
186311  return rc;
186312}
186313
186314
186315/*
186316** All individual term iterators in pPhrase are guaranteed to be valid and
186317** pointing to the same rowid when this function is called. This function
186318** checks if the current rowid really is a match, and if so populates
186319** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
186320** is set to true if this is really a match, or false otherwise.
186321**
186322** SQLITE_OK is returned if an error occurs, or an SQLite error code
186323** otherwise. It is not considered an error code if the current rowid is
186324** not a match.
186325*/
186326static int fts5ExprPhraseIsMatch(
186327  Fts5ExprNode *pNode,            /* Node pPhrase belongs to */
186328  Fts5ExprPhrase *pPhrase,        /* Phrase object to initialize */
186329  int *pbMatch                    /* OUT: Set to true if really a match */
186330){
186331  Fts5PoslistWriter writer = {0};
186332  Fts5PoslistReader aStatic[4];
186333  Fts5PoslistReader *aIter = aStatic;
186334  int i;
186335  int rc = SQLITE_OK;
186336
186337  fts5BufferZero(&pPhrase->poslist);
186338
186339  /* If the aStatic[] array is not large enough, allocate a large array
186340  ** using sqlite3_malloc(). This approach could be improved upon. */
186341  if( pPhrase->nTerm>ArraySize(aStatic) ){
186342    int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
186343    aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
186344    if( !aIter ) return SQLITE_NOMEM;
186345  }
186346  memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
186347
186348  /* Initialize a term iterator for each term in the phrase */
186349  for(i=0; i<pPhrase->nTerm; i++){
186350    Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
186351    int n = 0;
186352    int bFlag = 0;
186353    u8 *a = 0;
186354    if( pTerm->pSynonym ){
186355      Fts5Buffer buf = {0, 0, 0};
186356      rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
186357      if( rc ){
186358        sqlite3_free(a);
186359        goto ismatch_out;
186360      }
186361      if( a==buf.p ) bFlag = 1;
186362    }else{
186363      a = (u8*)pTerm->pIter->pData;
186364      n = pTerm->pIter->nData;
186365    }
186366    sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
186367    aIter[i].bFlag = (u8)bFlag;
186368    if( aIter[i].bEof ) goto ismatch_out;
186369  }
186370
186371  while( 1 ){
186372    int bMatch;
186373    i64 iPos = aIter[0].iPos;
186374    do {
186375      bMatch = 1;
186376      for(i=0; i<pPhrase->nTerm; i++){
186377        Fts5PoslistReader *pPos = &aIter[i];
186378        i64 iAdj = iPos + i;
186379        if( pPos->iPos!=iAdj ){
186380          bMatch = 0;
186381          while( pPos->iPos<iAdj ){
186382            if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
186383          }
186384          if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
186385        }
186386      }
186387    }while( bMatch==0 );
186388
186389    /* Append position iPos to the output */
186390    rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
186391    if( rc!=SQLITE_OK ) goto ismatch_out;
186392
186393    for(i=0; i<pPhrase->nTerm; i++){
186394      if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
186395    }
186396  }
186397
186398 ismatch_out:
186399  *pbMatch = (pPhrase->poslist.n>0);
186400  for(i=0; i<pPhrase->nTerm; i++){
186401    if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
186402  }
186403  if( aIter!=aStatic ) sqlite3_free(aIter);
186404  return rc;
186405}
186406
186407typedef struct Fts5LookaheadReader Fts5LookaheadReader;
186408struct Fts5LookaheadReader {
186409  const u8 *a;                    /* Buffer containing position list */
186410  int n;                          /* Size of buffer a[] in bytes */
186411  int i;                          /* Current offset in position list */
186412  i64 iPos;                       /* Current position */
186413  i64 iLookahead;                 /* Next position */
186414};
186415
186416#define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
186417
186418static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
186419  p->iPos = p->iLookahead;
186420  if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
186421    p->iLookahead = FTS5_LOOKAHEAD_EOF;
186422  }
186423  return (p->iPos==FTS5_LOOKAHEAD_EOF);
186424}
186425
186426static int fts5LookaheadReaderInit(
186427  const u8 *a, int n,             /* Buffer to read position list from */
186428  Fts5LookaheadReader *p          /* Iterator object to initialize */
186429){
186430  memset(p, 0, sizeof(Fts5LookaheadReader));
186431  p->a = a;
186432  p->n = n;
186433  fts5LookaheadReaderNext(p);
186434  return fts5LookaheadReaderNext(p);
186435}
186436
186437typedef struct Fts5NearTrimmer Fts5NearTrimmer;
186438struct Fts5NearTrimmer {
186439  Fts5LookaheadReader reader;     /* Input iterator */
186440  Fts5PoslistWriter writer;       /* Writer context */
186441  Fts5Buffer *pOut;               /* Output poslist */
186442};
186443
186444/*
186445** The near-set object passed as the first argument contains more than
186446** one phrase. All phrases currently point to the same row. The
186447** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
186448** tests if the current row contains instances of each phrase sufficiently
186449** close together to meet the NEAR constraint. Non-zero is returned if it
186450** does, or zero otherwise.
186451**
186452** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
186453** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
186454** occurs within this function (*pRc) is set accordingly before returning.
186455** The return value is undefined in both these cases.
186456**
186457** If no error occurs and non-zero (a match) is returned, the position-list
186458** of each phrase object is edited to contain only those entries that
186459** meet the constraint before returning.
186460*/
186461static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
186462  Fts5NearTrimmer aStatic[4];
186463  Fts5NearTrimmer *a = aStatic;
186464  Fts5ExprPhrase **apPhrase = pNear->apPhrase;
186465
186466  int i;
186467  int rc = *pRc;
186468  int bMatch;
186469
186470  assert( pNear->nPhrase>1 );
186471
186472  /* If the aStatic[] array is not large enough, allocate a large array
186473  ** using sqlite3_malloc(). This approach could be improved upon. */
186474  if( pNear->nPhrase>ArraySize(aStatic) ){
186475    int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
186476    a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
186477  }else{
186478    memset(aStatic, 0, sizeof(aStatic));
186479  }
186480  if( rc!=SQLITE_OK ){
186481    *pRc = rc;
186482    return 0;
186483  }
186484
186485  /* Initialize a lookahead iterator for each phrase. After passing the
186486  ** buffer and buffer size to the lookaside-reader init function, zero
186487  ** the phrase poslist buffer. The new poslist for the phrase (containing
186488  ** the same entries as the original with some entries removed on account
186489  ** of the NEAR constraint) is written over the original even as it is
186490  ** being read. This is safe as the entries for the new poslist are a
186491  ** subset of the old, so it is not possible for data yet to be read to
186492  ** be overwritten.  */
186493  for(i=0; i<pNear->nPhrase; i++){
186494    Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
186495    fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
186496    pPoslist->n = 0;
186497    a[i].pOut = pPoslist;
186498  }
186499
186500  while( 1 ){
186501    int iAdv;
186502    i64 iMin;
186503    i64 iMax;
186504
186505    /* This block advances the phrase iterators until they point to a set of
186506    ** entries that together comprise a match.  */
186507    iMax = a[0].reader.iPos;
186508    do {
186509      bMatch = 1;
186510      for(i=0; i<pNear->nPhrase; i++){
186511        Fts5LookaheadReader *pPos = &a[i].reader;
186512        iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
186513        if( pPos->iPos<iMin || pPos->iPos>iMax ){
186514          bMatch = 0;
186515          while( pPos->iPos<iMin ){
186516            if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
186517          }
186518          if( pPos->iPos>iMax ) iMax = pPos->iPos;
186519        }
186520      }
186521    }while( bMatch==0 );
186522
186523    /* Add an entry to each output position list */
186524    for(i=0; i<pNear->nPhrase; i++){
186525      i64 iPos = a[i].reader.iPos;
186526      Fts5PoslistWriter *pWriter = &a[i].writer;
186527      if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
186528        sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
186529      }
186530    }
186531
186532    iAdv = 0;
186533    iMin = a[0].reader.iLookahead;
186534    for(i=0; i<pNear->nPhrase; i++){
186535      if( a[i].reader.iLookahead < iMin ){
186536        iMin = a[i].reader.iLookahead;
186537        iAdv = i;
186538      }
186539    }
186540    if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
186541  }
186542
186543  ismatch_out: {
186544    int bRet = a[0].pOut->n>0;
186545    *pRc = rc;
186546    if( a!=aStatic ) sqlite3_free(a);
186547    return bRet;
186548  }
186549}
186550
186551/*
186552** Advance iterator pIter until it points to a value equal to or laster
186553** than the initial value of *piLast. If this means the iterator points
186554** to a value laster than *piLast, update *piLast to the new lastest value.
186555**
186556** If the iterator reaches EOF, set *pbEof to true before returning. If
186557** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
186558** are set, return a non-zero value. Otherwise, return zero.
186559*/
186560static int fts5ExprAdvanceto(
186561  Fts5IndexIter *pIter,           /* Iterator to advance */
186562  int bDesc,                      /* True if iterator is "rowid DESC" */
186563  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
186564  int *pRc,                       /* OUT: Error code */
186565  int *pbEof                      /* OUT: Set to true if EOF */
186566){
186567  i64 iLast = *piLast;
186568  i64 iRowid;
186569
186570  iRowid = pIter->iRowid;
186571  if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
186572    int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
186573    if( rc || sqlite3Fts5IterEof(pIter) ){
186574      *pRc = rc;
186575      *pbEof = 1;
186576      return 1;
186577    }
186578    iRowid = pIter->iRowid;
186579    assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
186580  }
186581  *piLast = iRowid;
186582
186583  return 0;
186584}
186585
186586static int fts5ExprSynonymAdvanceto(
186587  Fts5ExprTerm *pTerm,            /* Term iterator to advance */
186588  int bDesc,                      /* True if iterator is "rowid DESC" */
186589  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
186590  int *pRc                        /* OUT: Error code */
186591){
186592  int rc = SQLITE_OK;
186593  i64 iLast = *piLast;
186594  Fts5ExprTerm *p;
186595  int bEof = 0;
186596
186597  for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
186598    if( sqlite3Fts5IterEof(p->pIter)==0 ){
186599      i64 iRowid = p->pIter->iRowid;
186600      if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
186601        rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
186602      }
186603    }
186604  }
186605
186606  if( rc!=SQLITE_OK ){
186607    *pRc = rc;
186608    bEof = 1;
186609  }else{
186610    *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
186611  }
186612  return bEof;
186613}
186614
186615
186616static int fts5ExprNearTest(
186617  int *pRc,
186618  Fts5Expr *pExpr,                /* Expression that pNear is a part of */
186619  Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_STRING) */
186620){
186621  Fts5ExprNearset *pNear = pNode->pNear;
186622  int rc = *pRc;
186623
186624  if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
186625    Fts5ExprTerm *pTerm;
186626    Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
186627    pPhrase->poslist.n = 0;
186628    for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
186629      Fts5IndexIter *pIter = pTerm->pIter;
186630      if( sqlite3Fts5IterEof(pIter)==0 ){
186631        if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
186632          pPhrase->poslist.n = 1;
186633        }
186634      }
186635    }
186636    return pPhrase->poslist.n;
186637  }else{
186638    int i;
186639
186640    /* Check that each phrase in the nearset matches the current row.
186641    ** Populate the pPhrase->poslist buffers at the same time. If any
186642    ** phrase is not a match, break out of the loop early.  */
186643    for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
186644      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
186645      if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
186646        int bMatch = 0;
186647        rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
186648        if( bMatch==0 ) break;
186649      }else{
186650        Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
186651        fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
186652      }
186653    }
186654
186655    *pRc = rc;
186656    if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
186657      return 1;
186658    }
186659    return 0;
186660  }
186661}
186662
186663
186664/*
186665** Initialize all term iterators in the pNear object. If any term is found
186666** to match no documents at all, return immediately without initializing any
186667** further iterators.
186668**
186669** If an error occurs, return an SQLite error code. Otherwise, return
186670** SQLITE_OK. It is not considered an error if some term matches zero
186671** documents.
186672*/
186673static int fts5ExprNearInitAll(
186674  Fts5Expr *pExpr,
186675  Fts5ExprNode *pNode
186676){
186677  Fts5ExprNearset *pNear = pNode->pNear;
186678  int i;
186679
186680  assert( pNode->bNomatch==0 );
186681  for(i=0; i<pNear->nPhrase; i++){
186682    Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
186683    if( pPhrase->nTerm==0 ){
186684      pNode->bEof = 1;
186685      return SQLITE_OK;
186686    }else{
186687      int j;
186688      for(j=0; j<pPhrase->nTerm; j++){
186689        Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
186690        Fts5ExprTerm *p;
186691        int bHit = 0;
186692
186693        for(p=pTerm; p; p=p->pSynonym){
186694          int rc;
186695          if( p->pIter ){
186696            sqlite3Fts5IterClose(p->pIter);
186697            p->pIter = 0;
186698          }
186699          rc = sqlite3Fts5IndexQuery(
186700              pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
186701              (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
186702              (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
186703              pNear->pColset,
186704              &p->pIter
186705          );
186706          assert( (rc==SQLITE_OK)==(p->pIter!=0) );
186707          if( rc!=SQLITE_OK ) return rc;
186708          if( 0==sqlite3Fts5IterEof(p->pIter) ){
186709            bHit = 1;
186710          }
186711        }
186712
186713        if( bHit==0 ){
186714          pNode->bEof = 1;
186715          return SQLITE_OK;
186716        }
186717      }
186718    }
186719  }
186720
186721  pNode->bEof = 0;
186722  return SQLITE_OK;
186723}
186724
186725/*
186726** If pExpr is an ASC iterator, this function returns a value with the
186727** same sign as:
186728**
186729**   (iLhs - iRhs)
186730**
186731** Otherwise, if this is a DESC iterator, the opposite is returned:
186732**
186733**   (iRhs - iLhs)
186734*/
186735static int fts5RowidCmp(
186736  Fts5Expr *pExpr,
186737  i64 iLhs,
186738  i64 iRhs
186739){
186740  assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
186741  if( pExpr->bDesc==0 ){
186742    if( iLhs<iRhs ) return -1;
186743    return (iLhs > iRhs);
186744  }else{
186745    if( iLhs>iRhs ) return -1;
186746    return (iLhs < iRhs);
186747  }
186748}
186749
186750static void fts5ExprSetEof(Fts5ExprNode *pNode){
186751  int i;
186752  pNode->bEof = 1;
186753  pNode->bNomatch = 0;
186754  for(i=0; i<pNode->nChild; i++){
186755    fts5ExprSetEof(pNode->apChild[i]);
186756  }
186757}
186758
186759static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
186760  if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
186761    Fts5ExprNearset *pNear = pNode->pNear;
186762    int i;
186763    for(i=0; i<pNear->nPhrase; i++){
186764      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
186765      pPhrase->poslist.n = 0;
186766    }
186767  }else{
186768    int i;
186769    for(i=0; i<pNode->nChild; i++){
186770      fts5ExprNodeZeroPoslist(pNode->apChild[i]);
186771    }
186772  }
186773}
186774
186775
186776
186777/*
186778** Compare the values currently indicated by the two nodes as follows:
186779**
186780**    res = (*p1) - (*p2)
186781**
186782** Nodes that point to values that come later in the iteration order are
186783** considered to be larger. Nodes at EOF are the largest of all.
186784**
186785** This means that if the iteration order is ASC, then numerically larger
186786** rowids are considered larger. Or if it is the default DESC, numerically
186787** smaller rowids are larger.
186788*/
186789static int fts5NodeCompare(
186790  Fts5Expr *pExpr,
186791  Fts5ExprNode *p1,
186792  Fts5ExprNode *p2
186793){
186794  if( p2->bEof ) return -1;
186795  if( p1->bEof ) return +1;
186796  return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
186797}
186798
186799/*
186800** All individual term iterators in pNear are guaranteed to be valid when
186801** this function is called. This function checks if all term iterators
186802** point to the same rowid, and if not, advances them until they do.
186803** If an EOF is reached before this happens, *pbEof is set to true before
186804** returning.
186805**
186806** SQLITE_OK is returned if an error occurs, or an SQLite error code
186807** otherwise. It is not considered an error code if an iterator reaches
186808** EOF.
186809*/
186810static int fts5ExprNodeTest_STRING(
186811  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
186812  Fts5ExprNode *pNode
186813){
186814  Fts5ExprNearset *pNear = pNode->pNear;
186815  Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
186816  int rc = SQLITE_OK;
186817  i64 iLast;                      /* Lastest rowid any iterator points to */
186818  int i, j;                       /* Phrase and token index, respectively */
186819  int bMatch;                     /* True if all terms are at the same rowid */
186820  const int bDesc = pExpr->bDesc;
186821
186822  /* Check that this node should not be FTS5_TERM */
186823  assert( pNear->nPhrase>1
186824       || pNear->apPhrase[0]->nTerm>1
186825       || pNear->apPhrase[0]->aTerm[0].pSynonym
186826  );
186827
186828  /* Initialize iLast, the "lastest" rowid any iterator points to. If the
186829  ** iterator skips through rowids in the default ascending order, this means
186830  ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
186831  ** means the minimum rowid.  */
186832  if( pLeft->aTerm[0].pSynonym ){
186833    iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
186834  }else{
186835    iLast = pLeft->aTerm[0].pIter->iRowid;
186836  }
186837
186838  do {
186839    bMatch = 1;
186840    for(i=0; i<pNear->nPhrase; i++){
186841      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
186842      for(j=0; j<pPhrase->nTerm; j++){
186843        Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
186844        if( pTerm->pSynonym ){
186845          i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
186846          if( iRowid==iLast ) continue;
186847          bMatch = 0;
186848          if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
186849            pNode->bNomatch = 0;
186850            pNode->bEof = 1;
186851            return rc;
186852          }
186853        }else{
186854          Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
186855          if( pIter->iRowid==iLast || pIter->bEof ) continue;
186856          bMatch = 0;
186857          if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
186858            return rc;
186859          }
186860        }
186861      }
186862    }
186863  }while( bMatch==0 );
186864
186865  pNode->iRowid = iLast;
186866  pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
186867  assert( pNode->bEof==0 || pNode->bNomatch==0 );
186868
186869  return rc;
186870}
186871
186872/*
186873** Advance the first term iterator in the first phrase of pNear. Set output
186874** variable *pbEof to true if it reaches EOF or if an error occurs.
186875**
186876** Return SQLITE_OK if successful, or an SQLite error code if an error
186877** occurs.
186878*/
186879static int fts5ExprNodeNext_STRING(
186880  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
186881  Fts5ExprNode *pNode,            /* FTS5_STRING or FTS5_TERM node */
186882  int bFromValid,
186883  i64 iFrom
186884){
186885  Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
186886  int rc = SQLITE_OK;
186887
186888  pNode->bNomatch = 0;
186889  if( pTerm->pSynonym ){
186890    int bEof = 1;
186891    Fts5ExprTerm *p;
186892
186893    /* Find the firstest rowid any synonym points to. */
186894    i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
186895
186896    /* Advance each iterator that currently points to iRowid. Or, if iFrom
186897    ** is valid - each iterator that points to a rowid before iFrom.  */
186898    for(p=pTerm; p; p=p->pSynonym){
186899      if( sqlite3Fts5IterEof(p->pIter)==0 ){
186900        i64 ii = p->pIter->iRowid;
186901        if( ii==iRowid
186902         || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
186903        ){
186904          if( bFromValid ){
186905            rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
186906          }else{
186907            rc = sqlite3Fts5IterNext(p->pIter);
186908          }
186909          if( rc!=SQLITE_OK ) break;
186910          if( sqlite3Fts5IterEof(p->pIter)==0 ){
186911            bEof = 0;
186912          }
186913        }else{
186914          bEof = 0;
186915        }
186916      }
186917    }
186918
186919    /* Set the EOF flag if either all synonym iterators are at EOF or an
186920    ** error has occurred.  */
186921    pNode->bEof = (rc || bEof);
186922  }else{
186923    Fts5IndexIter *pIter = pTerm->pIter;
186924
186925    assert( Fts5NodeIsString(pNode) );
186926    if( bFromValid ){
186927      rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
186928    }else{
186929      rc = sqlite3Fts5IterNext(pIter);
186930    }
186931
186932    pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
186933  }
186934
186935  if( pNode->bEof==0 ){
186936    assert( rc==SQLITE_OK );
186937    rc = fts5ExprNodeTest_STRING(pExpr, pNode);
186938  }
186939
186940  return rc;
186941}
186942
186943
186944static int fts5ExprNodeTest_TERM(
186945  Fts5Expr *pExpr,                /* Expression that pNear is a part of */
186946  Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_TERM) */
186947){
186948  /* As this "NEAR" object is actually a single phrase that consists
186949  ** of a single term only, grab pointers into the poslist managed by the
186950  ** fts5_index.c iterator object. This is much faster than synthesizing
186951  ** a new poslist the way we have to for more complicated phrase or NEAR
186952  ** expressions.  */
186953  Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
186954  Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
186955
186956  assert( pNode->eType==FTS5_TERM );
186957  assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
186958  assert( pPhrase->aTerm[0].pSynonym==0 );
186959
186960  pPhrase->poslist.n = pIter->nData;
186961  if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
186962    pPhrase->poslist.p = (u8*)pIter->pData;
186963  }
186964  pNode->iRowid = pIter->iRowid;
186965  pNode->bNomatch = (pPhrase->poslist.n==0);
186966  return SQLITE_OK;
186967}
186968
186969/*
186970** xNext() method for a node of type FTS5_TERM.
186971*/
186972static int fts5ExprNodeNext_TERM(
186973  Fts5Expr *pExpr,
186974  Fts5ExprNode *pNode,
186975  int bFromValid,
186976  i64 iFrom
186977){
186978  int rc;
186979  Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
186980
186981  assert( pNode->bEof==0 );
186982  if( bFromValid ){
186983    rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
186984  }else{
186985    rc = sqlite3Fts5IterNext(pIter);
186986  }
186987  if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
186988    rc = fts5ExprNodeTest_TERM(pExpr, pNode);
186989  }else{
186990    pNode->bEof = 1;
186991    pNode->bNomatch = 0;
186992  }
186993  return rc;
186994}
186995
186996static void fts5ExprNodeTest_OR(
186997  Fts5Expr *pExpr,                /* Expression of which pNode is a part */
186998  Fts5ExprNode *pNode             /* Expression node to test */
186999){
187000  Fts5ExprNode *pNext = pNode->apChild[0];
187001  int i;
187002
187003  for(i=1; i<pNode->nChild; i++){
187004    Fts5ExprNode *pChild = pNode->apChild[i];
187005    int cmp = fts5NodeCompare(pExpr, pNext, pChild);
187006    if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
187007      pNext = pChild;
187008    }
187009  }
187010  pNode->iRowid = pNext->iRowid;
187011  pNode->bEof = pNext->bEof;
187012  pNode->bNomatch = pNext->bNomatch;
187013}
187014
187015static int fts5ExprNodeNext_OR(
187016  Fts5Expr *pExpr,
187017  Fts5ExprNode *pNode,
187018  int bFromValid,
187019  i64 iFrom
187020){
187021  int i;
187022  i64 iLast = pNode->iRowid;
187023
187024  for(i=0; i<pNode->nChild; i++){
187025    Fts5ExprNode *p1 = pNode->apChild[i];
187026    assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
187027    if( p1->bEof==0 ){
187028      if( (p1->iRowid==iLast)
187029       || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
187030      ){
187031        int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
187032        if( rc!=SQLITE_OK ){
187033          pNode->bNomatch = 0;
187034          return rc;
187035        }
187036      }
187037    }
187038  }
187039
187040  fts5ExprNodeTest_OR(pExpr, pNode);
187041  return SQLITE_OK;
187042}
187043
187044/*
187045** Argument pNode is an FTS5_AND node.
187046*/
187047static int fts5ExprNodeTest_AND(
187048  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
187049  Fts5ExprNode *pAnd              /* FTS5_AND node to advance */
187050){
187051  int iChild;
187052  i64 iLast = pAnd->iRowid;
187053  int rc = SQLITE_OK;
187054  int bMatch;
187055
187056  assert( pAnd->bEof==0 );
187057  do {
187058    pAnd->bNomatch = 0;
187059    bMatch = 1;
187060    for(iChild=0; iChild<pAnd->nChild; iChild++){
187061      Fts5ExprNode *pChild = pAnd->apChild[iChild];
187062      int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
187063      if( cmp>0 ){
187064        /* Advance pChild until it points to iLast or laster */
187065        rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
187066        if( rc!=SQLITE_OK ){
187067          pAnd->bNomatch = 0;
187068          return rc;
187069        }
187070      }
187071
187072      /* If the child node is now at EOF, so is the parent AND node. Otherwise,
187073      ** the child node is guaranteed to have advanced at least as far as
187074      ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
187075      ** new lastest rowid seen so far.  */
187076      assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
187077      if( pChild->bEof ){
187078        fts5ExprSetEof(pAnd);
187079        bMatch = 1;
187080        break;
187081      }else if( iLast!=pChild->iRowid ){
187082        bMatch = 0;
187083        iLast = pChild->iRowid;
187084      }
187085
187086      if( pChild->bNomatch ){
187087        pAnd->bNomatch = 1;
187088      }
187089    }
187090  }while( bMatch==0 );
187091
187092  if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
187093    fts5ExprNodeZeroPoslist(pAnd);
187094  }
187095  pAnd->iRowid = iLast;
187096  return SQLITE_OK;
187097}
187098
187099static int fts5ExprNodeNext_AND(
187100  Fts5Expr *pExpr,
187101  Fts5ExprNode *pNode,
187102  int bFromValid,
187103  i64 iFrom
187104){
187105  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
187106  if( rc==SQLITE_OK ){
187107    rc = fts5ExprNodeTest_AND(pExpr, pNode);
187108  }else{
187109    pNode->bNomatch = 0;
187110  }
187111  return rc;
187112}
187113
187114static int fts5ExprNodeTest_NOT(
187115  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
187116  Fts5ExprNode *pNode             /* FTS5_NOT node to advance */
187117){
187118  int rc = SQLITE_OK;
187119  Fts5ExprNode *p1 = pNode->apChild[0];
187120  Fts5ExprNode *p2 = pNode->apChild[1];
187121  assert( pNode->nChild==2 );
187122
187123  while( rc==SQLITE_OK && p1->bEof==0 ){
187124    int cmp = fts5NodeCompare(pExpr, p1, p2);
187125    if( cmp>0 ){
187126      rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
187127      cmp = fts5NodeCompare(pExpr, p1, p2);
187128    }
187129    assert( rc!=SQLITE_OK || cmp<=0 );
187130    if( cmp || p2->bNomatch ) break;
187131    rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
187132  }
187133  pNode->bEof = p1->bEof;
187134  pNode->bNomatch = p1->bNomatch;
187135  pNode->iRowid = p1->iRowid;
187136  if( p1->bEof ){
187137    fts5ExprNodeZeroPoslist(p2);
187138  }
187139  return rc;
187140}
187141
187142static int fts5ExprNodeNext_NOT(
187143  Fts5Expr *pExpr,
187144  Fts5ExprNode *pNode,
187145  int bFromValid,
187146  i64 iFrom
187147){
187148  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
187149  if( rc==SQLITE_OK ){
187150    rc = fts5ExprNodeTest_NOT(pExpr, pNode);
187151  }
187152  if( rc!=SQLITE_OK ){
187153    pNode->bNomatch = 0;
187154  }
187155  return rc;
187156}
187157
187158/*
187159** If pNode currently points to a match, this function returns SQLITE_OK
187160** without modifying it. Otherwise, pNode is advanced until it does point
187161** to a match or EOF is reached.
187162*/
187163static int fts5ExprNodeTest(
187164  Fts5Expr *pExpr,                /* Expression of which pNode is a part */
187165  Fts5ExprNode *pNode             /* Expression node to test */
187166){
187167  int rc = SQLITE_OK;
187168  if( pNode->bEof==0 ){
187169    switch( pNode->eType ){
187170
187171      case FTS5_STRING: {
187172        rc = fts5ExprNodeTest_STRING(pExpr, pNode);
187173        break;
187174      }
187175
187176      case FTS5_TERM: {
187177        rc = fts5ExprNodeTest_TERM(pExpr, pNode);
187178        break;
187179      }
187180
187181      case FTS5_AND: {
187182        rc = fts5ExprNodeTest_AND(pExpr, pNode);
187183        break;
187184      }
187185
187186      case FTS5_OR: {
187187        fts5ExprNodeTest_OR(pExpr, pNode);
187188        break;
187189      }
187190
187191      default: assert( pNode->eType==FTS5_NOT ); {
187192        rc = fts5ExprNodeTest_NOT(pExpr, pNode);
187193        break;
187194      }
187195    }
187196  }
187197  return rc;
187198}
187199
187200
187201/*
187202** Set node pNode, which is part of expression pExpr, to point to the first
187203** match. If there are no matches, set the Node.bEof flag to indicate EOF.
187204**
187205** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
187206** It is not an error if there are no matches.
187207*/
187208static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
187209  int rc = SQLITE_OK;
187210  pNode->bEof = 0;
187211  pNode->bNomatch = 0;
187212
187213  if( Fts5NodeIsString(pNode) ){
187214    /* Initialize all term iterators in the NEAR object. */
187215    rc = fts5ExprNearInitAll(pExpr, pNode);
187216  }else if( pNode->xNext==0 ){
187217    pNode->bEof = 1;
187218  }else{
187219    int i;
187220    int nEof = 0;
187221    for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
187222      Fts5ExprNode *pChild = pNode->apChild[i];
187223      rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
187224      assert( pChild->bEof==0 || pChild->bEof==1 );
187225      nEof += pChild->bEof;
187226    }
187227    pNode->iRowid = pNode->apChild[0]->iRowid;
187228
187229    switch( pNode->eType ){
187230      case FTS5_AND:
187231        if( nEof>0 ) fts5ExprSetEof(pNode);
187232        break;
187233
187234      case FTS5_OR:
187235        if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
187236        break;
187237
187238      default:
187239        assert( pNode->eType==FTS5_NOT );
187240        pNode->bEof = pNode->apChild[0]->bEof;
187241        break;
187242    }
187243  }
187244
187245  if( rc==SQLITE_OK ){
187246    rc = fts5ExprNodeTest(pExpr, pNode);
187247  }
187248  return rc;
187249}
187250
187251
187252/*
187253** Begin iterating through the set of documents in index pIdx matched by
187254** the MATCH expression passed as the first argument. If the "bDesc"
187255** parameter is passed a non-zero value, iteration is in descending rowid
187256** order. Or, if it is zero, in ascending order.
187257**
187258** If iterating in ascending rowid order (bDesc==0), the first document
187259** visited is that with the smallest rowid that is larger than or equal
187260** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
187261** then the first document visited must have a rowid smaller than or
187262** equal to iFirst.
187263**
187264** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
187265** is not considered an error if the query does not match any documents.
187266*/
187267static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
187268  Fts5ExprNode *pRoot = p->pRoot;
187269  int rc;                         /* Return code */
187270
187271  p->pIndex = pIdx;
187272  p->bDesc = bDesc;
187273  rc = fts5ExprNodeFirst(p, pRoot);
187274
187275  /* If not at EOF but the current rowid occurs earlier than iFirst in
187276  ** the iteration order, move to document iFirst or later. */
187277  if( rc==SQLITE_OK
187278   && 0==pRoot->bEof
187279   && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
187280  ){
187281    rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
187282  }
187283
187284  /* If the iterator is not at a real match, skip forward until it is. */
187285  while( pRoot->bNomatch ){
187286    assert( pRoot->bEof==0 && rc==SQLITE_OK );
187287    rc = fts5ExprNodeNext(p, pRoot, 0, 0);
187288  }
187289  return rc;
187290}
187291
187292/*
187293** Move to the next document
187294**
187295** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
187296** is not considered an error if the query does not match any documents.
187297*/
187298static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
187299  int rc;
187300  Fts5ExprNode *pRoot = p->pRoot;
187301  assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
187302  do {
187303    rc = fts5ExprNodeNext(p, pRoot, 0, 0);
187304    assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
187305  }while( pRoot->bNomatch );
187306  if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
187307    pRoot->bEof = 1;
187308  }
187309  return rc;
187310}
187311
187312static int sqlite3Fts5ExprEof(Fts5Expr *p){
187313  return p->pRoot->bEof;
187314}
187315
187316static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
187317  return p->pRoot->iRowid;
187318}
187319
187320static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
187321  int rc = SQLITE_OK;
187322  *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
187323  return rc;
187324}
187325
187326/*
187327** Free the phrase object passed as the only argument.
187328*/
187329static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
187330  if( pPhrase ){
187331    int i;
187332    for(i=0; i<pPhrase->nTerm; i++){
187333      Fts5ExprTerm *pSyn;
187334      Fts5ExprTerm *pNext;
187335      Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
187336      sqlite3_free(pTerm->zTerm);
187337      sqlite3Fts5IterClose(pTerm->pIter);
187338      for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
187339        pNext = pSyn->pSynonym;
187340        sqlite3Fts5IterClose(pSyn->pIter);
187341        fts5BufferFree((Fts5Buffer*)&pSyn[1]);
187342        sqlite3_free(pSyn);
187343      }
187344    }
187345    if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
187346    sqlite3_free(pPhrase);
187347  }
187348}
187349
187350/*
187351** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
187352** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
187353** appended to it and the results returned.
187354**
187355** If an OOM error occurs, both the pNear and pPhrase objects are freed and
187356** NULL returned.
187357*/
187358static Fts5ExprNearset *sqlite3Fts5ParseNearset(
187359  Fts5Parse *pParse,              /* Parse context */
187360  Fts5ExprNearset *pNear,         /* Existing nearset, or NULL */
187361  Fts5ExprPhrase *pPhrase         /* Recently parsed phrase */
187362){
187363  const int SZALLOC = 8;
187364  Fts5ExprNearset *pRet = 0;
187365
187366  if( pParse->rc==SQLITE_OK ){
187367    if( pPhrase==0 ){
187368      return pNear;
187369    }
187370    if( pNear==0 ){
187371      int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
187372      pRet = sqlite3_malloc(nByte);
187373      if( pRet==0 ){
187374        pParse->rc = SQLITE_NOMEM;
187375      }else{
187376        memset(pRet, 0, nByte);
187377      }
187378    }else if( (pNear->nPhrase % SZALLOC)==0 ){
187379      int nNew = pNear->nPhrase + SZALLOC;
187380      int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
187381
187382      pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
187383      if( pRet==0 ){
187384        pParse->rc = SQLITE_NOMEM;
187385      }
187386    }else{
187387      pRet = pNear;
187388    }
187389  }
187390
187391  if( pRet==0 ){
187392    assert( pParse->rc!=SQLITE_OK );
187393    sqlite3Fts5ParseNearsetFree(pNear);
187394    sqlite3Fts5ParsePhraseFree(pPhrase);
187395  }else{
187396    if( pRet->nPhrase>0 ){
187397      Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
187398      assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
187399      if( pPhrase->nTerm==0 ){
187400        fts5ExprPhraseFree(pPhrase);
187401        pRet->nPhrase--;
187402        pParse->nPhrase--;
187403        pPhrase = pLast;
187404      }else if( pLast->nTerm==0 ){
187405        fts5ExprPhraseFree(pLast);
187406        pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
187407        pParse->nPhrase--;
187408        pRet->nPhrase--;
187409      }
187410    }
187411    pRet->apPhrase[pRet->nPhrase++] = pPhrase;
187412  }
187413  return pRet;
187414}
187415
187416typedef struct TokenCtx TokenCtx;
187417struct TokenCtx {
187418  Fts5ExprPhrase *pPhrase;
187419  int rc;
187420};
187421
187422/*
187423** Callback for tokenizing terms used by ParseTerm().
187424*/
187425static int fts5ParseTokenize(
187426  void *pContext,                 /* Pointer to Fts5InsertCtx object */
187427  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
187428  const char *pToken,             /* Buffer containing token */
187429  int nToken,                     /* Size of token in bytes */
187430  int iUnused1,                   /* Start offset of token */
187431  int iUnused2                    /* End offset of token */
187432){
187433  int rc = SQLITE_OK;
187434  const int SZALLOC = 8;
187435  TokenCtx *pCtx = (TokenCtx*)pContext;
187436  Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
187437
187438  UNUSED_PARAM2(iUnused1, iUnused2);
187439
187440  /* If an error has already occurred, this is a no-op */
187441  if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
187442  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
187443
187444  if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
187445    Fts5ExprTerm *pSyn;
187446    int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
187447    pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
187448    if( pSyn==0 ){
187449      rc = SQLITE_NOMEM;
187450    }else{
187451      memset(pSyn, 0, nByte);
187452      pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
187453      memcpy(pSyn->zTerm, pToken, nToken);
187454      pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
187455      pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
187456    }
187457  }else{
187458    Fts5ExprTerm *pTerm;
187459    if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
187460      Fts5ExprPhrase *pNew;
187461      int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
187462
187463      pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
187464          sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
187465      );
187466      if( pNew==0 ){
187467        rc = SQLITE_NOMEM;
187468      }else{
187469        if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
187470        pCtx->pPhrase = pPhrase = pNew;
187471        pNew->nTerm = nNew - SZALLOC;
187472      }
187473    }
187474
187475    if( rc==SQLITE_OK ){
187476      pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
187477      memset(pTerm, 0, sizeof(Fts5ExprTerm));
187478      pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
187479    }
187480  }
187481
187482  pCtx->rc = rc;
187483  return rc;
187484}
187485
187486
187487/*
187488** Free the phrase object passed as the only argument.
187489*/
187490static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
187491  fts5ExprPhraseFree(pPhrase);
187492}
187493
187494/*
187495** Free the phrase object passed as the second argument.
187496*/
187497static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
187498  if( pNear ){
187499    int i;
187500    for(i=0; i<pNear->nPhrase; i++){
187501      fts5ExprPhraseFree(pNear->apPhrase[i]);
187502    }
187503    sqlite3_free(pNear->pColset);
187504    sqlite3_free(pNear);
187505  }
187506}
187507
187508static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
187509  assert( pParse->pExpr==0 );
187510  pParse->pExpr = p;
187511}
187512
187513/*
187514** This function is called by the parser to process a string token. The
187515** string may or may not be quoted. In any case it is tokenized and a
187516** phrase object consisting of all tokens returned.
187517*/
187518static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
187519  Fts5Parse *pParse,              /* Parse context */
187520  Fts5ExprPhrase *pAppend,        /* Phrase to append to */
187521  Fts5Token *pToken,              /* String to tokenize */
187522  int bPrefix                     /* True if there is a trailing "*" */
187523){
187524  Fts5Config *pConfig = pParse->pConfig;
187525  TokenCtx sCtx;                  /* Context object passed to callback */
187526  int rc;                         /* Tokenize return code */
187527  char *z = 0;
187528
187529  memset(&sCtx, 0, sizeof(TokenCtx));
187530  sCtx.pPhrase = pAppend;
187531
187532  rc = fts5ParseStringFromToken(pToken, &z);
187533  if( rc==SQLITE_OK ){
187534    int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
187535    int n;
187536    sqlite3Fts5Dequote(z);
187537    n = (int)strlen(z);
187538    rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
187539  }
187540  sqlite3_free(z);
187541  if( rc || (rc = sCtx.rc) ){
187542    pParse->rc = rc;
187543    fts5ExprPhraseFree(sCtx.pPhrase);
187544    sCtx.pPhrase = 0;
187545  }else{
187546
187547    if( pAppend==0 ){
187548      if( (pParse->nPhrase % 8)==0 ){
187549        int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
187550        Fts5ExprPhrase **apNew;
187551        apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
187552        if( apNew==0 ){
187553          pParse->rc = SQLITE_NOMEM;
187554          fts5ExprPhraseFree(sCtx.pPhrase);
187555          return 0;
187556        }
187557        pParse->apPhrase = apNew;
187558      }
187559      pParse->nPhrase++;
187560    }
187561
187562    if( sCtx.pPhrase==0 ){
187563      /* This happens when parsing a token or quoted phrase that contains
187564      ** no token characters at all. (e.g ... MATCH '""'). */
187565      sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
187566    }else if( sCtx.pPhrase->nTerm ){
187567      sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
187568    }
187569    pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
187570  }
187571
187572  return sCtx.pPhrase;
187573}
187574
187575/*
187576** Create a new FTS5 expression by cloning phrase iPhrase of the
187577** expression passed as the second argument.
187578*/
187579static int sqlite3Fts5ExprClonePhrase(
187580  Fts5Expr *pExpr,
187581  int iPhrase,
187582  Fts5Expr **ppNew
187583){
187584  int rc = SQLITE_OK;             /* Return code */
187585  Fts5ExprPhrase *pOrig;          /* The phrase extracted from pExpr */
187586  Fts5Expr *pNew = 0;             /* Expression to return via *ppNew */
187587  TokenCtx sCtx = {0,0};          /* Context object for fts5ParseTokenize */
187588
187589  pOrig = pExpr->apExprPhrase[iPhrase];
187590  pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
187591  if( rc==SQLITE_OK ){
187592    pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
187593        sizeof(Fts5ExprPhrase*));
187594  }
187595  if( rc==SQLITE_OK ){
187596    pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
187597        sizeof(Fts5ExprNode));
187598  }
187599  if( rc==SQLITE_OK ){
187600    pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
187601        sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
187602  }
187603  if( rc==SQLITE_OK ){
187604    Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
187605    if( pColsetOrig ){
187606      int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
187607      Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
187608      if( pColset ){
187609        memcpy(pColset, pColsetOrig, nByte);
187610      }
187611      pNew->pRoot->pNear->pColset = pColset;
187612    }
187613  }
187614
187615  if( pOrig->nTerm ){
187616    int i;                          /* Used to iterate through phrase terms */
187617    for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
187618      int tflags = 0;
187619      Fts5ExprTerm *p;
187620      for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
187621        const char *zTerm = p->zTerm;
187622        rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
187623            0, 0);
187624        tflags = FTS5_TOKEN_COLOCATED;
187625      }
187626      if( rc==SQLITE_OK ){
187627        sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
187628      }
187629    }
187630  }else{
187631    /* This happens when parsing a token or quoted phrase that contains
187632    ** no token characters at all. (e.g ... MATCH '""'). */
187633    sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
187634  }
187635
187636  if( rc==SQLITE_OK ){
187637    /* All the allocations succeeded. Put the expression object together. */
187638    pNew->pIndex = pExpr->pIndex;
187639    pNew->pConfig = pExpr->pConfig;
187640    pNew->nPhrase = 1;
187641    pNew->apExprPhrase[0] = sCtx.pPhrase;
187642    pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
187643    pNew->pRoot->pNear->nPhrase = 1;
187644    sCtx.pPhrase->pNode = pNew->pRoot;
187645
187646    if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
187647      pNew->pRoot->eType = FTS5_TERM;
187648      pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
187649    }else{
187650      pNew->pRoot->eType = FTS5_STRING;
187651      pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
187652    }
187653  }else{
187654    sqlite3Fts5ExprFree(pNew);
187655    fts5ExprPhraseFree(sCtx.pPhrase);
187656    pNew = 0;
187657  }
187658
187659  *ppNew = pNew;
187660  return rc;
187661}
187662
187663
187664/*
187665** Token pTok has appeared in a MATCH expression where the NEAR operator
187666** is expected. If token pTok does not contain "NEAR", store an error
187667** in the pParse object.
187668*/
187669static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
187670  if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
187671    sqlite3Fts5ParseError(
187672        pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
187673    );
187674  }
187675}
187676
187677static void sqlite3Fts5ParseSetDistance(
187678  Fts5Parse *pParse,
187679  Fts5ExprNearset *pNear,
187680  Fts5Token *p
187681){
187682  if( pNear ){
187683    int nNear = 0;
187684    int i;
187685    if( p->n ){
187686      for(i=0; i<p->n; i++){
187687        char c = (char)p->p[i];
187688        if( c<'0' || c>'9' ){
187689          sqlite3Fts5ParseError(
187690              pParse, "expected integer, got \"%.*s\"", p->n, p->p
187691              );
187692          return;
187693        }
187694        nNear = nNear * 10 + (p->p[i] - '0');
187695      }
187696    }else{
187697      nNear = FTS5_DEFAULT_NEARDIST;
187698    }
187699    pNear->nNear = nNear;
187700  }
187701}
187702
187703/*
187704** The second argument passed to this function may be NULL, or it may be
187705** an existing Fts5Colset object. This function returns a pointer to
187706** a new colset object containing the contents of (p) with new value column
187707** number iCol appended.
187708**
187709** If an OOM error occurs, store an error code in pParse and return NULL.
187710** The old colset object (if any) is not freed in this case.
187711*/
187712static Fts5Colset *fts5ParseColset(
187713  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
187714  Fts5Colset *p,                  /* Existing colset object */
187715  int iCol                        /* New column to add to colset object */
187716){
187717  int nCol = p ? p->nCol : 0;     /* Num. columns already in colset object */
187718  Fts5Colset *pNew;               /* New colset object to return */
187719
187720  assert( pParse->rc==SQLITE_OK );
187721  assert( iCol>=0 && iCol<pParse->pConfig->nCol );
187722
187723  pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
187724  if( pNew==0 ){
187725    pParse->rc = SQLITE_NOMEM;
187726  }else{
187727    int *aiCol = pNew->aiCol;
187728    int i, j;
187729    for(i=0; i<nCol; i++){
187730      if( aiCol[i]==iCol ) return pNew;
187731      if( aiCol[i]>iCol ) break;
187732    }
187733    for(j=nCol; j>i; j--){
187734      aiCol[j] = aiCol[j-1];
187735    }
187736    aiCol[i] = iCol;
187737    pNew->nCol = nCol+1;
187738
187739#ifndef NDEBUG
187740    /* Check that the array is in order and contains no duplicate entries. */
187741    for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
187742#endif
187743  }
187744
187745  return pNew;
187746}
187747
187748/*
187749** Allocate and return an Fts5Colset object specifying the inverse of
187750** the colset passed as the second argument. Free the colset passed
187751** as the second argument before returning.
187752*/
187753static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
187754  Fts5Colset *pRet;
187755  int nCol = pParse->pConfig->nCol;
187756
187757  pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
187758      sizeof(Fts5Colset) + sizeof(int)*nCol
187759  );
187760  if( pRet ){
187761    int i;
187762    int iOld = 0;
187763    for(i=0; i<nCol; i++){
187764      if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
187765        pRet->aiCol[pRet->nCol++] = i;
187766      }else{
187767        iOld++;
187768      }
187769    }
187770  }
187771
187772  sqlite3_free(p);
187773  return pRet;
187774}
187775
187776static Fts5Colset *sqlite3Fts5ParseColset(
187777  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
187778  Fts5Colset *pColset,            /* Existing colset object */
187779  Fts5Token *p
187780){
187781  Fts5Colset *pRet = 0;
187782  int iCol;
187783  char *z;                        /* Dequoted copy of token p */
187784
187785  z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
187786  if( pParse->rc==SQLITE_OK ){
187787    Fts5Config *pConfig = pParse->pConfig;
187788    sqlite3Fts5Dequote(z);
187789    for(iCol=0; iCol<pConfig->nCol; iCol++){
187790      if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
187791    }
187792    if( iCol==pConfig->nCol ){
187793      sqlite3Fts5ParseError(pParse, "no such column: %s", z);
187794    }else{
187795      pRet = fts5ParseColset(pParse, pColset, iCol);
187796    }
187797    sqlite3_free(z);
187798  }
187799
187800  if( pRet==0 ){
187801    assert( pParse->rc!=SQLITE_OK );
187802    sqlite3_free(pColset);
187803  }
187804
187805  return pRet;
187806}
187807
187808static void sqlite3Fts5ParseSetColset(
187809  Fts5Parse *pParse,
187810  Fts5ExprNearset *pNear,
187811  Fts5Colset *pColset
187812){
187813  if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
187814    pParse->rc = SQLITE_ERROR;
187815    pParse->zErr = sqlite3_mprintf(
187816      "fts5: column queries are not supported (detail=none)"
187817    );
187818    sqlite3_free(pColset);
187819    return;
187820  }
187821
187822  if( pNear ){
187823    pNear->pColset = pColset;
187824  }else{
187825    sqlite3_free(pColset);
187826  }
187827}
187828
187829static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
187830  switch( pNode->eType ){
187831    case FTS5_STRING: {
187832      Fts5ExprNearset *pNear = pNode->pNear;
187833      if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
187834       && pNear->apPhrase[0]->aTerm[0].pSynonym==0
187835      ){
187836        pNode->eType = FTS5_TERM;
187837        pNode->xNext = fts5ExprNodeNext_TERM;
187838      }else{
187839        pNode->xNext = fts5ExprNodeNext_STRING;
187840      }
187841      break;
187842    };
187843
187844    case FTS5_OR: {
187845      pNode->xNext = fts5ExprNodeNext_OR;
187846      break;
187847    };
187848
187849    case FTS5_AND: {
187850      pNode->xNext = fts5ExprNodeNext_AND;
187851      break;
187852    };
187853
187854    default: assert( pNode->eType==FTS5_NOT ); {
187855      pNode->xNext = fts5ExprNodeNext_NOT;
187856      break;
187857    };
187858  }
187859}
187860
187861static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
187862  if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
187863    int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
187864    memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
187865    p->nChild += pSub->nChild;
187866    sqlite3_free(pSub);
187867  }else{
187868    p->apChild[p->nChild++] = pSub;
187869  }
187870}
187871
187872/*
187873** Allocate and return a new expression object. If anything goes wrong (i.e.
187874** OOM error), leave an error code in pParse and return NULL.
187875*/
187876static Fts5ExprNode *sqlite3Fts5ParseNode(
187877  Fts5Parse *pParse,              /* Parse context */
187878  int eType,                      /* FTS5_STRING, AND, OR or NOT */
187879  Fts5ExprNode *pLeft,            /* Left hand child expression */
187880  Fts5ExprNode *pRight,           /* Right hand child expression */
187881  Fts5ExprNearset *pNear          /* For STRING expressions, the near cluster */
187882){
187883  Fts5ExprNode *pRet = 0;
187884
187885  if( pParse->rc==SQLITE_OK ){
187886    int nChild = 0;               /* Number of children of returned node */
187887    int nByte;                    /* Bytes of space to allocate for this node */
187888
187889    assert( (eType!=FTS5_STRING && !pNear)
187890         || (eType==FTS5_STRING && !pLeft && !pRight)
187891    );
187892    if( eType==FTS5_STRING && pNear==0 ) return 0;
187893    if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
187894    if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
187895
187896    if( eType==FTS5_NOT ){
187897      nChild = 2;
187898    }else if( eType==FTS5_AND || eType==FTS5_OR ){
187899      nChild = 2;
187900      if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
187901      if( pRight->eType==eType ) nChild += pRight->nChild-1;
187902    }
187903
187904    nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
187905    pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
187906
187907    if( pRet ){
187908      pRet->eType = eType;
187909      pRet->pNear = pNear;
187910      fts5ExprAssignXNext(pRet);
187911      if( eType==FTS5_STRING ){
187912        int iPhrase;
187913        for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
187914          pNear->apPhrase[iPhrase]->pNode = pRet;
187915          if( pNear->apPhrase[iPhrase]->nTerm==0 ){
187916            pRet->xNext = 0;
187917            pRet->eType = FTS5_EOF;
187918          }
187919        }
187920
187921        if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL
187922         && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1)
187923        ){
187924          assert( pParse->rc==SQLITE_OK );
187925          pParse->rc = SQLITE_ERROR;
187926          assert( pParse->zErr==0 );
187927          pParse->zErr = sqlite3_mprintf(
187928              "fts5: %s queries are not supported (detail!=full)",
187929              pNear->nPhrase==1 ? "phrase": "NEAR"
187930          );
187931          sqlite3_free(pRet);
187932          pRet = 0;
187933        }
187934
187935      }else{
187936        fts5ExprAddChildren(pRet, pLeft);
187937        fts5ExprAddChildren(pRet, pRight);
187938      }
187939    }
187940  }
187941
187942  if( pRet==0 ){
187943    assert( pParse->rc!=SQLITE_OK );
187944    sqlite3Fts5ParseNodeFree(pLeft);
187945    sqlite3Fts5ParseNodeFree(pRight);
187946    sqlite3Fts5ParseNearsetFree(pNear);
187947  }
187948  return pRet;
187949}
187950
187951static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
187952  Fts5Parse *pParse,              /* Parse context */
187953  Fts5ExprNode *pLeft,            /* Left hand child expression */
187954  Fts5ExprNode *pRight            /* Right hand child expression */
187955){
187956  Fts5ExprNode *pRet = 0;
187957  Fts5ExprNode *pPrev;
187958
187959  if( pParse->rc ){
187960    sqlite3Fts5ParseNodeFree(pLeft);
187961    sqlite3Fts5ParseNodeFree(pRight);
187962  }else{
187963
187964    assert( pLeft->eType==FTS5_STRING
187965        || pLeft->eType==FTS5_TERM
187966        || pLeft->eType==FTS5_EOF
187967        || pLeft->eType==FTS5_AND
187968    );
187969    assert( pRight->eType==FTS5_STRING
187970        || pRight->eType==FTS5_TERM
187971        || pRight->eType==FTS5_EOF
187972    );
187973
187974    if( pLeft->eType==FTS5_AND ){
187975      pPrev = pLeft->apChild[pLeft->nChild-1];
187976    }else{
187977      pPrev = pLeft;
187978    }
187979    assert( pPrev->eType==FTS5_STRING
187980        || pPrev->eType==FTS5_TERM
187981        || pPrev->eType==FTS5_EOF
187982        );
187983
187984    if( pRight->eType==FTS5_EOF ){
187985      assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
187986      sqlite3Fts5ParseNodeFree(pRight);
187987      pRet = pLeft;
187988      pParse->nPhrase--;
187989    }
187990    else if( pPrev->eType==FTS5_EOF ){
187991      Fts5ExprPhrase **ap;
187992
187993      if( pPrev==pLeft ){
187994        pRet = pRight;
187995      }else{
187996        pLeft->apChild[pLeft->nChild-1] = pRight;
187997        pRet = pLeft;
187998      }
187999
188000      ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
188001      assert( ap[0]==pPrev->pNear->apPhrase[0] );
188002      memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
188003      pParse->nPhrase--;
188004
188005      sqlite3Fts5ParseNodeFree(pPrev);
188006    }
188007    else{
188008      pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
188009    }
188010  }
188011
188012  return pRet;
188013}
188014
188015static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
188016  int nByte = 0;
188017  Fts5ExprTerm *p;
188018  char *zQuoted;
188019
188020  /* Determine the maximum amount of space required. */
188021  for(p=pTerm; p; p=p->pSynonym){
188022    nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
188023  }
188024  zQuoted = sqlite3_malloc(nByte);
188025
188026  if( zQuoted ){
188027    int i = 0;
188028    for(p=pTerm; p; p=p->pSynonym){
188029      char *zIn = p->zTerm;
188030      zQuoted[i++] = '"';
188031      while( *zIn ){
188032        if( *zIn=='"' ) zQuoted[i++] = '"';
188033        zQuoted[i++] = *zIn++;
188034      }
188035      zQuoted[i++] = '"';
188036      if( p->pSynonym ) zQuoted[i++] = '|';
188037    }
188038    if( pTerm->bPrefix ){
188039      zQuoted[i++] = ' ';
188040      zQuoted[i++] = '*';
188041    }
188042    zQuoted[i++] = '\0';
188043  }
188044  return zQuoted;
188045}
188046
188047static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
188048  char *zNew;
188049  va_list ap;
188050  va_start(ap, zFmt);
188051  zNew = sqlite3_vmprintf(zFmt, ap);
188052  va_end(ap);
188053  if( zApp && zNew ){
188054    char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
188055    sqlite3_free(zNew);
188056    zNew = zNew2;
188057  }
188058  sqlite3_free(zApp);
188059  return zNew;
188060}
188061
188062/*
188063** Compose a tcl-readable representation of expression pExpr. Return a
188064** pointer to a buffer containing that representation. It is the
188065** responsibility of the caller to at some point free the buffer using
188066** sqlite3_free().
188067*/
188068static char *fts5ExprPrintTcl(
188069  Fts5Config *pConfig,
188070  const char *zNearsetCmd,
188071  Fts5ExprNode *pExpr
188072){
188073  char *zRet = 0;
188074  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
188075    Fts5ExprNearset *pNear = pExpr->pNear;
188076    int i;
188077    int iTerm;
188078
188079    zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
188080    if( zRet==0 ) return 0;
188081    if( pNear->pColset ){
188082      int *aiCol = pNear->pColset->aiCol;
188083      int nCol = pNear->pColset->nCol;
188084      if( nCol==1 ){
188085        zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
188086      }else{
188087        zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
188088        for(i=1; i<pNear->pColset->nCol; i++){
188089          zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
188090        }
188091        zRet = fts5PrintfAppend(zRet, "} ");
188092      }
188093      if( zRet==0 ) return 0;
188094    }
188095
188096    if( pNear->nPhrase>1 ){
188097      zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
188098      if( zRet==0 ) return 0;
188099    }
188100
188101    zRet = fts5PrintfAppend(zRet, "--");
188102    if( zRet==0 ) return 0;
188103
188104    for(i=0; i<pNear->nPhrase; i++){
188105      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
188106
188107      zRet = fts5PrintfAppend(zRet, " {");
188108      for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
188109        char *zTerm = pPhrase->aTerm[iTerm].zTerm;
188110        zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
188111        if( pPhrase->aTerm[iTerm].bPrefix ){
188112          zRet = fts5PrintfAppend(zRet, "*");
188113        }
188114      }
188115
188116      if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
188117      if( zRet==0 ) return 0;
188118    }
188119
188120  }else{
188121    char const *zOp = 0;
188122    int i;
188123    switch( pExpr->eType ){
188124      case FTS5_AND: zOp = "AND"; break;
188125      case FTS5_NOT: zOp = "NOT"; break;
188126      default:
188127        assert( pExpr->eType==FTS5_OR );
188128        zOp = "OR";
188129        break;
188130    }
188131
188132    zRet = sqlite3_mprintf("%s", zOp);
188133    for(i=0; zRet && i<pExpr->nChild; i++){
188134      char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
188135      if( !z ){
188136        sqlite3_free(zRet);
188137        zRet = 0;
188138      }else{
188139        zRet = fts5PrintfAppend(zRet, " [%z]", z);
188140      }
188141    }
188142  }
188143
188144  return zRet;
188145}
188146
188147static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
188148  char *zRet = 0;
188149  if( pExpr->eType==0 ){
188150    return sqlite3_mprintf("\"\"");
188151  }else
188152  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
188153    Fts5ExprNearset *pNear = pExpr->pNear;
188154    int i;
188155    int iTerm;
188156
188157    if( pNear->pColset ){
188158      int iCol = pNear->pColset->aiCol[0];
188159      zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
188160      if( zRet==0 ) return 0;
188161    }
188162
188163    if( pNear->nPhrase>1 ){
188164      zRet = fts5PrintfAppend(zRet, "NEAR(");
188165      if( zRet==0 ) return 0;
188166    }
188167
188168    for(i=0; i<pNear->nPhrase; i++){
188169      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
188170      if( i!=0 ){
188171        zRet = fts5PrintfAppend(zRet, " ");
188172        if( zRet==0 ) return 0;
188173      }
188174      for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
188175        char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
188176        if( zTerm ){
188177          zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
188178          sqlite3_free(zTerm);
188179        }
188180        if( zTerm==0 || zRet==0 ){
188181          sqlite3_free(zRet);
188182          return 0;
188183        }
188184      }
188185    }
188186
188187    if( pNear->nPhrase>1 ){
188188      zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
188189      if( zRet==0 ) return 0;
188190    }
188191
188192  }else{
188193    char const *zOp = 0;
188194    int i;
188195
188196    switch( pExpr->eType ){
188197      case FTS5_AND: zOp = " AND "; break;
188198      case FTS5_NOT: zOp = " NOT "; break;
188199      default:
188200        assert( pExpr->eType==FTS5_OR );
188201        zOp = " OR ";
188202        break;
188203    }
188204
188205    for(i=0; i<pExpr->nChild; i++){
188206      char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
188207      if( z==0 ){
188208        sqlite3_free(zRet);
188209        zRet = 0;
188210      }else{
188211        int e = pExpr->apChild[i]->eType;
188212        int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
188213        zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
188214            (i==0 ? "" : zOp),
188215            (b?"(":""), z, (b?")":"")
188216        );
188217      }
188218      if( zRet==0 ) break;
188219    }
188220  }
188221
188222  return zRet;
188223}
188224
188225/*
188226** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
188227** and fts5_expr_tcl() (bTcl!=0).
188228*/
188229static void fts5ExprFunction(
188230  sqlite3_context *pCtx,          /* Function call context */
188231  int nArg,                       /* Number of args */
188232  sqlite3_value **apVal,          /* Function arguments */
188233  int bTcl
188234){
188235  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
188236  sqlite3 *db = sqlite3_context_db_handle(pCtx);
188237  const char *zExpr = 0;
188238  char *zErr = 0;
188239  Fts5Expr *pExpr = 0;
188240  int rc;
188241  int i;
188242
188243  const char **azConfig;          /* Array of arguments for Fts5Config */
188244  const char *zNearsetCmd = "nearset";
188245  int nConfig;                    /* Size of azConfig[] */
188246  Fts5Config *pConfig = 0;
188247  int iArg = 1;
188248
188249  if( nArg<1 ){
188250    zErr = sqlite3_mprintf("wrong number of arguments to function %s",
188251        bTcl ? "fts5_expr_tcl" : "fts5_expr"
188252    );
188253    sqlite3_result_error(pCtx, zErr, -1);
188254    sqlite3_free(zErr);
188255    return;
188256  }
188257
188258  if( bTcl && nArg>1 ){
188259    zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
188260    iArg = 2;
188261  }
188262
188263  nConfig = 3 + (nArg-iArg);
188264  azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
188265  if( azConfig==0 ){
188266    sqlite3_result_error_nomem(pCtx);
188267    return;
188268  }
188269  azConfig[0] = 0;
188270  azConfig[1] = "main";
188271  azConfig[2] = "tbl";
188272  for(i=3; iArg<nArg; iArg++){
188273    azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
188274  }
188275
188276  zExpr = (const char*)sqlite3_value_text(apVal[0]);
188277
188278  rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
188279  if( rc==SQLITE_OK ){
188280    rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pExpr, &zErr);
188281  }
188282  if( rc==SQLITE_OK ){
188283    char *zText;
188284    if( pExpr->pRoot->xNext==0 ){
188285      zText = sqlite3_mprintf("");
188286    }else if( bTcl ){
188287      zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
188288    }else{
188289      zText = fts5ExprPrint(pConfig, pExpr->pRoot);
188290    }
188291    if( zText==0 ){
188292      rc = SQLITE_NOMEM;
188293    }else{
188294      sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
188295      sqlite3_free(zText);
188296    }
188297  }
188298
188299  if( rc!=SQLITE_OK ){
188300    if( zErr ){
188301      sqlite3_result_error(pCtx, zErr, -1);
188302      sqlite3_free(zErr);
188303    }else{
188304      sqlite3_result_error_code(pCtx, rc);
188305    }
188306  }
188307  sqlite3_free((void *)azConfig);
188308  sqlite3Fts5ConfigFree(pConfig);
188309  sqlite3Fts5ExprFree(pExpr);
188310}
188311
188312static void fts5ExprFunctionHr(
188313  sqlite3_context *pCtx,          /* Function call context */
188314  int nArg,                       /* Number of args */
188315  sqlite3_value **apVal           /* Function arguments */
188316){
188317  fts5ExprFunction(pCtx, nArg, apVal, 0);
188318}
188319static void fts5ExprFunctionTcl(
188320  sqlite3_context *pCtx,          /* Function call context */
188321  int nArg,                       /* Number of args */
188322  sqlite3_value **apVal           /* Function arguments */
188323){
188324  fts5ExprFunction(pCtx, nArg, apVal, 1);
188325}
188326
188327/*
188328** The implementation of an SQLite user-defined-function that accepts a
188329** single integer as an argument. If the integer is an alpha-numeric
188330** unicode code point, 1 is returned. Otherwise 0.
188331*/
188332static void fts5ExprIsAlnum(
188333  sqlite3_context *pCtx,          /* Function call context */
188334  int nArg,                       /* Number of args */
188335  sqlite3_value **apVal           /* Function arguments */
188336){
188337  int iCode;
188338  if( nArg!=1 ){
188339    sqlite3_result_error(pCtx,
188340        "wrong number of arguments to function fts5_isalnum", -1
188341    );
188342    return;
188343  }
188344  iCode = sqlite3_value_int(apVal[0]);
188345  sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
188346}
188347
188348static void fts5ExprFold(
188349  sqlite3_context *pCtx,          /* Function call context */
188350  int nArg,                       /* Number of args */
188351  sqlite3_value **apVal           /* Function arguments */
188352){
188353  if( nArg!=1 && nArg!=2 ){
188354    sqlite3_result_error(pCtx,
188355        "wrong number of arguments to function fts5_fold", -1
188356    );
188357  }else{
188358    int iCode;
188359    int bRemoveDiacritics = 0;
188360    iCode = sqlite3_value_int(apVal[0]);
188361    if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
188362    sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
188363  }
188364}
188365
188366/*
188367** This is called during initialization to register the fts5_expr() scalar
188368** UDF with the SQLite handle passed as the only argument.
188369*/
188370static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
188371  struct Fts5ExprFunc {
188372    const char *z;
188373    void (*x)(sqlite3_context*,int,sqlite3_value**);
188374  } aFunc[] = {
188375    { "fts5_expr",     fts5ExprFunctionHr },
188376    { "fts5_expr_tcl", fts5ExprFunctionTcl },
188377    { "fts5_isalnum",  fts5ExprIsAlnum },
188378    { "fts5_fold",     fts5ExprFold },
188379  };
188380  int i;
188381  int rc = SQLITE_OK;
188382  void *pCtx = (void*)pGlobal;
188383
188384  for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
188385    struct Fts5ExprFunc *p = &aFunc[i];
188386    rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
188387  }
188388
188389  /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
188390#ifndef NDEBUG
188391  (void)sqlite3Fts5ParserTrace;
188392#endif
188393
188394  return rc;
188395}
188396
188397/*
188398** Return the number of phrases in expression pExpr.
188399*/
188400static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
188401  return (pExpr ? pExpr->nPhrase : 0);
188402}
188403
188404/*
188405** Return the number of terms in the iPhrase'th phrase in pExpr.
188406*/
188407static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
188408  if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
188409  return pExpr->apExprPhrase[iPhrase]->nTerm;
188410}
188411
188412/*
188413** This function is used to access the current position list for phrase
188414** iPhrase.
188415*/
188416static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
188417  int nRet;
188418  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
188419  Fts5ExprNode *pNode = pPhrase->pNode;
188420  if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
188421    *pa = pPhrase->poslist.p;
188422    nRet = pPhrase->poslist.n;
188423  }else{
188424    *pa = 0;
188425    nRet = 0;
188426  }
188427  return nRet;
188428}
188429
188430struct Fts5PoslistPopulator {
188431  Fts5PoslistWriter writer;
188432  int bOk;                        /* True if ok to populate */
188433  int bMiss;
188434};
188435
188436static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
188437  Fts5PoslistPopulator *pRet;
188438  pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
188439  if( pRet ){
188440    int i;
188441    memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
188442    for(i=0; i<pExpr->nPhrase; i++){
188443      Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
188444      Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
188445      assert( pExpr->apExprPhrase[i]->nTerm==1 );
188446      if( bLive &&
188447          (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
188448      ){
188449        pRet[i].bMiss = 1;
188450      }else{
188451        pBuf->n = 0;
188452      }
188453    }
188454  }
188455  return pRet;
188456}
188457
188458struct Fts5ExprCtx {
188459  Fts5Expr *pExpr;
188460  Fts5PoslistPopulator *aPopulator;
188461  i64 iOff;
188462};
188463typedef struct Fts5ExprCtx Fts5ExprCtx;
188464
188465/*
188466** TODO: Make this more efficient!
188467*/
188468static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
188469  int i;
188470  for(i=0; i<pColset->nCol; i++){
188471    if( pColset->aiCol[i]==iCol ) return 1;
188472  }
188473  return 0;
188474}
188475
188476static int fts5ExprPopulatePoslistsCb(
188477  void *pCtx,                /* Copy of 2nd argument to xTokenize() */
188478  int tflags,                /* Mask of FTS5_TOKEN_* flags */
188479  const char *pToken,        /* Pointer to buffer containing token */
188480  int nToken,                /* Size of token in bytes */
188481  int iUnused1,              /* Byte offset of token within input text */
188482  int iUnused2               /* Byte offset of end of token within input text */
188483){
188484  Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
188485  Fts5Expr *pExpr = p->pExpr;
188486  int i;
188487
188488  UNUSED_PARAM2(iUnused1, iUnused2);
188489
188490  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
188491  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
188492  for(i=0; i<pExpr->nPhrase; i++){
188493    Fts5ExprTerm *pTerm;
188494    if( p->aPopulator[i].bOk==0 ) continue;
188495    for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
188496      int nTerm = (int)strlen(pTerm->zTerm);
188497      if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
188498       && memcmp(pTerm->zTerm, pToken, nTerm)==0
188499      ){
188500        int rc = sqlite3Fts5PoslistWriterAppend(
188501            &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
188502        );
188503        if( rc ) return rc;
188504        break;
188505      }
188506    }
188507  }
188508  return SQLITE_OK;
188509}
188510
188511static int sqlite3Fts5ExprPopulatePoslists(
188512  Fts5Config *pConfig,
188513  Fts5Expr *pExpr,
188514  Fts5PoslistPopulator *aPopulator,
188515  int iCol,
188516  const char *z, int n
188517){
188518  int i;
188519  Fts5ExprCtx sCtx;
188520  sCtx.pExpr = pExpr;
188521  sCtx.aPopulator = aPopulator;
188522  sCtx.iOff = (((i64)iCol) << 32) - 1;
188523
188524  for(i=0; i<pExpr->nPhrase; i++){
188525    Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
188526    Fts5Colset *pColset = pNode->pNear->pColset;
188527    if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
188528     || aPopulator[i].bMiss
188529    ){
188530      aPopulator[i].bOk = 0;
188531    }else{
188532      aPopulator[i].bOk = 1;
188533    }
188534  }
188535
188536  return sqlite3Fts5Tokenize(pConfig,
188537      FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
188538  );
188539}
188540
188541static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
188542  if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
188543    pNode->pNear->apPhrase[0]->poslist.n = 0;
188544  }else{
188545    int i;
188546    for(i=0; i<pNode->nChild; i++){
188547      fts5ExprClearPoslists(pNode->apChild[i]);
188548    }
188549  }
188550}
188551
188552static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
188553  pNode->iRowid = iRowid;
188554  pNode->bEof = 0;
188555  switch( pNode->eType ){
188556    case FTS5_TERM:
188557    case FTS5_STRING:
188558      return (pNode->pNear->apPhrase[0]->poslist.n>0);
188559
188560    case FTS5_AND: {
188561      int i;
188562      for(i=0; i<pNode->nChild; i++){
188563        if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
188564          fts5ExprClearPoslists(pNode);
188565          return 0;
188566        }
188567      }
188568      break;
188569    }
188570
188571    case FTS5_OR: {
188572      int i;
188573      int bRet = 0;
188574      for(i=0; i<pNode->nChild; i++){
188575        if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
188576          bRet = 1;
188577        }
188578      }
188579      return bRet;
188580    }
188581
188582    default: {
188583      assert( pNode->eType==FTS5_NOT );
188584      if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
188585          || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
188586        ){
188587        fts5ExprClearPoslists(pNode);
188588        return 0;
188589      }
188590      break;
188591    }
188592  }
188593  return 1;
188594}
188595
188596static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
188597  fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
188598}
188599
188600/*
188601** This function is only called for detail=columns tables.
188602*/
188603static int sqlite3Fts5ExprPhraseCollist(
188604  Fts5Expr *pExpr,
188605  int iPhrase,
188606  const u8 **ppCollist,
188607  int *pnCollist
188608){
188609  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
188610  Fts5ExprNode *pNode = pPhrase->pNode;
188611  int rc = SQLITE_OK;
188612
188613  assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
188614  assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
188615
188616  if( pNode->bEof==0
188617   && pNode->iRowid==pExpr->pRoot->iRowid
188618   && pPhrase->poslist.n>0
188619  ){
188620    Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
188621    if( pTerm->pSynonym ){
188622      Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
188623      rc = fts5ExprSynonymList(
188624          pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
188625      );
188626    }else{
188627      *ppCollist = pPhrase->aTerm[0].pIter->pData;
188628      *pnCollist = pPhrase->aTerm[0].pIter->nData;
188629    }
188630  }else{
188631    *ppCollist = 0;
188632    *pnCollist = 0;
188633  }
188634
188635  return rc;
188636}
188637
188638
188639/*
188640** 2014 August 11
188641**
188642** The author disclaims copyright to this source code.  In place of
188643** a legal notice, here is a blessing:
188644**
188645**    May you do good and not evil.
188646**    May you find forgiveness for yourself and forgive others.
188647**    May you share freely, never taking more than you give.
188648**
188649******************************************************************************
188650**
188651*/
188652
188653
188654
188655/* #include "fts5Int.h" */
188656
188657typedef struct Fts5HashEntry Fts5HashEntry;
188658
188659/*
188660** This file contains the implementation of an in-memory hash table used
188661** to accumuluate "term -> doclist" content before it is flused to a level-0
188662** segment.
188663*/
188664
188665
188666struct Fts5Hash {
188667  int eDetail;                    /* Copy of Fts5Config.eDetail */
188668  int *pnByte;                    /* Pointer to bytes counter */
188669  int nEntry;                     /* Number of entries currently in hash */
188670  int nSlot;                      /* Size of aSlot[] array */
188671  Fts5HashEntry *pScan;           /* Current ordered scan item */
188672  Fts5HashEntry **aSlot;          /* Array of hash slots */
188673};
188674
188675/*
188676** Each entry in the hash table is represented by an object of the
188677** following type. Each object, its key (zKey[]) and its current data
188678** are stored in a single memory allocation. The position list data
188679** immediately follows the key data in memory.
188680**
188681** The data that follows the key is in a similar, but not identical format
188682** to the doclist data stored in the database. It is:
188683**
188684**   * Rowid, as a varint
188685**   * Position list, without 0x00 terminator.
188686**   * Size of previous position list and rowid, as a 4 byte
188687**     big-endian integer.
188688**
188689** iRowidOff:
188690**   Offset of last rowid written to data area. Relative to first byte of
188691**   structure.
188692**
188693** nData:
188694**   Bytes of data written since iRowidOff.
188695*/
188696struct Fts5HashEntry {
188697  Fts5HashEntry *pHashNext;       /* Next hash entry with same hash-key */
188698  Fts5HashEntry *pScanNext;       /* Next entry in sorted order */
188699
188700  int nAlloc;                     /* Total size of allocation */
188701  int iSzPoslist;                 /* Offset of space for 4-byte poslist size */
188702  int nData;                      /* Total bytes of data (incl. structure) */
188703  int nKey;                       /* Length of zKey[] in bytes */
188704  u8 bDel;                        /* Set delete-flag @ iSzPoslist */
188705  u8 bContent;                    /* Set content-flag (detail=none mode) */
188706  i16 iCol;                       /* Column of last value written */
188707  int iPos;                       /* Position of last value written */
188708  i64 iRowid;                     /* Rowid of last value written */
188709  char zKey[8];                   /* Nul-terminated entry key */
188710};
188711
188712/*
188713** Size of Fts5HashEntry without the zKey[] array.
188714*/
188715#define FTS5_HASHENTRYSIZE (sizeof(Fts5HashEntry)-8)
188716
188717
188718
188719/*
188720** Allocate a new hash table.
188721*/
188722static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
188723  int rc = SQLITE_OK;
188724  Fts5Hash *pNew;
188725
188726  *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
188727  if( pNew==0 ){
188728    rc = SQLITE_NOMEM;
188729  }else{
188730    int nByte;
188731    memset(pNew, 0, sizeof(Fts5Hash));
188732    pNew->pnByte = pnByte;
188733    pNew->eDetail = pConfig->eDetail;
188734
188735    pNew->nSlot = 1024;
188736    nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
188737    pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
188738    if( pNew->aSlot==0 ){
188739      sqlite3_free(pNew);
188740      *ppNew = 0;
188741      rc = SQLITE_NOMEM;
188742    }else{
188743      memset(pNew->aSlot, 0, nByte);
188744    }
188745  }
188746  return rc;
188747}
188748
188749/*
188750** Free a hash table object.
188751*/
188752static void sqlite3Fts5HashFree(Fts5Hash *pHash){
188753  if( pHash ){
188754    sqlite3Fts5HashClear(pHash);
188755    sqlite3_free(pHash->aSlot);
188756    sqlite3_free(pHash);
188757  }
188758}
188759
188760/*
188761** Empty (but do not delete) a hash table.
188762*/
188763static void sqlite3Fts5HashClear(Fts5Hash *pHash){
188764  int i;
188765  for(i=0; i<pHash->nSlot; i++){
188766    Fts5HashEntry *pNext;
188767    Fts5HashEntry *pSlot;
188768    for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
188769      pNext = pSlot->pHashNext;
188770      sqlite3_free(pSlot);
188771    }
188772  }
188773  memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
188774  pHash->nEntry = 0;
188775}
188776
188777static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
188778  int i;
188779  unsigned int h = 13;
188780  for(i=n-1; i>=0; i--){
188781    h = (h << 3) ^ h ^ p[i];
188782  }
188783  return (h % nSlot);
188784}
188785
188786static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
188787  int i;
188788  unsigned int h = 13;
188789  for(i=n-1; i>=0; i--){
188790    h = (h << 3) ^ h ^ p[i];
188791  }
188792  h = (h << 3) ^ h ^ b;
188793  return (h % nSlot);
188794}
188795
188796/*
188797** Resize the hash table by doubling the number of slots.
188798*/
188799static int fts5HashResize(Fts5Hash *pHash){
188800  int nNew = pHash->nSlot*2;
188801  int i;
188802  Fts5HashEntry **apNew;
188803  Fts5HashEntry **apOld = pHash->aSlot;
188804
188805  apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
188806  if( !apNew ) return SQLITE_NOMEM;
188807  memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
188808
188809  for(i=0; i<pHash->nSlot; i++){
188810    while( apOld[i] ){
188811      int iHash;
188812      Fts5HashEntry *p = apOld[i];
188813      apOld[i] = p->pHashNext;
188814      iHash = fts5HashKey(nNew, (u8*)p->zKey, (int)strlen(p->zKey));
188815      p->pHashNext = apNew[iHash];
188816      apNew[iHash] = p;
188817    }
188818  }
188819
188820  sqlite3_free(apOld);
188821  pHash->nSlot = nNew;
188822  pHash->aSlot = apNew;
188823  return SQLITE_OK;
188824}
188825
188826static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
188827  if( p->iSzPoslist ){
188828    u8 *pPtr = (u8*)p;
188829    if( pHash->eDetail==FTS5_DETAIL_NONE ){
188830      assert( p->nData==p->iSzPoslist );
188831      if( p->bDel ){
188832        pPtr[p->nData++] = 0x00;
188833        if( p->bContent ){
188834          pPtr[p->nData++] = 0x00;
188835        }
188836      }
188837    }else{
188838      int nSz = (p->nData - p->iSzPoslist - 1);       /* Size in bytes */
188839      int nPos = nSz*2 + p->bDel;                     /* Value of nPos field */
188840
188841      assert( p->bDel==0 || p->bDel==1 );
188842      if( nPos<=127 ){
188843        pPtr[p->iSzPoslist] = (u8)nPos;
188844      }else{
188845        int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
188846        memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
188847        sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
188848        p->nData += (nByte-1);
188849      }
188850    }
188851
188852    p->iSzPoslist = 0;
188853    p->bDel = 0;
188854    p->bContent = 0;
188855  }
188856}
188857
188858/*
188859** Add an entry to the in-memory hash table. The key is the concatenation
188860** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
188861**
188862**     (bByte || pToken) -> (iRowid,iCol,iPos)
188863**
188864** Or, if iCol is negative, then the value is a delete marker.
188865*/
188866static int sqlite3Fts5HashWrite(
188867  Fts5Hash *pHash,
188868  i64 iRowid,                     /* Rowid for this entry */
188869  int iCol,                       /* Column token appears in (-ve -> delete) */
188870  int iPos,                       /* Position of token within column */
188871  char bByte,                     /* First byte of token */
188872  const char *pToken, int nToken  /* Token to add or remove to or from index */
188873){
188874  unsigned int iHash;
188875  Fts5HashEntry *p;
188876  u8 *pPtr;
188877  int nIncr = 0;                  /* Amount to increment (*pHash->pnByte) by */
188878  int bNew;                       /* If non-delete entry should be written */
188879
188880  bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
188881
188882  /* Attempt to locate an existing hash entry */
188883  iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
188884  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
188885    if( p->zKey[0]==bByte
188886     && p->nKey==nToken
188887     && memcmp(&p->zKey[1], pToken, nToken)==0
188888    ){
188889      break;
188890    }
188891  }
188892
188893  /* If an existing hash entry cannot be found, create a new one. */
188894  if( p==0 ){
188895    /* Figure out how much space to allocate */
188896    int nByte = FTS5_HASHENTRYSIZE + (nToken+1) + 1 + 64;
188897    if( nByte<128 ) nByte = 128;
188898
188899    /* Grow the Fts5Hash.aSlot[] array if necessary. */
188900    if( (pHash->nEntry*2)>=pHash->nSlot ){
188901      int rc = fts5HashResize(pHash);
188902      if( rc!=SQLITE_OK ) return rc;
188903      iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
188904    }
188905
188906    /* Allocate new Fts5HashEntry and add it to the hash table. */
188907    p = (Fts5HashEntry*)sqlite3_malloc(nByte);
188908    if( !p ) return SQLITE_NOMEM;
188909    memset(p, 0, FTS5_HASHENTRYSIZE);
188910    p->nAlloc = nByte;
188911    p->zKey[0] = bByte;
188912    memcpy(&p->zKey[1], pToken, nToken);
188913    assert( iHash==fts5HashKey(pHash->nSlot, (u8*)p->zKey, nToken+1) );
188914    p->nKey = nToken;
188915    p->zKey[nToken+1] = '\0';
188916    p->nData = nToken+1 + 1 + FTS5_HASHENTRYSIZE;
188917    p->pHashNext = pHash->aSlot[iHash];
188918    pHash->aSlot[iHash] = p;
188919    pHash->nEntry++;
188920
188921    /* Add the first rowid field to the hash-entry */
188922    p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
188923    p->iRowid = iRowid;
188924
188925    p->iSzPoslist = p->nData;
188926    if( pHash->eDetail!=FTS5_DETAIL_NONE ){
188927      p->nData += 1;
188928      p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
188929    }
188930
188931    nIncr += p->nData;
188932  }else{
188933
188934    /* Appending to an existing hash-entry. Check that there is enough
188935    ** space to append the largest possible new entry. Worst case scenario
188936    ** is:
188937    **
188938    **     + 9 bytes for a new rowid,
188939    **     + 4 byte reserved for the "poslist size" varint.
188940    **     + 1 byte for a "new column" byte,
188941    **     + 3 bytes for a new column number (16-bit max) as a varint,
188942    **     + 5 bytes for the new position offset (32-bit max).
188943    */
188944    if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
188945      int nNew = p->nAlloc * 2;
188946      Fts5HashEntry *pNew;
188947      Fts5HashEntry **pp;
188948      pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
188949      if( pNew==0 ) return SQLITE_NOMEM;
188950      pNew->nAlloc = nNew;
188951      for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
188952      *pp = pNew;
188953      p = pNew;
188954    }
188955    nIncr -= p->nData;
188956  }
188957  assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
188958
188959  pPtr = (u8*)p;
188960
188961  /* If this is a new rowid, append the 4-byte size field for the previous
188962  ** entry, and the new rowid for this entry.  */
188963  if( iRowid!=p->iRowid ){
188964    fts5HashAddPoslistSize(pHash, p);
188965    p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
188966    p->iRowid = iRowid;
188967    bNew = 1;
188968    p->iSzPoslist = p->nData;
188969    if( pHash->eDetail!=FTS5_DETAIL_NONE ){
188970      p->nData += 1;
188971      p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
188972      p->iPos = 0;
188973    }
188974  }
188975
188976  if( iCol>=0 ){
188977    if( pHash->eDetail==FTS5_DETAIL_NONE ){
188978      p->bContent = 1;
188979    }else{
188980      /* Append a new column value, if necessary */
188981      assert( iCol>=p->iCol );
188982      if( iCol!=p->iCol ){
188983        if( pHash->eDetail==FTS5_DETAIL_FULL ){
188984          pPtr[p->nData++] = 0x01;
188985          p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
188986          p->iCol = (i16)iCol;
188987          p->iPos = 0;
188988        }else{
188989          bNew = 1;
188990          p->iCol = (i16)(iPos = iCol);
188991        }
188992      }
188993
188994      /* Append the new position offset, if necessary */
188995      if( bNew ){
188996        p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
188997        p->iPos = iPos;
188998      }
188999    }
189000  }else{
189001    /* This is a delete. Set the delete flag. */
189002    p->bDel = 1;
189003  }
189004
189005  nIncr += p->nData;
189006  *pHash->pnByte += nIncr;
189007  return SQLITE_OK;
189008}
189009
189010
189011/*
189012** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
189013** each sorted in key order. This function merges the two lists into a
189014** single list and returns a pointer to its first element.
189015*/
189016static Fts5HashEntry *fts5HashEntryMerge(
189017  Fts5HashEntry *pLeft,
189018  Fts5HashEntry *pRight
189019){
189020  Fts5HashEntry *p1 = pLeft;
189021  Fts5HashEntry *p2 = pRight;
189022  Fts5HashEntry *pRet = 0;
189023  Fts5HashEntry **ppOut = &pRet;
189024
189025  while( p1 || p2 ){
189026    if( p1==0 ){
189027      *ppOut = p2;
189028      p2 = 0;
189029    }else if( p2==0 ){
189030      *ppOut = p1;
189031      p1 = 0;
189032    }else{
189033      int i = 0;
189034      while( p1->zKey[i]==p2->zKey[i] ) i++;
189035
189036      if( ((u8)p1->zKey[i])>((u8)p2->zKey[i]) ){
189037        /* p2 is smaller */
189038        *ppOut = p2;
189039        ppOut = &p2->pScanNext;
189040        p2 = p2->pScanNext;
189041      }else{
189042        /* p1 is smaller */
189043        *ppOut = p1;
189044        ppOut = &p1->pScanNext;
189045        p1 = p1->pScanNext;
189046      }
189047      *ppOut = 0;
189048    }
189049  }
189050
189051  return pRet;
189052}
189053
189054/*
189055** Extract all tokens from hash table iHash and link them into a list
189056** in sorted order. The hash table is cleared before returning. It is
189057** the responsibility of the caller to free the elements of the returned
189058** list.
189059*/
189060static int fts5HashEntrySort(
189061  Fts5Hash *pHash,
189062  const char *pTerm, int nTerm,   /* Query prefix, if any */
189063  Fts5HashEntry **ppSorted
189064){
189065  const int nMergeSlot = 32;
189066  Fts5HashEntry **ap;
189067  Fts5HashEntry *pList;
189068  int iSlot;
189069  int i;
189070
189071  *ppSorted = 0;
189072  ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
189073  if( !ap ) return SQLITE_NOMEM;
189074  memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
189075
189076  for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
189077    Fts5HashEntry *pIter;
189078    for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
189079      if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){
189080        Fts5HashEntry *pEntry = pIter;
189081        pEntry->pScanNext = 0;
189082        for(i=0; ap[i]; i++){
189083          pEntry = fts5HashEntryMerge(pEntry, ap[i]);
189084          ap[i] = 0;
189085        }
189086        ap[i] = pEntry;
189087      }
189088    }
189089  }
189090
189091  pList = 0;
189092  for(i=0; i<nMergeSlot; i++){
189093    pList = fts5HashEntryMerge(pList, ap[i]);
189094  }
189095
189096  pHash->nEntry = 0;
189097  sqlite3_free(ap);
189098  *ppSorted = pList;
189099  return SQLITE_OK;
189100}
189101
189102/*
189103** Query the hash table for a doclist associated with term pTerm/nTerm.
189104*/
189105static int sqlite3Fts5HashQuery(
189106  Fts5Hash *pHash,                /* Hash table to query */
189107  const char *pTerm, int nTerm,   /* Query term */
189108  const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
189109  int *pnDoclist                  /* OUT: Size of doclist in bytes */
189110){
189111  unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
189112  Fts5HashEntry *p;
189113
189114  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
189115    if( memcmp(p->zKey, pTerm, nTerm)==0 && p->zKey[nTerm]==0 ) break;
189116  }
189117
189118  if( p ){
189119    fts5HashAddPoslistSize(pHash, p);
189120    *ppDoclist = (const u8*)&p->zKey[nTerm+1];
189121    *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
189122  }else{
189123    *ppDoclist = 0;
189124    *pnDoclist = 0;
189125  }
189126
189127  return SQLITE_OK;
189128}
189129
189130static int sqlite3Fts5HashScanInit(
189131  Fts5Hash *p,                    /* Hash table to query */
189132  const char *pTerm, int nTerm    /* Query prefix */
189133){
189134  return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
189135}
189136
189137static void sqlite3Fts5HashScanNext(Fts5Hash *p){
189138  assert( !sqlite3Fts5HashScanEof(p) );
189139  p->pScan = p->pScan->pScanNext;
189140}
189141
189142static int sqlite3Fts5HashScanEof(Fts5Hash *p){
189143  return (p->pScan==0);
189144}
189145
189146static void sqlite3Fts5HashScanEntry(
189147  Fts5Hash *pHash,
189148  const char **pzTerm,            /* OUT: term (nul-terminated) */
189149  const u8 **ppDoclist,           /* OUT: pointer to doclist */
189150  int *pnDoclist                  /* OUT: size of doclist in bytes */
189151){
189152  Fts5HashEntry *p;
189153  if( (p = pHash->pScan) ){
189154    int nTerm = (int)strlen(p->zKey);
189155    fts5HashAddPoslistSize(pHash, p);
189156    *pzTerm = p->zKey;
189157    *ppDoclist = (const u8*)&p->zKey[nTerm+1];
189158    *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
189159  }else{
189160    *pzTerm = 0;
189161    *ppDoclist = 0;
189162    *pnDoclist = 0;
189163  }
189164}
189165
189166
189167/*
189168** 2014 May 31
189169**
189170** The author disclaims copyright to this source code.  In place of
189171** a legal notice, here is a blessing:
189172**
189173**    May you do good and not evil.
189174**    May you find forgiveness for yourself and forgive others.
189175**    May you share freely, never taking more than you give.
189176**
189177******************************************************************************
189178**
189179** Low level access to the FTS index stored in the database file. The
189180** routines in this file file implement all read and write access to the
189181** %_data table. Other parts of the system access this functionality via
189182** the interface defined in fts5Int.h.
189183*/
189184
189185
189186/* #include "fts5Int.h" */
189187
189188/*
189189** Overview:
189190**
189191** The %_data table contains all the FTS indexes for an FTS5 virtual table.
189192** As well as the main term index, there may be up to 31 prefix indexes.
189193** The format is similar to FTS3/4, except that:
189194**
189195**   * all segment b-tree leaf data is stored in fixed size page records
189196**     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
189197**     taken to ensure it is possible to iterate in either direction through
189198**     the entries in a doclist, or to seek to a specific entry within a
189199**     doclist, without loading it into memory.
189200**
189201**   * large doclists that span many pages have associated "doclist index"
189202**     records that contain a copy of the first rowid on each page spanned by
189203**     the doclist. This is used to speed up seek operations, and merges of
189204**     large doclists with very small doclists.
189205**
189206**   * extra fields in the "structure record" record the state of ongoing
189207**     incremental merge operations.
189208**
189209*/
189210
189211
189212#define FTS5_OPT_WORK_UNIT  1000  /* Number of leaf pages per optimize step */
189213#define FTS5_WORK_UNIT      64    /* Number of leaf pages in unit of work */
189214
189215#define FTS5_MIN_DLIDX_SIZE 4     /* Add dlidx if this many empty pages */
189216
189217#define FTS5_MAIN_PREFIX '0'
189218
189219#if FTS5_MAX_PREFIX_INDEXES > 31
189220# error "FTS5_MAX_PREFIX_INDEXES is too large"
189221#endif
189222
189223/*
189224** Details:
189225**
189226** The %_data table managed by this module,
189227**
189228**     CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
189229**
189230** , contains the following 5 types of records. See the comments surrounding
189231** the FTS5_*_ROWID macros below for a description of how %_data rowids are
189232** assigned to each fo them.
189233**
189234** 1. Structure Records:
189235**
189236**   The set of segments that make up an index - the index structure - are
189237**   recorded in a single record within the %_data table. The record consists
189238**   of a single 32-bit configuration cookie value followed by a list of
189239**   SQLite varints. If the FTS table features more than one index (because
189240**   there are one or more prefix indexes), it is guaranteed that all share
189241**   the same cookie value.
189242**
189243**   Immediately following the configuration cookie, the record begins with
189244**   three varints:
189245**
189246**     + number of levels,
189247**     + total number of segments on all levels,
189248**     + value of write counter.
189249**
189250**   Then, for each level from 0 to nMax:
189251**
189252**     + number of input segments in ongoing merge.
189253**     + total number of segments in level.
189254**     + for each segment from oldest to newest:
189255**         + segment id (always > 0)
189256**         + first leaf page number (often 1, always greater than 0)
189257**         + final leaf page number
189258**
189259** 2. The Averages Record:
189260**
189261**   A single record within the %_data table. The data is a list of varints.
189262**   The first value is the number of rows in the index. Then, for each column
189263**   from left to right, the total number of tokens in the column for all
189264**   rows of the table.
189265**
189266** 3. Segment leaves:
189267**
189268**   TERM/DOCLIST FORMAT:
189269**
189270**     Most of each segment leaf is taken up by term/doclist data. The
189271**     general format of term/doclist, starting with the first term
189272**     on the leaf page, is:
189273**
189274**         varint : size of first term
189275**         blob:    first term data
189276**         doclist: first doclist
189277**         zero-or-more {
189278**           varint:  number of bytes in common with previous term
189279**           varint:  number of bytes of new term data (nNew)
189280**           blob:    nNew bytes of new term data
189281**           doclist: next doclist
189282**         }
189283**
189284**     doclist format:
189285**
189286**         varint:  first rowid
189287**         poslist: first poslist
189288**         zero-or-more {
189289**           varint:  rowid delta (always > 0)
189290**           poslist: next poslist
189291**         }
189292**
189293**     poslist format:
189294**
189295**         varint: size of poslist in bytes multiplied by 2, not including
189296**                 this field. Plus 1 if this entry carries the "delete" flag.
189297**         collist: collist for column 0
189298**         zero-or-more {
189299**           0x01 byte
189300**           varint: column number (I)
189301**           collist: collist for column I
189302**         }
189303**
189304**     collist format:
189305**
189306**         varint: first offset + 2
189307**         zero-or-more {
189308**           varint: offset delta + 2
189309**         }
189310**
189311**   PAGE FORMAT
189312**
189313**     Each leaf page begins with a 4-byte header containing 2 16-bit
189314**     unsigned integer fields in big-endian format. They are:
189315**
189316**       * The byte offset of the first rowid on the page, if it exists
189317**         and occurs before the first term (otherwise 0).
189318**
189319**       * The byte offset of the start of the page footer. If the page
189320**         footer is 0 bytes in size, then this field is the same as the
189321**         size of the leaf page in bytes.
189322**
189323**     The page footer consists of a single varint for each term located
189324**     on the page. Each varint is the byte offset of the current term
189325**     within the page, delta-compressed against the previous value. In
189326**     other words, the first varint in the footer is the byte offset of
189327**     the first term, the second is the byte offset of the second less that
189328**     of the first, and so on.
189329**
189330**     The term/doclist format described above is accurate if the entire
189331**     term/doclist data fits on a single leaf page. If this is not the case,
189332**     the format is changed in two ways:
189333**
189334**       + if the first rowid on a page occurs before the first term, it
189335**         is stored as a literal value:
189336**
189337**             varint:  first rowid
189338**
189339**       + the first term on each page is stored in the same way as the
189340**         very first term of the segment:
189341**
189342**             varint : size of first term
189343**             blob:    first term data
189344**
189345** 5. Segment doclist indexes:
189346**
189347**   Doclist indexes are themselves b-trees, however they usually consist of
189348**   a single leaf record only. The format of each doclist index leaf page
189349**   is:
189350**
189351**     * Flags byte. Bits are:
189352**         0x01: Clear if leaf is also the root page, otherwise set.
189353**
189354**     * Page number of fts index leaf page. As a varint.
189355**
189356**     * First rowid on page indicated by previous field. As a varint.
189357**
189358**     * A list of varints, one for each subsequent termless page. A
189359**       positive delta if the termless page contains at least one rowid,
189360**       or an 0x00 byte otherwise.
189361**
189362**   Internal doclist index nodes are:
189363**
189364**     * Flags byte. Bits are:
189365**         0x01: Clear for root page, otherwise set.
189366**
189367**     * Page number of first child page. As a varint.
189368**
189369**     * Copy of first rowid on page indicated by previous field. As a varint.
189370**
189371**     * A list of delta-encoded varints - the first rowid on each subsequent
189372**       child page.
189373**
189374*/
189375
189376/*
189377** Rowids for the averages and structure records in the %_data table.
189378*/
189379#define FTS5_AVERAGES_ROWID     1    /* Rowid used for the averages record */
189380#define FTS5_STRUCTURE_ROWID   10    /* The structure record */
189381
189382/*
189383** Macros determining the rowids used by segment leaves and dlidx leaves
189384** and nodes. All nodes and leaves are stored in the %_data table with large
189385** positive rowids.
189386**
189387** Each segment has a unique non-zero 16-bit id.
189388**
189389** The rowid for each segment leaf is found by passing the segment id and
189390** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
189391** sequentially starting from 1.
189392*/
189393#define FTS5_DATA_ID_B     16     /* Max seg id number 65535 */
189394#define FTS5_DATA_DLI_B     1     /* Doclist-index flag (1 bit) */
189395#define FTS5_DATA_HEIGHT_B  5     /* Max dlidx tree height of 32 */
189396#define FTS5_DATA_PAGE_B   31     /* Max page number of 2147483648 */
189397
189398#define fts5_dri(segid, dlidx, height, pgno) (                                 \
189399 ((i64)(segid)  << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) +    \
189400 ((i64)(dlidx)  << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) +                  \
189401 ((i64)(height) << (FTS5_DATA_PAGE_B)) +                                       \
189402 ((i64)(pgno))                                                                 \
189403)
189404
189405#define FTS5_SEGMENT_ROWID(segid, pgno)       fts5_dri(segid, 0, 0, pgno)
189406#define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
189407
189408/*
189409** Maximum segments permitted in a single index
189410*/
189411#define FTS5_MAX_SEGMENT 2000
189412
189413#ifdef SQLITE_DEBUG
189414static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
189415#endif
189416
189417
189418/*
189419** Each time a blob is read from the %_data table, it is padded with this
189420** many zero bytes. This makes it easier to decode the various record formats
189421** without overreading if the records are corrupt.
189422*/
189423#define FTS5_DATA_ZERO_PADDING 8
189424#define FTS5_DATA_PADDING 20
189425
189426typedef struct Fts5Data Fts5Data;
189427typedef struct Fts5DlidxIter Fts5DlidxIter;
189428typedef struct Fts5DlidxLvl Fts5DlidxLvl;
189429typedef struct Fts5DlidxWriter Fts5DlidxWriter;
189430typedef struct Fts5Iter Fts5Iter;
189431typedef struct Fts5PageWriter Fts5PageWriter;
189432typedef struct Fts5SegIter Fts5SegIter;
189433typedef struct Fts5DoclistIter Fts5DoclistIter;
189434typedef struct Fts5SegWriter Fts5SegWriter;
189435typedef struct Fts5Structure Fts5Structure;
189436typedef struct Fts5StructureLevel Fts5StructureLevel;
189437typedef struct Fts5StructureSegment Fts5StructureSegment;
189438
189439struct Fts5Data {
189440  u8 *p;                          /* Pointer to buffer containing record */
189441  int nn;                         /* Size of record in bytes */
189442  int szLeaf;                     /* Size of leaf without page-index */
189443};
189444
189445/*
189446** One object per %_data table.
189447*/
189448struct Fts5Index {
189449  Fts5Config *pConfig;            /* Virtual table configuration */
189450  char *zDataTbl;                 /* Name of %_data table */
189451  int nWorkUnit;                  /* Leaf pages in a "unit" of work */
189452
189453  /*
189454  ** Variables related to the accumulation of tokens and doclists within the
189455  ** in-memory hash tables before they are flushed to disk.
189456  */
189457  Fts5Hash *pHash;                /* Hash table for in-memory data */
189458  int nPendingData;               /* Current bytes of pending data */
189459  i64 iWriteRowid;                /* Rowid for current doc being written */
189460  int bDelete;                    /* Current write is a delete */
189461
189462  /* Error state. */
189463  int rc;                         /* Current error code */
189464
189465  /* State used by the fts5DataXXX() functions. */
189466  sqlite3_blob *pReader;          /* RO incr-blob open on %_data table */
189467  sqlite3_stmt *pWriter;          /* "INSERT ... %_data VALUES(?,?)" */
189468  sqlite3_stmt *pDeleter;         /* "DELETE FROM %_data ... id>=? AND id<=?" */
189469  sqlite3_stmt *pIdxWriter;       /* "INSERT ... %_idx VALUES(?,?,?,?)" */
189470  sqlite3_stmt *pIdxDeleter;      /* "DELETE FROM %_idx WHERE segid=? */
189471  sqlite3_stmt *pIdxSelect;
189472  int nRead;                      /* Total number of blocks read */
189473
189474  sqlite3_stmt *pDataVersion;
189475  i64 iStructVersion;             /* data_version when pStruct read */
189476  Fts5Structure *pStruct;         /* Current db structure (or NULL) */
189477};
189478
189479struct Fts5DoclistIter {
189480  u8 *aEof;                       /* Pointer to 1 byte past end of doclist */
189481
189482  /* Output variables. aPoslist==0 at EOF */
189483  i64 iRowid;
189484  u8 *aPoslist;
189485  int nPoslist;
189486  int nSize;
189487};
189488
189489/*
189490** The contents of the "structure" record for each index are represented
189491** using an Fts5Structure record in memory. Which uses instances of the
189492** other Fts5StructureXXX types as components.
189493*/
189494struct Fts5StructureSegment {
189495  int iSegid;                     /* Segment id */
189496  int pgnoFirst;                  /* First leaf page number in segment */
189497  int pgnoLast;                   /* Last leaf page number in segment */
189498};
189499struct Fts5StructureLevel {
189500  int nMerge;                     /* Number of segments in incr-merge */
189501  int nSeg;                       /* Total number of segments on level */
189502  Fts5StructureSegment *aSeg;     /* Array of segments. aSeg[0] is oldest. */
189503};
189504struct Fts5Structure {
189505  int nRef;                       /* Object reference count */
189506  u64 nWriteCounter;              /* Total leaves written to level 0 */
189507  int nSegment;                   /* Total segments in this structure */
189508  int nLevel;                     /* Number of levels in this index */
189509  Fts5StructureLevel aLevel[1];   /* Array of nLevel level objects */
189510};
189511
189512/*
189513** An object of type Fts5SegWriter is used to write to segments.
189514*/
189515struct Fts5PageWriter {
189516  int pgno;                       /* Page number for this page */
189517  int iPrevPgidx;                 /* Previous value written into pgidx */
189518  Fts5Buffer buf;                 /* Buffer containing leaf data */
189519  Fts5Buffer pgidx;               /* Buffer containing page-index */
189520  Fts5Buffer term;                /* Buffer containing previous term on page */
189521};
189522struct Fts5DlidxWriter {
189523  int pgno;                       /* Page number for this page */
189524  int bPrevValid;                 /* True if iPrev is valid */
189525  i64 iPrev;                      /* Previous rowid value written to page */
189526  Fts5Buffer buf;                 /* Buffer containing page data */
189527};
189528struct Fts5SegWriter {
189529  int iSegid;                     /* Segid to write to */
189530  Fts5PageWriter writer;          /* PageWriter object */
189531  i64 iPrevRowid;                 /* Previous rowid written to current leaf */
189532  u8 bFirstRowidInDoclist;        /* True if next rowid is first in doclist */
189533  u8 bFirstRowidInPage;           /* True if next rowid is first in page */
189534  /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
189535  u8 bFirstTermInPage;            /* True if next term will be first in leaf */
189536  int nLeafWritten;               /* Number of leaf pages written */
189537  int nEmpty;                     /* Number of contiguous term-less nodes */
189538
189539  int nDlidx;                     /* Allocated size of aDlidx[] array */
189540  Fts5DlidxWriter *aDlidx;        /* Array of Fts5DlidxWriter objects */
189541
189542  /* Values to insert into the %_idx table */
189543  Fts5Buffer btterm;              /* Next term to insert into %_idx table */
189544  int iBtPage;                    /* Page number corresponding to btterm */
189545};
189546
189547typedef struct Fts5CResult Fts5CResult;
189548struct Fts5CResult {
189549  u16 iFirst;                     /* aSeg[] index of firstest iterator */
189550  u8 bTermEq;                     /* True if the terms are equal */
189551};
189552
189553/*
189554** Object for iterating through a single segment, visiting each term/rowid
189555** pair in the segment.
189556**
189557** pSeg:
189558**   The segment to iterate through.
189559**
189560** iLeafPgno:
189561**   Current leaf page number within segment.
189562**
189563** iLeafOffset:
189564**   Byte offset within the current leaf that is the first byte of the
189565**   position list data (one byte passed the position-list size field).
189566**   rowid field of the current entry. Usually this is the size field of the
189567**   position list data. The exception is if the rowid for the current entry
189568**   is the last thing on the leaf page.
189569**
189570** pLeaf:
189571**   Buffer containing current leaf page data. Set to NULL at EOF.
189572**
189573** iTermLeafPgno, iTermLeafOffset:
189574**   Leaf page number containing the last term read from the segment. And
189575**   the offset immediately following the term data.
189576**
189577** flags:
189578**   Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
189579**
189580**   FTS5_SEGITER_ONETERM:
189581**     If set, set the iterator to point to EOF after the current doclist
189582**     has been exhausted. Do not proceed to the next term in the segment.
189583**
189584**   FTS5_SEGITER_REVERSE:
189585**     This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
189586**     it is set, iterate through rowid in descending order instead of the
189587**     default ascending order.
189588**
189589** iRowidOffset/nRowidOffset/aRowidOffset:
189590**     These are used if the FTS5_SEGITER_REVERSE flag is set.
189591**
189592**     For each rowid on the page corresponding to the current term, the
189593**     corresponding aRowidOffset[] entry is set to the byte offset of the
189594**     start of the "position-list-size" field within the page.
189595**
189596** iTermIdx:
189597**     Index of current term on iTermLeafPgno.
189598*/
189599struct Fts5SegIter {
189600  Fts5StructureSegment *pSeg;     /* Segment to iterate through */
189601  int flags;                      /* Mask of configuration flags */
189602  int iLeafPgno;                  /* Current leaf page number */
189603  Fts5Data *pLeaf;                /* Current leaf data */
189604  Fts5Data *pNextLeaf;            /* Leaf page (iLeafPgno+1) */
189605  int iLeafOffset;                /* Byte offset within current leaf */
189606
189607  /* Next method */
189608  void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
189609
189610  /* The page and offset from which the current term was read. The offset
189611  ** is the offset of the first rowid in the current doclist.  */
189612  int iTermLeafPgno;
189613  int iTermLeafOffset;
189614
189615  int iPgidxOff;                  /* Next offset in pgidx */
189616  int iEndofDoclist;
189617
189618  /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
189619  int iRowidOffset;               /* Current entry in aRowidOffset[] */
189620  int nRowidOffset;               /* Allocated size of aRowidOffset[] array */
189621  int *aRowidOffset;              /* Array of offset to rowid fields */
189622
189623  Fts5DlidxIter *pDlidx;          /* If there is a doclist-index */
189624
189625  /* Variables populated based on current entry. */
189626  Fts5Buffer term;                /* Current term */
189627  i64 iRowid;                     /* Current rowid */
189628  int nPos;                       /* Number of bytes in current position list */
189629  u8 bDel;                        /* True if the delete flag is set */
189630};
189631
189632/*
189633** Argument is a pointer to an Fts5Data structure that contains a
189634** leaf page.
189635*/
189636#define ASSERT_SZLEAF_OK(x) assert( \
189637    (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
189638)
189639
189640#define FTS5_SEGITER_ONETERM 0x01
189641#define FTS5_SEGITER_REVERSE 0x02
189642
189643/*
189644** Argument is a pointer to an Fts5Data structure that contains a leaf
189645** page. This macro evaluates to true if the leaf contains no terms, or
189646** false if it contains at least one term.
189647*/
189648#define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
189649
189650#define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
189651
189652#define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
189653
189654/*
189655** Object for iterating through the merged results of one or more segments,
189656** visiting each term/rowid pair in the merged data.
189657**
189658** nSeg is always a power of two greater than or equal to the number of
189659** segments that this object is merging data from. Both the aSeg[] and
189660** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
189661** with zeroed objects - these are handled as if they were iterators opened
189662** on empty segments.
189663**
189664** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
189665** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
189666** comparison in this context is the index of the iterator that currently
189667** points to the smaller term/rowid combination. Iterators at EOF are
189668** considered to be greater than all other iterators.
189669**
189670** aFirst[1] contains the index in aSeg[] of the iterator that points to
189671** the smallest key overall. aFirst[0] is unused.
189672**
189673** poslist:
189674**   Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
189675**   There is no way to tell if this is populated or not.
189676*/
189677struct Fts5Iter {
189678  Fts5IndexIter base;             /* Base class containing output vars */
189679
189680  Fts5Index *pIndex;              /* Index that owns this iterator */
189681  Fts5Structure *pStruct;         /* Database structure for this iterator */
189682  Fts5Buffer poslist;             /* Buffer containing current poslist */
189683  Fts5Colset *pColset;            /* Restrict matches to these columns */
189684
189685  /* Invoked to set output variables. */
189686  void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
189687
189688  int nSeg;                       /* Size of aSeg[] array */
189689  int bRev;                       /* True to iterate in reverse order */
189690  u8 bSkipEmpty;                  /* True to skip deleted entries */
189691
189692  i64 iSwitchRowid;               /* Firstest rowid of other than aFirst[1] */
189693  Fts5CResult *aFirst;            /* Current merge state (see above) */
189694  Fts5SegIter aSeg[1];            /* Array of segment iterators */
189695};
189696
189697
189698/*
189699** An instance of the following type is used to iterate through the contents
189700** of a doclist-index record.
189701**
189702** pData:
189703**   Record containing the doclist-index data.
189704**
189705** bEof:
189706**   Set to true once iterator has reached EOF.
189707**
189708** iOff:
189709**   Set to the current offset within record pData.
189710*/
189711struct Fts5DlidxLvl {
189712  Fts5Data *pData;              /* Data for current page of this level */
189713  int iOff;                     /* Current offset into pData */
189714  int bEof;                     /* At EOF already */
189715  int iFirstOff;                /* Used by reverse iterators */
189716
189717  /* Output variables */
189718  int iLeafPgno;                /* Page number of current leaf page */
189719  i64 iRowid;                   /* First rowid on leaf iLeafPgno */
189720};
189721struct Fts5DlidxIter {
189722  int nLvl;
189723  int iSegid;
189724  Fts5DlidxLvl aLvl[1];
189725};
189726
189727static void fts5PutU16(u8 *aOut, u16 iVal){
189728  aOut[0] = (iVal>>8);
189729  aOut[1] = (iVal&0xFF);
189730}
189731
189732static u16 fts5GetU16(const u8 *aIn){
189733  return ((u16)aIn[0] << 8) + aIn[1];
189734}
189735
189736/*
189737** Allocate and return a buffer at least nByte bytes in size.
189738**
189739** If an OOM error is encountered, return NULL and set the error code in
189740** the Fts5Index handle passed as the first argument.
189741*/
189742static void *fts5IdxMalloc(Fts5Index *p, int nByte){
189743  return sqlite3Fts5MallocZero(&p->rc, nByte);
189744}
189745
189746/*
189747** Compare the contents of the pLeft buffer with the pRight/nRight blob.
189748**
189749** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
189750** +ve if pRight is smaller than pLeft. In other words:
189751**
189752**     res = *pLeft - *pRight
189753*/
189754#ifdef SQLITE_DEBUG
189755static int fts5BufferCompareBlob(
189756  Fts5Buffer *pLeft,              /* Left hand side of comparison */
189757  const u8 *pRight, int nRight    /* Right hand side of comparison */
189758){
189759  int nCmp = MIN(pLeft->n, nRight);
189760  int res = memcmp(pLeft->p, pRight, nCmp);
189761  return (res==0 ? (pLeft->n - nRight) : res);
189762}
189763#endif
189764
189765/*
189766** Compare the contents of the two buffers using memcmp(). If one buffer
189767** is a prefix of the other, it is considered the lesser.
189768**
189769** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
189770** +ve if pRight is smaller than pLeft. In other words:
189771**
189772**     res = *pLeft - *pRight
189773*/
189774static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
189775  int nCmp = MIN(pLeft->n, pRight->n);
189776  int res = memcmp(pLeft->p, pRight->p, nCmp);
189777  return (res==0 ? (pLeft->n - pRight->n) : res);
189778}
189779
189780static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
189781  int ret;
189782  fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
189783  return ret;
189784}
189785
189786/*
189787** Close the read-only blob handle, if it is open.
189788*/
189789static void fts5CloseReader(Fts5Index *p){
189790  if( p->pReader ){
189791    sqlite3_blob *pReader = p->pReader;
189792    p->pReader = 0;
189793    sqlite3_blob_close(pReader);
189794  }
189795}
189796
189797
189798/*
189799** Retrieve a record from the %_data table.
189800**
189801** If an error occurs, NULL is returned and an error left in the
189802** Fts5Index object.
189803*/
189804static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
189805  Fts5Data *pRet = 0;
189806  if( p->rc==SQLITE_OK ){
189807    int rc = SQLITE_OK;
189808
189809    if( p->pReader ){
189810      /* This call may return SQLITE_ABORT if there has been a savepoint
189811      ** rollback since it was last used. In this case a new blob handle
189812      ** is required.  */
189813      sqlite3_blob *pBlob = p->pReader;
189814      p->pReader = 0;
189815      rc = sqlite3_blob_reopen(pBlob, iRowid);
189816      assert( p->pReader==0 );
189817      p->pReader = pBlob;
189818      if( rc!=SQLITE_OK ){
189819        fts5CloseReader(p);
189820      }
189821      if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
189822    }
189823
189824    /* If the blob handle is not open at this point, open it and seek
189825    ** to the requested entry.  */
189826    if( p->pReader==0 && rc==SQLITE_OK ){
189827      Fts5Config *pConfig = p->pConfig;
189828      rc = sqlite3_blob_open(pConfig->db,
189829          pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
189830      );
189831    }
189832
189833    /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
189834    ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
189835    ** All the reasons those functions might return SQLITE_ERROR - missing
189836    ** table, missing row, non-blob/text in block column - indicate
189837    ** backing store corruption.  */
189838    if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
189839
189840    if( rc==SQLITE_OK ){
189841      u8 *aOut = 0;               /* Read blob data into this buffer */
189842      int nByte = sqlite3_blob_bytes(p->pReader);
189843      int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
189844      pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
189845      if( pRet ){
189846        pRet->nn = nByte;
189847        aOut = pRet->p = (u8*)&pRet[1];
189848      }else{
189849        rc = SQLITE_NOMEM;
189850      }
189851
189852      if( rc==SQLITE_OK ){
189853        rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
189854      }
189855      if( rc!=SQLITE_OK ){
189856        sqlite3_free(pRet);
189857        pRet = 0;
189858      }else{
189859        /* TODO1: Fix this */
189860        pRet->szLeaf = fts5GetU16(&pRet->p[2]);
189861      }
189862    }
189863    p->rc = rc;
189864    p->nRead++;
189865  }
189866
189867  assert( (pRet==0)==(p->rc!=SQLITE_OK) );
189868  return pRet;
189869}
189870
189871/*
189872** Release a reference to data record returned by an earlier call to
189873** fts5DataRead().
189874*/
189875static void fts5DataRelease(Fts5Data *pData){
189876  sqlite3_free(pData);
189877}
189878
189879static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
189880  Fts5Data *pRet = fts5DataRead(p, iRowid);
189881  if( pRet ){
189882    if( pRet->szLeaf>pRet->nn ){
189883      p->rc = FTS5_CORRUPT;
189884      fts5DataRelease(pRet);
189885      pRet = 0;
189886    }
189887  }
189888  return pRet;
189889}
189890
189891static int fts5IndexPrepareStmt(
189892  Fts5Index *p,
189893  sqlite3_stmt **ppStmt,
189894  char *zSql
189895){
189896  if( p->rc==SQLITE_OK ){
189897    if( zSql ){
189898      p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0);
189899    }else{
189900      p->rc = SQLITE_NOMEM;
189901    }
189902  }
189903  sqlite3_free(zSql);
189904  return p->rc;
189905}
189906
189907
189908/*
189909** INSERT OR REPLACE a record into the %_data table.
189910*/
189911static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
189912  if( p->rc!=SQLITE_OK ) return;
189913
189914  if( p->pWriter==0 ){
189915    Fts5Config *pConfig = p->pConfig;
189916    fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
189917          "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
189918          pConfig->zDb, pConfig->zName
189919    ));
189920    if( p->rc ) return;
189921  }
189922
189923  sqlite3_bind_int64(p->pWriter, 1, iRowid);
189924  sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
189925  sqlite3_step(p->pWriter);
189926  p->rc = sqlite3_reset(p->pWriter);
189927}
189928
189929/*
189930** Execute the following SQL:
189931**
189932**     DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
189933*/
189934static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
189935  if( p->rc!=SQLITE_OK ) return;
189936
189937  if( p->pDeleter==0 ){
189938    int rc;
189939    Fts5Config *pConfig = p->pConfig;
189940    char *zSql = sqlite3_mprintf(
189941        "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
189942          pConfig->zDb, pConfig->zName
189943    );
189944    if( zSql==0 ){
189945      rc = SQLITE_NOMEM;
189946    }else{
189947      rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0);
189948      sqlite3_free(zSql);
189949    }
189950    if( rc!=SQLITE_OK ){
189951      p->rc = rc;
189952      return;
189953    }
189954  }
189955
189956  sqlite3_bind_int64(p->pDeleter, 1, iFirst);
189957  sqlite3_bind_int64(p->pDeleter, 2, iLast);
189958  sqlite3_step(p->pDeleter);
189959  p->rc = sqlite3_reset(p->pDeleter);
189960}
189961
189962/*
189963** Remove all records associated with segment iSegid.
189964*/
189965static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
189966  i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
189967  i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
189968  fts5DataDelete(p, iFirst, iLast);
189969  if( p->pIdxDeleter==0 ){
189970    Fts5Config *pConfig = p->pConfig;
189971    fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
189972          "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
189973          pConfig->zDb, pConfig->zName
189974    ));
189975  }
189976  if( p->rc==SQLITE_OK ){
189977    sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
189978    sqlite3_step(p->pIdxDeleter);
189979    p->rc = sqlite3_reset(p->pIdxDeleter);
189980  }
189981}
189982
189983/*
189984** Release a reference to an Fts5Structure object returned by an earlier
189985** call to fts5StructureRead() or fts5StructureDecode().
189986*/
189987static void fts5StructureRelease(Fts5Structure *pStruct){
189988  if( pStruct && 0>=(--pStruct->nRef) ){
189989    int i;
189990    assert( pStruct->nRef==0 );
189991    for(i=0; i<pStruct->nLevel; i++){
189992      sqlite3_free(pStruct->aLevel[i].aSeg);
189993    }
189994    sqlite3_free(pStruct);
189995  }
189996}
189997
189998static void fts5StructureRef(Fts5Structure *pStruct){
189999  pStruct->nRef++;
190000}
190001
190002/*
190003** Deserialize and return the structure record currently stored in serialized
190004** form within buffer pData/nData.
190005**
190006** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
190007** are over-allocated by one slot. This allows the structure contents
190008** to be more easily edited.
190009**
190010** If an error occurs, *ppOut is set to NULL and an SQLite error code
190011** returned. Otherwise, *ppOut is set to point to the new object and
190012** SQLITE_OK returned.
190013*/
190014static int fts5StructureDecode(
190015  const u8 *pData,                /* Buffer containing serialized structure */
190016  int nData,                      /* Size of buffer pData in bytes */
190017  int *piCookie,                  /* Configuration cookie value */
190018  Fts5Structure **ppOut           /* OUT: Deserialized object */
190019){
190020  int rc = SQLITE_OK;
190021  int i = 0;
190022  int iLvl;
190023  int nLevel = 0;
190024  int nSegment = 0;
190025  int nByte;                      /* Bytes of space to allocate at pRet */
190026  Fts5Structure *pRet = 0;        /* Structure object to return */
190027
190028  /* Grab the cookie value */
190029  if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
190030  i = 4;
190031
190032  /* Read the total number of levels and segments from the start of the
190033  ** structure record.  */
190034  i += fts5GetVarint32(&pData[i], nLevel);
190035  i += fts5GetVarint32(&pData[i], nSegment);
190036  nByte = (
190037      sizeof(Fts5Structure) +                    /* Main structure */
190038      sizeof(Fts5StructureLevel) * (nLevel-1)    /* aLevel[] array */
190039  );
190040  pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
190041
190042  if( pRet ){
190043    pRet->nRef = 1;
190044    pRet->nLevel = nLevel;
190045    pRet->nSegment = nSegment;
190046    i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
190047
190048    for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
190049      Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
190050      int nTotal = 0;
190051      int iSeg;
190052
190053      if( i>=nData ){
190054        rc = FTS5_CORRUPT;
190055      }else{
190056        i += fts5GetVarint32(&pData[i], pLvl->nMerge);
190057        i += fts5GetVarint32(&pData[i], nTotal);
190058        assert( nTotal>=pLvl->nMerge );
190059        pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
190060            nTotal * sizeof(Fts5StructureSegment)
190061        );
190062      }
190063
190064      if( rc==SQLITE_OK ){
190065        pLvl->nSeg = nTotal;
190066        for(iSeg=0; iSeg<nTotal; iSeg++){
190067          if( i>=nData ){
190068            rc = FTS5_CORRUPT;
190069            break;
190070          }
190071          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
190072          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
190073          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
190074        }
190075      }
190076    }
190077    if( rc!=SQLITE_OK ){
190078      fts5StructureRelease(pRet);
190079      pRet = 0;
190080    }
190081  }
190082
190083  *ppOut = pRet;
190084  return rc;
190085}
190086
190087/*
190088**
190089*/
190090static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
190091  if( *pRc==SQLITE_OK ){
190092    Fts5Structure *pStruct = *ppStruct;
190093    int nLevel = pStruct->nLevel;
190094    int nByte = (
190095        sizeof(Fts5Structure) +                  /* Main structure */
190096        sizeof(Fts5StructureLevel) * (nLevel+1)  /* aLevel[] array */
190097    );
190098
190099    pStruct = sqlite3_realloc(pStruct, nByte);
190100    if( pStruct ){
190101      memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
190102      pStruct->nLevel++;
190103      *ppStruct = pStruct;
190104    }else{
190105      *pRc = SQLITE_NOMEM;
190106    }
190107  }
190108}
190109
190110/*
190111** Extend level iLvl so that there is room for at least nExtra more
190112** segments.
190113*/
190114static void fts5StructureExtendLevel(
190115  int *pRc,
190116  Fts5Structure *pStruct,
190117  int iLvl,
190118  int nExtra,
190119  int bInsert
190120){
190121  if( *pRc==SQLITE_OK ){
190122    Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
190123    Fts5StructureSegment *aNew;
190124    int nByte;
190125
190126    nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
190127    aNew = sqlite3_realloc(pLvl->aSeg, nByte);
190128    if( aNew ){
190129      if( bInsert==0 ){
190130        memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
190131      }else{
190132        int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
190133        memmove(&aNew[nExtra], aNew, nMove);
190134        memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
190135      }
190136      pLvl->aSeg = aNew;
190137    }else{
190138      *pRc = SQLITE_NOMEM;
190139    }
190140  }
190141}
190142
190143static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
190144  Fts5Structure *pRet = 0;
190145  Fts5Config *pConfig = p->pConfig;
190146  int iCookie;                    /* Configuration cookie */
190147  Fts5Data *pData;
190148
190149  pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
190150  if( p->rc==SQLITE_OK ){
190151    /* TODO: Do we need this if the leaf-index is appended? Probably... */
190152    memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
190153    p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
190154    if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
190155      p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
190156    }
190157    fts5DataRelease(pData);
190158    if( p->rc!=SQLITE_OK ){
190159      fts5StructureRelease(pRet);
190160      pRet = 0;
190161    }
190162  }
190163
190164  return pRet;
190165}
190166
190167static i64 fts5IndexDataVersion(Fts5Index *p){
190168  i64 iVersion = 0;
190169
190170  if( p->rc==SQLITE_OK ){
190171    if( p->pDataVersion==0 ){
190172      p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
190173          sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
190174          );
190175      if( p->rc ) return 0;
190176    }
190177
190178    if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
190179      iVersion = sqlite3_column_int64(p->pDataVersion, 0);
190180    }
190181    p->rc = sqlite3_reset(p->pDataVersion);
190182  }
190183
190184  return iVersion;
190185}
190186
190187/*
190188** Read, deserialize and return the structure record.
190189**
190190** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
190191** are over-allocated as described for function fts5StructureDecode()
190192** above.
190193**
190194** If an error occurs, NULL is returned and an error code left in the
190195** Fts5Index handle. If an error has already occurred when this function
190196** is called, it is a no-op.
190197*/
190198static Fts5Structure *fts5StructureRead(Fts5Index *p){
190199
190200  if( p->pStruct==0 ){
190201    p->iStructVersion = fts5IndexDataVersion(p);
190202    if( p->rc==SQLITE_OK ){
190203      p->pStruct = fts5StructureReadUncached(p);
190204    }
190205  }
190206
190207#if 0
190208  else{
190209    Fts5Structure *pTest = fts5StructureReadUncached(p);
190210    if( pTest ){
190211      int i, j;
190212      assert_nc( p->pStruct->nSegment==pTest->nSegment );
190213      assert_nc( p->pStruct->nLevel==pTest->nLevel );
190214      for(i=0; i<pTest->nLevel; i++){
190215        assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
190216        assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
190217        for(j=0; j<pTest->aLevel[i].nSeg; j++){
190218          Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
190219          Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
190220          assert_nc( p1->iSegid==p2->iSegid );
190221          assert_nc( p1->pgnoFirst==p2->pgnoFirst );
190222          assert_nc( p1->pgnoLast==p2->pgnoLast );
190223        }
190224      }
190225      fts5StructureRelease(pTest);
190226    }
190227  }
190228#endif
190229
190230  if( p->rc!=SQLITE_OK ) return 0;
190231  assert( p->iStructVersion!=0 );
190232  assert( p->pStruct!=0 );
190233  fts5StructureRef(p->pStruct);
190234  return p->pStruct;
190235}
190236
190237static void fts5StructureInvalidate(Fts5Index *p){
190238  if( p->pStruct ){
190239    fts5StructureRelease(p->pStruct);
190240    p->pStruct = 0;
190241  }
190242}
190243
190244/*
190245** Return the total number of segments in index structure pStruct. This
190246** function is only ever used as part of assert() conditions.
190247*/
190248#ifdef SQLITE_DEBUG
190249static int fts5StructureCountSegments(Fts5Structure *pStruct){
190250  int nSegment = 0;               /* Total number of segments */
190251  if( pStruct ){
190252    int iLvl;                     /* Used to iterate through levels */
190253    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
190254      nSegment += pStruct->aLevel[iLvl].nSeg;
190255    }
190256  }
190257
190258  return nSegment;
190259}
190260#endif
190261
190262#define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) {     \
190263  assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) );             \
190264  memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob);             \
190265  (pBuf)->n += nBlob;                                      \
190266}
190267
190268#define fts5BufferSafeAppendVarint(pBuf, iVal) {                \
190269  (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal));  \
190270  assert( (pBuf)->nSpace>=(pBuf)->n );                          \
190271}
190272
190273
190274/*
190275** Serialize and store the "structure" record.
190276**
190277** If an error occurs, leave an error code in the Fts5Index object. If an
190278** error has already occurred, this function is a no-op.
190279*/
190280static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
190281  if( p->rc==SQLITE_OK ){
190282    Fts5Buffer buf;               /* Buffer to serialize record into */
190283    int iLvl;                     /* Used to iterate through levels */
190284    int iCookie;                  /* Cookie value to store */
190285
190286    assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
190287    memset(&buf, 0, sizeof(Fts5Buffer));
190288
190289    /* Append the current configuration cookie */
190290    iCookie = p->pConfig->iCookie;
190291    if( iCookie<0 ) iCookie = 0;
190292
190293    if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
190294      sqlite3Fts5Put32(buf.p, iCookie);
190295      buf.n = 4;
190296      fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
190297      fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
190298      fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
190299    }
190300
190301    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
190302      int iSeg;                     /* Used to iterate through segments */
190303      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
190304      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
190305      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
190306      assert( pLvl->nMerge<=pLvl->nSeg );
190307
190308      for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
190309        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
190310        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
190311        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
190312      }
190313    }
190314
190315    fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
190316    fts5BufferFree(&buf);
190317  }
190318}
190319
190320#if 0
190321static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
190322static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
190323  int rc = SQLITE_OK;
190324  Fts5Buffer buf;
190325  memset(&buf, 0, sizeof(buf));
190326  fts5DebugStructure(&rc, &buf, pStruct);
190327  fprintf(stdout, "%s: %s\n", zCaption, buf.p);
190328  fflush(stdout);
190329  fts5BufferFree(&buf);
190330}
190331#else
190332# define fts5PrintStructure(x,y)
190333#endif
190334
190335static int fts5SegmentSize(Fts5StructureSegment *pSeg){
190336  return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
190337}
190338
190339/*
190340** Return a copy of index structure pStruct. Except, promote as many
190341** segments as possible to level iPromote. If an OOM occurs, NULL is
190342** returned.
190343*/
190344static void fts5StructurePromoteTo(
190345  Fts5Index *p,
190346  int iPromote,
190347  int szPromote,
190348  Fts5Structure *pStruct
190349){
190350  int il, is;
190351  Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
190352
190353  if( pOut->nMerge==0 ){
190354    for(il=iPromote+1; il<pStruct->nLevel; il++){
190355      Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
190356      if( pLvl->nMerge ) return;
190357      for(is=pLvl->nSeg-1; is>=0; is--){
190358        int sz = fts5SegmentSize(&pLvl->aSeg[is]);
190359        if( sz>szPromote ) return;
190360        fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
190361        if( p->rc ) return;
190362        memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
190363        pOut->nSeg++;
190364        pLvl->nSeg--;
190365      }
190366    }
190367  }
190368}
190369
190370/*
190371** A new segment has just been written to level iLvl of index structure
190372** pStruct. This function determines if any segments should be promoted
190373** as a result. Segments are promoted in two scenarios:
190374**
190375**   a) If the segment just written is smaller than one or more segments
190376**      within the previous populated level, it is promoted to the previous
190377**      populated level.
190378**
190379**   b) If the segment just written is larger than the newest segment on
190380**      the next populated level, then that segment, and any other adjacent
190381**      segments that are also smaller than the one just written, are
190382**      promoted.
190383**
190384** If one or more segments are promoted, the structure object is updated
190385** to reflect this.
190386*/
190387static void fts5StructurePromote(
190388  Fts5Index *p,                   /* FTS5 backend object */
190389  int iLvl,                       /* Index level just updated */
190390  Fts5Structure *pStruct          /* Index structure */
190391){
190392  if( p->rc==SQLITE_OK ){
190393    int iTst;
190394    int iPromote = -1;
190395    int szPromote = 0;            /* Promote anything this size or smaller */
190396    Fts5StructureSegment *pSeg;   /* Segment just written */
190397    int szSeg;                    /* Size of segment just written */
190398    int nSeg = pStruct->aLevel[iLvl].nSeg;
190399
190400    if( nSeg==0 ) return;
190401    pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
190402    szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
190403
190404    /* Check for condition (a) */
190405    for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
190406    if( iTst>=0 ){
190407      int i;
190408      int szMax = 0;
190409      Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
190410      assert( pTst->nMerge==0 );
190411      for(i=0; i<pTst->nSeg; i++){
190412        int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
190413        if( sz>szMax ) szMax = sz;
190414      }
190415      if( szMax>=szSeg ){
190416        /* Condition (a) is true. Promote the newest segment on level
190417        ** iLvl to level iTst.  */
190418        iPromote = iTst;
190419        szPromote = szMax;
190420      }
190421    }
190422
190423    /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
190424    ** is a no-op if it is not.  */
190425    if( iPromote<0 ){
190426      iPromote = iLvl;
190427      szPromote = szSeg;
190428    }
190429    fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
190430  }
190431}
190432
190433
190434/*
190435** Advance the iterator passed as the only argument. If the end of the
190436** doclist-index page is reached, return non-zero.
190437*/
190438static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
190439  Fts5Data *pData = pLvl->pData;
190440
190441  if( pLvl->iOff==0 ){
190442    assert( pLvl->bEof==0 );
190443    pLvl->iOff = 1;
190444    pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
190445    pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
190446    pLvl->iFirstOff = pLvl->iOff;
190447  }else{
190448    int iOff;
190449    for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
190450      if( pData->p[iOff] ) break;
190451    }
190452
190453    if( iOff<pData->nn ){
190454      i64 iVal;
190455      pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
190456      iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
190457      pLvl->iRowid += iVal;
190458      pLvl->iOff = iOff;
190459    }else{
190460      pLvl->bEof = 1;
190461    }
190462  }
190463
190464  return pLvl->bEof;
190465}
190466
190467/*
190468** Advance the iterator passed as the only argument.
190469*/
190470static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
190471  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
190472
190473  assert( iLvl<pIter->nLvl );
190474  if( fts5DlidxLvlNext(pLvl) ){
190475    if( (iLvl+1) < pIter->nLvl ){
190476      fts5DlidxIterNextR(p, pIter, iLvl+1);
190477      if( pLvl[1].bEof==0 ){
190478        fts5DataRelease(pLvl->pData);
190479        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
190480        pLvl->pData = fts5DataRead(p,
190481            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
190482        );
190483        if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
190484      }
190485    }
190486  }
190487
190488  return pIter->aLvl[0].bEof;
190489}
190490static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
190491  return fts5DlidxIterNextR(p, pIter, 0);
190492}
190493
190494/*
190495** The iterator passed as the first argument has the following fields set
190496** as follows. This function sets up the rest of the iterator so that it
190497** points to the first rowid in the doclist-index.
190498**
190499**   pData:
190500**     pointer to doclist-index record,
190501**
190502** When this function is called pIter->iLeafPgno is the page number the
190503** doclist is associated with (the one featuring the term).
190504*/
190505static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
190506  int i;
190507  for(i=0; i<pIter->nLvl; i++){
190508    fts5DlidxLvlNext(&pIter->aLvl[i]);
190509  }
190510  return pIter->aLvl[0].bEof;
190511}
190512
190513
190514static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
190515  return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
190516}
190517
190518static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
190519  int i;
190520
190521  /* Advance each level to the last entry on the last page */
190522  for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
190523    Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
190524    while( fts5DlidxLvlNext(pLvl)==0 );
190525    pLvl->bEof = 0;
190526
190527    if( i>0 ){
190528      Fts5DlidxLvl *pChild = &pLvl[-1];
190529      fts5DataRelease(pChild->pData);
190530      memset(pChild, 0, sizeof(Fts5DlidxLvl));
190531      pChild->pData = fts5DataRead(p,
190532          FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
190533      );
190534    }
190535  }
190536}
190537
190538/*
190539** Move the iterator passed as the only argument to the previous entry.
190540*/
190541static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
190542  int iOff = pLvl->iOff;
190543
190544  assert( pLvl->bEof==0 );
190545  if( iOff<=pLvl->iFirstOff ){
190546    pLvl->bEof = 1;
190547  }else{
190548    u8 *a = pLvl->pData->p;
190549    i64 iVal;
190550    int iLimit;
190551    int ii;
190552    int nZero = 0;
190553
190554    /* Currently iOff points to the first byte of a varint. This block
190555    ** decrements iOff until it points to the first byte of the previous
190556    ** varint. Taking care not to read any memory locations that occur
190557    ** before the buffer in memory.  */
190558    iLimit = (iOff>9 ? iOff-9 : 0);
190559    for(iOff--; iOff>iLimit; iOff--){
190560      if( (a[iOff-1] & 0x80)==0 ) break;
190561    }
190562
190563    fts5GetVarint(&a[iOff], (u64*)&iVal);
190564    pLvl->iRowid -= iVal;
190565    pLvl->iLeafPgno--;
190566
190567    /* Skip backwards past any 0x00 varints. */
190568    for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
190569      nZero++;
190570    }
190571    if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
190572      /* The byte immediately before the last 0x00 byte has the 0x80 bit
190573      ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
190574      ** bytes before a[ii]. */
190575      int bZero = 0;              /* True if last 0x00 counts */
190576      if( (ii-8)>=pLvl->iFirstOff ){
190577        int j;
190578        for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
190579        bZero = (j>8);
190580      }
190581      if( bZero==0 ) nZero--;
190582    }
190583    pLvl->iLeafPgno -= nZero;
190584    pLvl->iOff = iOff - nZero;
190585  }
190586
190587  return pLvl->bEof;
190588}
190589
190590static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
190591  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
190592
190593  assert( iLvl<pIter->nLvl );
190594  if( fts5DlidxLvlPrev(pLvl) ){
190595    if( (iLvl+1) < pIter->nLvl ){
190596      fts5DlidxIterPrevR(p, pIter, iLvl+1);
190597      if( pLvl[1].bEof==0 ){
190598        fts5DataRelease(pLvl->pData);
190599        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
190600        pLvl->pData = fts5DataRead(p,
190601            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
190602        );
190603        if( pLvl->pData ){
190604          while( fts5DlidxLvlNext(pLvl)==0 );
190605          pLvl->bEof = 0;
190606        }
190607      }
190608    }
190609  }
190610
190611  return pIter->aLvl[0].bEof;
190612}
190613static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
190614  return fts5DlidxIterPrevR(p, pIter, 0);
190615}
190616
190617/*
190618** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
190619*/
190620static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
190621  if( pIter ){
190622    int i;
190623    for(i=0; i<pIter->nLvl; i++){
190624      fts5DataRelease(pIter->aLvl[i].pData);
190625    }
190626    sqlite3_free(pIter);
190627  }
190628}
190629
190630static Fts5DlidxIter *fts5DlidxIterInit(
190631  Fts5Index *p,                   /* Fts5 Backend to iterate within */
190632  int bRev,                       /* True for ORDER BY ASC */
190633  int iSegid,                     /* Segment id */
190634  int iLeafPg                     /* Leaf page number to load dlidx for */
190635){
190636  Fts5DlidxIter *pIter = 0;
190637  int i;
190638  int bDone = 0;
190639
190640  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
190641    int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
190642    Fts5DlidxIter *pNew;
190643
190644    pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
190645    if( pNew==0 ){
190646      p->rc = SQLITE_NOMEM;
190647    }else{
190648      i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
190649      Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
190650      pIter = pNew;
190651      memset(pLvl, 0, sizeof(Fts5DlidxLvl));
190652      pLvl->pData = fts5DataRead(p, iRowid);
190653      if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
190654        bDone = 1;
190655      }
190656      pIter->nLvl = i+1;
190657    }
190658  }
190659
190660  if( p->rc==SQLITE_OK ){
190661    pIter->iSegid = iSegid;
190662    if( bRev==0 ){
190663      fts5DlidxIterFirst(pIter);
190664    }else{
190665      fts5DlidxIterLast(p, pIter);
190666    }
190667  }
190668
190669  if( p->rc!=SQLITE_OK ){
190670    fts5DlidxIterFree(pIter);
190671    pIter = 0;
190672  }
190673
190674  return pIter;
190675}
190676
190677static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
190678  return pIter->aLvl[0].iRowid;
190679}
190680static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
190681  return pIter->aLvl[0].iLeafPgno;
190682}
190683
190684/*
190685** Load the next leaf page into the segment iterator.
190686*/
190687static void fts5SegIterNextPage(
190688  Fts5Index *p,                   /* FTS5 backend object */
190689  Fts5SegIter *pIter              /* Iterator to advance to next page */
190690){
190691  Fts5Data *pLeaf;
190692  Fts5StructureSegment *pSeg = pIter->pSeg;
190693  fts5DataRelease(pIter->pLeaf);
190694  pIter->iLeafPgno++;
190695  if( pIter->pNextLeaf ){
190696    pIter->pLeaf = pIter->pNextLeaf;
190697    pIter->pNextLeaf = 0;
190698  }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
190699    pIter->pLeaf = fts5LeafRead(p,
190700        FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
190701    );
190702  }else{
190703    pIter->pLeaf = 0;
190704  }
190705  pLeaf = pIter->pLeaf;
190706
190707  if( pLeaf ){
190708    pIter->iPgidxOff = pLeaf->szLeaf;
190709    if( fts5LeafIsTermless(pLeaf) ){
190710      pIter->iEndofDoclist = pLeaf->nn+1;
190711    }else{
190712      pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
190713          pIter->iEndofDoclist
190714      );
190715    }
190716  }
190717}
190718
190719/*
190720** Argument p points to a buffer containing a varint to be interpreted as a
190721** position list size field. Read the varint and return the number of bytes
190722** read. Before returning, set *pnSz to the number of bytes in the position
190723** list, and *pbDel to true if the delete flag is set, or false otherwise.
190724*/
190725static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
190726  int nSz;
190727  int n = 0;
190728  fts5FastGetVarint32(p, n, nSz);
190729  assert_nc( nSz>=0 );
190730  *pnSz = nSz/2;
190731  *pbDel = nSz & 0x0001;
190732  return n;
190733}
190734
190735/*
190736** Fts5SegIter.iLeafOffset currently points to the first byte of a
190737** position-list size field. Read the value of the field and store it
190738** in the following variables:
190739**
190740**   Fts5SegIter.nPos
190741**   Fts5SegIter.bDel
190742**
190743** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
190744** position list content (if any).
190745*/
190746static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
190747  if( p->rc==SQLITE_OK ){
190748    int iOff = pIter->iLeafOffset;  /* Offset to read at */
190749    ASSERT_SZLEAF_OK(pIter->pLeaf);
190750    if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
190751      int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
190752      pIter->bDel = 0;
190753      pIter->nPos = 1;
190754      if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
190755        pIter->bDel = 1;
190756        iOff++;
190757        if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
190758          pIter->nPos = 1;
190759          iOff++;
190760        }else{
190761          pIter->nPos = 0;
190762        }
190763      }
190764    }else{
190765      int nSz;
190766      fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
190767      pIter->bDel = (nSz & 0x0001);
190768      pIter->nPos = nSz>>1;
190769      assert_nc( pIter->nPos>=0 );
190770    }
190771    pIter->iLeafOffset = iOff;
190772  }
190773}
190774
190775static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
190776  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
190777  int iOff = pIter->iLeafOffset;
190778
190779  ASSERT_SZLEAF_OK(pIter->pLeaf);
190780  if( iOff>=pIter->pLeaf->szLeaf ){
190781    fts5SegIterNextPage(p, pIter);
190782    if( pIter->pLeaf==0 ){
190783      if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
190784      return;
190785    }
190786    iOff = 4;
190787    a = pIter->pLeaf->p;
190788  }
190789  iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
190790  pIter->iLeafOffset = iOff;
190791}
190792
190793/*
190794** Fts5SegIter.iLeafOffset currently points to the first byte of the
190795** "nSuffix" field of a term. Function parameter nKeep contains the value
190796** of the "nPrefix" field (if there was one - it is passed 0 if this is
190797** the first term in the segment).
190798**
190799** This function populates:
190800**
190801**   Fts5SegIter.term
190802**   Fts5SegIter.rowid
190803**
190804** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
190805** the first position list. The position list belonging to document
190806** (Fts5SegIter.iRowid).
190807*/
190808static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
190809  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
190810  int iOff = pIter->iLeafOffset;  /* Offset to read at */
190811  int nNew;                       /* Bytes of new data */
190812
190813  iOff += fts5GetVarint32(&a[iOff], nNew);
190814  if( iOff+nNew>pIter->pLeaf->nn ){
190815    p->rc = FTS5_CORRUPT;
190816    return;
190817  }
190818  pIter->term.n = nKeep;
190819  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
190820  iOff += nNew;
190821  pIter->iTermLeafOffset = iOff;
190822  pIter->iTermLeafPgno = pIter->iLeafPgno;
190823  pIter->iLeafOffset = iOff;
190824
190825  if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
190826    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
190827  }else{
190828    int nExtra;
190829    pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
190830    pIter->iEndofDoclist += nExtra;
190831  }
190832
190833  fts5SegIterLoadRowid(p, pIter);
190834}
190835
190836static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
190837static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
190838static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
190839
190840static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
190841  if( pIter->flags & FTS5_SEGITER_REVERSE ){
190842    pIter->xNext = fts5SegIterNext_Reverse;
190843  }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
190844    pIter->xNext = fts5SegIterNext_None;
190845  }else{
190846    pIter->xNext = fts5SegIterNext;
190847  }
190848}
190849
190850/*
190851** Initialize the iterator object pIter to iterate through the entries in
190852** segment pSeg. The iterator is left pointing to the first entry when
190853** this function returns.
190854**
190855** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
190856** an error has already occurred when this function is called, it is a no-op.
190857*/
190858static void fts5SegIterInit(
190859  Fts5Index *p,                   /* FTS index object */
190860  Fts5StructureSegment *pSeg,     /* Description of segment */
190861  Fts5SegIter *pIter              /* Object to populate */
190862){
190863  if( pSeg->pgnoFirst==0 ){
190864    /* This happens if the segment is being used as an input to an incremental
190865    ** merge and all data has already been "trimmed". See function
190866    ** fts5TrimSegments() for details. In this case leave the iterator empty.
190867    ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
190868    ** at EOF already. */
190869    assert( pIter->pLeaf==0 );
190870    return;
190871  }
190872
190873  if( p->rc==SQLITE_OK ){
190874    memset(pIter, 0, sizeof(*pIter));
190875    fts5SegIterSetNext(p, pIter);
190876    pIter->pSeg = pSeg;
190877    pIter->iLeafPgno = pSeg->pgnoFirst-1;
190878    fts5SegIterNextPage(p, pIter);
190879  }
190880
190881  if( p->rc==SQLITE_OK ){
190882    pIter->iLeafOffset = 4;
190883    assert_nc( pIter->pLeaf->nn>4 );
190884    assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
190885    pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
190886    fts5SegIterLoadTerm(p, pIter, 0);
190887    fts5SegIterLoadNPos(p, pIter);
190888  }
190889}
190890
190891/*
190892** This function is only ever called on iterators created by calls to
190893** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
190894**
190895** The iterator is in an unusual state when this function is called: the
190896** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
190897** the position-list size field for the first relevant rowid on the page.
190898** Fts5SegIter.rowid is set, but nPos and bDel are not.
190899**
190900** This function advances the iterator so that it points to the last
190901** relevant rowid on the page and, if necessary, initializes the
190902** aRowidOffset[] and iRowidOffset variables. At this point the iterator
190903** is in its regular state - Fts5SegIter.iLeafOffset points to the first
190904** byte of the position list content associated with said rowid.
190905*/
190906static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
190907  int eDetail = p->pConfig->eDetail;
190908  int n = pIter->pLeaf->szLeaf;
190909  int i = pIter->iLeafOffset;
190910  u8 *a = pIter->pLeaf->p;
190911  int iRowidOffset = 0;
190912
190913  if( n>pIter->iEndofDoclist ){
190914    n = pIter->iEndofDoclist;
190915  }
190916
190917  ASSERT_SZLEAF_OK(pIter->pLeaf);
190918  while( 1 ){
190919    i64 iDelta = 0;
190920
190921    if( eDetail==FTS5_DETAIL_NONE ){
190922      /* todo */
190923      if( i<n && a[i]==0 ){
190924        i++;
190925        if( i<n && a[i]==0 ) i++;
190926      }
190927    }else{
190928      int nPos;
190929      int bDummy;
190930      i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
190931      i += nPos;
190932    }
190933    if( i>=n ) break;
190934    i += fts5GetVarint(&a[i], (u64*)&iDelta);
190935    pIter->iRowid += iDelta;
190936
190937    /* If necessary, grow the pIter->aRowidOffset[] array. */
190938    if( iRowidOffset>=pIter->nRowidOffset ){
190939      int nNew = pIter->nRowidOffset + 8;
190940      int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
190941      if( aNew==0 ){
190942        p->rc = SQLITE_NOMEM;
190943        break;
190944      }
190945      pIter->aRowidOffset = aNew;
190946      pIter->nRowidOffset = nNew;
190947    }
190948
190949    pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
190950    pIter->iLeafOffset = i;
190951  }
190952  pIter->iRowidOffset = iRowidOffset;
190953  fts5SegIterLoadNPos(p, pIter);
190954}
190955
190956/*
190957**
190958*/
190959static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
190960  assert( pIter->flags & FTS5_SEGITER_REVERSE );
190961  assert( pIter->flags & FTS5_SEGITER_ONETERM );
190962
190963  fts5DataRelease(pIter->pLeaf);
190964  pIter->pLeaf = 0;
190965  while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
190966    Fts5Data *pNew;
190967    pIter->iLeafPgno--;
190968    pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
190969          pIter->pSeg->iSegid, pIter->iLeafPgno
190970    ));
190971    if( pNew ){
190972      /* iTermLeafOffset may be equal to szLeaf if the term is the last
190973      ** thing on the page - i.e. the first rowid is on the following page.
190974      ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
190975      if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
190976        assert( pIter->pLeaf==0 );
190977        if( pIter->iTermLeafOffset<pNew->szLeaf ){
190978          pIter->pLeaf = pNew;
190979          pIter->iLeafOffset = pIter->iTermLeafOffset;
190980        }
190981      }else{
190982        int iRowidOff;
190983        iRowidOff = fts5LeafFirstRowidOff(pNew);
190984        if( iRowidOff ){
190985          pIter->pLeaf = pNew;
190986          pIter->iLeafOffset = iRowidOff;
190987        }
190988      }
190989
190990      if( pIter->pLeaf ){
190991        u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
190992        pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
190993        break;
190994      }else{
190995        fts5DataRelease(pNew);
190996      }
190997    }
190998  }
190999
191000  if( pIter->pLeaf ){
191001    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
191002    fts5SegIterReverseInitPage(p, pIter);
191003  }
191004}
191005
191006/*
191007** Return true if the iterator passed as the second argument currently
191008** points to a delete marker. A delete marker is an entry with a 0 byte
191009** position-list.
191010*/
191011static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
191012  Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
191013  return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
191014}
191015
191016/*
191017** Advance iterator pIter to the next entry.
191018**
191019** This version of fts5SegIterNext() is only used by reverse iterators.
191020*/
191021static void fts5SegIterNext_Reverse(
191022  Fts5Index *p,                   /* FTS5 backend object */
191023  Fts5SegIter *pIter,             /* Iterator to advance */
191024  int *pbUnused                   /* Unused */
191025){
191026  assert( pIter->flags & FTS5_SEGITER_REVERSE );
191027  assert( pIter->pNextLeaf==0 );
191028  UNUSED_PARAM(pbUnused);
191029
191030  if( pIter->iRowidOffset>0 ){
191031    u8 *a = pIter->pLeaf->p;
191032    int iOff;
191033    i64 iDelta;
191034
191035    pIter->iRowidOffset--;
191036    pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
191037    fts5SegIterLoadNPos(p, pIter);
191038    iOff = pIter->iLeafOffset;
191039    if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
191040      iOff += pIter->nPos;
191041    }
191042    fts5GetVarint(&a[iOff], (u64*)&iDelta);
191043    pIter->iRowid -= iDelta;
191044  }else{
191045    fts5SegIterReverseNewPage(p, pIter);
191046  }
191047}
191048
191049/*
191050** Advance iterator pIter to the next entry.
191051**
191052** This version of fts5SegIterNext() is only used if detail=none and the
191053** iterator is not a reverse direction iterator.
191054*/
191055static void fts5SegIterNext_None(
191056  Fts5Index *p,                   /* FTS5 backend object */
191057  Fts5SegIter *pIter,             /* Iterator to advance */
191058  int *pbNewTerm                  /* OUT: Set for new term */
191059){
191060  int iOff;
191061
191062  assert( p->rc==SQLITE_OK );
191063  assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
191064  assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
191065
191066  ASSERT_SZLEAF_OK(pIter->pLeaf);
191067  iOff = pIter->iLeafOffset;
191068
191069  /* Next entry is on the next page */
191070  if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
191071    fts5SegIterNextPage(p, pIter);
191072    if( p->rc || pIter->pLeaf==0 ) return;
191073    pIter->iRowid = 0;
191074    iOff = 4;
191075  }
191076
191077  if( iOff<pIter->iEndofDoclist ){
191078    /* Next entry is on the current page */
191079    i64 iDelta;
191080    iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
191081    pIter->iLeafOffset = iOff;
191082    pIter->iRowid += iDelta;
191083  }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
191084    if( pIter->pSeg ){
191085      int nKeep = 0;
191086      if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
191087        iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
191088      }
191089      pIter->iLeafOffset = iOff;
191090      fts5SegIterLoadTerm(p, pIter, nKeep);
191091    }else{
191092      const u8 *pList = 0;
191093      const char *zTerm = 0;
191094      int nList;
191095      sqlite3Fts5HashScanNext(p->pHash);
191096      sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
191097      if( pList==0 ) goto next_none_eof;
191098      pIter->pLeaf->p = (u8*)pList;
191099      pIter->pLeaf->nn = nList;
191100      pIter->pLeaf->szLeaf = nList;
191101      pIter->iEndofDoclist = nList;
191102      sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
191103      pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
191104    }
191105
191106    if( pbNewTerm ) *pbNewTerm = 1;
191107  }else{
191108    goto next_none_eof;
191109  }
191110
191111  fts5SegIterLoadNPos(p, pIter);
191112
191113  return;
191114 next_none_eof:
191115  fts5DataRelease(pIter->pLeaf);
191116  pIter->pLeaf = 0;
191117}
191118
191119
191120/*
191121** Advance iterator pIter to the next entry.
191122**
191123** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
191124** is not considered an error if the iterator reaches EOF. If an error has
191125** already occurred when this function is called, it is a no-op.
191126*/
191127static void fts5SegIterNext(
191128  Fts5Index *p,                   /* FTS5 backend object */
191129  Fts5SegIter *pIter,             /* Iterator to advance */
191130  int *pbNewTerm                  /* OUT: Set for new term */
191131){
191132  Fts5Data *pLeaf = pIter->pLeaf;
191133  int iOff;
191134  int bNewTerm = 0;
191135  int nKeep = 0;
191136  u8 *a;
191137  int n;
191138
191139  assert( pbNewTerm==0 || *pbNewTerm==0 );
191140  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
191141
191142  /* Search for the end of the position list within the current page. */
191143  a = pLeaf->p;
191144  n = pLeaf->szLeaf;
191145
191146  ASSERT_SZLEAF_OK(pLeaf);
191147  iOff = pIter->iLeafOffset + pIter->nPos;
191148
191149  if( iOff<n ){
191150    /* The next entry is on the current page. */
191151    assert_nc( iOff<=pIter->iEndofDoclist );
191152    if( iOff>=pIter->iEndofDoclist ){
191153      bNewTerm = 1;
191154      if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
191155        iOff += fts5GetVarint32(&a[iOff], nKeep);
191156      }
191157    }else{
191158      u64 iDelta;
191159      iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
191160      pIter->iRowid += iDelta;
191161      assert_nc( iDelta>0 );
191162    }
191163    pIter->iLeafOffset = iOff;
191164
191165  }else if( pIter->pSeg==0 ){
191166    const u8 *pList = 0;
191167    const char *zTerm = 0;
191168    int nList = 0;
191169    assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
191170    if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
191171      sqlite3Fts5HashScanNext(p->pHash);
191172      sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
191173    }
191174    if( pList==0 ){
191175      fts5DataRelease(pIter->pLeaf);
191176      pIter->pLeaf = 0;
191177    }else{
191178      pIter->pLeaf->p = (u8*)pList;
191179      pIter->pLeaf->nn = nList;
191180      pIter->pLeaf->szLeaf = nList;
191181      pIter->iEndofDoclist = nList+1;
191182      sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
191183          (u8*)zTerm);
191184      pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
191185      *pbNewTerm = 1;
191186    }
191187  }else{
191188    iOff = 0;
191189    /* Next entry is not on the current page */
191190    while( iOff==0 ){
191191      fts5SegIterNextPage(p, pIter);
191192      pLeaf = pIter->pLeaf;
191193      if( pLeaf==0 ) break;
191194      ASSERT_SZLEAF_OK(pLeaf);
191195      if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
191196        iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
191197        pIter->iLeafOffset = iOff;
191198
191199        if( pLeaf->nn>pLeaf->szLeaf ){
191200          pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
191201              &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
191202          );
191203        }
191204      }
191205      else if( pLeaf->nn>pLeaf->szLeaf ){
191206        pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
191207            &pLeaf->p[pLeaf->szLeaf], iOff
191208        );
191209        pIter->iLeafOffset = iOff;
191210        pIter->iEndofDoclist = iOff;
191211        bNewTerm = 1;
191212      }
191213      assert_nc( iOff<pLeaf->szLeaf );
191214      if( iOff>pLeaf->szLeaf ){
191215        p->rc = FTS5_CORRUPT;
191216        return;
191217      }
191218    }
191219  }
191220
191221  /* Check if the iterator is now at EOF. If so, return early. */
191222  if( pIter->pLeaf ){
191223    if( bNewTerm ){
191224      if( pIter->flags & FTS5_SEGITER_ONETERM ){
191225        fts5DataRelease(pIter->pLeaf);
191226        pIter->pLeaf = 0;
191227      }else{
191228        fts5SegIterLoadTerm(p, pIter, nKeep);
191229        fts5SegIterLoadNPos(p, pIter);
191230        if( pbNewTerm ) *pbNewTerm = 1;
191231      }
191232    }else{
191233      /* The following could be done by calling fts5SegIterLoadNPos(). But
191234      ** this block is particularly performance critical, so equivalent
191235      ** code is inlined.
191236      **
191237      ** Later: Switched back to fts5SegIterLoadNPos() because it supports
191238      ** detail=none mode. Not ideal.
191239      */
191240      int nSz;
191241      assert( p->rc==SQLITE_OK );
191242      assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
191243      fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
191244      pIter->bDel = (nSz & 0x0001);
191245      pIter->nPos = nSz>>1;
191246      assert_nc( pIter->nPos>=0 );
191247    }
191248  }
191249}
191250
191251#define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
191252
191253#define fts5IndexSkipVarint(a, iOff) {            \
191254  int iEnd = iOff+9;                              \
191255  while( (a[iOff++] & 0x80) && iOff<iEnd );       \
191256}
191257
191258/*
191259** Iterator pIter currently points to the first rowid in a doclist. This
191260** function sets the iterator up so that iterates in reverse order through
191261** the doclist.
191262*/
191263static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
191264  Fts5DlidxIter *pDlidx = pIter->pDlidx;
191265  Fts5Data *pLast = 0;
191266  int pgnoLast = 0;
191267
191268  if( pDlidx ){
191269    int iSegid = pIter->pSeg->iSegid;
191270    pgnoLast = fts5DlidxIterPgno(pDlidx);
191271    pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
191272  }else{
191273    Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */
191274
191275    /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
191276    ** position-list content for the current rowid. Back it up so that it
191277    ** points to the start of the position-list size field. */
191278    int iPoslist;
191279    if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
191280      iPoslist = pIter->iTermLeafOffset;
191281    }else{
191282      iPoslist = 4;
191283    }
191284    fts5IndexSkipVarint(pLeaf->p, iPoslist);
191285    pIter->iLeafOffset = iPoslist;
191286
191287    /* If this condition is true then the largest rowid for the current
191288    ** term may not be stored on the current page. So search forward to
191289    ** see where said rowid really is.  */
191290    if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
191291      int pgno;
191292      Fts5StructureSegment *pSeg = pIter->pSeg;
191293
191294      /* The last rowid in the doclist may not be on the current page. Search
191295      ** forward to find the page containing the last rowid.  */
191296      for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
191297        i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
191298        Fts5Data *pNew = fts5DataRead(p, iAbs);
191299        if( pNew ){
191300          int iRowid, bTermless;
191301          iRowid = fts5LeafFirstRowidOff(pNew);
191302          bTermless = fts5LeafIsTermless(pNew);
191303          if( iRowid ){
191304            SWAPVAL(Fts5Data*, pNew, pLast);
191305            pgnoLast = pgno;
191306          }
191307          fts5DataRelease(pNew);
191308          if( bTermless==0 ) break;
191309        }
191310      }
191311    }
191312  }
191313
191314  /* If pLast is NULL at this point, then the last rowid for this doclist
191315  ** lies on the page currently indicated by the iterator. In this case
191316  ** pIter->iLeafOffset is already set to point to the position-list size
191317  ** field associated with the first relevant rowid on the page.
191318  **
191319  ** Or, if pLast is non-NULL, then it is the page that contains the last
191320  ** rowid. In this case configure the iterator so that it points to the
191321  ** first rowid on this page.
191322  */
191323  if( pLast ){
191324    int iOff;
191325    fts5DataRelease(pIter->pLeaf);
191326    pIter->pLeaf = pLast;
191327    pIter->iLeafPgno = pgnoLast;
191328    iOff = fts5LeafFirstRowidOff(pLast);
191329    iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
191330    pIter->iLeafOffset = iOff;
191331
191332    if( fts5LeafIsTermless(pLast) ){
191333      pIter->iEndofDoclist = pLast->nn+1;
191334    }else{
191335      pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
191336    }
191337
191338  }
191339
191340  fts5SegIterReverseInitPage(p, pIter);
191341}
191342
191343/*
191344** Iterator pIter currently points to the first rowid of a doclist.
191345** There is a doclist-index associated with the final term on the current
191346** page. If the current term is the last term on the page, load the
191347** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
191348*/
191349static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
191350  int iSeg = pIter->pSeg->iSegid;
191351  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
191352  Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
191353
191354  assert( pIter->flags & FTS5_SEGITER_ONETERM );
191355  assert( pIter->pDlidx==0 );
191356
191357  /* Check if the current doclist ends on this page. If it does, return
191358  ** early without loading the doclist-index (as it belongs to a different
191359  ** term. */
191360  if( pIter->iTermLeafPgno==pIter->iLeafPgno
191361   && pIter->iEndofDoclist<pLeaf->szLeaf
191362  ){
191363    return;
191364  }
191365
191366  pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
191367}
191368
191369/*
191370** The iterator object passed as the second argument currently contains
191371** no valid values except for the Fts5SegIter.pLeaf member variable. This
191372** function searches the leaf page for a term matching (pTerm/nTerm).
191373**
191374** If the specified term is found on the page, then the iterator is left
191375** pointing to it. If argument bGe is zero and the term is not found,
191376** the iterator is left pointing at EOF.
191377**
191378** If bGe is non-zero and the specified term is not found, then the
191379** iterator is left pointing to the smallest term in the segment that
191380** is larger than the specified term, even if this term is not on the
191381** current page.
191382*/
191383static void fts5LeafSeek(
191384  Fts5Index *p,                   /* Leave any error code here */
191385  int bGe,                        /* True for a >= search */
191386  Fts5SegIter *pIter,             /* Iterator to seek */
191387  const u8 *pTerm, int nTerm      /* Term to search for */
191388){
191389  int iOff;
191390  const u8 *a = pIter->pLeaf->p;
191391  int szLeaf = pIter->pLeaf->szLeaf;
191392  int n = pIter->pLeaf->nn;
191393
191394  int nMatch = 0;
191395  int nKeep = 0;
191396  int nNew = 0;
191397  int iTermOff;
191398  int iPgidx;                     /* Current offset in pgidx */
191399  int bEndOfPage = 0;
191400
191401  assert( p->rc==SQLITE_OK );
191402
191403  iPgidx = szLeaf;
191404  iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
191405  iOff = iTermOff;
191406  if( iOff>n ){
191407    p->rc = FTS5_CORRUPT;
191408    return;
191409  }
191410
191411  while( 1 ){
191412
191413    /* Figure out how many new bytes are in this term */
191414    fts5FastGetVarint32(a, iOff, nNew);
191415    if( nKeep<nMatch ){
191416      goto search_failed;
191417    }
191418
191419    assert( nKeep>=nMatch );
191420    if( nKeep==nMatch ){
191421      int nCmp;
191422      int i;
191423      nCmp = MIN(nNew, nTerm-nMatch);
191424      for(i=0; i<nCmp; i++){
191425        if( a[iOff+i]!=pTerm[nMatch+i] ) break;
191426      }
191427      nMatch += i;
191428
191429      if( nTerm==nMatch ){
191430        if( i==nNew ){
191431          goto search_success;
191432        }else{
191433          goto search_failed;
191434        }
191435      }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
191436        goto search_failed;
191437      }
191438    }
191439
191440    if( iPgidx>=n ){
191441      bEndOfPage = 1;
191442      break;
191443    }
191444
191445    iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
191446    iTermOff += nKeep;
191447    iOff = iTermOff;
191448
191449    if( iOff>=n ){
191450      p->rc = FTS5_CORRUPT;
191451      return;
191452    }
191453
191454    /* Read the nKeep field of the next term. */
191455    fts5FastGetVarint32(a, iOff, nKeep);
191456  }
191457
191458 search_failed:
191459  if( bGe==0 ){
191460    fts5DataRelease(pIter->pLeaf);
191461    pIter->pLeaf = 0;
191462    return;
191463  }else if( bEndOfPage ){
191464    do {
191465      fts5SegIterNextPage(p, pIter);
191466      if( pIter->pLeaf==0 ) return;
191467      a = pIter->pLeaf->p;
191468      if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
191469        iPgidx = pIter->pLeaf->szLeaf;
191470        iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
191471        if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
191472          p->rc = FTS5_CORRUPT;
191473        }else{
191474          nKeep = 0;
191475          iTermOff = iOff;
191476          n = pIter->pLeaf->nn;
191477          iOff += fts5GetVarint32(&a[iOff], nNew);
191478          break;
191479        }
191480      }
191481    }while( 1 );
191482  }
191483
191484 search_success:
191485
191486  pIter->iLeafOffset = iOff + nNew;
191487  pIter->iTermLeafOffset = pIter->iLeafOffset;
191488  pIter->iTermLeafPgno = pIter->iLeafPgno;
191489
191490  fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
191491  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
191492
191493  if( iPgidx>=n ){
191494    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
191495  }else{
191496    int nExtra;
191497    iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
191498    pIter->iEndofDoclist = iTermOff + nExtra;
191499  }
191500  pIter->iPgidxOff = iPgidx;
191501
191502  fts5SegIterLoadRowid(p, pIter);
191503  fts5SegIterLoadNPos(p, pIter);
191504}
191505
191506static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
191507  if( p->pIdxSelect==0 ){
191508    Fts5Config *pConfig = p->pConfig;
191509    fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
191510          "SELECT pgno FROM '%q'.'%q_idx' WHERE "
191511          "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
191512          pConfig->zDb, pConfig->zName
191513    ));
191514  }
191515  return p->pIdxSelect;
191516}
191517
191518/*
191519** Initialize the object pIter to point to term pTerm/nTerm within segment
191520** pSeg. If there is no such term in the index, the iterator is set to EOF.
191521**
191522** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
191523** an error has already occurred when this function is called, it is a no-op.
191524*/
191525static void fts5SegIterSeekInit(
191526  Fts5Index *p,                   /* FTS5 backend */
191527  const u8 *pTerm, int nTerm,     /* Term to seek to */
191528  int flags,                      /* Mask of FTS5INDEX_XXX flags */
191529  Fts5StructureSegment *pSeg,     /* Description of segment */
191530  Fts5SegIter *pIter              /* Object to populate */
191531){
191532  int iPg = 1;
191533  int bGe = (flags & FTS5INDEX_QUERY_SCAN);
191534  int bDlidx = 0;                 /* True if there is a doclist-index */
191535  sqlite3_stmt *pIdxSelect = 0;
191536
191537  assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
191538  assert( pTerm && nTerm );
191539  memset(pIter, 0, sizeof(*pIter));
191540  pIter->pSeg = pSeg;
191541
191542  /* This block sets stack variable iPg to the leaf page number that may
191543  ** contain term (pTerm/nTerm), if it is present in the segment. */
191544  pIdxSelect = fts5IdxSelectStmt(p);
191545  if( p->rc ) return;
191546  sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
191547  sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
191548  if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
191549    i64 val = sqlite3_column_int(pIdxSelect, 0);
191550    iPg = (int)(val>>1);
191551    bDlidx = (val & 0x0001);
191552  }
191553  p->rc = sqlite3_reset(pIdxSelect);
191554
191555  if( iPg<pSeg->pgnoFirst ){
191556    iPg = pSeg->pgnoFirst;
191557    bDlidx = 0;
191558  }
191559
191560  pIter->iLeafPgno = iPg - 1;
191561  fts5SegIterNextPage(p, pIter);
191562
191563  if( pIter->pLeaf ){
191564    fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
191565  }
191566
191567  if( p->rc==SQLITE_OK && bGe==0 ){
191568    pIter->flags |= FTS5_SEGITER_ONETERM;
191569    if( pIter->pLeaf ){
191570      if( flags & FTS5INDEX_QUERY_DESC ){
191571        pIter->flags |= FTS5_SEGITER_REVERSE;
191572      }
191573      if( bDlidx ){
191574        fts5SegIterLoadDlidx(p, pIter);
191575      }
191576      if( flags & FTS5INDEX_QUERY_DESC ){
191577        fts5SegIterReverse(p, pIter);
191578      }
191579    }
191580  }
191581
191582  fts5SegIterSetNext(p, pIter);
191583
191584  /* Either:
191585  **
191586  **   1) an error has occurred, or
191587  **   2) the iterator points to EOF, or
191588  **   3) the iterator points to an entry with term (pTerm/nTerm), or
191589  **   4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
191590  **      to an entry with a term greater than or equal to (pTerm/nTerm).
191591  */
191592  assert( p->rc!=SQLITE_OK                                          /* 1 */
191593   || pIter->pLeaf==0                                               /* 2 */
191594   || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0          /* 3 */
191595   || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0)  /* 4 */
191596  );
191597}
191598
191599/*
191600** Initialize the object pIter to point to term pTerm/nTerm within the
191601** in-memory hash table. If there is no such term in the hash-table, the
191602** iterator is set to EOF.
191603**
191604** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
191605** an error has already occurred when this function is called, it is a no-op.
191606*/
191607static void fts5SegIterHashInit(
191608  Fts5Index *p,                   /* FTS5 backend */
191609  const u8 *pTerm, int nTerm,     /* Term to seek to */
191610  int flags,                      /* Mask of FTS5INDEX_XXX flags */
191611  Fts5SegIter *pIter              /* Object to populate */
191612){
191613  const u8 *pList = 0;
191614  int nList = 0;
191615  const u8 *z = 0;
191616  int n = 0;
191617
191618  assert( p->pHash );
191619  assert( p->rc==SQLITE_OK );
191620
191621  if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
191622    p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
191623    sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
191624    n = (z ? (int)strlen((const char*)z) : 0);
191625  }else{
191626    pIter->flags |= FTS5_SEGITER_ONETERM;
191627    sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
191628    z = pTerm;
191629    n = nTerm;
191630  }
191631
191632  if( pList ){
191633    Fts5Data *pLeaf;
191634    sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
191635    pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
191636    if( pLeaf==0 ) return;
191637    pLeaf->p = (u8*)pList;
191638    pLeaf->nn = pLeaf->szLeaf = nList;
191639    pIter->pLeaf = pLeaf;
191640    pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
191641    pIter->iEndofDoclist = pLeaf->nn;
191642
191643    if( flags & FTS5INDEX_QUERY_DESC ){
191644      pIter->flags |= FTS5_SEGITER_REVERSE;
191645      fts5SegIterReverseInitPage(p, pIter);
191646    }else{
191647      fts5SegIterLoadNPos(p, pIter);
191648    }
191649  }
191650
191651  fts5SegIterSetNext(p, pIter);
191652}
191653
191654/*
191655** Zero the iterator passed as the only argument.
191656*/
191657static void fts5SegIterClear(Fts5SegIter *pIter){
191658  fts5BufferFree(&pIter->term);
191659  fts5DataRelease(pIter->pLeaf);
191660  fts5DataRelease(pIter->pNextLeaf);
191661  fts5DlidxIterFree(pIter->pDlidx);
191662  sqlite3_free(pIter->aRowidOffset);
191663  memset(pIter, 0, sizeof(Fts5SegIter));
191664}
191665
191666#ifdef SQLITE_DEBUG
191667
191668/*
191669** This function is used as part of the big assert() procedure implemented by
191670** fts5AssertMultiIterSetup(). It ensures that the result currently stored
191671** in *pRes is the correct result of comparing the current positions of the
191672** two iterators.
191673*/
191674static void fts5AssertComparisonResult(
191675  Fts5Iter *pIter,
191676  Fts5SegIter *p1,
191677  Fts5SegIter *p2,
191678  Fts5CResult *pRes
191679){
191680  int i1 = p1 - pIter->aSeg;
191681  int i2 = p2 - pIter->aSeg;
191682
191683  if( p1->pLeaf || p2->pLeaf ){
191684    if( p1->pLeaf==0 ){
191685      assert( pRes->iFirst==i2 );
191686    }else if( p2->pLeaf==0 ){
191687      assert( pRes->iFirst==i1 );
191688    }else{
191689      int nMin = MIN(p1->term.n, p2->term.n);
191690      int res = memcmp(p1->term.p, p2->term.p, nMin);
191691      if( res==0 ) res = p1->term.n - p2->term.n;
191692
191693      if( res==0 ){
191694        assert( pRes->bTermEq==1 );
191695        assert( p1->iRowid!=p2->iRowid );
191696        res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
191697      }else{
191698        assert( pRes->bTermEq==0 );
191699      }
191700
191701      if( res<0 ){
191702        assert( pRes->iFirst==i1 );
191703      }else{
191704        assert( pRes->iFirst==i2 );
191705      }
191706    }
191707  }
191708}
191709
191710/*
191711** This function is a no-op unless SQLITE_DEBUG is defined when this module
191712** is compiled. In that case, this function is essentially an assert()
191713** statement used to verify that the contents of the pIter->aFirst[] array
191714** are correct.
191715*/
191716static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
191717  if( p->rc==SQLITE_OK ){
191718    Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
191719    int i;
191720
191721    assert( (pFirst->pLeaf==0)==pIter->base.bEof );
191722
191723    /* Check that pIter->iSwitchRowid is set correctly. */
191724    for(i=0; i<pIter->nSeg; i++){
191725      Fts5SegIter *p1 = &pIter->aSeg[i];
191726      assert( p1==pFirst
191727           || p1->pLeaf==0
191728           || fts5BufferCompare(&pFirst->term, &p1->term)
191729           || p1->iRowid==pIter->iSwitchRowid
191730           || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
191731      );
191732    }
191733
191734    for(i=0; i<pIter->nSeg; i+=2){
191735      Fts5SegIter *p1 = &pIter->aSeg[i];
191736      Fts5SegIter *p2 = &pIter->aSeg[i+1];
191737      Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
191738      fts5AssertComparisonResult(pIter, p1, p2, pRes);
191739    }
191740
191741    for(i=1; i<(pIter->nSeg / 2); i+=2){
191742      Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
191743      Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
191744      Fts5CResult *pRes = &pIter->aFirst[i];
191745      fts5AssertComparisonResult(pIter, p1, p2, pRes);
191746    }
191747  }
191748}
191749#else
191750# define fts5AssertMultiIterSetup(x,y)
191751#endif
191752
191753/*
191754** Do the comparison necessary to populate pIter->aFirst[iOut].
191755**
191756** If the returned value is non-zero, then it is the index of an entry
191757** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
191758** to a key that is a duplicate of another, higher priority,
191759** segment-iterator in the pSeg->aSeg[] array.
191760*/
191761static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
191762  int i1;                         /* Index of left-hand Fts5SegIter */
191763  int i2;                         /* Index of right-hand Fts5SegIter */
191764  int iRes;
191765  Fts5SegIter *p1;                /* Left-hand Fts5SegIter */
191766  Fts5SegIter *p2;                /* Right-hand Fts5SegIter */
191767  Fts5CResult *pRes = &pIter->aFirst[iOut];
191768
191769  assert( iOut<pIter->nSeg && iOut>0 );
191770  assert( pIter->bRev==0 || pIter->bRev==1 );
191771
191772  if( iOut>=(pIter->nSeg/2) ){
191773    i1 = (iOut - pIter->nSeg/2) * 2;
191774    i2 = i1 + 1;
191775  }else{
191776    i1 = pIter->aFirst[iOut*2].iFirst;
191777    i2 = pIter->aFirst[iOut*2+1].iFirst;
191778  }
191779  p1 = &pIter->aSeg[i1];
191780  p2 = &pIter->aSeg[i2];
191781
191782  pRes->bTermEq = 0;
191783  if( p1->pLeaf==0 ){           /* If p1 is at EOF */
191784    iRes = i2;
191785  }else if( p2->pLeaf==0 ){     /* If p2 is at EOF */
191786    iRes = i1;
191787  }else{
191788    int res = fts5BufferCompare(&p1->term, &p2->term);
191789    if( res==0 ){
191790      assert( i2>i1 );
191791      assert( i2!=0 );
191792      pRes->bTermEq = 1;
191793      if( p1->iRowid==p2->iRowid ){
191794        p1->bDel = p2->bDel;
191795        return i2;
191796      }
191797      res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
191798    }
191799    assert( res!=0 );
191800    if( res<0 ){
191801      iRes = i1;
191802    }else{
191803      iRes = i2;
191804    }
191805  }
191806
191807  pRes->iFirst = (u16)iRes;
191808  return 0;
191809}
191810
191811/*
191812** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
191813** It is an error if leaf iLeafPgno does not exist or contains no rowids.
191814*/
191815static void fts5SegIterGotoPage(
191816  Fts5Index *p,                   /* FTS5 backend object */
191817  Fts5SegIter *pIter,             /* Iterator to advance */
191818  int iLeafPgno
191819){
191820  assert( iLeafPgno>pIter->iLeafPgno );
191821
191822  if( iLeafPgno>pIter->pSeg->pgnoLast ){
191823    p->rc = FTS5_CORRUPT;
191824  }else{
191825    fts5DataRelease(pIter->pNextLeaf);
191826    pIter->pNextLeaf = 0;
191827    pIter->iLeafPgno = iLeafPgno-1;
191828    fts5SegIterNextPage(p, pIter);
191829    assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
191830
191831    if( p->rc==SQLITE_OK ){
191832      int iOff;
191833      u8 *a = pIter->pLeaf->p;
191834      int n = pIter->pLeaf->szLeaf;
191835
191836      iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
191837      if( iOff<4 || iOff>=n ){
191838        p->rc = FTS5_CORRUPT;
191839      }else{
191840        iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
191841        pIter->iLeafOffset = iOff;
191842        fts5SegIterLoadNPos(p, pIter);
191843      }
191844    }
191845  }
191846}
191847
191848/*
191849** Advance the iterator passed as the second argument until it is at or
191850** past rowid iFrom. Regardless of the value of iFrom, the iterator is
191851** always advanced at least once.
191852*/
191853static void fts5SegIterNextFrom(
191854  Fts5Index *p,                   /* FTS5 backend object */
191855  Fts5SegIter *pIter,             /* Iterator to advance */
191856  i64 iMatch                      /* Advance iterator at least this far */
191857){
191858  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
191859  Fts5DlidxIter *pDlidx = pIter->pDlidx;
191860  int iLeafPgno = pIter->iLeafPgno;
191861  int bMove = 1;
191862
191863  assert( pIter->flags & FTS5_SEGITER_ONETERM );
191864  assert( pIter->pDlidx );
191865  assert( pIter->pLeaf );
191866
191867  if( bRev==0 ){
191868    while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
191869      iLeafPgno = fts5DlidxIterPgno(pDlidx);
191870      fts5DlidxIterNext(p, pDlidx);
191871    }
191872    assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
191873    if( iLeafPgno>pIter->iLeafPgno ){
191874      fts5SegIterGotoPage(p, pIter, iLeafPgno);
191875      bMove = 0;
191876    }
191877  }else{
191878    assert( pIter->pNextLeaf==0 );
191879    assert( iMatch<pIter->iRowid );
191880    while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
191881      fts5DlidxIterPrev(p, pDlidx);
191882    }
191883    iLeafPgno = fts5DlidxIterPgno(pDlidx);
191884
191885    assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
191886
191887    if( iLeafPgno<pIter->iLeafPgno ){
191888      pIter->iLeafPgno = iLeafPgno+1;
191889      fts5SegIterReverseNewPage(p, pIter);
191890      bMove = 0;
191891    }
191892  }
191893
191894  do{
191895    if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
191896    if( pIter->pLeaf==0 ) break;
191897    if( bRev==0 && pIter->iRowid>=iMatch ) break;
191898    if( bRev!=0 && pIter->iRowid<=iMatch ) break;
191899    bMove = 1;
191900  }while( p->rc==SQLITE_OK );
191901}
191902
191903
191904/*
191905** Free the iterator object passed as the second argument.
191906*/
191907static void fts5MultiIterFree(Fts5Iter *pIter){
191908  if( pIter ){
191909    int i;
191910    for(i=0; i<pIter->nSeg; i++){
191911      fts5SegIterClear(&pIter->aSeg[i]);
191912    }
191913    fts5StructureRelease(pIter->pStruct);
191914    fts5BufferFree(&pIter->poslist);
191915    sqlite3_free(pIter);
191916  }
191917}
191918
191919static void fts5MultiIterAdvanced(
191920  Fts5Index *p,                   /* FTS5 backend to iterate within */
191921  Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
191922  int iChanged,                   /* Index of sub-iterator just advanced */
191923  int iMinset                     /* Minimum entry in aFirst[] to set */
191924){
191925  int i;
191926  for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
191927    int iEq;
191928    if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
191929      Fts5SegIter *pSeg = &pIter->aSeg[iEq];
191930      assert( p->rc==SQLITE_OK );
191931      pSeg->xNext(p, pSeg, 0);
191932      i = pIter->nSeg + iEq;
191933    }
191934  }
191935}
191936
191937/*
191938** Sub-iterator iChanged of iterator pIter has just been advanced. It still
191939** points to the same term though - just a different rowid. This function
191940** attempts to update the contents of the pIter->aFirst[] accordingly.
191941** If it does so successfully, 0 is returned. Otherwise 1.
191942**
191943** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
191944** on the iterator instead. That function does the same as this one, except
191945** that it deals with more complicated cases as well.
191946*/
191947static int fts5MultiIterAdvanceRowid(
191948  Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
191949  int iChanged,                   /* Index of sub-iterator just advanced */
191950  Fts5SegIter **ppFirst
191951){
191952  Fts5SegIter *pNew = &pIter->aSeg[iChanged];
191953
191954  if( pNew->iRowid==pIter->iSwitchRowid
191955   || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
191956  ){
191957    int i;
191958    Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
191959    pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
191960    for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
191961      Fts5CResult *pRes = &pIter->aFirst[i];
191962
191963      assert( pNew->pLeaf );
191964      assert( pRes->bTermEq==0 || pOther->pLeaf );
191965
191966      if( pRes->bTermEq ){
191967        if( pNew->iRowid==pOther->iRowid ){
191968          return 1;
191969        }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
191970          pIter->iSwitchRowid = pOther->iRowid;
191971          pNew = pOther;
191972        }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
191973          pIter->iSwitchRowid = pOther->iRowid;
191974        }
191975      }
191976      pRes->iFirst = (u16)(pNew - pIter->aSeg);
191977      if( i==1 ) break;
191978
191979      pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
191980    }
191981  }
191982
191983  *ppFirst = pNew;
191984  return 0;
191985}
191986
191987/*
191988** Set the pIter->bEof variable based on the state of the sub-iterators.
191989*/
191990static void fts5MultiIterSetEof(Fts5Iter *pIter){
191991  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
191992  pIter->base.bEof = pSeg->pLeaf==0;
191993  pIter->iSwitchRowid = pSeg->iRowid;
191994}
191995
191996/*
191997** Move the iterator to the next entry.
191998**
191999** If an error occurs, an error code is left in Fts5Index.rc. It is not
192000** considered an error if the iterator reaches EOF, or if it is already at
192001** EOF when this function is called.
192002*/
192003static void fts5MultiIterNext(
192004  Fts5Index *p,
192005  Fts5Iter *pIter,
192006  int bFrom,                      /* True if argument iFrom is valid */
192007  i64 iFrom                       /* Advance at least as far as this */
192008){
192009  int bUseFrom = bFrom;
192010  assert( pIter->base.bEof==0 );
192011  while( p->rc==SQLITE_OK ){
192012    int iFirst = pIter->aFirst[1].iFirst;
192013    int bNewTerm = 0;
192014    Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
192015    assert( p->rc==SQLITE_OK );
192016    if( bUseFrom && pSeg->pDlidx ){
192017      fts5SegIterNextFrom(p, pSeg, iFrom);
192018    }else{
192019      pSeg->xNext(p, pSeg, &bNewTerm);
192020    }
192021
192022    if( pSeg->pLeaf==0 || bNewTerm
192023     || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
192024    ){
192025      fts5MultiIterAdvanced(p, pIter, iFirst, 1);
192026      fts5MultiIterSetEof(pIter);
192027      pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
192028      if( pSeg->pLeaf==0 ) return;
192029    }
192030
192031    fts5AssertMultiIterSetup(p, pIter);
192032    assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
192033    if( pIter->bSkipEmpty==0 || pSeg->nPos ){
192034      pIter->xSetOutputs(pIter, pSeg);
192035      return;
192036    }
192037    bUseFrom = 0;
192038  }
192039}
192040
192041static void fts5MultiIterNext2(
192042  Fts5Index *p,
192043  Fts5Iter *pIter,
192044  int *pbNewTerm                  /* OUT: True if *might* be new term */
192045){
192046  assert( pIter->bSkipEmpty );
192047  if( p->rc==SQLITE_OK ){
192048    do {
192049      int iFirst = pIter->aFirst[1].iFirst;
192050      Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
192051      int bNewTerm = 0;
192052
192053      assert( p->rc==SQLITE_OK );
192054      pSeg->xNext(p, pSeg, &bNewTerm);
192055      if( pSeg->pLeaf==0 || bNewTerm
192056       || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
192057      ){
192058        fts5MultiIterAdvanced(p, pIter, iFirst, 1);
192059        fts5MultiIterSetEof(pIter);
192060        *pbNewTerm = 1;
192061      }else{
192062        *pbNewTerm = 0;
192063      }
192064      fts5AssertMultiIterSetup(p, pIter);
192065
192066    }while( fts5MultiIterIsEmpty(p, pIter) );
192067  }
192068}
192069
192070static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
192071  UNUSED_PARAM2(pUnused1, pUnused2);
192072}
192073
192074static Fts5Iter *fts5MultiIterAlloc(
192075  Fts5Index *p,                   /* FTS5 backend to iterate within */
192076  int nSeg
192077){
192078  Fts5Iter *pNew;
192079  int nSlot;                      /* Power of two >= nSeg */
192080
192081  for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
192082  pNew = fts5IdxMalloc(p,
192083      sizeof(Fts5Iter) +                  /* pNew */
192084      sizeof(Fts5SegIter) * (nSlot-1) +   /* pNew->aSeg[] */
192085      sizeof(Fts5CResult) * nSlot         /* pNew->aFirst[] */
192086  );
192087  if( pNew ){
192088    pNew->nSeg = nSlot;
192089    pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
192090    pNew->pIndex = p;
192091    pNew->xSetOutputs = fts5IterSetOutputs_Noop;
192092  }
192093  return pNew;
192094}
192095
192096static void fts5PoslistCallback(
192097  Fts5Index *pUnused,
192098  void *pContext,
192099  const u8 *pChunk, int nChunk
192100){
192101  UNUSED_PARAM(pUnused);
192102  assert_nc( nChunk>=0 );
192103  if( nChunk>0 ){
192104    fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
192105  }
192106}
192107
192108typedef struct PoslistCallbackCtx PoslistCallbackCtx;
192109struct PoslistCallbackCtx {
192110  Fts5Buffer *pBuf;               /* Append to this buffer */
192111  Fts5Colset *pColset;            /* Restrict matches to this column */
192112  int eState;                     /* See above */
192113};
192114
192115typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
192116struct PoslistOffsetsCtx {
192117  Fts5Buffer *pBuf;               /* Append to this buffer */
192118  Fts5Colset *pColset;            /* Restrict matches to this column */
192119  int iRead;
192120  int iWrite;
192121};
192122
192123/*
192124** TODO: Make this more efficient!
192125*/
192126static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
192127  int i;
192128  for(i=0; i<pColset->nCol; i++){
192129    if( pColset->aiCol[i]==iCol ) return 1;
192130  }
192131  return 0;
192132}
192133
192134static void fts5PoslistOffsetsCallback(
192135  Fts5Index *pUnused,
192136  void *pContext,
192137  const u8 *pChunk, int nChunk
192138){
192139  PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
192140  UNUSED_PARAM(pUnused);
192141  assert_nc( nChunk>=0 );
192142  if( nChunk>0 ){
192143    int i = 0;
192144    while( i<nChunk ){
192145      int iVal;
192146      i += fts5GetVarint32(&pChunk[i], iVal);
192147      iVal += pCtx->iRead - 2;
192148      pCtx->iRead = iVal;
192149      if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
192150        fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
192151        pCtx->iWrite = iVal;
192152      }
192153    }
192154  }
192155}
192156
192157static void fts5PoslistFilterCallback(
192158  Fts5Index *pUnused,
192159  void *pContext,
192160  const u8 *pChunk, int nChunk
192161){
192162  PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
192163  UNUSED_PARAM(pUnused);
192164  assert_nc( nChunk>=0 );
192165  if( nChunk>0 ){
192166    /* Search through to find the first varint with value 1. This is the
192167    ** start of the next columns hits. */
192168    int i = 0;
192169    int iStart = 0;
192170
192171    if( pCtx->eState==2 ){
192172      int iCol;
192173      fts5FastGetVarint32(pChunk, i, iCol);
192174      if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
192175        pCtx->eState = 1;
192176        fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
192177      }else{
192178        pCtx->eState = 0;
192179      }
192180    }
192181
192182    do {
192183      while( i<nChunk && pChunk[i]!=0x01 ){
192184        while( pChunk[i] & 0x80 ) i++;
192185        i++;
192186      }
192187      if( pCtx->eState ){
192188        fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
192189      }
192190      if( i<nChunk ){
192191        int iCol;
192192        iStart = i;
192193        i++;
192194        if( i>=nChunk ){
192195          pCtx->eState = 2;
192196        }else{
192197          fts5FastGetVarint32(pChunk, i, iCol);
192198          pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
192199          if( pCtx->eState ){
192200            fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
192201            iStart = i;
192202          }
192203        }
192204      }
192205    }while( i<nChunk );
192206  }
192207}
192208
192209static void fts5ChunkIterate(
192210  Fts5Index *p,                   /* Index object */
192211  Fts5SegIter *pSeg,              /* Poslist of this iterator */
192212  void *pCtx,                     /* Context pointer for xChunk callback */
192213  void (*xChunk)(Fts5Index*, void*, const u8*, int)
192214){
192215  int nRem = pSeg->nPos;          /* Number of bytes still to come */
192216  Fts5Data *pData = 0;
192217  u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
192218  int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
192219  int pgno = pSeg->iLeafPgno;
192220  int pgnoSave = 0;
192221
192222  /* This function does notmwork with detail=none databases. */
192223  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
192224
192225  if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
192226    pgnoSave = pgno+1;
192227  }
192228
192229  while( 1 ){
192230    xChunk(p, pCtx, pChunk, nChunk);
192231    nRem -= nChunk;
192232    fts5DataRelease(pData);
192233    if( nRem<=0 ){
192234      break;
192235    }else{
192236      pgno++;
192237      pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
192238      if( pData==0 ) break;
192239      pChunk = &pData->p[4];
192240      nChunk = MIN(nRem, pData->szLeaf - 4);
192241      if( pgno==pgnoSave ){
192242        assert( pSeg->pNextLeaf==0 );
192243        pSeg->pNextLeaf = pData;
192244        pData = 0;
192245      }
192246    }
192247  }
192248}
192249
192250/*
192251** Iterator pIter currently points to a valid entry (not EOF). This
192252** function appends the position list data for the current entry to
192253** buffer pBuf. It does not make a copy of the position-list size
192254** field.
192255*/
192256static void fts5SegiterPoslist(
192257  Fts5Index *p,
192258  Fts5SegIter *pSeg,
192259  Fts5Colset *pColset,
192260  Fts5Buffer *pBuf
192261){
192262  if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
192263    if( pColset==0 ){
192264      fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
192265    }else{
192266      if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
192267        PoslistCallbackCtx sCtx;
192268        sCtx.pBuf = pBuf;
192269        sCtx.pColset = pColset;
192270        sCtx.eState = fts5IndexColsetTest(pColset, 0);
192271        assert( sCtx.eState==0 || sCtx.eState==1 );
192272        fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
192273      }else{
192274        PoslistOffsetsCtx sCtx;
192275        memset(&sCtx, 0, sizeof(sCtx));
192276        sCtx.pBuf = pBuf;
192277        sCtx.pColset = pColset;
192278        fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
192279      }
192280    }
192281  }
192282}
192283
192284/*
192285** IN/OUT parameter (*pa) points to a position list n bytes in size. If
192286** the position list contains entries for column iCol, then (*pa) is set
192287** to point to the sub-position-list for that column and the number of
192288** bytes in it returned. Or, if the argument position list does not
192289** contain any entries for column iCol, return 0.
192290*/
192291static int fts5IndexExtractCol(
192292  const u8 **pa,                  /* IN/OUT: Pointer to poslist */
192293  int n,                          /* IN: Size of poslist in bytes */
192294  int iCol                        /* Column to extract from poslist */
192295){
192296  int iCurrent = 0;               /* Anything before the first 0x01 is col 0 */
192297  const u8 *p = *pa;
192298  const u8 *pEnd = &p[n];         /* One byte past end of position list */
192299
192300  while( iCol>iCurrent ){
192301    /* Advance pointer p until it points to pEnd or an 0x01 byte that is
192302    ** not part of a varint. Note that it is not possible for a negative
192303    ** or extremely large varint to occur within an uncorrupted position
192304    ** list. So the last byte of each varint may be assumed to have a clear
192305    ** 0x80 bit.  */
192306    while( *p!=0x01 ){
192307      while( *p++ & 0x80 );
192308      if( p>=pEnd ) return 0;
192309    }
192310    *pa = p++;
192311    iCurrent = *p++;
192312    if( iCurrent & 0x80 ){
192313      p--;
192314      p += fts5GetVarint32(p, iCurrent);
192315    }
192316  }
192317  if( iCol!=iCurrent ) return 0;
192318
192319  /* Advance pointer p until it points to pEnd or an 0x01 byte that is
192320  ** not part of a varint */
192321  while( p<pEnd && *p!=0x01 ){
192322    while( *p++ & 0x80 );
192323  }
192324
192325  return p - (*pa);
192326}
192327
192328static int fts5IndexExtractColset (
192329  Fts5Colset *pColset,            /* Colset to filter on */
192330  const u8 *pPos, int nPos,       /* Position list */
192331  Fts5Buffer *pBuf                /* Output buffer */
192332){
192333  int rc = SQLITE_OK;
192334  int i;
192335
192336  fts5BufferZero(pBuf);
192337  for(i=0; i<pColset->nCol; i++){
192338    const u8 *pSub = pPos;
192339    int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
192340    if( nSub ){
192341      fts5BufferAppendBlob(&rc, pBuf, nSub, pSub);
192342    }
192343  }
192344  return rc;
192345}
192346
192347/*
192348** xSetOutputs callback used by detail=none tables.
192349*/
192350static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
192351  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
192352  pIter->base.iRowid = pSeg->iRowid;
192353  pIter->base.nData = pSeg->nPos;
192354}
192355
192356/*
192357** xSetOutputs callback used by detail=full and detail=col tables when no
192358** column filters are specified.
192359*/
192360static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
192361  pIter->base.iRowid = pSeg->iRowid;
192362  pIter->base.nData = pSeg->nPos;
192363
192364  assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
192365  assert( pIter->pColset==0 );
192366
192367  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
192368    /* All data is stored on the current page. Populate the output
192369    ** variables to point into the body of the page object. */
192370    pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
192371  }else{
192372    /* The data is distributed over two or more pages. Copy it into the
192373    ** Fts5Iter.poslist buffer and then set the output pointer to point
192374    ** to this buffer.  */
192375    fts5BufferZero(&pIter->poslist);
192376    fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
192377    pIter->base.pData = pIter->poslist.p;
192378  }
192379}
192380
192381/*
192382** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
192383** against no columns at all).
192384*/
192385static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
192386  UNUSED_PARAM(pSeg);
192387  pIter->base.nData = 0;
192388}
192389
192390/*
192391** xSetOutputs callback used by detail=col when there is a column filter
192392** and there are 100 or more columns. Also called as a fallback from
192393** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
192394*/
192395static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
192396  fts5BufferZero(&pIter->poslist);
192397  fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
192398  pIter->base.iRowid = pSeg->iRowid;
192399  pIter->base.pData = pIter->poslist.p;
192400  pIter->base.nData = pIter->poslist.n;
192401}
192402
192403/*
192404** xSetOutputs callback used when:
192405**
192406**   * detail=col,
192407**   * there is a column filter, and
192408**   * the table contains 100 or fewer columns.
192409**
192410** The last point is to ensure all column numbers are stored as
192411** single-byte varints.
192412*/
192413static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
192414
192415  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
192416  assert( pIter->pColset );
192417
192418  if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
192419    fts5IterSetOutputs_Col(pIter, pSeg);
192420  }else{
192421    u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
192422    u8 *pEnd = (u8*)&a[pSeg->nPos];
192423    int iPrev = 0;
192424    int *aiCol = pIter->pColset->aiCol;
192425    int *aiColEnd = &aiCol[pIter->pColset->nCol];
192426
192427    u8 *aOut = pIter->poslist.p;
192428    int iPrevOut = 0;
192429
192430    pIter->base.iRowid = pSeg->iRowid;
192431
192432    while( a<pEnd ){
192433      iPrev += (int)a++[0] - 2;
192434      while( *aiCol<iPrev ){
192435        aiCol++;
192436        if( aiCol==aiColEnd ) goto setoutputs_col_out;
192437      }
192438      if( *aiCol==iPrev ){
192439        *aOut++ = (u8)((iPrev - iPrevOut) + 2);
192440        iPrevOut = iPrev;
192441      }
192442    }
192443
192444setoutputs_col_out:
192445    pIter->base.pData = pIter->poslist.p;
192446    pIter->base.nData = aOut - pIter->poslist.p;
192447  }
192448}
192449
192450/*
192451** xSetOutputs callback used by detail=full when there is a column filter.
192452*/
192453static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
192454  Fts5Colset *pColset = pIter->pColset;
192455  pIter->base.iRowid = pSeg->iRowid;
192456
192457  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
192458  assert( pColset );
192459
192460  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
192461    /* All data is stored on the current page. Populate the output
192462    ** variables to point into the body of the page object. */
192463    const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
192464    if( pColset->nCol==1 ){
192465      pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
192466      pIter->base.pData = a;
192467    }else{
192468      fts5BufferZero(&pIter->poslist);
192469      fts5IndexExtractColset(pColset, a, pSeg->nPos, &pIter->poslist);
192470      pIter->base.pData = pIter->poslist.p;
192471      pIter->base.nData = pIter->poslist.n;
192472    }
192473  }else{
192474    /* The data is distributed over two or more pages. Copy it into the
192475    ** Fts5Iter.poslist buffer and then set the output pointer to point
192476    ** to this buffer.  */
192477    fts5BufferZero(&pIter->poslist);
192478    fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
192479    pIter->base.pData = pIter->poslist.p;
192480    pIter->base.nData = pIter->poslist.n;
192481  }
192482}
192483
192484static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
192485  if( *pRc==SQLITE_OK ){
192486    Fts5Config *pConfig = pIter->pIndex->pConfig;
192487    if( pConfig->eDetail==FTS5_DETAIL_NONE ){
192488      pIter->xSetOutputs = fts5IterSetOutputs_None;
192489    }
192490
192491    else if( pIter->pColset==0 ){
192492      pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
192493    }
192494
192495    else if( pIter->pColset->nCol==0 ){
192496      pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
192497    }
192498
192499    else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
192500      pIter->xSetOutputs = fts5IterSetOutputs_Full;
192501    }
192502
192503    else{
192504      assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
192505      if( pConfig->nCol<=100 ){
192506        pIter->xSetOutputs = fts5IterSetOutputs_Col100;
192507        sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
192508      }else{
192509        pIter->xSetOutputs = fts5IterSetOutputs_Col;
192510      }
192511    }
192512  }
192513}
192514
192515
192516/*
192517** Allocate a new Fts5Iter object.
192518**
192519** The new object will be used to iterate through data in structure pStruct.
192520** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
192521** is zero or greater, data from the first nSegment segments on level iLevel
192522** is merged.
192523**
192524** The iterator initially points to the first term/rowid entry in the
192525** iterated data.
192526*/
192527static void fts5MultiIterNew(
192528  Fts5Index *p,                   /* FTS5 backend to iterate within */
192529  Fts5Structure *pStruct,         /* Structure of specific index */
192530  int flags,                      /* FTS5INDEX_QUERY_XXX flags */
192531  Fts5Colset *pColset,            /* Colset to filter on (or NULL) */
192532  const u8 *pTerm, int nTerm,     /* Term to seek to (or NULL/0) */
192533  int iLevel,                     /* Level to iterate (-1 for all) */
192534  int nSegment,                   /* Number of segments to merge (iLevel>=0) */
192535  Fts5Iter **ppOut                /* New object */
192536){
192537  int nSeg = 0;                   /* Number of segment-iters in use */
192538  int iIter = 0;                  /* */
192539  int iSeg;                       /* Used to iterate through segments */
192540  Fts5StructureLevel *pLvl;
192541  Fts5Iter *pNew;
192542
192543  assert( (pTerm==0 && nTerm==0) || iLevel<0 );
192544
192545  /* Allocate space for the new multi-seg-iterator. */
192546  if( p->rc==SQLITE_OK ){
192547    if( iLevel<0 ){
192548      assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
192549      nSeg = pStruct->nSegment;
192550      nSeg += (p->pHash ? 1 : 0);
192551    }else{
192552      nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
192553    }
192554  }
192555  *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
192556  if( pNew==0 ) return;
192557  pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
192558  pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
192559  pNew->pStruct = pStruct;
192560  pNew->pColset = pColset;
192561  fts5StructureRef(pStruct);
192562  if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
192563    fts5IterSetOutputCb(&p->rc, pNew);
192564  }
192565
192566  /* Initialize each of the component segment iterators. */
192567  if( p->rc==SQLITE_OK ){
192568    if( iLevel<0 ){
192569      Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
192570      if( p->pHash ){
192571        /* Add a segment iterator for the current contents of the hash table. */
192572        Fts5SegIter *pIter = &pNew->aSeg[iIter++];
192573        fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
192574      }
192575      for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
192576        for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
192577          Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
192578          Fts5SegIter *pIter = &pNew->aSeg[iIter++];
192579          if( pTerm==0 ){
192580            fts5SegIterInit(p, pSeg, pIter);
192581          }else{
192582            fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
192583          }
192584        }
192585      }
192586    }else{
192587      pLvl = &pStruct->aLevel[iLevel];
192588      for(iSeg=nSeg-1; iSeg>=0; iSeg--){
192589        fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
192590      }
192591    }
192592    assert( iIter==nSeg );
192593  }
192594
192595  /* If the above was successful, each component iterators now points
192596  ** to the first entry in its segment. In this case initialize the
192597  ** aFirst[] array. Or, if an error has occurred, free the iterator
192598  ** object and set the output variable to NULL.  */
192599  if( p->rc==SQLITE_OK ){
192600    for(iIter=pNew->nSeg-1; iIter>0; iIter--){
192601      int iEq;
192602      if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
192603        Fts5SegIter *pSeg = &pNew->aSeg[iEq];
192604        if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
192605        fts5MultiIterAdvanced(p, pNew, iEq, iIter);
192606      }
192607    }
192608    fts5MultiIterSetEof(pNew);
192609    fts5AssertMultiIterSetup(p, pNew);
192610
192611    if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
192612      fts5MultiIterNext(p, pNew, 0, 0);
192613    }else if( pNew->base.bEof==0 ){
192614      Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
192615      pNew->xSetOutputs(pNew, pSeg);
192616    }
192617
192618  }else{
192619    fts5MultiIterFree(pNew);
192620    *ppOut = 0;
192621  }
192622}
192623
192624/*
192625** Create an Fts5Iter that iterates through the doclist provided
192626** as the second argument.
192627*/
192628static void fts5MultiIterNew2(
192629  Fts5Index *p,                   /* FTS5 backend to iterate within */
192630  Fts5Data *pData,                /* Doclist to iterate through */
192631  int bDesc,                      /* True for descending rowid order */
192632  Fts5Iter **ppOut                /* New object */
192633){
192634  Fts5Iter *pNew;
192635  pNew = fts5MultiIterAlloc(p, 2);
192636  if( pNew ){
192637    Fts5SegIter *pIter = &pNew->aSeg[1];
192638
192639    pIter->flags = FTS5_SEGITER_ONETERM;
192640    if( pData->szLeaf>0 ){
192641      pIter->pLeaf = pData;
192642      pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
192643      pIter->iEndofDoclist = pData->nn;
192644      pNew->aFirst[1].iFirst = 1;
192645      if( bDesc ){
192646        pNew->bRev = 1;
192647        pIter->flags |= FTS5_SEGITER_REVERSE;
192648        fts5SegIterReverseInitPage(p, pIter);
192649      }else{
192650        fts5SegIterLoadNPos(p, pIter);
192651      }
192652      pData = 0;
192653    }else{
192654      pNew->base.bEof = 1;
192655    }
192656    fts5SegIterSetNext(p, pIter);
192657
192658    *ppOut = pNew;
192659  }
192660
192661  fts5DataRelease(pData);
192662}
192663
192664/*
192665** Return true if the iterator is at EOF or if an error has occurred.
192666** False otherwise.
192667*/
192668static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
192669  assert( p->rc
192670      || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
192671  );
192672  return (p->rc || pIter->base.bEof);
192673}
192674
192675/*
192676** Return the rowid of the entry that the iterator currently points
192677** to. If the iterator points to EOF when this function is called the
192678** results are undefined.
192679*/
192680static i64 fts5MultiIterRowid(Fts5Iter *pIter){
192681  assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
192682  return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
192683}
192684
192685/*
192686** Move the iterator to the next entry at or following iMatch.
192687*/
192688static void fts5MultiIterNextFrom(
192689  Fts5Index *p,
192690  Fts5Iter *pIter,
192691  i64 iMatch
192692){
192693  while( 1 ){
192694    i64 iRowid;
192695    fts5MultiIterNext(p, pIter, 1, iMatch);
192696    if( fts5MultiIterEof(p, pIter) ) break;
192697    iRowid = fts5MultiIterRowid(pIter);
192698    if( pIter->bRev==0 && iRowid>=iMatch ) break;
192699    if( pIter->bRev!=0 && iRowid<=iMatch ) break;
192700  }
192701}
192702
192703/*
192704** Return a pointer to a buffer containing the term associated with the
192705** entry that the iterator currently points to.
192706*/
192707static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
192708  Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
192709  *pn = p->term.n;
192710  return p->term.p;
192711}
192712
192713/*
192714** Allocate a new segment-id for the structure pStruct. The new segment
192715** id must be between 1 and 65335 inclusive, and must not be used by
192716** any currently existing segment. If a free segment id cannot be found,
192717** SQLITE_FULL is returned.
192718**
192719** If an error has already occurred, this function is a no-op. 0 is
192720** returned in this case.
192721*/
192722static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
192723  int iSegid = 0;
192724
192725  if( p->rc==SQLITE_OK ){
192726    if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
192727      p->rc = SQLITE_FULL;
192728    }else{
192729      /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
192730      ** array is 63 elements, or 252 bytes, in size.  */
192731      u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
192732      int iLvl, iSeg;
192733      int i;
192734      u32 mask;
192735      memset(aUsed, 0, sizeof(aUsed));
192736      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
192737        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
192738          int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
192739          if( iId<=FTS5_MAX_SEGMENT ){
192740            aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
192741          }
192742        }
192743      }
192744
192745      for(i=0; aUsed[i]==0xFFFFFFFF; i++);
192746      mask = aUsed[i];
192747      for(iSegid=0; mask & (1 << iSegid); iSegid++);
192748      iSegid += 1 + i*32;
192749
192750#ifdef SQLITE_DEBUG
192751      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
192752        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
192753          assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
192754        }
192755      }
192756      assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
192757
192758      {
192759        sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
192760        if( p->rc==SQLITE_OK ){
192761          u8 aBlob[2] = {0xff, 0xff};
192762          sqlite3_bind_int(pIdxSelect, 1, iSegid);
192763          sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
192764          assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
192765          p->rc = sqlite3_reset(pIdxSelect);
192766        }
192767      }
192768#endif
192769    }
192770  }
192771
192772  return iSegid;
192773}
192774
192775/*
192776** Discard all data currently cached in the hash-tables.
192777*/
192778static void fts5IndexDiscardData(Fts5Index *p){
192779  assert( p->pHash || p->nPendingData==0 );
192780  if( p->pHash ){
192781    sqlite3Fts5HashClear(p->pHash);
192782    p->nPendingData = 0;
192783  }
192784}
192785
192786/*
192787** Return the size of the prefix, in bytes, that buffer
192788** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
192789**
192790** Buffer (pNew/<length-unknown>) is guaranteed to be greater
192791** than buffer (pOld/nOld).
192792*/
192793static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
192794  int i;
192795  for(i=0; i<nOld; i++){
192796    if( pOld[i]!=pNew[i] ) break;
192797  }
192798  return i;
192799}
192800
192801static void fts5WriteDlidxClear(
192802  Fts5Index *p,
192803  Fts5SegWriter *pWriter,
192804  int bFlush                      /* If true, write dlidx to disk */
192805){
192806  int i;
192807  assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
192808  for(i=0; i<pWriter->nDlidx; i++){
192809    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
192810    if( pDlidx->buf.n==0 ) break;
192811    if( bFlush ){
192812      assert( pDlidx->pgno!=0 );
192813      fts5DataWrite(p,
192814          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
192815          pDlidx->buf.p, pDlidx->buf.n
192816      );
192817    }
192818    sqlite3Fts5BufferZero(&pDlidx->buf);
192819    pDlidx->bPrevValid = 0;
192820  }
192821}
192822
192823/*
192824** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
192825** Any new array elements are zeroed before returning.
192826*/
192827static int fts5WriteDlidxGrow(
192828  Fts5Index *p,
192829  Fts5SegWriter *pWriter,
192830  int nLvl
192831){
192832  if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
192833    Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
192834        pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
192835    );
192836    if( aDlidx==0 ){
192837      p->rc = SQLITE_NOMEM;
192838    }else{
192839      int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
192840      memset(&aDlidx[pWriter->nDlidx], 0, nByte);
192841      pWriter->aDlidx = aDlidx;
192842      pWriter->nDlidx = nLvl;
192843    }
192844  }
192845  return p->rc;
192846}
192847
192848/*
192849** If the current doclist-index accumulating in pWriter->aDlidx[] is large
192850** enough, flush it to disk and return 1. Otherwise discard it and return
192851** zero.
192852*/
192853static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
192854  int bFlag = 0;
192855
192856  /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
192857  ** to the database, also write the doclist-index to disk.  */
192858  if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
192859    bFlag = 1;
192860  }
192861  fts5WriteDlidxClear(p, pWriter, bFlag);
192862  pWriter->nEmpty = 0;
192863  return bFlag;
192864}
192865
192866/*
192867** This function is called whenever processing of the doclist for the
192868** last term on leaf page (pWriter->iBtPage) is completed.
192869**
192870** The doclist-index for that term is currently stored in-memory within the
192871** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
192872** writes it out to disk. Or, if it is too small to bother with, discards
192873** it.
192874**
192875** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
192876*/
192877static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
192878  int bFlag;
192879
192880  assert( pWriter->iBtPage || pWriter->nEmpty==0 );
192881  if( pWriter->iBtPage==0 ) return;
192882  bFlag = fts5WriteFlushDlidx(p, pWriter);
192883
192884  if( p->rc==SQLITE_OK ){
192885    const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
192886    /* The following was already done in fts5WriteInit(): */
192887    /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
192888    sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
192889    sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
192890    sqlite3_step(p->pIdxWriter);
192891    p->rc = sqlite3_reset(p->pIdxWriter);
192892  }
192893  pWriter->iBtPage = 0;
192894}
192895
192896/*
192897** This is called once for each leaf page except the first that contains
192898** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
192899** is larger than all terms written to earlier leaves, and equal to or
192900** smaller than the first term on the new leaf.
192901**
192902** If an error occurs, an error code is left in Fts5Index.rc. If an error
192903** has already occurred when this function is called, it is a no-op.
192904*/
192905static void fts5WriteBtreeTerm(
192906  Fts5Index *p,                   /* FTS5 backend object */
192907  Fts5SegWriter *pWriter,         /* Writer object */
192908  int nTerm, const u8 *pTerm      /* First term on new page */
192909){
192910  fts5WriteFlushBtree(p, pWriter);
192911  fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
192912  pWriter->iBtPage = pWriter->writer.pgno;
192913}
192914
192915/*
192916** This function is called when flushing a leaf page that contains no
192917** terms at all to disk.
192918*/
192919static void fts5WriteBtreeNoTerm(
192920  Fts5Index *p,                   /* FTS5 backend object */
192921  Fts5SegWriter *pWriter          /* Writer object */
192922){
192923  /* If there were no rowids on the leaf page either and the doclist-index
192924  ** has already been started, append an 0x00 byte to it.  */
192925  if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
192926    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
192927    assert( pDlidx->bPrevValid );
192928    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
192929  }
192930
192931  /* Increment the "number of sequential leaves without a term" counter. */
192932  pWriter->nEmpty++;
192933}
192934
192935static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
192936  i64 iRowid;
192937  int iOff;
192938
192939  iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
192940  fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
192941  return iRowid;
192942}
192943
192944/*
192945** Rowid iRowid has just been appended to the current leaf page. It is the
192946** first on the page. This function appends an appropriate entry to the current
192947** doclist-index.
192948*/
192949static void fts5WriteDlidxAppend(
192950  Fts5Index *p,
192951  Fts5SegWriter *pWriter,
192952  i64 iRowid
192953){
192954  int i;
192955  int bDone = 0;
192956
192957  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
192958    i64 iVal;
192959    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
192960
192961    if( pDlidx->buf.n>=p->pConfig->pgsz ){
192962      /* The current doclist-index page is full. Write it to disk and push
192963      ** a copy of iRowid (which will become the first rowid on the next
192964      ** doclist-index leaf page) up into the next level of the b-tree
192965      ** hierarchy. If the node being flushed is currently the root node,
192966      ** also push its first rowid upwards. */
192967      pDlidx->buf.p[0] = 0x01;    /* Not the root node */
192968      fts5DataWrite(p,
192969          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
192970          pDlidx->buf.p, pDlidx->buf.n
192971      );
192972      fts5WriteDlidxGrow(p, pWriter, i+2);
192973      pDlidx = &pWriter->aDlidx[i];
192974      if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
192975        i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
192976
192977        /* This was the root node. Push its first rowid up to the new root. */
192978        pDlidx[1].pgno = pDlidx->pgno;
192979        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
192980        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
192981        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
192982        pDlidx[1].bPrevValid = 1;
192983        pDlidx[1].iPrev = iFirst;
192984      }
192985
192986      sqlite3Fts5BufferZero(&pDlidx->buf);
192987      pDlidx->bPrevValid = 0;
192988      pDlidx->pgno++;
192989    }else{
192990      bDone = 1;
192991    }
192992
192993    if( pDlidx->bPrevValid ){
192994      iVal = iRowid - pDlidx->iPrev;
192995    }else{
192996      i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
192997      assert( pDlidx->buf.n==0 );
192998      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
192999      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
193000      iVal = iRowid;
193001    }
193002
193003    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
193004    pDlidx->bPrevValid = 1;
193005    pDlidx->iPrev = iRowid;
193006  }
193007}
193008
193009static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
193010  static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
193011  Fts5PageWriter *pPage = &pWriter->writer;
193012  i64 iRowid;
193013
193014static int nCall = 0;
193015nCall++;
193016
193017  assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
193018
193019  /* Set the szLeaf header field. */
193020  assert( 0==fts5GetU16(&pPage->buf.p[2]) );
193021  fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
193022
193023  if( pWriter->bFirstTermInPage ){
193024    /* No term was written to this page. */
193025    assert( pPage->pgidx.n==0 );
193026    fts5WriteBtreeNoTerm(p, pWriter);
193027  }else{
193028    /* Append the pgidx to the page buffer. Set the szLeaf header field. */
193029    fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
193030  }
193031
193032  /* Write the page out to disk */
193033  iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
193034  fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
193035
193036  /* Initialize the next page. */
193037  fts5BufferZero(&pPage->buf);
193038  fts5BufferZero(&pPage->pgidx);
193039  fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
193040  pPage->iPrevPgidx = 0;
193041  pPage->pgno++;
193042
193043  /* Increase the leaves written counter */
193044  pWriter->nLeafWritten++;
193045
193046  /* The new leaf holds no terms or rowids */
193047  pWriter->bFirstTermInPage = 1;
193048  pWriter->bFirstRowidInPage = 1;
193049}
193050
193051/*
193052** Append term pTerm/nTerm to the segment being written by the writer passed
193053** as the second argument.
193054**
193055** If an error occurs, set the Fts5Index.rc error code. If an error has
193056** already occurred, this function is a no-op.
193057*/
193058static void fts5WriteAppendTerm(
193059  Fts5Index *p,
193060  Fts5SegWriter *pWriter,
193061  int nTerm, const u8 *pTerm
193062){
193063  int nPrefix;                    /* Bytes of prefix compression for term */
193064  Fts5PageWriter *pPage = &pWriter->writer;
193065  Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
193066
193067  assert( p->rc==SQLITE_OK );
193068  assert( pPage->buf.n>=4 );
193069  assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
193070
193071  /* If the current leaf page is full, flush it to disk. */
193072  if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
193073    if( pPage->buf.n>4 ){
193074      fts5WriteFlushLeaf(p, pWriter);
193075    }
193076    fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
193077  }
193078
193079  /* TODO1: Updating pgidx here. */
193080  pPgidx->n += sqlite3Fts5PutVarint(
193081      &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
193082  );
193083  pPage->iPrevPgidx = pPage->buf.n;
193084#if 0
193085  fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
193086  pPgidx->n += 2;
193087#endif
193088
193089  if( pWriter->bFirstTermInPage ){
193090    nPrefix = 0;
193091    if( pPage->pgno!=1 ){
193092      /* This is the first term on a leaf that is not the leftmost leaf in
193093      ** the segment b-tree. In this case it is necessary to add a term to
193094      ** the b-tree hierarchy that is (a) larger than the largest term
193095      ** already written to the segment and (b) smaller than or equal to
193096      ** this term. In other words, a prefix of (pTerm/nTerm) that is one
193097      ** byte longer than the longest prefix (pTerm/nTerm) shares with the
193098      ** previous term.
193099      **
193100      ** Usually, the previous term is available in pPage->term. The exception
193101      ** is if this is the first term written in an incremental-merge step.
193102      ** In this case the previous term is not available, so just write a
193103      ** copy of (pTerm/nTerm) into the parent node. This is slightly
193104      ** inefficient, but still correct.  */
193105      int n = nTerm;
193106      if( pPage->term.n ){
193107        n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
193108      }
193109      fts5WriteBtreeTerm(p, pWriter, n, pTerm);
193110      pPage = &pWriter->writer;
193111    }
193112  }else{
193113    nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
193114    fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
193115  }
193116
193117  /* Append the number of bytes of new data, then the term data itself
193118  ** to the page. */
193119  fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
193120  fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
193121
193122  /* Update the Fts5PageWriter.term field. */
193123  fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
193124  pWriter->bFirstTermInPage = 0;
193125
193126  pWriter->bFirstRowidInPage = 0;
193127  pWriter->bFirstRowidInDoclist = 1;
193128
193129  assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
193130  pWriter->aDlidx[0].pgno = pPage->pgno;
193131}
193132
193133/*
193134** Append a rowid and position-list size field to the writers output.
193135*/
193136static void fts5WriteAppendRowid(
193137  Fts5Index *p,
193138  Fts5SegWriter *pWriter,
193139  i64 iRowid
193140){
193141  if( p->rc==SQLITE_OK ){
193142    Fts5PageWriter *pPage = &pWriter->writer;
193143
193144    if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
193145      fts5WriteFlushLeaf(p, pWriter);
193146    }
193147
193148    /* If this is to be the first rowid written to the page, set the
193149    ** rowid-pointer in the page-header. Also append a value to the dlidx
193150    ** buffer, in case a doclist-index is required.  */
193151    if( pWriter->bFirstRowidInPage ){
193152      fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
193153      fts5WriteDlidxAppend(p, pWriter, iRowid);
193154    }
193155
193156    /* Write the rowid. */
193157    if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
193158      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
193159    }else{
193160      assert( p->rc || iRowid>pWriter->iPrevRowid );
193161      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
193162    }
193163    pWriter->iPrevRowid = iRowid;
193164    pWriter->bFirstRowidInDoclist = 0;
193165    pWriter->bFirstRowidInPage = 0;
193166  }
193167}
193168
193169static void fts5WriteAppendPoslistData(
193170  Fts5Index *p,
193171  Fts5SegWriter *pWriter,
193172  const u8 *aData,
193173  int nData
193174){
193175  Fts5PageWriter *pPage = &pWriter->writer;
193176  const u8 *a = aData;
193177  int n = nData;
193178
193179  assert( p->pConfig->pgsz>0 );
193180  while( p->rc==SQLITE_OK
193181     && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
193182  ){
193183    int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
193184    int nCopy = 0;
193185    while( nCopy<nReq ){
193186      i64 dummy;
193187      nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
193188    }
193189    fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
193190    a += nCopy;
193191    n -= nCopy;
193192    fts5WriteFlushLeaf(p, pWriter);
193193  }
193194  if( n>0 ){
193195    fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
193196  }
193197}
193198
193199/*
193200** Flush any data cached by the writer object to the database. Free any
193201** allocations associated with the writer.
193202*/
193203static void fts5WriteFinish(
193204  Fts5Index *p,
193205  Fts5SegWriter *pWriter,         /* Writer object */
193206  int *pnLeaf                     /* OUT: Number of leaf pages in b-tree */
193207){
193208  int i;
193209  Fts5PageWriter *pLeaf = &pWriter->writer;
193210  if( p->rc==SQLITE_OK ){
193211    assert( pLeaf->pgno>=1 );
193212    if( pLeaf->buf.n>4 ){
193213      fts5WriteFlushLeaf(p, pWriter);
193214    }
193215    *pnLeaf = pLeaf->pgno-1;
193216    if( pLeaf->pgno>1 ){
193217      fts5WriteFlushBtree(p, pWriter);
193218    }
193219  }
193220  fts5BufferFree(&pLeaf->term);
193221  fts5BufferFree(&pLeaf->buf);
193222  fts5BufferFree(&pLeaf->pgidx);
193223  fts5BufferFree(&pWriter->btterm);
193224
193225  for(i=0; i<pWriter->nDlidx; i++){
193226    sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
193227  }
193228  sqlite3_free(pWriter->aDlidx);
193229}
193230
193231static void fts5WriteInit(
193232  Fts5Index *p,
193233  Fts5SegWriter *pWriter,
193234  int iSegid
193235){
193236  const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
193237
193238  memset(pWriter, 0, sizeof(Fts5SegWriter));
193239  pWriter->iSegid = iSegid;
193240
193241  fts5WriteDlidxGrow(p, pWriter, 1);
193242  pWriter->writer.pgno = 1;
193243  pWriter->bFirstTermInPage = 1;
193244  pWriter->iBtPage = 1;
193245
193246  assert( pWriter->writer.buf.n==0 );
193247  assert( pWriter->writer.pgidx.n==0 );
193248
193249  /* Grow the two buffers to pgsz + padding bytes in size. */
193250  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
193251  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
193252
193253  if( p->pIdxWriter==0 ){
193254    Fts5Config *pConfig = p->pConfig;
193255    fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
193256          "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
193257          pConfig->zDb, pConfig->zName
193258    ));
193259  }
193260
193261  if( p->rc==SQLITE_OK ){
193262    /* Initialize the 4-byte leaf-page header to 0x00. */
193263    memset(pWriter->writer.buf.p, 0, 4);
193264    pWriter->writer.buf.n = 4;
193265
193266    /* Bind the current output segment id to the index-writer. This is an
193267    ** optimization over binding the same value over and over as rows are
193268    ** inserted into %_idx by the current writer.  */
193269    sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
193270  }
193271}
193272
193273/*
193274** Iterator pIter was used to iterate through the input segments of on an
193275** incremental merge operation. This function is called if the incremental
193276** merge step has finished but the input has not been completely exhausted.
193277*/
193278static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
193279  int i;
193280  Fts5Buffer buf;
193281  memset(&buf, 0, sizeof(Fts5Buffer));
193282  for(i=0; i<pIter->nSeg; i++){
193283    Fts5SegIter *pSeg = &pIter->aSeg[i];
193284    if( pSeg->pSeg==0 ){
193285      /* no-op */
193286    }else if( pSeg->pLeaf==0 ){
193287      /* All keys from this input segment have been transfered to the output.
193288      ** Set both the first and last page-numbers to 0 to indicate that the
193289      ** segment is now empty. */
193290      pSeg->pSeg->pgnoLast = 0;
193291      pSeg->pSeg->pgnoFirst = 0;
193292    }else{
193293      int iOff = pSeg->iTermLeafOffset;     /* Offset on new first leaf page */
193294      i64 iLeafRowid;
193295      Fts5Data *pData;
193296      int iId = pSeg->pSeg->iSegid;
193297      u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
193298
193299      iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
193300      pData = fts5DataRead(p, iLeafRowid);
193301      if( pData ){
193302        fts5BufferZero(&buf);
193303        fts5BufferGrow(&p->rc, &buf, pData->nn);
193304        fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
193305        fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
193306        fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
193307        fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
193308        if( p->rc==SQLITE_OK ){
193309          /* Set the szLeaf field */
193310          fts5PutU16(&buf.p[2], (u16)buf.n);
193311        }
193312
193313        /* Set up the new page-index array */
193314        fts5BufferAppendVarint(&p->rc, &buf, 4);
193315        if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
193316         && pSeg->iEndofDoclist<pData->szLeaf
193317        ){
193318          int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
193319          fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
193320          fts5BufferAppendBlob(&p->rc, &buf,
193321              pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
193322          );
193323        }
193324
193325        fts5DataRelease(pData);
193326        pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
193327        fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
193328        fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
193329      }
193330    }
193331  }
193332  fts5BufferFree(&buf);
193333}
193334
193335static void fts5MergeChunkCallback(
193336  Fts5Index *p,
193337  void *pCtx,
193338  const u8 *pChunk, int nChunk
193339){
193340  Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
193341  fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
193342}
193343
193344/*
193345**
193346*/
193347static void fts5IndexMergeLevel(
193348  Fts5Index *p,                   /* FTS5 backend object */
193349  Fts5Structure **ppStruct,       /* IN/OUT: Stucture of index */
193350  int iLvl,                       /* Level to read input from */
193351  int *pnRem                      /* Write up to this many output leaves */
193352){
193353  Fts5Structure *pStruct = *ppStruct;
193354  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
193355  Fts5StructureLevel *pLvlOut;
193356  Fts5Iter *pIter = 0;       /* Iterator to read input data */
193357  int nRem = pnRem ? *pnRem : 0;  /* Output leaf pages left to write */
193358  int nInput;                     /* Number of input segments */
193359  Fts5SegWriter writer;           /* Writer object */
193360  Fts5StructureSegment *pSeg;     /* Output segment */
193361  Fts5Buffer term;
193362  int bOldest;                    /* True if the output segment is the oldest */
193363  int eDetail = p->pConfig->eDetail;
193364  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
193365
193366  assert( iLvl<pStruct->nLevel );
193367  assert( pLvl->nMerge<=pLvl->nSeg );
193368
193369  memset(&writer, 0, sizeof(Fts5SegWriter));
193370  memset(&term, 0, sizeof(Fts5Buffer));
193371  if( pLvl->nMerge ){
193372    pLvlOut = &pStruct->aLevel[iLvl+1];
193373    assert( pLvlOut->nSeg>0 );
193374    nInput = pLvl->nMerge;
193375    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
193376
193377    fts5WriteInit(p, &writer, pSeg->iSegid);
193378    writer.writer.pgno = pSeg->pgnoLast+1;
193379    writer.iBtPage = 0;
193380  }else{
193381    int iSegid = fts5AllocateSegid(p, pStruct);
193382
193383    /* Extend the Fts5Structure object as required to ensure the output
193384    ** segment exists. */
193385    if( iLvl==pStruct->nLevel-1 ){
193386      fts5StructureAddLevel(&p->rc, ppStruct);
193387      pStruct = *ppStruct;
193388    }
193389    fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
193390    if( p->rc ) return;
193391    pLvl = &pStruct->aLevel[iLvl];
193392    pLvlOut = &pStruct->aLevel[iLvl+1];
193393
193394    fts5WriteInit(p, &writer, iSegid);
193395
193396    /* Add the new segment to the output level */
193397    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
193398    pLvlOut->nSeg++;
193399    pSeg->pgnoFirst = 1;
193400    pSeg->iSegid = iSegid;
193401    pStruct->nSegment++;
193402
193403    /* Read input from all segments in the input level */
193404    nInput = pLvl->nSeg;
193405  }
193406  bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
193407
193408  assert( iLvl>=0 );
193409  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
193410      fts5MultiIterEof(p, pIter)==0;
193411      fts5MultiIterNext(p, pIter, 0, 0)
193412  ){
193413    Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
193414    int nPos;                     /* position-list size field value */
193415    int nTerm;
193416    const u8 *pTerm;
193417
193418    /* Check for key annihilation. */
193419    if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
193420
193421    pTerm = fts5MultiIterTerm(pIter, &nTerm);
193422    if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
193423      if( pnRem && writer.nLeafWritten>nRem ){
193424        break;
193425      }
193426
193427      /* This is a new term. Append a term to the output segment. */
193428      fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
193429      fts5BufferSet(&p->rc, &term, nTerm, pTerm);
193430    }
193431
193432    /* Append the rowid to the output */
193433    /* WRITEPOSLISTSIZE */
193434    fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
193435
193436    if( eDetail==FTS5_DETAIL_NONE ){
193437      if( pSegIter->bDel ){
193438        fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
193439        if( pSegIter->nPos>0 ){
193440          fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
193441        }
193442      }
193443    }else{
193444      /* Append the position-list data to the output */
193445      nPos = pSegIter->nPos*2 + pSegIter->bDel;
193446      fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
193447      fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
193448    }
193449  }
193450
193451  /* Flush the last leaf page to disk. Set the output segment b-tree height
193452  ** and last leaf page number at the same time.  */
193453  fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
193454
193455  if( fts5MultiIterEof(p, pIter) ){
193456    int i;
193457
193458    /* Remove the redundant segments from the %_data table */
193459    for(i=0; i<nInput; i++){
193460      fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
193461    }
193462
193463    /* Remove the redundant segments from the input level */
193464    if( pLvl->nSeg!=nInput ){
193465      int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
193466      memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
193467    }
193468    pStruct->nSegment -= nInput;
193469    pLvl->nSeg -= nInput;
193470    pLvl->nMerge = 0;
193471    if( pSeg->pgnoLast==0 ){
193472      pLvlOut->nSeg--;
193473      pStruct->nSegment--;
193474    }
193475  }else{
193476    assert( pSeg->pgnoLast>0 );
193477    fts5TrimSegments(p, pIter);
193478    pLvl->nMerge = nInput;
193479  }
193480
193481  fts5MultiIterFree(pIter);
193482  fts5BufferFree(&term);
193483  if( pnRem ) *pnRem -= writer.nLeafWritten;
193484}
193485
193486/*
193487** Do up to nPg pages of automerge work on the index.
193488**
193489** Return true if any changes were actually made, or false otherwise.
193490*/
193491static int fts5IndexMerge(
193492  Fts5Index *p,                   /* FTS5 backend object */
193493  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
193494  int nPg,                        /* Pages of work to do */
193495  int nMin                        /* Minimum number of segments to merge */
193496){
193497  int nRem = nPg;
193498  int bRet = 0;
193499  Fts5Structure *pStruct = *ppStruct;
193500  while( nRem>0 && p->rc==SQLITE_OK ){
193501    int iLvl;                   /* To iterate through levels */
193502    int iBestLvl = 0;           /* Level offering the most input segments */
193503    int nBest = 0;              /* Number of input segments on best level */
193504
193505    /* Set iBestLvl to the level to read input segments from. */
193506    assert( pStruct->nLevel>0 );
193507    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
193508      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
193509      if( pLvl->nMerge ){
193510        if( pLvl->nMerge>nBest ){
193511          iBestLvl = iLvl;
193512          nBest = pLvl->nMerge;
193513        }
193514        break;
193515      }
193516      if( pLvl->nSeg>nBest ){
193517        nBest = pLvl->nSeg;
193518        iBestLvl = iLvl;
193519      }
193520    }
193521
193522    /* If nBest is still 0, then the index must be empty. */
193523#ifdef SQLITE_DEBUG
193524    for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
193525      assert( pStruct->aLevel[iLvl].nSeg==0 );
193526    }
193527#endif
193528
193529    if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
193530      break;
193531    }
193532    bRet = 1;
193533    fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
193534    if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
193535      fts5StructurePromote(p, iBestLvl+1, pStruct);
193536    }
193537  }
193538  *ppStruct = pStruct;
193539  return bRet;
193540}
193541
193542/*
193543** A total of nLeaf leaf pages of data has just been flushed to a level-0
193544** segment. This function updates the write-counter accordingly and, if
193545** necessary, performs incremental merge work.
193546**
193547** If an error occurs, set the Fts5Index.rc error code. If an error has
193548** already occurred, this function is a no-op.
193549*/
193550static void fts5IndexAutomerge(
193551  Fts5Index *p,                   /* FTS5 backend object */
193552  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
193553  int nLeaf                       /* Number of output leaves just written */
193554){
193555  if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
193556    Fts5Structure *pStruct = *ppStruct;
193557    u64 nWrite;                   /* Initial value of write-counter */
193558    int nWork;                    /* Number of work-quanta to perform */
193559    int nRem;                     /* Number of leaf pages left to write */
193560
193561    /* Update the write-counter. While doing so, set nWork. */
193562    nWrite = pStruct->nWriteCounter;
193563    nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
193564    pStruct->nWriteCounter += nLeaf;
193565    nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
193566
193567    fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
193568  }
193569}
193570
193571static void fts5IndexCrisismerge(
193572  Fts5Index *p,                   /* FTS5 backend object */
193573  Fts5Structure **ppStruct        /* IN/OUT: Current structure of index */
193574){
193575  const int nCrisis = p->pConfig->nCrisisMerge;
193576  Fts5Structure *pStruct = *ppStruct;
193577  int iLvl = 0;
193578
193579  assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
193580  while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
193581    fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
193582    assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
193583    fts5StructurePromote(p, iLvl+1, pStruct);
193584    iLvl++;
193585  }
193586  *ppStruct = pStruct;
193587}
193588
193589static int fts5IndexReturn(Fts5Index *p){
193590  int rc = p->rc;
193591  p->rc = SQLITE_OK;
193592  return rc;
193593}
193594
193595typedef struct Fts5FlushCtx Fts5FlushCtx;
193596struct Fts5FlushCtx {
193597  Fts5Index *pIdx;
193598  Fts5SegWriter writer;
193599};
193600
193601/*
193602** Buffer aBuf[] contains a list of varints, all small enough to fit
193603** in a 32-bit integer. Return the size of the largest prefix of this
193604** list nMax bytes or less in size.
193605*/
193606static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
193607  int ret;
193608  u32 dummy;
193609  ret = fts5GetVarint32(aBuf, dummy);
193610  if( ret<nMax ){
193611    while( 1 ){
193612      int i = fts5GetVarint32(&aBuf[ret], dummy);
193613      if( (ret + i) > nMax ) break;
193614      ret += i;
193615    }
193616  }
193617  return ret;
193618}
193619
193620/*
193621** Flush the contents of in-memory hash table iHash to a new level-0
193622** segment on disk. Also update the corresponding structure record.
193623**
193624** If an error occurs, set the Fts5Index.rc error code. If an error has
193625** already occurred, this function is a no-op.
193626*/
193627static void fts5FlushOneHash(Fts5Index *p){
193628  Fts5Hash *pHash = p->pHash;
193629  Fts5Structure *pStruct;
193630  int iSegid;
193631  int pgnoLast = 0;                 /* Last leaf page number in segment */
193632
193633  /* Obtain a reference to the index structure and allocate a new segment-id
193634  ** for the new level-0 segment.  */
193635  pStruct = fts5StructureRead(p);
193636  iSegid = fts5AllocateSegid(p, pStruct);
193637  fts5StructureInvalidate(p);
193638
193639  if( iSegid ){
193640    const int pgsz = p->pConfig->pgsz;
193641    int eDetail = p->pConfig->eDetail;
193642    Fts5StructureSegment *pSeg;   /* New segment within pStruct */
193643    Fts5Buffer *pBuf;             /* Buffer in which to assemble leaf page */
193644    Fts5Buffer *pPgidx;           /* Buffer in which to assemble pgidx */
193645
193646    Fts5SegWriter writer;
193647    fts5WriteInit(p, &writer, iSegid);
193648
193649    pBuf = &writer.writer.buf;
193650    pPgidx = &writer.writer.pgidx;
193651
193652    /* fts5WriteInit() should have initialized the buffers to (most likely)
193653    ** the maximum space required. */
193654    assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
193655    assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
193656
193657    /* Begin scanning through hash table entries. This loop runs once for each
193658    ** term/doclist currently stored within the hash table. */
193659    if( p->rc==SQLITE_OK ){
193660      p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
193661    }
193662    while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
193663      const char *zTerm;          /* Buffer containing term */
193664      const u8 *pDoclist;         /* Pointer to doclist for this term */
193665      int nDoclist;               /* Size of doclist in bytes */
193666
193667      /* Write the term for this entry to disk. */
193668      sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
193669      fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
193670
193671      assert( writer.bFirstRowidInPage==0 );
193672      if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
193673        /* The entire doclist will fit on the current leaf. */
193674        fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
193675      }else{
193676        i64 iRowid = 0;
193677        i64 iDelta = 0;
193678        int iOff = 0;
193679
193680        /* The entire doclist will not fit on this leaf. The following
193681        ** loop iterates through the poslists that make up the current
193682        ** doclist.  */
193683        while( p->rc==SQLITE_OK && iOff<nDoclist ){
193684          iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
193685          iRowid += iDelta;
193686
193687          if( writer.bFirstRowidInPage ){
193688            fts5PutU16(&pBuf->p[0], (u16)pBuf->n);   /* first rowid on page */
193689            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
193690            writer.bFirstRowidInPage = 0;
193691            fts5WriteDlidxAppend(p, &writer, iRowid);
193692          }else{
193693            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
193694          }
193695          assert( pBuf->n<=pBuf->nSpace );
193696
193697          if( eDetail==FTS5_DETAIL_NONE ){
193698            if( iOff<nDoclist && pDoclist[iOff]==0 ){
193699              pBuf->p[pBuf->n++] = 0;
193700              iOff++;
193701              if( iOff<nDoclist && pDoclist[iOff]==0 ){
193702                pBuf->p[pBuf->n++] = 0;
193703                iOff++;
193704              }
193705            }
193706            if( (pBuf->n + pPgidx->n)>=pgsz ){
193707              fts5WriteFlushLeaf(p, &writer);
193708            }
193709          }else{
193710            int bDummy;
193711            int nPos;
193712            int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
193713            nCopy += nPos;
193714            if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
193715              /* The entire poslist will fit on the current leaf. So copy
193716              ** it in one go. */
193717              fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
193718            }else{
193719              /* The entire poslist will not fit on this leaf. So it needs
193720              ** to be broken into sections. The only qualification being
193721              ** that each varint must be stored contiguously.  */
193722              const u8 *pPoslist = &pDoclist[iOff];
193723              int iPos = 0;
193724              while( p->rc==SQLITE_OK ){
193725                int nSpace = pgsz - pBuf->n - pPgidx->n;
193726                int n = 0;
193727                if( (nCopy - iPos)<=nSpace ){
193728                  n = nCopy - iPos;
193729                }else{
193730                  n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
193731                }
193732                assert( n>0 );
193733                fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
193734                iPos += n;
193735                if( (pBuf->n + pPgidx->n)>=pgsz ){
193736                  fts5WriteFlushLeaf(p, &writer);
193737                }
193738                if( iPos>=nCopy ) break;
193739              }
193740            }
193741            iOff += nCopy;
193742          }
193743        }
193744      }
193745
193746      /* TODO2: Doclist terminator written here. */
193747      /* pBuf->p[pBuf->n++] = '\0'; */
193748      assert( pBuf->n<=pBuf->nSpace );
193749      sqlite3Fts5HashScanNext(pHash);
193750    }
193751    sqlite3Fts5HashClear(pHash);
193752    fts5WriteFinish(p, &writer, &pgnoLast);
193753
193754    /* Update the Fts5Structure. It is written back to the database by the
193755    ** fts5StructureRelease() call below.  */
193756    if( pStruct->nLevel==0 ){
193757      fts5StructureAddLevel(&p->rc, &pStruct);
193758    }
193759    fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
193760    if( p->rc==SQLITE_OK ){
193761      pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
193762      pSeg->iSegid = iSegid;
193763      pSeg->pgnoFirst = 1;
193764      pSeg->pgnoLast = pgnoLast;
193765      pStruct->nSegment++;
193766    }
193767    fts5StructurePromote(p, 0, pStruct);
193768  }
193769
193770  fts5IndexAutomerge(p, &pStruct, pgnoLast);
193771  fts5IndexCrisismerge(p, &pStruct);
193772  fts5StructureWrite(p, pStruct);
193773  fts5StructureRelease(pStruct);
193774}
193775
193776/*
193777** Flush any data stored in the in-memory hash tables to the database.
193778*/
193779static void fts5IndexFlush(Fts5Index *p){
193780  /* Unless it is empty, flush the hash table to disk */
193781  if( p->nPendingData ){
193782    assert( p->pHash );
193783    p->nPendingData = 0;
193784    fts5FlushOneHash(p);
193785  }
193786}
193787
193788static Fts5Structure *fts5IndexOptimizeStruct(
193789  Fts5Index *p,
193790  Fts5Structure *pStruct
193791){
193792  Fts5Structure *pNew = 0;
193793  int nByte = sizeof(Fts5Structure);
193794  int nSeg = pStruct->nSegment;
193795  int i;
193796
193797  /* Figure out if this structure requires optimization. A structure does
193798  ** not require optimization if either:
193799  **
193800  **  + it consists of fewer than two segments, or
193801  **  + all segments are on the same level, or
193802  **  + all segments except one are currently inputs to a merge operation.
193803  **
193804  ** In the first case, return NULL. In the second, increment the ref-count
193805  ** on *pStruct and return a copy of the pointer to it.
193806  */
193807  if( nSeg<2 ) return 0;
193808  for(i=0; i<pStruct->nLevel; i++){
193809    int nThis = pStruct->aLevel[i].nSeg;
193810    if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
193811      fts5StructureRef(pStruct);
193812      return pStruct;
193813    }
193814    assert( pStruct->aLevel[i].nMerge<=nThis );
193815  }
193816
193817  nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
193818  pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
193819
193820  if( pNew ){
193821    Fts5StructureLevel *pLvl;
193822    nByte = nSeg * sizeof(Fts5StructureSegment);
193823    pNew->nLevel = pStruct->nLevel+1;
193824    pNew->nRef = 1;
193825    pNew->nWriteCounter = pStruct->nWriteCounter;
193826    pLvl = &pNew->aLevel[pStruct->nLevel];
193827    pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
193828    if( pLvl->aSeg ){
193829      int iLvl, iSeg;
193830      int iSegOut = 0;
193831      /* Iterate through all segments, from oldest to newest. Add them to
193832      ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
193833      ** segment in the data structure.  */
193834      for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
193835        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
193836          pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
193837          iSegOut++;
193838        }
193839      }
193840      pNew->nSegment = pLvl->nSeg = nSeg;
193841    }else{
193842      sqlite3_free(pNew);
193843      pNew = 0;
193844    }
193845  }
193846
193847  return pNew;
193848}
193849
193850static int sqlite3Fts5IndexOptimize(Fts5Index *p){
193851  Fts5Structure *pStruct;
193852  Fts5Structure *pNew = 0;
193853
193854  assert( p->rc==SQLITE_OK );
193855  fts5IndexFlush(p);
193856  pStruct = fts5StructureRead(p);
193857  fts5StructureInvalidate(p);
193858
193859  if( pStruct ){
193860    pNew = fts5IndexOptimizeStruct(p, pStruct);
193861  }
193862  fts5StructureRelease(pStruct);
193863
193864  assert( pNew==0 || pNew->nSegment>0 );
193865  if( pNew ){
193866    int iLvl;
193867    for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
193868    while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
193869      int nRem = FTS5_OPT_WORK_UNIT;
193870      fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
193871    }
193872
193873    fts5StructureWrite(p, pNew);
193874    fts5StructureRelease(pNew);
193875  }
193876
193877  return fts5IndexReturn(p);
193878}
193879
193880/*
193881** This is called to implement the special "VALUES('merge', $nMerge)"
193882** INSERT command.
193883*/
193884static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
193885  Fts5Structure *pStruct = fts5StructureRead(p);
193886  if( pStruct ){
193887    int nMin = p->pConfig->nUsermerge;
193888    fts5StructureInvalidate(p);
193889    if( nMerge<0 ){
193890      Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
193891      fts5StructureRelease(pStruct);
193892      pStruct = pNew;
193893      nMin = 2;
193894      nMerge = nMerge*-1;
193895    }
193896    if( pStruct && pStruct->nLevel ){
193897      if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
193898        fts5StructureWrite(p, pStruct);
193899      }
193900    }
193901    fts5StructureRelease(pStruct);
193902  }
193903  return fts5IndexReturn(p);
193904}
193905
193906static void fts5AppendRowid(
193907  Fts5Index *p,
193908  i64 iDelta,
193909  Fts5Iter *pUnused,
193910  Fts5Buffer *pBuf
193911){
193912  UNUSED_PARAM(pUnused);
193913  fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
193914}
193915
193916static void fts5AppendPoslist(
193917  Fts5Index *p,
193918  i64 iDelta,
193919  Fts5Iter *pMulti,
193920  Fts5Buffer *pBuf
193921){
193922  int nData = pMulti->base.nData;
193923  assert( nData>0 );
193924  if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
193925    fts5BufferSafeAppendVarint(pBuf, iDelta);
193926    fts5BufferSafeAppendVarint(pBuf, nData*2);
193927    fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
193928  }
193929}
193930
193931
193932static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
193933  u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
193934
193935  assert( pIter->aPoslist );
193936  if( p>=pIter->aEof ){
193937    pIter->aPoslist = 0;
193938  }else{
193939    i64 iDelta;
193940
193941    p += fts5GetVarint(p, (u64*)&iDelta);
193942    pIter->iRowid += iDelta;
193943
193944    /* Read position list size */
193945    if( p[0] & 0x80 ){
193946      int nPos;
193947      pIter->nSize = fts5GetVarint32(p, nPos);
193948      pIter->nPoslist = (nPos>>1);
193949    }else{
193950      pIter->nPoslist = ((int)(p[0])) >> 1;
193951      pIter->nSize = 1;
193952    }
193953
193954    pIter->aPoslist = p;
193955  }
193956}
193957
193958static void fts5DoclistIterInit(
193959  Fts5Buffer *pBuf,
193960  Fts5DoclistIter *pIter
193961){
193962  memset(pIter, 0, sizeof(*pIter));
193963  pIter->aPoslist = pBuf->p;
193964  pIter->aEof = &pBuf->p[pBuf->n];
193965  fts5DoclistIterNext(pIter);
193966}
193967
193968#if 0
193969/*
193970** Append a doclist to buffer pBuf.
193971**
193972** This function assumes that space within the buffer has already been
193973** allocated.
193974*/
193975static void fts5MergeAppendDocid(
193976  Fts5Buffer *pBuf,               /* Buffer to write to */
193977  i64 *piLastRowid,               /* IN/OUT: Previous rowid written (if any) */
193978  i64 iRowid                      /* Rowid to append */
193979){
193980  assert( pBuf->n!=0 || (*piLastRowid)==0 );
193981  fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
193982  *piLastRowid = iRowid;
193983}
193984#endif
193985
193986#define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) {       \
193987  assert( (pBuf)->n!=0 || (iLastRowid)==0 );                   \
193988  fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
193989  (iLastRowid) = (iRowid);                                     \
193990}
193991
193992/*
193993** Swap the contents of buffer *p1 with that of *p2.
193994*/
193995static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
193996  Fts5Buffer tmp = *p1;
193997  *p1 = *p2;
193998  *p2 = tmp;
193999}
194000
194001static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
194002  int i = *piOff;
194003  if( i>=pBuf->n ){
194004    *piOff = -1;
194005  }else{
194006    u64 iVal;
194007    *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
194008    *piRowid += iVal;
194009  }
194010}
194011
194012/*
194013** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
194014** In this case the buffers consist of a delta-encoded list of rowids only.
194015*/
194016static void fts5MergeRowidLists(
194017  Fts5Index *p,                   /* FTS5 backend object */
194018  Fts5Buffer *p1,                 /* First list to merge */
194019  Fts5Buffer *p2                  /* Second list to merge */
194020){
194021  int i1 = 0;
194022  int i2 = 0;
194023  i64 iRowid1 = 0;
194024  i64 iRowid2 = 0;
194025  i64 iOut = 0;
194026
194027  Fts5Buffer out;
194028  memset(&out, 0, sizeof(out));
194029  sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
194030  if( p->rc ) return;
194031
194032  fts5NextRowid(p1, &i1, &iRowid1);
194033  fts5NextRowid(p2, &i2, &iRowid2);
194034  while( i1>=0 || i2>=0 ){
194035    if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
194036      assert( iOut==0 || iRowid1>iOut );
194037      fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
194038      iOut = iRowid1;
194039      fts5NextRowid(p1, &i1, &iRowid1);
194040    }else{
194041      assert( iOut==0 || iRowid2>iOut );
194042      fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
194043      iOut = iRowid2;
194044      if( i1>=0 && iRowid1==iRowid2 ){
194045        fts5NextRowid(p1, &i1, &iRowid1);
194046      }
194047      fts5NextRowid(p2, &i2, &iRowid2);
194048    }
194049  }
194050
194051  fts5BufferSwap(&out, p1);
194052  fts5BufferFree(&out);
194053}
194054
194055/*
194056** Buffers p1 and p2 contain doclists. This function merges the content
194057** of the two doclists together and sets buffer p1 to the result before
194058** returning.
194059**
194060** If an error occurs, an error code is left in p->rc. If an error has
194061** already occurred, this function is a no-op.
194062*/
194063static void fts5MergePrefixLists(
194064  Fts5Index *p,                   /* FTS5 backend object */
194065  Fts5Buffer *p1,                 /* First list to merge */
194066  Fts5Buffer *p2                  /* Second list to merge */
194067){
194068  if( p2->n ){
194069    i64 iLastRowid = 0;
194070    Fts5DoclistIter i1;
194071    Fts5DoclistIter i2;
194072    Fts5Buffer out = {0, 0, 0};
194073    Fts5Buffer tmp = {0, 0, 0};
194074
194075    if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return;
194076    fts5DoclistIterInit(p1, &i1);
194077    fts5DoclistIterInit(p2, &i2);
194078
194079    while( 1 ){
194080      if( i1.iRowid<i2.iRowid ){
194081        /* Copy entry from i1 */
194082        fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
194083        fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
194084        fts5DoclistIterNext(&i1);
194085        if( i1.aPoslist==0 ) break;
194086      }
194087      else if( i2.iRowid!=i1.iRowid ){
194088        /* Copy entry from i2 */
194089        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
194090        fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
194091        fts5DoclistIterNext(&i2);
194092        if( i2.aPoslist==0 ) break;
194093      }
194094      else{
194095        /* Merge the two position lists. */
194096        i64 iPos1 = 0;
194097        i64 iPos2 = 0;
194098        int iOff1 = 0;
194099        int iOff2 = 0;
194100        u8 *a1 = &i1.aPoslist[i1.nSize];
194101        u8 *a2 = &i2.aPoslist[i2.nSize];
194102
194103        i64 iPrev = 0;
194104        Fts5PoslistWriter writer;
194105        memset(&writer, 0, sizeof(writer));
194106
194107        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
194108        fts5BufferZero(&tmp);
194109        sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
194110        if( p->rc ) break;
194111
194112        sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
194113        sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
194114        assert( iPos1>=0 && iPos2>=0 );
194115
194116        if( iPos1<iPos2 ){
194117          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
194118          sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
194119        }else{
194120          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
194121          sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
194122        }
194123
194124        if( iPos1>=0 && iPos2>=0 ){
194125          while( 1 ){
194126            if( iPos1<iPos2 ){
194127              if( iPos1!=iPrev ){
194128                sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
194129              }
194130              sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
194131              if( iPos1<0 ) break;
194132            }else{
194133              assert( iPos2!=iPrev );
194134              sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
194135              sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
194136              if( iPos2<0 ) break;
194137            }
194138          }
194139        }
194140
194141        if( iPos1>=0 ){
194142          if( iPos1!=iPrev ){
194143            sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
194144          }
194145          fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
194146        }else{
194147          assert( iPos2>=0 && iPos2!=iPrev );
194148          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
194149          fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
194150        }
194151
194152        /* WRITEPOSLISTSIZE */
194153        fts5BufferSafeAppendVarint(&out, tmp.n * 2);
194154        fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
194155        fts5DoclistIterNext(&i1);
194156        fts5DoclistIterNext(&i2);
194157        if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
194158      }
194159    }
194160
194161    if( i1.aPoslist ){
194162      fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
194163      fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
194164    }
194165    else if( i2.aPoslist ){
194166      fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
194167      fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
194168    }
194169
194170    fts5BufferSet(&p->rc, p1, out.n, out.p);
194171    fts5BufferFree(&tmp);
194172    fts5BufferFree(&out);
194173  }
194174}
194175
194176static void fts5SetupPrefixIter(
194177  Fts5Index *p,                   /* Index to read from */
194178  int bDesc,                      /* True for "ORDER BY rowid DESC" */
194179  const u8 *pToken,               /* Buffer containing prefix to match */
194180  int nToken,                     /* Size of buffer pToken in bytes */
194181  Fts5Colset *pColset,            /* Restrict matches to these columns */
194182  Fts5Iter **ppIter          /* OUT: New iterator */
194183){
194184  Fts5Structure *pStruct;
194185  Fts5Buffer *aBuf;
194186  const int nBuf = 32;
194187
194188  void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
194189  void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
194190  if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
194191    xMerge = fts5MergeRowidLists;
194192    xAppend = fts5AppendRowid;
194193  }else{
194194    xMerge = fts5MergePrefixLists;
194195    xAppend = fts5AppendPoslist;
194196  }
194197
194198  aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
194199  pStruct = fts5StructureRead(p);
194200
194201  if( aBuf && pStruct ){
194202    const int flags = FTS5INDEX_QUERY_SCAN
194203                    | FTS5INDEX_QUERY_SKIPEMPTY
194204                    | FTS5INDEX_QUERY_NOOUTPUT;
194205    int i;
194206    i64 iLastRowid = 0;
194207    Fts5Iter *p1 = 0;     /* Iterator used to gather data from index */
194208    Fts5Data *pData;
194209    Fts5Buffer doclist;
194210    int bNewTerm = 1;
194211
194212    memset(&doclist, 0, sizeof(doclist));
194213    fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
194214    fts5IterSetOutputCb(&p->rc, p1);
194215    for( /* no-op */ ;
194216        fts5MultiIterEof(p, p1)==0;
194217        fts5MultiIterNext2(p, p1, &bNewTerm)
194218    ){
194219      Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
194220      int nTerm = pSeg->term.n;
194221      const u8 *pTerm = pSeg->term.p;
194222      p1->xSetOutputs(p1, pSeg);
194223
194224      assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
194225      if( bNewTerm ){
194226        if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
194227      }
194228
194229      if( p1->base.nData==0 ) continue;
194230
194231      if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
194232        for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
194233          assert( i<nBuf );
194234          if( aBuf[i].n==0 ){
194235            fts5BufferSwap(&doclist, &aBuf[i]);
194236            fts5BufferZero(&doclist);
194237          }else{
194238            xMerge(p, &doclist, &aBuf[i]);
194239            fts5BufferZero(&aBuf[i]);
194240          }
194241        }
194242        iLastRowid = 0;
194243      }
194244
194245      xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
194246      iLastRowid = p1->base.iRowid;
194247    }
194248
194249    for(i=0; i<nBuf; i++){
194250      if( p->rc==SQLITE_OK ){
194251        xMerge(p, &doclist, &aBuf[i]);
194252      }
194253      fts5BufferFree(&aBuf[i]);
194254    }
194255    fts5MultiIterFree(p1);
194256
194257    pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
194258    if( pData ){
194259      pData->p = (u8*)&pData[1];
194260      pData->nn = pData->szLeaf = doclist.n;
194261      memcpy(pData->p, doclist.p, doclist.n);
194262      fts5MultiIterNew2(p, pData, bDesc, ppIter);
194263    }
194264    fts5BufferFree(&doclist);
194265  }
194266
194267  fts5StructureRelease(pStruct);
194268  sqlite3_free(aBuf);
194269}
194270
194271
194272/*
194273** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
194274** to the document with rowid iRowid.
194275*/
194276static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
194277  assert( p->rc==SQLITE_OK );
194278
194279  /* Allocate the hash table if it has not already been allocated */
194280  if( p->pHash==0 ){
194281    p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
194282  }
194283
194284  /* Flush the hash table to disk if required */
194285  if( iRowid<p->iWriteRowid
194286   || (iRowid==p->iWriteRowid && p->bDelete==0)
194287   || (p->nPendingData > p->pConfig->nHashSize)
194288  ){
194289    fts5IndexFlush(p);
194290  }
194291
194292  p->iWriteRowid = iRowid;
194293  p->bDelete = bDelete;
194294  return fts5IndexReturn(p);
194295}
194296
194297/*
194298** Commit data to disk.
194299*/
194300static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){
194301  assert( p->rc==SQLITE_OK );
194302  fts5IndexFlush(p);
194303  if( bCommit ) fts5CloseReader(p);
194304  return fts5IndexReturn(p);
194305}
194306
194307/*
194308** Discard any data stored in the in-memory hash tables. Do not write it
194309** to the database. Additionally, assume that the contents of the %_data
194310** table may have changed on disk. So any in-memory caches of %_data
194311** records must be invalidated.
194312*/
194313static int sqlite3Fts5IndexRollback(Fts5Index *p){
194314  fts5CloseReader(p);
194315  fts5IndexDiscardData(p);
194316  fts5StructureInvalidate(p);
194317  /* assert( p->rc==SQLITE_OK ); */
194318  return SQLITE_OK;
194319}
194320
194321/*
194322** The %_data table is completely empty when this function is called. This
194323** function populates it with the initial structure objects for each index,
194324** and the initial version of the "averages" record (a zero-byte blob).
194325*/
194326static int sqlite3Fts5IndexReinit(Fts5Index *p){
194327  Fts5Structure s;
194328  fts5StructureInvalidate(p);
194329  memset(&s, 0, sizeof(Fts5Structure));
194330  fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
194331  fts5StructureWrite(p, &s);
194332  return fts5IndexReturn(p);
194333}
194334
194335/*
194336** Open a new Fts5Index handle. If the bCreate argument is true, create
194337** and initialize the underlying %_data table.
194338**
194339** If successful, set *pp to point to the new object and return SQLITE_OK.
194340** Otherwise, set *pp to NULL and return an SQLite error code.
194341*/
194342static int sqlite3Fts5IndexOpen(
194343  Fts5Config *pConfig,
194344  int bCreate,
194345  Fts5Index **pp,
194346  char **pzErr
194347){
194348  int rc = SQLITE_OK;
194349  Fts5Index *p;                   /* New object */
194350
194351  *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
194352  if( rc==SQLITE_OK ){
194353    p->pConfig = pConfig;
194354    p->nWorkUnit = FTS5_WORK_UNIT;
194355    p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
194356    if( p->zDataTbl && bCreate ){
194357      rc = sqlite3Fts5CreateTable(
194358          pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
194359      );
194360      if( rc==SQLITE_OK ){
194361        rc = sqlite3Fts5CreateTable(pConfig, "idx",
194362            "segid, term, pgno, PRIMARY KEY(segid, term)",
194363            1, pzErr
194364        );
194365      }
194366      if( rc==SQLITE_OK ){
194367        rc = sqlite3Fts5IndexReinit(p);
194368      }
194369    }
194370  }
194371
194372  assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
194373  if( rc ){
194374    sqlite3Fts5IndexClose(p);
194375    *pp = 0;
194376  }
194377  return rc;
194378}
194379
194380/*
194381** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
194382*/
194383static int sqlite3Fts5IndexClose(Fts5Index *p){
194384  int rc = SQLITE_OK;
194385  if( p ){
194386    assert( p->pReader==0 );
194387    fts5StructureInvalidate(p);
194388    sqlite3_finalize(p->pWriter);
194389    sqlite3_finalize(p->pDeleter);
194390    sqlite3_finalize(p->pIdxWriter);
194391    sqlite3_finalize(p->pIdxDeleter);
194392    sqlite3_finalize(p->pIdxSelect);
194393    sqlite3_finalize(p->pDataVersion);
194394    sqlite3Fts5HashFree(p->pHash);
194395    sqlite3_free(p->zDataTbl);
194396    sqlite3_free(p);
194397  }
194398  return rc;
194399}
194400
194401/*
194402** Argument p points to a buffer containing utf-8 text that is n bytes in
194403** size. Return the number of bytes in the nChar character prefix of the
194404** buffer, or 0 if there are less than nChar characters in total.
194405*/
194406static int sqlite3Fts5IndexCharlenToBytelen(
194407  const char *p,
194408  int nByte,
194409  int nChar
194410){
194411  int n = 0;
194412  int i;
194413  for(i=0; i<nChar; i++){
194414    if( n>=nByte ) return 0;      /* Input contains fewer than nChar chars */
194415    if( (unsigned char)p[n++]>=0xc0 ){
194416      while( (p[n] & 0xc0)==0x80 ) n++;
194417    }
194418  }
194419  return n;
194420}
194421
194422/*
194423** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
194424** unicode characters in the string.
194425*/
194426static int fts5IndexCharlen(const char *pIn, int nIn){
194427  int nChar = 0;
194428  int i = 0;
194429  while( i<nIn ){
194430    if( (unsigned char)pIn[i++]>=0xc0 ){
194431      while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
194432    }
194433    nChar++;
194434  }
194435  return nChar;
194436}
194437
194438/*
194439** Insert or remove data to or from the index. Each time a document is
194440** added to or removed from the index, this function is called one or more
194441** times.
194442**
194443** For an insert, it must be called once for each token in the new document.
194444** If the operation is a delete, it must be called (at least) once for each
194445** unique token in the document with an iCol value less than zero. The iPos
194446** argument is ignored for a delete.
194447*/
194448static int sqlite3Fts5IndexWrite(
194449  Fts5Index *p,                   /* Index to write to */
194450  int iCol,                       /* Column token appears in (-ve -> delete) */
194451  int iPos,                       /* Position of token within column */
194452  const char *pToken, int nToken  /* Token to add or remove to or from index */
194453){
194454  int i;                          /* Used to iterate through indexes */
194455  int rc = SQLITE_OK;             /* Return code */
194456  Fts5Config *pConfig = p->pConfig;
194457
194458  assert( p->rc==SQLITE_OK );
194459  assert( (iCol<0)==p->bDelete );
194460
194461  /* Add the entry to the main terms index. */
194462  rc = sqlite3Fts5HashWrite(
194463      p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
194464  );
194465
194466  for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
194467    const int nChar = pConfig->aPrefix[i];
194468    int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
194469    if( nByte ){
194470      rc = sqlite3Fts5HashWrite(p->pHash,
194471          p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
194472          nByte
194473      );
194474    }
194475  }
194476
194477  return rc;
194478}
194479
194480/*
194481** Open a new iterator to iterate though all rowid that match the
194482** specified token or token prefix.
194483*/
194484static int sqlite3Fts5IndexQuery(
194485  Fts5Index *p,                   /* FTS index to query */
194486  const char *pToken, int nToken, /* Token (or prefix) to query for */
194487  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
194488  Fts5Colset *pColset,            /* Match these columns only */
194489  Fts5IndexIter **ppIter          /* OUT: New iterator object */
194490){
194491  Fts5Config *pConfig = p->pConfig;
194492  Fts5Iter *pRet = 0;
194493  Fts5Buffer buf = {0, 0, 0};
194494
194495  /* If the QUERY_SCAN flag is set, all other flags must be clear. */
194496  assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
194497
194498  if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
194499    int iIdx = 0;                 /* Index to search */
194500    memcpy(&buf.p[1], pToken, nToken);
194501
194502    /* Figure out which index to search and set iIdx accordingly. If this
194503    ** is a prefix query for which there is no prefix index, set iIdx to
194504    ** greater than pConfig->nPrefix to indicate that the query will be
194505    ** satisfied by scanning multiple terms in the main index.
194506    **
194507    ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
194508    ** prefix-query. Instead of using a prefix-index (if one exists),
194509    ** evaluate the prefix query using the main FTS index. This is used
194510    ** for internal sanity checking by the integrity-check in debug
194511    ** mode only.  */
194512#ifdef SQLITE_DEBUG
194513    if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
194514      assert( flags & FTS5INDEX_QUERY_PREFIX );
194515      iIdx = 1+pConfig->nPrefix;
194516    }else
194517#endif
194518    if( flags & FTS5INDEX_QUERY_PREFIX ){
194519      int nChar = fts5IndexCharlen(pToken, nToken);
194520      for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
194521        if( pConfig->aPrefix[iIdx-1]==nChar ) break;
194522      }
194523    }
194524
194525    if( iIdx<=pConfig->nPrefix ){
194526      /* Straight index lookup */
194527      Fts5Structure *pStruct = fts5StructureRead(p);
194528      buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
194529      if( pStruct ){
194530        fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
194531            pColset, buf.p, nToken+1, -1, 0, &pRet
194532        );
194533        fts5StructureRelease(pStruct);
194534      }
194535    }else{
194536      /* Scan multiple terms in the main index */
194537      int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
194538      buf.p[0] = FTS5_MAIN_PREFIX;
194539      fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
194540      assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
194541      fts5IterSetOutputCb(&p->rc, pRet);
194542      if( p->rc==SQLITE_OK ){
194543        Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
194544        if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
194545      }
194546    }
194547
194548    if( p->rc ){
194549      sqlite3Fts5IterClose(&pRet->base);
194550      pRet = 0;
194551      fts5CloseReader(p);
194552    }
194553
194554    *ppIter = &pRet->base;
194555    sqlite3Fts5BufferFree(&buf);
194556  }
194557  return fts5IndexReturn(p);
194558}
194559
194560/*
194561** Return true if the iterator passed as the only argument is at EOF.
194562*/
194563/*
194564** Move to the next matching rowid.
194565*/
194566static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
194567  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
194568  assert( pIter->pIndex->rc==SQLITE_OK );
194569  fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
194570  return fts5IndexReturn(pIter->pIndex);
194571}
194572
194573/*
194574** Move to the next matching term/rowid. Used by the fts5vocab module.
194575*/
194576static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
194577  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
194578  Fts5Index *p = pIter->pIndex;
194579
194580  assert( pIter->pIndex->rc==SQLITE_OK );
194581
194582  fts5MultiIterNext(p, pIter, 0, 0);
194583  if( p->rc==SQLITE_OK ){
194584    Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
194585    if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
194586      fts5DataRelease(pSeg->pLeaf);
194587      pSeg->pLeaf = 0;
194588      pIter->base.bEof = 1;
194589    }
194590  }
194591
194592  return fts5IndexReturn(pIter->pIndex);
194593}
194594
194595/*
194596** Move to the next matching rowid that occurs at or after iMatch. The
194597** definition of "at or after" depends on whether this iterator iterates
194598** in ascending or descending rowid order.
194599*/
194600static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
194601  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
194602  fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
194603  return fts5IndexReturn(pIter->pIndex);
194604}
194605
194606/*
194607** Return the current term.
194608*/
194609static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
194610  int n;
194611  const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
194612  *pn = n-1;
194613  return &z[1];
194614}
194615
194616/*
194617** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
194618*/
194619static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
194620  if( pIndexIter ){
194621    Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
194622    Fts5Index *pIndex = pIter->pIndex;
194623    fts5MultiIterFree(pIter);
194624    fts5CloseReader(pIndex);
194625  }
194626}
194627
194628/*
194629** Read and decode the "averages" record from the database.
194630**
194631** Parameter anSize must point to an array of size nCol, where nCol is
194632** the number of user defined columns in the FTS table.
194633*/
194634static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
194635  int nCol = p->pConfig->nCol;
194636  Fts5Data *pData;
194637
194638  *pnRow = 0;
194639  memset(anSize, 0, sizeof(i64) * nCol);
194640  pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
194641  if( p->rc==SQLITE_OK && pData->nn ){
194642    int i = 0;
194643    int iCol;
194644    i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
194645    for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
194646      i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
194647    }
194648  }
194649
194650  fts5DataRelease(pData);
194651  return fts5IndexReturn(p);
194652}
194653
194654/*
194655** Replace the current "averages" record with the contents of the buffer
194656** supplied as the second argument.
194657*/
194658static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
194659  assert( p->rc==SQLITE_OK );
194660  fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
194661  return fts5IndexReturn(p);
194662}
194663
194664/*
194665** Return the total number of blocks this module has read from the %_data
194666** table since it was created.
194667*/
194668static int sqlite3Fts5IndexReads(Fts5Index *p){
194669  return p->nRead;
194670}
194671
194672/*
194673** Set the 32-bit cookie value stored at the start of all structure
194674** records to the value passed as the second argument.
194675**
194676** Return SQLITE_OK if successful, or an SQLite error code if an error
194677** occurs.
194678*/
194679static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
194680  int rc;                              /* Return code */
194681  Fts5Config *pConfig = p->pConfig;    /* Configuration object */
194682  u8 aCookie[4];                       /* Binary representation of iNew */
194683  sqlite3_blob *pBlob = 0;
194684
194685  assert( p->rc==SQLITE_OK );
194686  sqlite3Fts5Put32(aCookie, iNew);
194687
194688  rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
194689      "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
194690  );
194691  if( rc==SQLITE_OK ){
194692    sqlite3_blob_write(pBlob, aCookie, 4, 0);
194693    rc = sqlite3_blob_close(pBlob);
194694  }
194695
194696  return rc;
194697}
194698
194699static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
194700  Fts5Structure *pStruct;
194701  pStruct = fts5StructureRead(p);
194702  fts5StructureRelease(pStruct);
194703  return fts5IndexReturn(p);
194704}
194705
194706
194707/*************************************************************************
194708**************************************************************************
194709** Below this point is the implementation of the integrity-check
194710** functionality.
194711*/
194712
194713/*
194714** Return a simple checksum value based on the arguments.
194715*/
194716static u64 sqlite3Fts5IndexEntryCksum(
194717  i64 iRowid,
194718  int iCol,
194719  int iPos,
194720  int iIdx,
194721  const char *pTerm,
194722  int nTerm
194723){
194724  int i;
194725  u64 ret = iRowid;
194726  ret += (ret<<3) + iCol;
194727  ret += (ret<<3) + iPos;
194728  if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
194729  for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
194730  return ret;
194731}
194732
194733#ifdef SQLITE_DEBUG
194734/*
194735** This function is purely an internal test. It does not contribute to
194736** FTS functionality, or even the integrity-check, in any way.
194737**
194738** Instead, it tests that the same set of pgno/rowid combinations are
194739** visited regardless of whether the doclist-index identified by parameters
194740** iSegid/iLeaf is iterated in forwards or reverse order.
194741*/
194742static void fts5TestDlidxReverse(
194743  Fts5Index *p,
194744  int iSegid,                     /* Segment id to load from */
194745  int iLeaf                       /* Load doclist-index for this leaf */
194746){
194747  Fts5DlidxIter *pDlidx = 0;
194748  u64 cksum1 = 13;
194749  u64 cksum2 = 13;
194750
194751  for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
194752      fts5DlidxIterEof(p, pDlidx)==0;
194753      fts5DlidxIterNext(p, pDlidx)
194754  ){
194755    i64 iRowid = fts5DlidxIterRowid(pDlidx);
194756    int pgno = fts5DlidxIterPgno(pDlidx);
194757    assert( pgno>iLeaf );
194758    cksum1 += iRowid + ((i64)pgno<<32);
194759  }
194760  fts5DlidxIterFree(pDlidx);
194761  pDlidx = 0;
194762
194763  for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
194764      fts5DlidxIterEof(p, pDlidx)==0;
194765      fts5DlidxIterPrev(p, pDlidx)
194766  ){
194767    i64 iRowid = fts5DlidxIterRowid(pDlidx);
194768    int pgno = fts5DlidxIterPgno(pDlidx);
194769    assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
194770    cksum2 += iRowid + ((i64)pgno<<32);
194771  }
194772  fts5DlidxIterFree(pDlidx);
194773  pDlidx = 0;
194774
194775  if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
194776}
194777
194778static int fts5QueryCksum(
194779  Fts5Index *p,                   /* Fts5 index object */
194780  int iIdx,
194781  const char *z,                  /* Index key to query for */
194782  int n,                          /* Size of index key in bytes */
194783  int flags,                      /* Flags for Fts5IndexQuery */
194784  u64 *pCksum                     /* IN/OUT: Checksum value */
194785){
194786  int eDetail = p->pConfig->eDetail;
194787  u64 cksum = *pCksum;
194788  Fts5IndexIter *pIter = 0;
194789  int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
194790
194791  while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
194792    i64 rowid = pIter->iRowid;
194793
194794    if( eDetail==FTS5_DETAIL_NONE ){
194795      cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
194796    }else{
194797      Fts5PoslistReader sReader;
194798      for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
194799          sReader.bEof==0;
194800          sqlite3Fts5PoslistReaderNext(&sReader)
194801      ){
194802        int iCol = FTS5_POS2COLUMN(sReader.iPos);
194803        int iOff = FTS5_POS2OFFSET(sReader.iPos);
194804        cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
194805      }
194806    }
194807    if( rc==SQLITE_OK ){
194808      rc = sqlite3Fts5IterNext(pIter);
194809    }
194810  }
194811  sqlite3Fts5IterClose(pIter);
194812
194813  *pCksum = cksum;
194814  return rc;
194815}
194816
194817
194818/*
194819** This function is also purely an internal test. It does not contribute to
194820** FTS functionality, or even the integrity-check, in any way.
194821*/
194822static void fts5TestTerm(
194823  Fts5Index *p,
194824  Fts5Buffer *pPrev,              /* Previous term */
194825  const char *z, int n,           /* Possibly new term to test */
194826  u64 expected,
194827  u64 *pCksum
194828){
194829  int rc = p->rc;
194830  if( pPrev->n==0 ){
194831    fts5BufferSet(&rc, pPrev, n, (const u8*)z);
194832  }else
194833  if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
194834    u64 cksum3 = *pCksum;
194835    const char *zTerm = (const char*)&pPrev->p[1];  /* term sans prefix-byte */
194836    int nTerm = pPrev->n-1;            /* Size of zTerm in bytes */
194837    int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
194838    int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
194839    u64 ck1 = 0;
194840    u64 ck2 = 0;
194841
194842    /* Check that the results returned for ASC and DESC queries are
194843    ** the same. If not, call this corruption.  */
194844    rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
194845    if( rc==SQLITE_OK ){
194846      int f = flags|FTS5INDEX_QUERY_DESC;
194847      rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
194848    }
194849    if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
194850
194851    /* If this is a prefix query, check that the results returned if the
194852    ** the index is disabled are the same. In both ASC and DESC order.
194853    **
194854    ** This check may only be performed if the hash table is empty. This
194855    ** is because the hash table only supports a single scan query at
194856    ** a time, and the multi-iter loop from which this function is called
194857    ** is already performing such a scan. */
194858    if( p->nPendingData==0 ){
194859      if( iIdx>0 && rc==SQLITE_OK ){
194860        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
194861        ck2 = 0;
194862        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
194863        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
194864      }
194865      if( iIdx>0 && rc==SQLITE_OK ){
194866        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
194867        ck2 = 0;
194868        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
194869        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
194870      }
194871    }
194872
194873    cksum3 ^= ck1;
194874    fts5BufferSet(&rc, pPrev, n, (const u8*)z);
194875
194876    if( rc==SQLITE_OK && cksum3!=expected ){
194877      rc = FTS5_CORRUPT;
194878    }
194879    *pCksum = cksum3;
194880  }
194881  p->rc = rc;
194882}
194883
194884#else
194885# define fts5TestDlidxReverse(x,y,z)
194886# define fts5TestTerm(u,v,w,x,y,z)
194887#endif
194888
194889/*
194890** Check that:
194891**
194892**   1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
194893**      contain zero terms.
194894**   2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
194895**      contain zero rowids.
194896*/
194897static void fts5IndexIntegrityCheckEmpty(
194898  Fts5Index *p,
194899  Fts5StructureSegment *pSeg,     /* Segment to check internal consistency */
194900  int iFirst,
194901  int iNoRowid,
194902  int iLast
194903){
194904  int i;
194905
194906  /* Now check that the iter.nEmpty leaves following the current leaf
194907  ** (a) exist and (b) contain no terms. */
194908  for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
194909    Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
194910    if( pLeaf ){
194911      if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
194912      if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
194913    }
194914    fts5DataRelease(pLeaf);
194915  }
194916}
194917
194918static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
194919  int iTermOff = 0;
194920  int ii;
194921
194922  Fts5Buffer buf1 = {0,0,0};
194923  Fts5Buffer buf2 = {0,0,0};
194924
194925  ii = pLeaf->szLeaf;
194926  while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
194927    int res;
194928    int iOff;
194929    int nIncr;
194930
194931    ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
194932    iTermOff += nIncr;
194933    iOff = iTermOff;
194934
194935    if( iOff>=pLeaf->szLeaf ){
194936      p->rc = FTS5_CORRUPT;
194937    }else if( iTermOff==nIncr ){
194938      int nByte;
194939      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
194940      if( (iOff+nByte)>pLeaf->szLeaf ){
194941        p->rc = FTS5_CORRUPT;
194942      }else{
194943        fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
194944      }
194945    }else{
194946      int nKeep, nByte;
194947      iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
194948      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
194949      if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
194950        p->rc = FTS5_CORRUPT;
194951      }else{
194952        buf1.n = nKeep;
194953        fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
194954      }
194955
194956      if( p->rc==SQLITE_OK ){
194957        res = fts5BufferCompare(&buf1, &buf2);
194958        if( res<=0 ) p->rc = FTS5_CORRUPT;
194959      }
194960    }
194961    fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
194962  }
194963
194964  fts5BufferFree(&buf1);
194965  fts5BufferFree(&buf2);
194966}
194967
194968static void fts5IndexIntegrityCheckSegment(
194969  Fts5Index *p,                   /* FTS5 backend object */
194970  Fts5StructureSegment *pSeg      /* Segment to check internal consistency */
194971){
194972  Fts5Config *pConfig = p->pConfig;
194973  sqlite3_stmt *pStmt = 0;
194974  int rc2;
194975  int iIdxPrevLeaf = pSeg->pgnoFirst-1;
194976  int iDlidxPrevLeaf = pSeg->pgnoLast;
194977
194978  if( pSeg->pgnoFirst==0 ) return;
194979
194980  fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
194981      "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
194982      pConfig->zDb, pConfig->zName, pSeg->iSegid
194983  ));
194984
194985  /* Iterate through the b-tree hierarchy.  */
194986  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
194987    i64 iRow;                     /* Rowid for this leaf */
194988    Fts5Data *pLeaf;              /* Data for this leaf */
194989
194990    int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
194991    const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
194992    int iIdxLeaf = sqlite3_column_int(pStmt, 2);
194993    int bIdxDlidx = sqlite3_column_int(pStmt, 3);
194994
194995    /* If the leaf in question has already been trimmed from the segment,
194996    ** ignore this b-tree entry. Otherwise, load it into memory. */
194997    if( iIdxLeaf<pSeg->pgnoFirst ) continue;
194998    iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
194999    pLeaf = fts5LeafRead(p, iRow);
195000    if( pLeaf==0 ) break;
195001
195002    /* Check that the leaf contains at least one term, and that it is equal
195003    ** to or larger than the split-key in zIdxTerm.  Also check that if there
195004    ** is also a rowid pointer within the leaf page header, it points to a
195005    ** location before the term.  */
195006    if( pLeaf->nn<=pLeaf->szLeaf ){
195007      p->rc = FTS5_CORRUPT;
195008    }else{
195009      int iOff;                   /* Offset of first term on leaf */
195010      int iRowidOff;              /* Offset of first rowid on leaf */
195011      int nTerm;                  /* Size of term on leaf in bytes */
195012      int res;                    /* Comparison of term and split-key */
195013
195014      iOff = fts5LeafFirstTermOff(pLeaf);
195015      iRowidOff = fts5LeafFirstRowidOff(pLeaf);
195016      if( iRowidOff>=iOff ){
195017        p->rc = FTS5_CORRUPT;
195018      }else{
195019        iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
195020        res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
195021        if( res==0 ) res = nTerm - nIdxTerm;
195022        if( res<0 ) p->rc = FTS5_CORRUPT;
195023      }
195024
195025      fts5IntegrityCheckPgidx(p, pLeaf);
195026    }
195027    fts5DataRelease(pLeaf);
195028    if( p->rc ) break;
195029
195030    /* Now check that the iter.nEmpty leaves following the current leaf
195031    ** (a) exist and (b) contain no terms. */
195032    fts5IndexIntegrityCheckEmpty(
195033        p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
195034    );
195035    if( p->rc ) break;
195036
195037    /* If there is a doclist-index, check that it looks right. */
195038    if( bIdxDlidx ){
195039      Fts5DlidxIter *pDlidx = 0;  /* For iterating through doclist index */
195040      int iPrevLeaf = iIdxLeaf;
195041      int iSegid = pSeg->iSegid;
195042      int iPg = 0;
195043      i64 iKey;
195044
195045      for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
195046          fts5DlidxIterEof(p, pDlidx)==0;
195047          fts5DlidxIterNext(p, pDlidx)
195048      ){
195049
195050        /* Check any rowid-less pages that occur before the current leaf. */
195051        for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
195052          iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
195053          pLeaf = fts5DataRead(p, iKey);
195054          if( pLeaf ){
195055            if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
195056            fts5DataRelease(pLeaf);
195057          }
195058        }
195059        iPrevLeaf = fts5DlidxIterPgno(pDlidx);
195060
195061        /* Check that the leaf page indicated by the iterator really does
195062        ** contain the rowid suggested by the same. */
195063        iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
195064        pLeaf = fts5DataRead(p, iKey);
195065        if( pLeaf ){
195066          i64 iRowid;
195067          int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
195068          ASSERT_SZLEAF_OK(pLeaf);
195069          if( iRowidOff>=pLeaf->szLeaf ){
195070            p->rc = FTS5_CORRUPT;
195071          }else{
195072            fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
195073            if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
195074          }
195075          fts5DataRelease(pLeaf);
195076        }
195077      }
195078
195079      iDlidxPrevLeaf = iPg;
195080      fts5DlidxIterFree(pDlidx);
195081      fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
195082    }else{
195083      iDlidxPrevLeaf = pSeg->pgnoLast;
195084      /* TODO: Check there is no doclist index */
195085    }
195086
195087    iIdxPrevLeaf = iIdxLeaf;
195088  }
195089
195090  rc2 = sqlite3_finalize(pStmt);
195091  if( p->rc==SQLITE_OK ) p->rc = rc2;
195092
195093  /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
195094#if 0
195095  if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
195096    p->rc = FTS5_CORRUPT;
195097  }
195098#endif
195099}
195100
195101
195102/*
195103** Run internal checks to ensure that the FTS index (a) is internally
195104** consistent and (b) contains entries for which the XOR of the checksums
195105** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
195106**
195107** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
195108** checksum does not match. Return SQLITE_OK if all checks pass without
195109** error, or some other SQLite error code if another error (e.g. OOM)
195110** occurs.
195111*/
195112static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
195113  int eDetail = p->pConfig->eDetail;
195114  u64 cksum2 = 0;                 /* Checksum based on contents of indexes */
195115  Fts5Buffer poslist = {0,0,0};   /* Buffer used to hold a poslist */
195116  Fts5Iter *pIter;                /* Used to iterate through entire index */
195117  Fts5Structure *pStruct;         /* Index structure */
195118
195119#ifdef SQLITE_DEBUG
195120  /* Used by extra internal tests only run if NDEBUG is not defined */
195121  u64 cksum3 = 0;                 /* Checksum based on contents of indexes */
195122  Fts5Buffer term = {0,0,0};      /* Buffer used to hold most recent term */
195123#endif
195124  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
195125
195126  /* Load the FTS index structure */
195127  pStruct = fts5StructureRead(p);
195128
195129  /* Check that the internal nodes of each segment match the leaves */
195130  if( pStruct ){
195131    int iLvl, iSeg;
195132    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
195133      for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
195134        Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
195135        fts5IndexIntegrityCheckSegment(p, pSeg);
195136      }
195137    }
195138  }
195139
195140  /* The cksum argument passed to this function is a checksum calculated
195141  ** based on all expected entries in the FTS index (including prefix index
195142  ** entries). This block checks that a checksum calculated based on the
195143  ** actual contents of FTS index is identical.
195144  **
195145  ** Two versions of the same checksum are calculated. The first (stack
195146  ** variable cksum2) based on entries extracted from the full-text index
195147  ** while doing a linear scan of each individual index in turn.
195148  **
195149  ** As each term visited by the linear scans, a separate query for the
195150  ** same term is performed. cksum3 is calculated based on the entries
195151  ** extracted by these queries.
195152  */
195153  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
195154      fts5MultiIterEof(p, pIter)==0;
195155      fts5MultiIterNext(p, pIter, 0, 0)
195156  ){
195157    int n;                      /* Size of term in bytes */
195158    i64 iPos = 0;               /* Position read from poslist */
195159    int iOff = 0;               /* Offset within poslist */
195160    i64 iRowid = fts5MultiIterRowid(pIter);
195161    char *z = (char*)fts5MultiIterTerm(pIter, &n);
195162
195163    /* If this is a new term, query for it. Update cksum3 with the results. */
195164    fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
195165
195166    if( eDetail==FTS5_DETAIL_NONE ){
195167      if( 0==fts5MultiIterIsEmpty(p, pIter) ){
195168        cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
195169      }
195170    }else{
195171      poslist.n = 0;
195172      fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
195173      while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
195174        int iCol = FTS5_POS2COLUMN(iPos);
195175        int iTokOff = FTS5_POS2OFFSET(iPos);
195176        cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
195177      }
195178    }
195179  }
195180  fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
195181
195182  fts5MultiIterFree(pIter);
195183  if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
195184
195185  fts5StructureRelease(pStruct);
195186#ifdef SQLITE_DEBUG
195187  fts5BufferFree(&term);
195188#endif
195189  fts5BufferFree(&poslist);
195190  return fts5IndexReturn(p);
195191}
195192
195193/*************************************************************************
195194**************************************************************************
195195** Below this point is the implementation of the fts5_decode() scalar
195196** function only.
195197*/
195198
195199/*
195200** Decode a segment-data rowid from the %_data table. This function is
195201** the opposite of macro FTS5_SEGMENT_ROWID().
195202*/
195203static void fts5DecodeRowid(
195204  i64 iRowid,                     /* Rowid from %_data table */
195205  int *piSegid,                   /* OUT: Segment id */
195206  int *pbDlidx,                   /* OUT: Dlidx flag */
195207  int *piHeight,                  /* OUT: Height */
195208  int *piPgno                     /* OUT: Page number */
195209){
195210  *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
195211  iRowid >>= FTS5_DATA_PAGE_B;
195212
195213  *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
195214  iRowid >>= FTS5_DATA_HEIGHT_B;
195215
195216  *pbDlidx = (int)(iRowid & 0x0001);
195217  iRowid >>= FTS5_DATA_DLI_B;
195218
195219  *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
195220}
195221
195222static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
195223  int iSegid, iHeight, iPgno, bDlidx;       /* Rowid compenents */
195224  fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
195225
195226  if( iSegid==0 ){
195227    if( iKey==FTS5_AVERAGES_ROWID ){
195228      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
195229    }else{
195230      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
195231    }
195232  }
195233  else{
195234    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
195235        bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
195236    );
195237  }
195238}
195239
195240static void fts5DebugStructure(
195241  int *pRc,                       /* IN/OUT: error code */
195242  Fts5Buffer *pBuf,
195243  Fts5Structure *p
195244){
195245  int iLvl, iSeg;                 /* Iterate through levels, segments */
195246
195247  for(iLvl=0; iLvl<p->nLevel; iLvl++){
195248    Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
195249    sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
195250        " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
195251    );
195252    for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
195253      Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
195254      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
195255          pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
195256      );
195257    }
195258    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
195259  }
195260}
195261
195262/*
195263** This is part of the fts5_decode() debugging aid.
195264**
195265** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
195266** function appends a human-readable representation of the same object
195267** to the buffer passed as the second argument.
195268*/
195269static void fts5DecodeStructure(
195270  int *pRc,                       /* IN/OUT: error code */
195271  Fts5Buffer *pBuf,
195272  const u8 *pBlob, int nBlob
195273){
195274  int rc;                         /* Return code */
195275  Fts5Structure *p = 0;           /* Decoded structure object */
195276
195277  rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
195278  if( rc!=SQLITE_OK ){
195279    *pRc = rc;
195280    return;
195281  }
195282
195283  fts5DebugStructure(pRc, pBuf, p);
195284  fts5StructureRelease(p);
195285}
195286
195287/*
195288** This is part of the fts5_decode() debugging aid.
195289**
195290** Arguments pBlob/nBlob contain an "averages" record. This function
195291** appends a human-readable representation of record to the buffer passed
195292** as the second argument.
195293*/
195294static void fts5DecodeAverages(
195295  int *pRc,                       /* IN/OUT: error code */
195296  Fts5Buffer *pBuf,
195297  const u8 *pBlob, int nBlob
195298){
195299  int i = 0;
195300  const char *zSpace = "";
195301
195302  while( i<nBlob ){
195303    u64 iVal;
195304    i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
195305    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
195306    zSpace = " ";
195307  }
195308}
195309
195310/*
195311** Buffer (a/n) is assumed to contain a list of serialized varints. Read
195312** each varint and append its string representation to buffer pBuf. Return
195313** after either the input buffer is exhausted or a 0 value is read.
195314**
195315** The return value is the number of bytes read from the input buffer.
195316*/
195317static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
195318  int iOff = 0;
195319  while( iOff<n ){
195320    int iVal;
195321    iOff += fts5GetVarint32(&a[iOff], iVal);
195322    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
195323  }
195324  return iOff;
195325}
195326
195327/*
195328** The start of buffer (a/n) contains the start of a doclist. The doclist
195329** may or may not finish within the buffer. This function appends a text
195330** representation of the part of the doclist that is present to buffer
195331** pBuf.
195332**
195333** The return value is the number of bytes read from the input buffer.
195334*/
195335static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
195336  i64 iDocid = 0;
195337  int iOff = 0;
195338
195339  if( n>0 ){
195340    iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
195341    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
195342  }
195343  while( iOff<n ){
195344    int nPos;
195345    int bDel;
195346    iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
195347    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
195348    iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
195349    if( iOff<n ){
195350      i64 iDelta;
195351      iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
195352      iDocid += iDelta;
195353      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
195354    }
195355  }
195356
195357  return iOff;
195358}
195359
195360/*
195361** This function is part of the fts5_decode() debugging function. It is
195362** only ever used with detail=none tables.
195363**
195364** Buffer (pData/nData) contains a doclist in the format used by detail=none
195365** tables. This function appends a human-readable version of that list to
195366** buffer pBuf.
195367**
195368** If *pRc is other than SQLITE_OK when this function is called, it is a
195369** no-op. If an OOM or other error occurs within this function, *pRc is
195370** set to an SQLite error code before returning. The final state of buffer
195371** pBuf is undefined in this case.
195372*/
195373static void fts5DecodeRowidList(
195374  int *pRc,                       /* IN/OUT: Error code */
195375  Fts5Buffer *pBuf,               /* Buffer to append text to */
195376  const u8 *pData, int nData      /* Data to decode list-of-rowids from */
195377){
195378  int i = 0;
195379  i64 iRowid = 0;
195380
195381  while( i<nData ){
195382    const char *zApp = "";
195383    u64 iVal;
195384    i += sqlite3Fts5GetVarint(&pData[i], &iVal);
195385    iRowid += iVal;
195386
195387    if( i<nData && pData[i]==0x00 ){
195388      i++;
195389      if( i<nData && pData[i]==0x00 ){
195390        i++;
195391        zApp = "+";
195392      }else{
195393        zApp = "*";
195394      }
195395    }
195396
195397    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
195398  }
195399}
195400
195401/*
195402** The implementation of user-defined scalar function fts5_decode().
195403*/
195404static void fts5DecodeFunction(
195405  sqlite3_context *pCtx,          /* Function call context */
195406  int nArg,                       /* Number of args (always 2) */
195407  sqlite3_value **apVal           /* Function arguments */
195408){
195409  i64 iRowid;                     /* Rowid for record being decoded */
195410  int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
195411  const u8 *aBlob; int n;         /* Record to decode */
195412  u8 *a = 0;
195413  Fts5Buffer s;                   /* Build up text to return here */
195414  int rc = SQLITE_OK;             /* Return code */
195415  int nSpace = 0;
195416  int eDetailNone = (sqlite3_user_data(pCtx)!=0);
195417
195418  assert( nArg==2 );
195419  UNUSED_PARAM(nArg);
195420  memset(&s, 0, sizeof(Fts5Buffer));
195421  iRowid = sqlite3_value_int64(apVal[0]);
195422
195423  /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
195424  ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
195425  ** buffer overreads even if the record is corrupt.  */
195426  n = sqlite3_value_bytes(apVal[1]);
195427  aBlob = sqlite3_value_blob(apVal[1]);
195428  nSpace = n + FTS5_DATA_ZERO_PADDING;
195429  a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
195430  if( a==0 ) goto decode_out;
195431  memcpy(a, aBlob, n);
195432
195433
195434  fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
195435
195436  fts5DebugRowid(&rc, &s, iRowid);
195437  if( bDlidx ){
195438    Fts5Data dlidx;
195439    Fts5DlidxLvl lvl;
195440
195441    dlidx.p = a;
195442    dlidx.nn = n;
195443
195444    memset(&lvl, 0, sizeof(Fts5DlidxLvl));
195445    lvl.pData = &dlidx;
195446    lvl.iLeafPgno = iPgno;
195447
195448    for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
195449      sqlite3Fts5BufferAppendPrintf(&rc, &s,
195450          " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
195451      );
195452    }
195453  }else if( iSegid==0 ){
195454    if( iRowid==FTS5_AVERAGES_ROWID ){
195455      fts5DecodeAverages(&rc, &s, a, n);
195456    }else{
195457      fts5DecodeStructure(&rc, &s, a, n);
195458    }
195459  }else if( eDetailNone ){
195460    Fts5Buffer term;              /* Current term read from page */
195461    int szLeaf;
195462    int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
195463    int iTermOff;
195464    int nKeep = 0;
195465    int iOff;
195466
195467    memset(&term, 0, sizeof(Fts5Buffer));
195468
195469    /* Decode any entries that occur before the first term. */
195470    if( szLeaf<n ){
195471      iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
195472    }else{
195473      iTermOff = szLeaf;
195474    }
195475    fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
195476
195477    iOff = iTermOff;
195478    while( iOff<szLeaf ){
195479      int nAppend;
195480
195481      /* Read the term data for the next term*/
195482      iOff += fts5GetVarint32(&a[iOff], nAppend);
195483      term.n = nKeep;
195484      fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
195485      sqlite3Fts5BufferAppendPrintf(
195486          &rc, &s, " term=%.*s", term.n, (const char*)term.p
195487      );
195488      iOff += nAppend;
195489
195490      /* Figure out where the doclist for this term ends */
195491      if( iPgidxOff<n ){
195492        int nIncr;
195493        iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
195494        iTermOff += nIncr;
195495      }else{
195496        iTermOff = szLeaf;
195497      }
195498
195499      fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
195500      iOff = iTermOff;
195501      if( iOff<szLeaf ){
195502        iOff += fts5GetVarint32(&a[iOff], nKeep);
195503      }
195504    }
195505
195506    fts5BufferFree(&term);
195507  }else{
195508    Fts5Buffer term;              /* Current term read from page */
195509    int szLeaf;                   /* Offset of pgidx in a[] */
195510    int iPgidxOff;
195511    int iPgidxPrev = 0;           /* Previous value read from pgidx */
195512    int iTermOff = 0;
195513    int iRowidOff = 0;
195514    int iOff;
195515    int nDoclist;
195516
195517    memset(&term, 0, sizeof(Fts5Buffer));
195518
195519    if( n<4 ){
195520      sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
195521      goto decode_out;
195522    }else{
195523      iRowidOff = fts5GetU16(&a[0]);
195524      iPgidxOff = szLeaf = fts5GetU16(&a[2]);
195525      if( iPgidxOff<n ){
195526        fts5GetVarint32(&a[iPgidxOff], iTermOff);
195527      }
195528    }
195529
195530    /* Decode the position list tail at the start of the page */
195531    if( iRowidOff!=0 ){
195532      iOff = iRowidOff;
195533    }else if( iTermOff!=0 ){
195534      iOff = iTermOff;
195535    }else{
195536      iOff = szLeaf;
195537    }
195538    fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
195539
195540    /* Decode any more doclist data that appears on the page before the
195541    ** first term. */
195542    nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
195543    fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
195544
195545    while( iPgidxOff<n ){
195546      int bFirst = (iPgidxOff==szLeaf);     /* True for first term on page */
195547      int nByte;                            /* Bytes of data */
195548      int iEnd;
195549
195550      iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
195551      iPgidxPrev += nByte;
195552      iOff = iPgidxPrev;
195553
195554      if( iPgidxOff<n ){
195555        fts5GetVarint32(&a[iPgidxOff], nByte);
195556        iEnd = iPgidxPrev + nByte;
195557      }else{
195558        iEnd = szLeaf;
195559      }
195560
195561      if( bFirst==0 ){
195562        iOff += fts5GetVarint32(&a[iOff], nByte);
195563        term.n = nByte;
195564      }
195565      iOff += fts5GetVarint32(&a[iOff], nByte);
195566      fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
195567      iOff += nByte;
195568
195569      sqlite3Fts5BufferAppendPrintf(
195570          &rc, &s, " term=%.*s", term.n, (const char*)term.p
195571      );
195572      iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
195573    }
195574
195575    fts5BufferFree(&term);
195576  }
195577
195578 decode_out:
195579  sqlite3_free(a);
195580  if( rc==SQLITE_OK ){
195581    sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
195582  }else{
195583    sqlite3_result_error_code(pCtx, rc);
195584  }
195585  fts5BufferFree(&s);
195586}
195587
195588/*
195589** The implementation of user-defined scalar function fts5_rowid().
195590*/
195591static void fts5RowidFunction(
195592  sqlite3_context *pCtx,          /* Function call context */
195593  int nArg,                       /* Number of args (always 2) */
195594  sqlite3_value **apVal           /* Function arguments */
195595){
195596  const char *zArg;
195597  if( nArg==0 ){
195598    sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
195599  }else{
195600    zArg = (const char*)sqlite3_value_text(apVal[0]);
195601    if( 0==sqlite3_stricmp(zArg, "segment") ){
195602      i64 iRowid;
195603      int segid, pgno;
195604      if( nArg!=3 ){
195605        sqlite3_result_error(pCtx,
195606            "should be: fts5_rowid('segment', segid, pgno))", -1
195607        );
195608      }else{
195609        segid = sqlite3_value_int(apVal[1]);
195610        pgno = sqlite3_value_int(apVal[2]);
195611        iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
195612        sqlite3_result_int64(pCtx, iRowid);
195613      }
195614    }else{
195615      sqlite3_result_error(pCtx,
195616        "first arg to fts5_rowid() must be 'segment'" , -1
195617      );
195618    }
195619  }
195620}
195621
195622/*
195623** This is called as part of registering the FTS5 module with database
195624** connection db. It registers several user-defined scalar functions useful
195625** with FTS5.
195626**
195627** If successful, SQLITE_OK is returned. If an error occurs, some other
195628** SQLite error code is returned instead.
195629*/
195630static int sqlite3Fts5IndexInit(sqlite3 *db){
195631  int rc = sqlite3_create_function(
195632      db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
195633  );
195634
195635  if( rc==SQLITE_OK ){
195636    rc = sqlite3_create_function(
195637        db, "fts5_decode_none", 2,
195638        SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
195639    );
195640  }
195641
195642  if( rc==SQLITE_OK ){
195643    rc = sqlite3_create_function(
195644        db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
195645    );
195646  }
195647  return rc;
195648}
195649
195650
195651static int sqlite3Fts5IndexReset(Fts5Index *p){
195652  assert( p->pStruct==0 || p->iStructVersion!=0 );
195653  if( fts5IndexDataVersion(p)!=p->iStructVersion ){
195654    fts5StructureInvalidate(p);
195655  }
195656  return fts5IndexReturn(p);
195657}
195658
195659/*
195660** 2014 Jun 09
195661**
195662** The author disclaims copyright to this source code.  In place of
195663** a legal notice, here is a blessing:
195664**
195665**    May you do good and not evil.
195666**    May you find forgiveness for yourself and forgive others.
195667**    May you share freely, never taking more than you give.
195668**
195669******************************************************************************
195670**
195671** This is an SQLite module implementing full-text search.
195672*/
195673
195674
195675/* #include "fts5Int.h" */
195676
195677/*
195678** This variable is set to false when running tests for which the on disk
195679** structures should not be corrupt. Otherwise, true. If it is false, extra
195680** assert() conditions in the fts5 code are activated - conditions that are
195681** only true if it is guaranteed that the fts5 database is not corrupt.
195682*/
195683SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
195684
195685
195686typedef struct Fts5Auxdata Fts5Auxdata;
195687typedef struct Fts5Auxiliary Fts5Auxiliary;
195688typedef struct Fts5Cursor Fts5Cursor;
195689typedef struct Fts5Sorter Fts5Sorter;
195690typedef struct Fts5Table Fts5Table;
195691typedef struct Fts5TokenizerModule Fts5TokenizerModule;
195692
195693/*
195694** NOTES ON TRANSACTIONS:
195695**
195696** SQLite invokes the following virtual table methods as transactions are
195697** opened and closed by the user:
195698**
195699**     xBegin():    Start of a new transaction.
195700**     xSync():     Initial part of two-phase commit.
195701**     xCommit():   Final part of two-phase commit.
195702**     xRollback(): Rollback the transaction.
195703**
195704** Anything that is required as part of a commit that may fail is performed
195705** in the xSync() callback. Current versions of SQLite ignore any errors
195706** returned by xCommit().
195707**
195708** And as sub-transactions are opened/closed:
195709**
195710**     xSavepoint(int S):  Open savepoint S.
195711**     xRelease(int S):    Commit and close savepoint S.
195712**     xRollbackTo(int S): Rollback to start of savepoint S.
195713**
195714** During a write-transaction the fts5_index.c module may cache some data
195715** in-memory. It is flushed to disk whenever xSync(), xRelease() or
195716** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
195717** is called.
195718**
195719** Additionally, if SQLITE_DEBUG is defined, an instance of the following
195720** structure is used to record the current transaction state. This information
195721** is not required, but it is used in the assert() statements executed by
195722** function fts5CheckTransactionState() (see below).
195723*/
195724struct Fts5TransactionState {
195725  int eState;                     /* 0==closed, 1==open, 2==synced */
195726  int iSavepoint;                 /* Number of open savepoints (0 -> none) */
195727};
195728
195729/*
195730** A single object of this type is allocated when the FTS5 module is
195731** registered with a database handle. It is used to store pointers to
195732** all registered FTS5 extensions - tokenizers and auxiliary functions.
195733*/
195734struct Fts5Global {
195735  fts5_api api;                   /* User visible part of object (see fts5.h) */
195736  sqlite3 *db;                    /* Associated database connection */
195737  i64 iNextId;                    /* Used to allocate unique cursor ids */
195738  Fts5Auxiliary *pAux;            /* First in list of all aux. functions */
195739  Fts5TokenizerModule *pTok;      /* First in list of all tokenizer modules */
195740  Fts5TokenizerModule *pDfltTok;  /* Default tokenizer module */
195741  Fts5Cursor *pCsr;               /* First in list of all open cursors */
195742};
195743
195744/*
195745** Each auxiliary function registered with the FTS5 module is represented
195746** by an object of the following type. All such objects are stored as part
195747** of the Fts5Global.pAux list.
195748*/
195749struct Fts5Auxiliary {
195750  Fts5Global *pGlobal;            /* Global context for this function */
195751  char *zFunc;                    /* Function name (nul-terminated) */
195752  void *pUserData;                /* User-data pointer */
195753  fts5_extension_function xFunc;  /* Callback function */
195754  void (*xDestroy)(void*);        /* Destructor function */
195755  Fts5Auxiliary *pNext;           /* Next registered auxiliary function */
195756};
195757
195758/*
195759** Each tokenizer module registered with the FTS5 module is represented
195760** by an object of the following type. All such objects are stored as part
195761** of the Fts5Global.pTok list.
195762*/
195763struct Fts5TokenizerModule {
195764  char *zName;                    /* Name of tokenizer */
195765  void *pUserData;                /* User pointer passed to xCreate() */
195766  fts5_tokenizer x;               /* Tokenizer functions */
195767  void (*xDestroy)(void*);        /* Destructor function */
195768  Fts5TokenizerModule *pNext;     /* Next registered tokenizer module */
195769};
195770
195771/*
195772** Virtual-table object.
195773*/
195774struct Fts5Table {
195775  sqlite3_vtab base;              /* Base class used by SQLite core */
195776  Fts5Config *pConfig;            /* Virtual table configuration */
195777  Fts5Index *pIndex;              /* Full-text index */
195778  Fts5Storage *pStorage;          /* Document store */
195779  Fts5Global *pGlobal;            /* Global (connection wide) data */
195780  Fts5Cursor *pSortCsr;           /* Sort data from this cursor */
195781#ifdef SQLITE_DEBUG
195782  struct Fts5TransactionState ts;
195783#endif
195784};
195785
195786struct Fts5MatchPhrase {
195787  Fts5Buffer *pPoslist;           /* Pointer to current poslist */
195788  int nTerm;                      /* Size of phrase in terms */
195789};
195790
195791/*
195792** pStmt:
195793**   SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
195794**
195795** aIdx[]:
195796**   There is one entry in the aIdx[] array for each phrase in the query,
195797**   the value of which is the offset within aPoslist[] following the last
195798**   byte of the position list for the corresponding phrase.
195799*/
195800struct Fts5Sorter {
195801  sqlite3_stmt *pStmt;
195802  i64 iRowid;                     /* Current rowid */
195803  const u8 *aPoslist;             /* Position lists for current row */
195804  int nIdx;                       /* Number of entries in aIdx[] */
195805  int aIdx[1];                    /* Offsets into aPoslist for current row */
195806};
195807
195808
195809/*
195810** Virtual-table cursor object.
195811**
195812** iSpecial:
195813**   If this is a 'special' query (refer to function fts5SpecialMatch()),
195814**   then this variable contains the result of the query.
195815**
195816** iFirstRowid, iLastRowid:
195817**   These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
195818**   cursor iterates in ascending order of rowids, iFirstRowid is the lower
195819**   limit of rowids to return, and iLastRowid the upper. In other words, the
195820**   WHERE clause in the user's query might have been:
195821**
195822**       <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
195823**
195824**   If the cursor iterates in descending order of rowid, iFirstRowid
195825**   is the upper limit (i.e. the "first" rowid visited) and iLastRowid
195826**   the lower.
195827*/
195828struct Fts5Cursor {
195829  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
195830  Fts5Cursor *pNext;              /* Next cursor in Fts5Cursor.pCsr list */
195831  int *aColumnSize;               /* Values for xColumnSize() */
195832  i64 iCsrId;                     /* Cursor id */
195833
195834  /* Zero from this point onwards on cursor reset */
195835  int ePlan;                      /* FTS5_PLAN_XXX value */
195836  int bDesc;                      /* True for "ORDER BY rowid DESC" queries */
195837  i64 iFirstRowid;                /* Return no rowids earlier than this */
195838  i64 iLastRowid;                 /* Return no rowids later than this */
195839  sqlite3_stmt *pStmt;            /* Statement used to read %_content */
195840  Fts5Expr *pExpr;                /* Expression for MATCH queries */
195841  Fts5Sorter *pSorter;            /* Sorter for "ORDER BY rank" queries */
195842  int csrflags;                   /* Mask of cursor flags (see below) */
195843  i64 iSpecial;                   /* Result of special query */
195844
195845  /* "rank" function. Populated on demand from vtab.xColumn(). */
195846  char *zRank;                    /* Custom rank function */
195847  char *zRankArgs;                /* Custom rank function args */
195848  Fts5Auxiliary *pRank;           /* Rank callback (or NULL) */
195849  int nRankArg;                   /* Number of trailing arguments for rank() */
195850  sqlite3_value **apRankArg;      /* Array of trailing arguments */
195851  sqlite3_stmt *pRankArgStmt;     /* Origin of objects in apRankArg[] */
195852
195853  /* Auxiliary data storage */
195854  Fts5Auxiliary *pAux;            /* Currently executing extension function */
195855  Fts5Auxdata *pAuxdata;          /* First in linked list of saved aux-data */
195856
195857  /* Cache used by auxiliary functions xInst() and xInstCount() */
195858  Fts5PoslistReader *aInstIter;   /* One for each phrase */
195859  int nInstAlloc;                 /* Size of aInst[] array (entries / 3) */
195860  int nInstCount;                 /* Number of phrase instances */
195861  int *aInst;                     /* 3 integers per phrase instance */
195862};
195863
195864/*
195865** Bits that make up the "idxNum" parameter passed indirectly by
195866** xBestIndex() to xFilter().
195867*/
195868#define FTS5_BI_MATCH        0x0001         /* <tbl> MATCH ? */
195869#define FTS5_BI_RANK         0x0002         /* rank MATCH ? */
195870#define FTS5_BI_ROWID_EQ     0x0004         /* rowid == ? */
195871#define FTS5_BI_ROWID_LE     0x0008         /* rowid <= ? */
195872#define FTS5_BI_ROWID_GE     0x0010         /* rowid >= ? */
195873
195874#define FTS5_BI_ORDER_RANK   0x0020
195875#define FTS5_BI_ORDER_ROWID  0x0040
195876#define FTS5_BI_ORDER_DESC   0x0080
195877
195878/*
195879** Values for Fts5Cursor.csrflags
195880*/
195881#define FTS5CSR_EOF               0x01
195882#define FTS5CSR_REQUIRE_CONTENT   0x02
195883#define FTS5CSR_REQUIRE_DOCSIZE   0x04
195884#define FTS5CSR_REQUIRE_INST      0x08
195885#define FTS5CSR_FREE_ZRANK        0x10
195886#define FTS5CSR_REQUIRE_RESEEK    0x20
195887#define FTS5CSR_REQUIRE_POSLIST   0x40
195888
195889#define BitFlagAllTest(x,y) (((x) & (y))==(y))
195890#define BitFlagTest(x,y)    (((x) & (y))!=0)
195891
195892
195893/*
195894** Macros to Set(), Clear() and Test() cursor flags.
195895*/
195896#define CsrFlagSet(pCsr, flag)   ((pCsr)->csrflags |= (flag))
195897#define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
195898#define CsrFlagTest(pCsr, flag)  ((pCsr)->csrflags & (flag))
195899
195900struct Fts5Auxdata {
195901  Fts5Auxiliary *pAux;            /* Extension to which this belongs */
195902  void *pPtr;                     /* Pointer value */
195903  void(*xDelete)(void*);          /* Destructor */
195904  Fts5Auxdata *pNext;             /* Next object in linked list */
195905};
195906
195907#ifdef SQLITE_DEBUG
195908#define FTS5_BEGIN      1
195909#define FTS5_SYNC       2
195910#define FTS5_COMMIT     3
195911#define FTS5_ROLLBACK   4
195912#define FTS5_SAVEPOINT  5
195913#define FTS5_RELEASE    6
195914#define FTS5_ROLLBACKTO 7
195915static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
195916  switch( op ){
195917    case FTS5_BEGIN:
195918      assert( p->ts.eState==0 );
195919      p->ts.eState = 1;
195920      p->ts.iSavepoint = -1;
195921      break;
195922
195923    case FTS5_SYNC:
195924      assert( p->ts.eState==1 );
195925      p->ts.eState = 2;
195926      break;
195927
195928    case FTS5_COMMIT:
195929      assert( p->ts.eState==2 );
195930      p->ts.eState = 0;
195931      break;
195932
195933    case FTS5_ROLLBACK:
195934      assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
195935      p->ts.eState = 0;
195936      break;
195937
195938    case FTS5_SAVEPOINT:
195939      assert( p->ts.eState==1 );
195940      assert( iSavepoint>=0 );
195941      assert( iSavepoint>p->ts.iSavepoint );
195942      p->ts.iSavepoint = iSavepoint;
195943      break;
195944
195945    case FTS5_RELEASE:
195946      assert( p->ts.eState==1 );
195947      assert( iSavepoint>=0 );
195948      assert( iSavepoint<=p->ts.iSavepoint );
195949      p->ts.iSavepoint = iSavepoint-1;
195950      break;
195951
195952    case FTS5_ROLLBACKTO:
195953      assert( p->ts.eState==1 );
195954      assert( iSavepoint>=0 );
195955      assert( iSavepoint<=p->ts.iSavepoint );
195956      p->ts.iSavepoint = iSavepoint;
195957      break;
195958  }
195959}
195960#else
195961# define fts5CheckTransactionState(x,y,z)
195962#endif
195963
195964/*
195965** Return true if pTab is a contentless table.
195966*/
195967static int fts5IsContentless(Fts5Table *pTab){
195968  return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
195969}
195970
195971/*
195972** Delete a virtual table handle allocated by fts5InitVtab().
195973*/
195974static void fts5FreeVtab(Fts5Table *pTab){
195975  if( pTab ){
195976    sqlite3Fts5IndexClose(pTab->pIndex);
195977    sqlite3Fts5StorageClose(pTab->pStorage);
195978    sqlite3Fts5ConfigFree(pTab->pConfig);
195979    sqlite3_free(pTab);
195980  }
195981}
195982
195983/*
195984** The xDisconnect() virtual table method.
195985*/
195986static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
195987  fts5FreeVtab((Fts5Table*)pVtab);
195988  return SQLITE_OK;
195989}
195990
195991/*
195992** The xDestroy() virtual table method.
195993*/
195994static int fts5DestroyMethod(sqlite3_vtab *pVtab){
195995  Fts5Table *pTab = (Fts5Table*)pVtab;
195996  int rc = sqlite3Fts5DropAll(pTab->pConfig);
195997  if( rc==SQLITE_OK ){
195998    fts5FreeVtab((Fts5Table*)pVtab);
195999  }
196000  return rc;
196001}
196002
196003/*
196004** This function is the implementation of both the xConnect and xCreate
196005** methods of the FTS3 virtual table.
196006**
196007** The argv[] array contains the following:
196008**
196009**   argv[0]   -> module name  ("fts5")
196010**   argv[1]   -> database name
196011**   argv[2]   -> table name
196012**   argv[...] -> "column name" and other module argument fields.
196013*/
196014static int fts5InitVtab(
196015  int bCreate,                    /* True for xCreate, false for xConnect */
196016  sqlite3 *db,                    /* The SQLite database connection */
196017  void *pAux,                     /* Hash table containing tokenizers */
196018  int argc,                       /* Number of elements in argv array */
196019  const char * const *argv,       /* xCreate/xConnect argument array */
196020  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
196021  char **pzErr                    /* Write any error message here */
196022){
196023  Fts5Global *pGlobal = (Fts5Global*)pAux;
196024  const char **azConfig = (const char**)argv;
196025  int rc = SQLITE_OK;             /* Return code */
196026  Fts5Config *pConfig = 0;        /* Results of parsing argc/argv */
196027  Fts5Table *pTab = 0;            /* New virtual table object */
196028
196029  /* Allocate the new vtab object and parse the configuration */
196030  pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
196031  if( rc==SQLITE_OK ){
196032    rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
196033    assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
196034  }
196035  if( rc==SQLITE_OK ){
196036    pTab->pConfig = pConfig;
196037    pTab->pGlobal = pGlobal;
196038  }
196039
196040  /* Open the index sub-system */
196041  if( rc==SQLITE_OK ){
196042    rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
196043  }
196044
196045  /* Open the storage sub-system */
196046  if( rc==SQLITE_OK ){
196047    rc = sqlite3Fts5StorageOpen(
196048        pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
196049    );
196050  }
196051
196052  /* Call sqlite3_declare_vtab() */
196053  if( rc==SQLITE_OK ){
196054    rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
196055  }
196056
196057  /* Load the initial configuration */
196058  if( rc==SQLITE_OK ){
196059    assert( pConfig->pzErrmsg==0 );
196060    pConfig->pzErrmsg = pzErr;
196061    rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
196062    sqlite3Fts5IndexRollback(pTab->pIndex);
196063    pConfig->pzErrmsg = 0;
196064  }
196065
196066  if( rc!=SQLITE_OK ){
196067    fts5FreeVtab(pTab);
196068    pTab = 0;
196069  }else if( bCreate ){
196070    fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
196071  }
196072  *ppVTab = (sqlite3_vtab*)pTab;
196073  return rc;
196074}
196075
196076/*
196077** The xConnect() and xCreate() methods for the virtual table. All the
196078** work is done in function fts5InitVtab().
196079*/
196080static int fts5ConnectMethod(
196081  sqlite3 *db,                    /* Database connection */
196082  void *pAux,                     /* Pointer to tokenizer hash table */
196083  int argc,                       /* Number of elements in argv array */
196084  const char * const *argv,       /* xCreate/xConnect argument array */
196085  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
196086  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
196087){
196088  return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
196089}
196090static int fts5CreateMethod(
196091  sqlite3 *db,                    /* Database connection */
196092  void *pAux,                     /* Pointer to tokenizer hash table */
196093  int argc,                       /* Number of elements in argv array */
196094  const char * const *argv,       /* xCreate/xConnect argument array */
196095  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
196096  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
196097){
196098  return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
196099}
196100
196101/*
196102** The different query plans.
196103*/
196104#define FTS5_PLAN_MATCH          1       /* (<tbl> MATCH ?) */
196105#define FTS5_PLAN_SOURCE         2       /* A source cursor for SORTED_MATCH */
196106#define FTS5_PLAN_SPECIAL        3       /* An internal query */
196107#define FTS5_PLAN_SORTED_MATCH   4       /* (<tbl> MATCH ? ORDER BY rank) */
196108#define FTS5_PLAN_SCAN           5       /* No usable constraint */
196109#define FTS5_PLAN_ROWID          6       /* (rowid = ?) */
196110
196111/*
196112** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
196113** extension is currently being used by a version of SQLite too old to
196114** support index-info flags. In that case this function is a no-op.
196115*/
196116static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
196117#if SQLITE_VERSION_NUMBER>=3008012
196118#ifndef SQLITE_CORE
196119  if( sqlite3_libversion_number()>=3008012 )
196120#endif
196121  {
196122    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
196123  }
196124#endif
196125}
196126
196127/*
196128** Implementation of the xBestIndex method for FTS5 tables. Within the
196129** WHERE constraint, it searches for the following:
196130**
196131**   1. A MATCH constraint against the special column.
196132**   2. A MATCH constraint against the "rank" column.
196133**   3. An == constraint against the rowid column.
196134**   4. A < or <= constraint against the rowid column.
196135**   5. A > or >= constraint against the rowid column.
196136**
196137** Within the ORDER BY, either:
196138**
196139**   5. ORDER BY rank [ASC|DESC]
196140**   6. ORDER BY rowid [ASC|DESC]
196141**
196142** Costs are assigned as follows:
196143**
196144**  a) If an unusable MATCH operator is present in the WHERE clause, the
196145**     cost is unconditionally set to 1e50 (a really big number).
196146**
196147**  a) If a MATCH operator is present, the cost depends on the other
196148**     constraints also present. As follows:
196149**
196150**       * No other constraints:         cost=1000.0
196151**       * One rowid range constraint:   cost=750.0
196152**       * Both rowid range constraints: cost=500.0
196153**       * An == rowid constraint:       cost=100.0
196154**
196155**  b) Otherwise, if there is no MATCH:
196156**
196157**       * No other constraints:         cost=1000000.0
196158**       * One rowid range constraint:   cost=750000.0
196159**       * Both rowid range constraints: cost=250000.0
196160**       * An == rowid constraint:       cost=10.0
196161**
196162** Costs are not modified by the ORDER BY clause.
196163*/
196164static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
196165  Fts5Table *pTab = (Fts5Table*)pVTab;
196166  Fts5Config *pConfig = pTab->pConfig;
196167  int idxFlags = 0;               /* Parameter passed through to xFilter() */
196168  int bHasMatch;
196169  int iNext;
196170  int i;
196171
196172  struct Constraint {
196173    int op;                       /* Mask against sqlite3_index_constraint.op */
196174    int fts5op;                   /* FTS5 mask for idxFlags */
196175    int iCol;                     /* 0==rowid, 1==tbl, 2==rank */
196176    int omit;                     /* True to omit this if found */
196177    int iConsIndex;               /* Index in pInfo->aConstraint[] */
196178  } aConstraint[] = {
196179    {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
196180                                    FTS5_BI_MATCH,    1, 1, -1},
196181    {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
196182                                    FTS5_BI_RANK,     2, 1, -1},
196183    {SQLITE_INDEX_CONSTRAINT_EQ,    FTS5_BI_ROWID_EQ, 0, 0, -1},
196184    {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
196185                                    FTS5_BI_ROWID_LE, 0, 0, -1},
196186    {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
196187                                    FTS5_BI_ROWID_GE, 0, 0, -1},
196188  };
196189
196190  int aColMap[3];
196191  aColMap[0] = -1;
196192  aColMap[1] = pConfig->nCol;
196193  aColMap[2] = pConfig->nCol+1;
196194
196195  /* Set idxFlags flags for all WHERE clause terms that will be used. */
196196  for(i=0; i<pInfo->nConstraint; i++){
196197    struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
196198    int j;
196199    for(j=0; j<ArraySize(aConstraint); j++){
196200      struct Constraint *pC = &aConstraint[j];
196201      if( p->iColumn==aColMap[pC->iCol] && p->op & pC->op ){
196202        if( p->usable ){
196203          pC->iConsIndex = i;
196204          idxFlags |= pC->fts5op;
196205        }else if( j==0 ){
196206          /* As there exists an unusable MATCH constraint this is an
196207          ** unusable plan. Set a prohibitively high cost. */
196208          pInfo->estimatedCost = 1e50;
196209          return SQLITE_OK;
196210        }
196211      }
196212    }
196213  }
196214
196215  /* Set idxFlags flags for the ORDER BY clause */
196216  if( pInfo->nOrderBy==1 ){
196217    int iSort = pInfo->aOrderBy[0].iColumn;
196218    if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
196219      idxFlags |= FTS5_BI_ORDER_RANK;
196220    }else if( iSort==-1 ){
196221      idxFlags |= FTS5_BI_ORDER_ROWID;
196222    }
196223    if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
196224      pInfo->orderByConsumed = 1;
196225      if( pInfo->aOrderBy[0].desc ){
196226        idxFlags |= FTS5_BI_ORDER_DESC;
196227      }
196228    }
196229  }
196230
196231  /* Calculate the estimated cost based on the flags set in idxFlags. */
196232  bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
196233  if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
196234    pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
196235    if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
196236  }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
196237    pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
196238  }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
196239    pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
196240  }else{
196241    pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
196242  }
196243
196244  /* Assign argvIndex values to each constraint in use. */
196245  iNext = 1;
196246  for(i=0; i<ArraySize(aConstraint); i++){
196247    struct Constraint *pC = &aConstraint[i];
196248    if( pC->iConsIndex>=0 ){
196249      pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
196250      pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
196251    }
196252  }
196253
196254  pInfo->idxNum = idxFlags;
196255  return SQLITE_OK;
196256}
196257
196258static int fts5NewTransaction(Fts5Table *pTab){
196259  Fts5Cursor *pCsr;
196260  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
196261    if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
196262  }
196263  return sqlite3Fts5StorageReset(pTab->pStorage);
196264}
196265
196266/*
196267** Implementation of xOpen method.
196268*/
196269static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
196270  Fts5Table *pTab = (Fts5Table*)pVTab;
196271  Fts5Config *pConfig = pTab->pConfig;
196272  Fts5Cursor *pCsr = 0;           /* New cursor object */
196273  int nByte;                      /* Bytes of space to allocate */
196274  int rc;                         /* Return code */
196275
196276  rc = fts5NewTransaction(pTab);
196277  if( rc==SQLITE_OK ){
196278    nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
196279    pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
196280    if( pCsr ){
196281      Fts5Global *pGlobal = pTab->pGlobal;
196282      memset(pCsr, 0, nByte);
196283      pCsr->aColumnSize = (int*)&pCsr[1];
196284      pCsr->pNext = pGlobal->pCsr;
196285      pGlobal->pCsr = pCsr;
196286      pCsr->iCsrId = ++pGlobal->iNextId;
196287    }else{
196288      rc = SQLITE_NOMEM;
196289    }
196290  }
196291  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
196292  return rc;
196293}
196294
196295static int fts5StmtType(Fts5Cursor *pCsr){
196296  if( pCsr->ePlan==FTS5_PLAN_SCAN ){
196297    return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
196298  }
196299  return FTS5_STMT_LOOKUP;
196300}
196301
196302/*
196303** This function is called after the cursor passed as the only argument
196304** is moved to point at a different row. It clears all cached data
196305** specific to the previous row stored by the cursor object.
196306*/
196307static void fts5CsrNewrow(Fts5Cursor *pCsr){
196308  CsrFlagSet(pCsr,
196309      FTS5CSR_REQUIRE_CONTENT
196310    | FTS5CSR_REQUIRE_DOCSIZE
196311    | FTS5CSR_REQUIRE_INST
196312    | FTS5CSR_REQUIRE_POSLIST
196313  );
196314}
196315
196316static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
196317  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
196318  Fts5Auxdata *pData;
196319  Fts5Auxdata *pNext;
196320
196321  sqlite3_free(pCsr->aInstIter);
196322  sqlite3_free(pCsr->aInst);
196323  if( pCsr->pStmt ){
196324    int eStmt = fts5StmtType(pCsr);
196325    sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
196326  }
196327  if( pCsr->pSorter ){
196328    Fts5Sorter *pSorter = pCsr->pSorter;
196329    sqlite3_finalize(pSorter->pStmt);
196330    sqlite3_free(pSorter);
196331  }
196332
196333  if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
196334    sqlite3Fts5ExprFree(pCsr->pExpr);
196335  }
196336
196337  for(pData=pCsr->pAuxdata; pData; pData=pNext){
196338    pNext = pData->pNext;
196339    if( pData->xDelete ) pData->xDelete(pData->pPtr);
196340    sqlite3_free(pData);
196341  }
196342
196343  sqlite3_finalize(pCsr->pRankArgStmt);
196344  sqlite3_free(pCsr->apRankArg);
196345
196346  if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
196347    sqlite3_free(pCsr->zRank);
196348    sqlite3_free(pCsr->zRankArgs);
196349  }
196350
196351  memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
196352}
196353
196354
196355/*
196356** Close the cursor.  For additional information see the documentation
196357** on the xClose method of the virtual table interface.
196358*/
196359static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
196360  if( pCursor ){
196361    Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
196362    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
196363    Fts5Cursor **pp;
196364
196365    fts5FreeCursorComponents(pCsr);
196366    /* Remove the cursor from the Fts5Global.pCsr list */
196367    for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
196368    *pp = pCsr->pNext;
196369
196370    sqlite3_free(pCsr);
196371  }
196372  return SQLITE_OK;
196373}
196374
196375static int fts5SorterNext(Fts5Cursor *pCsr){
196376  Fts5Sorter *pSorter = pCsr->pSorter;
196377  int rc;
196378
196379  rc = sqlite3_step(pSorter->pStmt);
196380  if( rc==SQLITE_DONE ){
196381    rc = SQLITE_OK;
196382    CsrFlagSet(pCsr, FTS5CSR_EOF);
196383  }else if( rc==SQLITE_ROW ){
196384    const u8 *a;
196385    const u8 *aBlob;
196386    int nBlob;
196387    int i;
196388    int iOff = 0;
196389    rc = SQLITE_OK;
196390
196391    pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
196392    nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
196393    aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
196394
196395    /* nBlob==0 in detail=none mode. */
196396    if( nBlob>0 ){
196397      for(i=0; i<(pSorter->nIdx-1); i++){
196398        int iVal;
196399        a += fts5GetVarint32(a, iVal);
196400        iOff += iVal;
196401        pSorter->aIdx[i] = iOff;
196402      }
196403      pSorter->aIdx[i] = &aBlob[nBlob] - a;
196404      pSorter->aPoslist = a;
196405    }
196406
196407    fts5CsrNewrow(pCsr);
196408  }
196409
196410  return rc;
196411}
196412
196413
196414/*
196415** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
196416** open on table pTab.
196417*/
196418static void fts5TripCursors(Fts5Table *pTab){
196419  Fts5Cursor *pCsr;
196420  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
196421    if( pCsr->ePlan==FTS5_PLAN_MATCH
196422     && pCsr->base.pVtab==(sqlite3_vtab*)pTab
196423    ){
196424      CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
196425    }
196426  }
196427}
196428
196429/*
196430** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
196431** argument, close and reopen all Fts5IndexIter iterators that the cursor
196432** is using. Then attempt to move the cursor to a rowid equal to or laster
196433** (in the cursors sort order - ASC or DESC) than the current rowid.
196434**
196435** If the new rowid is not equal to the old, set output parameter *pbSkip
196436** to 1 before returning. Otherwise, leave it unchanged.
196437**
196438** Return SQLITE_OK if successful or if no reseek was required, or an
196439** error code if an error occurred.
196440*/
196441static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
196442  int rc = SQLITE_OK;
196443  assert( *pbSkip==0 );
196444  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
196445    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
196446    int bDesc = pCsr->bDesc;
196447    i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
196448
196449    rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
196450    if( rc==SQLITE_OK &&  iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
196451      *pbSkip = 1;
196452    }
196453
196454    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
196455    fts5CsrNewrow(pCsr);
196456    if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
196457      CsrFlagSet(pCsr, FTS5CSR_EOF);
196458      *pbSkip = 1;
196459    }
196460  }
196461  return rc;
196462}
196463
196464
196465/*
196466** Advance the cursor to the next row in the table that matches the
196467** search criteria.
196468**
196469** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
196470** even if we reach end-of-file.  The fts5EofMethod() will be called
196471** subsequently to determine whether or not an EOF was hit.
196472*/
196473static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
196474  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
196475  int rc;
196476
196477  assert( (pCsr->ePlan<3)==
196478          (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
196479  );
196480  assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
196481
196482  if( pCsr->ePlan<3 ){
196483    int bSkip = 0;
196484    if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
196485    rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
196486    CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
196487    fts5CsrNewrow(pCsr);
196488  }else{
196489    switch( pCsr->ePlan ){
196490      case FTS5_PLAN_SPECIAL: {
196491        CsrFlagSet(pCsr, FTS5CSR_EOF);
196492        rc = SQLITE_OK;
196493        break;
196494      }
196495
196496      case FTS5_PLAN_SORTED_MATCH: {
196497        rc = fts5SorterNext(pCsr);
196498        break;
196499      }
196500
196501      default:
196502        rc = sqlite3_step(pCsr->pStmt);
196503        if( rc!=SQLITE_ROW ){
196504          CsrFlagSet(pCsr, FTS5CSR_EOF);
196505          rc = sqlite3_reset(pCsr->pStmt);
196506        }else{
196507          rc = SQLITE_OK;
196508        }
196509        break;
196510    }
196511  }
196512
196513  return rc;
196514}
196515
196516
196517static int fts5PrepareStatement(
196518  sqlite3_stmt **ppStmt,
196519  Fts5Config *pConfig,
196520  const char *zFmt,
196521  ...
196522){
196523  sqlite3_stmt *pRet = 0;
196524  int rc;
196525  char *zSql;
196526  va_list ap;
196527
196528  va_start(ap, zFmt);
196529  zSql = sqlite3_vmprintf(zFmt, ap);
196530  if( zSql==0 ){
196531    rc = SQLITE_NOMEM;
196532  }else{
196533    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pRet, 0);
196534    if( rc!=SQLITE_OK ){
196535      *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
196536    }
196537    sqlite3_free(zSql);
196538  }
196539
196540  va_end(ap);
196541  *ppStmt = pRet;
196542  return rc;
196543}
196544
196545static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
196546  Fts5Config *pConfig = pTab->pConfig;
196547  Fts5Sorter *pSorter;
196548  int nPhrase;
196549  int nByte;
196550  int rc;
196551  const char *zRank = pCsr->zRank;
196552  const char *zRankArgs = pCsr->zRankArgs;
196553
196554  nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
196555  nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
196556  pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
196557  if( pSorter==0 ) return SQLITE_NOMEM;
196558  memset(pSorter, 0, nByte);
196559  pSorter->nIdx = nPhrase;
196560
196561  /* TODO: It would be better to have some system for reusing statement
196562  ** handles here, rather than preparing a new one for each query. But that
196563  ** is not possible as SQLite reference counts the virtual table objects.
196564  ** And since the statement required here reads from this very virtual
196565  ** table, saving it creates a circular reference.
196566  **
196567  ** If SQLite a built-in statement cache, this wouldn't be a problem. */
196568  rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
196569      "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
196570      pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
196571      (zRankArgs ? ", " : ""),
196572      (zRankArgs ? zRankArgs : ""),
196573      bDesc ? "DESC" : "ASC"
196574  );
196575
196576  pCsr->pSorter = pSorter;
196577  if( rc==SQLITE_OK ){
196578    assert( pTab->pSortCsr==0 );
196579    pTab->pSortCsr = pCsr;
196580    rc = fts5SorterNext(pCsr);
196581    pTab->pSortCsr = 0;
196582  }
196583
196584  if( rc!=SQLITE_OK ){
196585    sqlite3_finalize(pSorter->pStmt);
196586    sqlite3_free(pSorter);
196587    pCsr->pSorter = 0;
196588  }
196589
196590  return rc;
196591}
196592
196593static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
196594  int rc;
196595  Fts5Expr *pExpr = pCsr->pExpr;
196596  rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
196597  if( sqlite3Fts5ExprEof(pExpr) ){
196598    CsrFlagSet(pCsr, FTS5CSR_EOF);
196599  }
196600  fts5CsrNewrow(pCsr);
196601  return rc;
196602}
196603
196604/*
196605** Process a "special" query. A special query is identified as one with a
196606** MATCH expression that begins with a '*' character. The remainder of
196607** the text passed to the MATCH operator are used as  the special query
196608** parameters.
196609*/
196610static int fts5SpecialMatch(
196611  Fts5Table *pTab,
196612  Fts5Cursor *pCsr,
196613  const char *zQuery
196614){
196615  int rc = SQLITE_OK;             /* Return code */
196616  const char *z = zQuery;         /* Special query text */
196617  int n;                          /* Number of bytes in text at z */
196618
196619  while( z[0]==' ' ) z++;
196620  for(n=0; z[n] && z[n]!=' '; n++);
196621
196622  assert( pTab->base.zErrMsg==0 );
196623  pCsr->ePlan = FTS5_PLAN_SPECIAL;
196624
196625  if( 0==sqlite3_strnicmp("reads", z, n) ){
196626    pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
196627  }
196628  else if( 0==sqlite3_strnicmp("id", z, n) ){
196629    pCsr->iSpecial = pCsr->iCsrId;
196630  }
196631  else{
196632    /* An unrecognized directive. Return an error message. */
196633    pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
196634    rc = SQLITE_ERROR;
196635  }
196636
196637  return rc;
196638}
196639
196640/*
196641** Search for an auxiliary function named zName that can be used with table
196642** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
196643** structure. Otherwise, if no such function exists, return NULL.
196644*/
196645static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
196646  Fts5Auxiliary *pAux;
196647
196648  for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
196649    if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
196650  }
196651
196652  /* No function of the specified name was found. Return 0. */
196653  return 0;
196654}
196655
196656
196657static int fts5FindRankFunction(Fts5Cursor *pCsr){
196658  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
196659  Fts5Config *pConfig = pTab->pConfig;
196660  int rc = SQLITE_OK;
196661  Fts5Auxiliary *pAux = 0;
196662  const char *zRank = pCsr->zRank;
196663  const char *zRankArgs = pCsr->zRankArgs;
196664
196665  if( zRankArgs ){
196666    char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
196667    if( zSql ){
196668      sqlite3_stmt *pStmt = 0;
196669      rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0);
196670      sqlite3_free(zSql);
196671      assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
196672      if( rc==SQLITE_OK ){
196673        if( SQLITE_ROW==sqlite3_step(pStmt) ){
196674          int nByte;
196675          pCsr->nRankArg = sqlite3_column_count(pStmt);
196676          nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
196677          pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
196678          if( rc==SQLITE_OK ){
196679            int i;
196680            for(i=0; i<pCsr->nRankArg; i++){
196681              pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
196682            }
196683          }
196684          pCsr->pRankArgStmt = pStmt;
196685        }else{
196686          rc = sqlite3_finalize(pStmt);
196687          assert( rc!=SQLITE_OK );
196688        }
196689      }
196690    }
196691  }
196692
196693  if( rc==SQLITE_OK ){
196694    pAux = fts5FindAuxiliary(pTab, zRank);
196695    if( pAux==0 ){
196696      assert( pTab->base.zErrMsg==0 );
196697      pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
196698      rc = SQLITE_ERROR;
196699    }
196700  }
196701
196702  pCsr->pRank = pAux;
196703  return rc;
196704}
196705
196706
196707static int fts5CursorParseRank(
196708  Fts5Config *pConfig,
196709  Fts5Cursor *pCsr,
196710  sqlite3_value *pRank
196711){
196712  int rc = SQLITE_OK;
196713  if( pRank ){
196714    const char *z = (const char*)sqlite3_value_text(pRank);
196715    char *zRank = 0;
196716    char *zRankArgs = 0;
196717
196718    if( z==0 ){
196719      if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
196720    }else{
196721      rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
196722    }
196723    if( rc==SQLITE_OK ){
196724      pCsr->zRank = zRank;
196725      pCsr->zRankArgs = zRankArgs;
196726      CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
196727    }else if( rc==SQLITE_ERROR ){
196728      pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
196729          "parse error in rank function: %s", z
196730      );
196731    }
196732  }else{
196733    if( pConfig->zRank ){
196734      pCsr->zRank = (char*)pConfig->zRank;
196735      pCsr->zRankArgs = (char*)pConfig->zRankArgs;
196736    }else{
196737      pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
196738      pCsr->zRankArgs = 0;
196739    }
196740  }
196741  return rc;
196742}
196743
196744static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
196745  if( pVal ){
196746    int eType = sqlite3_value_numeric_type(pVal);
196747    if( eType==SQLITE_INTEGER ){
196748      return sqlite3_value_int64(pVal);
196749    }
196750  }
196751  return iDefault;
196752}
196753
196754/*
196755** This is the xFilter interface for the virtual table.  See
196756** the virtual table xFilter method documentation for additional
196757** information.
196758**
196759** There are three possible query strategies:
196760**
196761**   1. Full-text search using a MATCH operator.
196762**   2. A by-rowid lookup.
196763**   3. A full-table scan.
196764*/
196765static int fts5FilterMethod(
196766  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
196767  int idxNum,                     /* Strategy index */
196768  const char *zUnused,            /* Unused */
196769  int nVal,                       /* Number of elements in apVal */
196770  sqlite3_value **apVal           /* Arguments for the indexing scheme */
196771){
196772  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
196773  Fts5Config *pConfig = pTab->pConfig;
196774  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
196775  int rc = SQLITE_OK;             /* Error code */
196776  int iVal = 0;                   /* Counter for apVal[] */
196777  int bDesc;                      /* True if ORDER BY [rank|rowid] DESC */
196778  int bOrderByRank;               /* True if ORDER BY rank */
196779  sqlite3_value *pMatch = 0;      /* <tbl> MATCH ? expression (or NULL) */
196780  sqlite3_value *pRank = 0;       /* rank MATCH ? expression (or NULL) */
196781  sqlite3_value *pRowidEq = 0;    /* rowid = ? expression (or NULL) */
196782  sqlite3_value *pRowidLe = 0;    /* rowid <= ? expression (or NULL) */
196783  sqlite3_value *pRowidGe = 0;    /* rowid >= ? expression (or NULL) */
196784  char **pzErrmsg = pConfig->pzErrmsg;
196785
196786  UNUSED_PARAM(zUnused);
196787  UNUSED_PARAM(nVal);
196788
196789  if( pCsr->ePlan ){
196790    fts5FreeCursorComponents(pCsr);
196791    memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
196792  }
196793
196794  assert( pCsr->pStmt==0 );
196795  assert( pCsr->pExpr==0 );
196796  assert( pCsr->csrflags==0 );
196797  assert( pCsr->pRank==0 );
196798  assert( pCsr->zRank==0 );
196799  assert( pCsr->zRankArgs==0 );
196800
196801  assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
196802  pConfig->pzErrmsg = &pTab->base.zErrMsg;
196803
196804  /* Decode the arguments passed through to this function.
196805  **
196806  ** Note: The following set of if(...) statements must be in the same
196807  ** order as the corresponding entries in the struct at the top of
196808  ** fts5BestIndexMethod().  */
196809  if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
196810  if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
196811  if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
196812  if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
196813  if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
196814  assert( iVal==nVal );
196815  bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
196816  pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
196817
196818  /* Set the cursor upper and lower rowid limits. Only some strategies
196819  ** actually use them. This is ok, as the xBestIndex() method leaves the
196820  ** sqlite3_index_constraint.omit flag clear for range constraints
196821  ** on the rowid field.  */
196822  if( pRowidEq ){
196823    pRowidLe = pRowidGe = pRowidEq;
196824  }
196825  if( bDesc ){
196826    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
196827    pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
196828  }else{
196829    pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
196830    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
196831  }
196832
196833  if( pTab->pSortCsr ){
196834    /* If pSortCsr is non-NULL, then this call is being made as part of
196835    ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
196836    ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
196837    ** return results to the user for this query. The current cursor
196838    ** (pCursor) is used to execute the query issued by function
196839    ** fts5CursorFirstSorted() above.  */
196840    assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
196841    assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
196842    assert( pCsr->iLastRowid==LARGEST_INT64 );
196843    assert( pCsr->iFirstRowid==SMALLEST_INT64 );
196844    pCsr->ePlan = FTS5_PLAN_SOURCE;
196845    pCsr->pExpr = pTab->pSortCsr->pExpr;
196846    rc = fts5CursorFirst(pTab, pCsr, bDesc);
196847  }else if( pMatch ){
196848    const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
196849    if( zExpr==0 ) zExpr = "";
196850
196851    rc = fts5CursorParseRank(pConfig, pCsr, pRank);
196852    if( rc==SQLITE_OK ){
196853      if( zExpr[0]=='*' ){
196854        /* The user has issued a query of the form "MATCH '*...'". This
196855        ** indicates that the MATCH expression is not a full text query,
196856        ** but a request for an internal parameter.  */
196857        rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
196858      }else{
196859        char **pzErr = &pTab->base.zErrMsg;
196860        rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pCsr->pExpr, pzErr);
196861        if( rc==SQLITE_OK ){
196862          if( bOrderByRank ){
196863            pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
196864            rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
196865          }else{
196866            pCsr->ePlan = FTS5_PLAN_MATCH;
196867            rc = fts5CursorFirst(pTab, pCsr, bDesc);
196868          }
196869        }
196870      }
196871    }
196872  }else if( pConfig->zContent==0 ){
196873    *pConfig->pzErrmsg = sqlite3_mprintf(
196874        "%s: table does not support scanning", pConfig->zName
196875    );
196876    rc = SQLITE_ERROR;
196877  }else{
196878    /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
196879    ** by rowid (ePlan==FTS5_PLAN_ROWID).  */
196880    pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
196881    rc = sqlite3Fts5StorageStmt(
196882        pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
196883    );
196884    if( rc==SQLITE_OK ){
196885      if( pCsr->ePlan==FTS5_PLAN_ROWID ){
196886        sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
196887      }else{
196888        sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
196889        sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
196890      }
196891      rc = fts5NextMethod(pCursor);
196892    }
196893  }
196894
196895  pConfig->pzErrmsg = pzErrmsg;
196896  return rc;
196897}
196898
196899/*
196900** This is the xEof method of the virtual table. SQLite calls this
196901** routine to find out if it has reached the end of a result set.
196902*/
196903static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
196904  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
196905  return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
196906}
196907
196908/*
196909** Return the rowid that the cursor currently points to.
196910*/
196911static i64 fts5CursorRowid(Fts5Cursor *pCsr){
196912  assert( pCsr->ePlan==FTS5_PLAN_MATCH
196913       || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
196914       || pCsr->ePlan==FTS5_PLAN_SOURCE
196915  );
196916  if( pCsr->pSorter ){
196917    return pCsr->pSorter->iRowid;
196918  }else{
196919    return sqlite3Fts5ExprRowid(pCsr->pExpr);
196920  }
196921}
196922
196923/*
196924** This is the xRowid method. The SQLite core calls this routine to
196925** retrieve the rowid for the current row of the result set. fts5
196926** exposes %_content.rowid as the rowid for the virtual table. The
196927** rowid should be written to *pRowid.
196928*/
196929static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
196930  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
196931  int ePlan = pCsr->ePlan;
196932
196933  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
196934  switch( ePlan ){
196935    case FTS5_PLAN_SPECIAL:
196936      *pRowid = 0;
196937      break;
196938
196939    case FTS5_PLAN_SOURCE:
196940    case FTS5_PLAN_MATCH:
196941    case FTS5_PLAN_SORTED_MATCH:
196942      *pRowid = fts5CursorRowid(pCsr);
196943      break;
196944
196945    default:
196946      *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
196947      break;
196948  }
196949
196950  return SQLITE_OK;
196951}
196952
196953/*
196954** If the cursor requires seeking (bSeekRequired flag is set), seek it.
196955** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
196956**
196957** If argument bErrormsg is true and an error occurs, an error message may
196958** be left in sqlite3_vtab.zErrMsg.
196959*/
196960static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
196961  int rc = SQLITE_OK;
196962
196963  /* If the cursor does not yet have a statement handle, obtain one now. */
196964  if( pCsr->pStmt==0 ){
196965    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
196966    int eStmt = fts5StmtType(pCsr);
196967    rc = sqlite3Fts5StorageStmt(
196968        pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
196969    );
196970    assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
196971    assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
196972  }
196973
196974  if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
196975    assert( pCsr->pExpr );
196976    sqlite3_reset(pCsr->pStmt);
196977    sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
196978    rc = sqlite3_step(pCsr->pStmt);
196979    if( rc==SQLITE_ROW ){
196980      rc = SQLITE_OK;
196981      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
196982    }else{
196983      rc = sqlite3_reset(pCsr->pStmt);
196984      if( rc==SQLITE_OK ){
196985        rc = FTS5_CORRUPT;
196986      }
196987    }
196988  }
196989  return rc;
196990}
196991
196992static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
196993  va_list ap;                     /* ... printf arguments */
196994  va_start(ap, zFormat);
196995  assert( p->base.zErrMsg==0 );
196996  p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
196997  va_end(ap);
196998}
196999
197000/*
197001** This function is called to handle an FTS INSERT command. In other words,
197002** an INSERT statement of the form:
197003**
197004**     INSERT INTO fts(fts) VALUES($pCmd)
197005**     INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
197006**
197007** Argument pVal is the value assigned to column "fts" by the INSERT
197008** statement. This function returns SQLITE_OK if successful, or an SQLite
197009** error code if an error occurs.
197010**
197011** The commands implemented by this function are documented in the "Special
197012** INSERT Directives" section of the documentation. It should be updated if
197013** more commands are added to this function.
197014*/
197015static int fts5SpecialInsert(
197016  Fts5Table *pTab,                /* Fts5 table object */
197017  const char *zCmd,               /* Text inserted into table-name column */
197018  sqlite3_value *pVal             /* Value inserted into rank column */
197019){
197020  Fts5Config *pConfig = pTab->pConfig;
197021  int rc = SQLITE_OK;
197022  int bError = 0;
197023
197024  if( 0==sqlite3_stricmp("delete-all", zCmd) ){
197025    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
197026      fts5SetVtabError(pTab,
197027          "'delete-all' may only be used with a "
197028          "contentless or external content fts5 table"
197029      );
197030      rc = SQLITE_ERROR;
197031    }else{
197032      rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
197033    }
197034  }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
197035    if( pConfig->eContent==FTS5_CONTENT_NONE ){
197036      fts5SetVtabError(pTab,
197037          "'rebuild' may not be used with a contentless fts5 table"
197038      );
197039      rc = SQLITE_ERROR;
197040    }else{
197041      rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
197042    }
197043  }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
197044    rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
197045  }else if( 0==sqlite3_stricmp("merge", zCmd) ){
197046    int nMerge = sqlite3_value_int(pVal);
197047    rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
197048  }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
197049    rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
197050#ifdef SQLITE_DEBUG
197051  }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
197052    pConfig->bPrefixIndex = sqlite3_value_int(pVal);
197053#endif
197054  }else{
197055    rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
197056    if( rc==SQLITE_OK ){
197057      rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
197058    }
197059    if( rc==SQLITE_OK ){
197060      if( bError ){
197061        rc = SQLITE_ERROR;
197062      }else{
197063        rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
197064      }
197065    }
197066  }
197067  return rc;
197068}
197069
197070static int fts5SpecialDelete(
197071  Fts5Table *pTab,
197072  sqlite3_value **apVal
197073){
197074  int rc = SQLITE_OK;
197075  int eType1 = sqlite3_value_type(apVal[1]);
197076  if( eType1==SQLITE_INTEGER ){
197077    sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
197078    rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
197079  }
197080  return rc;
197081}
197082
197083static void fts5StorageInsert(
197084  int *pRc,
197085  Fts5Table *pTab,
197086  sqlite3_value **apVal,
197087  i64 *piRowid
197088){
197089  int rc = *pRc;
197090  if( rc==SQLITE_OK ){
197091    rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
197092  }
197093  if( rc==SQLITE_OK ){
197094    rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
197095  }
197096  *pRc = rc;
197097}
197098
197099/*
197100** This function is the implementation of the xUpdate callback used by
197101** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
197102** inserted, updated or deleted.
197103**
197104** A delete specifies a single argument - the rowid of the row to remove.
197105**
197106** Update and insert operations pass:
197107**
197108**   1. The "old" rowid, or NULL.
197109**   2. The "new" rowid.
197110**   3. Values for each of the nCol matchable columns.
197111**   4. Values for the two hidden columns (<tablename> and "rank").
197112*/
197113static int fts5UpdateMethod(
197114  sqlite3_vtab *pVtab,            /* Virtual table handle */
197115  int nArg,                       /* Size of argument array */
197116  sqlite3_value **apVal,          /* Array of arguments */
197117  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
197118){
197119  Fts5Table *pTab = (Fts5Table*)pVtab;
197120  Fts5Config *pConfig = pTab->pConfig;
197121  int eType0;                     /* value_type() of apVal[0] */
197122  int rc = SQLITE_OK;             /* Return code */
197123
197124  /* A transaction must be open when this is called. */
197125  assert( pTab->ts.eState==1 );
197126
197127  assert( pVtab->zErrMsg==0 );
197128  assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
197129  assert( nArg==1
197130      || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
197131      || sqlite3_value_type(apVal[1])==SQLITE_NULL
197132  );
197133  assert( pTab->pConfig->pzErrmsg==0 );
197134  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
197135
197136  /* Put any active cursors into REQUIRE_SEEK state. */
197137  fts5TripCursors(pTab);
197138
197139  eType0 = sqlite3_value_type(apVal[0]);
197140  if( eType0==SQLITE_NULL
197141   && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
197142  ){
197143    /* A "special" INSERT op. These are handled separately. */
197144    const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
197145    if( pConfig->eContent!=FTS5_CONTENT_NORMAL
197146      && 0==sqlite3_stricmp("delete", z)
197147    ){
197148      rc = fts5SpecialDelete(pTab, apVal);
197149    }else{
197150      rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
197151    }
197152  }else{
197153    /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
197154    ** any conflict on the rowid value must be detected before any
197155    ** modifications are made to the database file. There are 4 cases:
197156    **
197157    **   1) DELETE
197158    **   2) UPDATE (rowid not modified)
197159    **   3) UPDATE (rowid modified)
197160    **   4) INSERT
197161    **
197162    ** Cases 3 and 4 may violate the rowid constraint.
197163    */
197164    int eConflict = SQLITE_ABORT;
197165    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
197166      eConflict = sqlite3_vtab_on_conflict(pConfig->db);
197167    }
197168
197169    assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
197170    assert( nArg!=1 || eType0==SQLITE_INTEGER );
197171
197172    /* Filter out attempts to run UPDATE or DELETE on contentless tables.
197173    ** This is not suported.  */
197174    if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
197175      pTab->base.zErrMsg = sqlite3_mprintf(
197176          "cannot %s contentless fts5 table: %s",
197177          (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
197178      );
197179      rc = SQLITE_ERROR;
197180    }
197181
197182    /* DELETE */
197183    else if( nArg==1 ){
197184      i64 iDel = sqlite3_value_int64(apVal[0]);  /* Rowid to delete */
197185      rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
197186    }
197187
197188    /* INSERT */
197189    else if( eType0!=SQLITE_INTEGER ){
197190      /* If this is a REPLACE, first remove the current entry (if any) */
197191      if( eConflict==SQLITE_REPLACE
197192       && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
197193      ){
197194        i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
197195        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
197196      }
197197      fts5StorageInsert(&rc, pTab, apVal, pRowid);
197198    }
197199
197200    /* UPDATE */
197201    else{
197202      i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */
197203      i64 iNew = sqlite3_value_int64(apVal[1]);  /* New rowid */
197204      if( iOld!=iNew ){
197205        if( eConflict==SQLITE_REPLACE ){
197206          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
197207          if( rc==SQLITE_OK ){
197208            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
197209          }
197210          fts5StorageInsert(&rc, pTab, apVal, pRowid);
197211        }else{
197212          rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
197213          if( rc==SQLITE_OK ){
197214            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
197215          }
197216          if( rc==SQLITE_OK ){
197217            rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
197218          }
197219        }
197220      }else{
197221        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
197222        fts5StorageInsert(&rc, pTab, apVal, pRowid);
197223      }
197224    }
197225  }
197226
197227  pTab->pConfig->pzErrmsg = 0;
197228  return rc;
197229}
197230
197231/*
197232** Implementation of xSync() method.
197233*/
197234static int fts5SyncMethod(sqlite3_vtab *pVtab){
197235  int rc;
197236  Fts5Table *pTab = (Fts5Table*)pVtab;
197237  fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
197238  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
197239  fts5TripCursors(pTab);
197240  rc = sqlite3Fts5StorageSync(pTab->pStorage, 1);
197241  pTab->pConfig->pzErrmsg = 0;
197242  return rc;
197243}
197244
197245/*
197246** Implementation of xBegin() method.
197247*/
197248static int fts5BeginMethod(sqlite3_vtab *pVtab){
197249  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
197250  fts5NewTransaction((Fts5Table*)pVtab);
197251  return SQLITE_OK;
197252}
197253
197254/*
197255** Implementation of xCommit() method. This is a no-op. The contents of
197256** the pending-terms hash-table have already been flushed into the database
197257** by fts5SyncMethod().
197258*/
197259static int fts5CommitMethod(sqlite3_vtab *pVtab){
197260  UNUSED_PARAM(pVtab);  /* Call below is a no-op for NDEBUG builds */
197261  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
197262  return SQLITE_OK;
197263}
197264
197265/*
197266** Implementation of xRollback(). Discard the contents of the pending-terms
197267** hash-table. Any changes made to the database are reverted by SQLite.
197268*/
197269static int fts5RollbackMethod(sqlite3_vtab *pVtab){
197270  int rc;
197271  Fts5Table *pTab = (Fts5Table*)pVtab;
197272  fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
197273  rc = sqlite3Fts5StorageRollback(pTab->pStorage);
197274  return rc;
197275}
197276
197277static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
197278
197279static void *fts5ApiUserData(Fts5Context *pCtx){
197280  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197281  return pCsr->pAux->pUserData;
197282}
197283
197284static int fts5ApiColumnCount(Fts5Context *pCtx){
197285  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197286  return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
197287}
197288
197289static int fts5ApiColumnTotalSize(
197290  Fts5Context *pCtx,
197291  int iCol,
197292  sqlite3_int64 *pnToken
197293){
197294  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197295  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
197296  return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
197297}
197298
197299static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
197300  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197301  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
197302  return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
197303}
197304
197305static int fts5ApiTokenize(
197306  Fts5Context *pCtx,
197307  const char *pText, int nText,
197308  void *pUserData,
197309  int (*xToken)(void*, int, const char*, int, int, int)
197310){
197311  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197312  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
197313  return sqlite3Fts5Tokenize(
197314      pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
197315  );
197316}
197317
197318static int fts5ApiPhraseCount(Fts5Context *pCtx){
197319  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197320  return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
197321}
197322
197323static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
197324  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197325  return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
197326}
197327
197328static int fts5ApiColumnText(
197329  Fts5Context *pCtx,
197330  int iCol,
197331  const char **pz,
197332  int *pn
197333){
197334  int rc = SQLITE_OK;
197335  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197336  if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
197337    *pz = 0;
197338    *pn = 0;
197339  }else{
197340    rc = fts5SeekCursor(pCsr, 0);
197341    if( rc==SQLITE_OK ){
197342      *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
197343      *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
197344    }
197345  }
197346  return rc;
197347}
197348
197349static int fts5CsrPoslist(
197350  Fts5Cursor *pCsr,
197351  int iPhrase,
197352  const u8 **pa,
197353  int *pn
197354){
197355  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
197356  int rc = SQLITE_OK;
197357  int bLive = (pCsr->pSorter==0);
197358
197359  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
197360
197361    if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
197362      Fts5PoslistPopulator *aPopulator;
197363      int i;
197364      aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
197365      if( aPopulator==0 ) rc = SQLITE_NOMEM;
197366      for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
197367        int n; const char *z;
197368        rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
197369        if( rc==SQLITE_OK ){
197370          rc = sqlite3Fts5ExprPopulatePoslists(
197371              pConfig, pCsr->pExpr, aPopulator, i, z, n
197372          );
197373        }
197374      }
197375      sqlite3_free(aPopulator);
197376
197377      if( pCsr->pSorter ){
197378        sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
197379      }
197380    }
197381    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
197382  }
197383
197384  if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
197385    Fts5Sorter *pSorter = pCsr->pSorter;
197386    int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
197387    *pn = pSorter->aIdx[iPhrase] - i1;
197388    *pa = &pSorter->aPoslist[i1];
197389  }else{
197390    *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
197391  }
197392
197393  return rc;
197394}
197395
197396/*
197397** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
197398** correctly for the current view. Return SQLITE_OK if successful, or an
197399** SQLite error code otherwise.
197400*/
197401static int fts5CacheInstArray(Fts5Cursor *pCsr){
197402  int rc = SQLITE_OK;
197403  Fts5PoslistReader *aIter;       /* One iterator for each phrase */
197404  int nIter;                      /* Number of iterators/phrases */
197405
197406  nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
197407  if( pCsr->aInstIter==0 ){
197408    int nByte = sizeof(Fts5PoslistReader) * nIter;
197409    pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
197410  }
197411  aIter = pCsr->aInstIter;
197412
197413  if( aIter ){
197414    int nInst = 0;                /* Number instances seen so far */
197415    int i;
197416
197417    /* Initialize all iterators */
197418    for(i=0; i<nIter && rc==SQLITE_OK; i++){
197419      const u8 *a;
197420      int n;
197421      rc = fts5CsrPoslist(pCsr, i, &a, &n);
197422      if( rc==SQLITE_OK ){
197423        sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
197424      }
197425    }
197426
197427    if( rc==SQLITE_OK ){
197428      while( 1 ){
197429        int *aInst;
197430        int iBest = -1;
197431        for(i=0; i<nIter; i++){
197432          if( (aIter[i].bEof==0)
197433              && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
197434            ){
197435            iBest = i;
197436          }
197437        }
197438        if( iBest<0 ) break;
197439
197440        nInst++;
197441        if( nInst>=pCsr->nInstAlloc ){
197442          pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
197443          aInst = (int*)sqlite3_realloc(
197444              pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
197445              );
197446          if( aInst ){
197447            pCsr->aInst = aInst;
197448          }else{
197449            rc = SQLITE_NOMEM;
197450            break;
197451          }
197452        }
197453
197454        aInst = &pCsr->aInst[3 * (nInst-1)];
197455        aInst[0] = iBest;
197456        aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
197457        aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
197458        sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
197459      }
197460    }
197461
197462    pCsr->nInstCount = nInst;
197463    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
197464  }
197465  return rc;
197466}
197467
197468static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
197469  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197470  int rc = SQLITE_OK;
197471  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
197472   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
197473    *pnInst = pCsr->nInstCount;
197474  }
197475  return rc;
197476}
197477
197478static int fts5ApiInst(
197479  Fts5Context *pCtx,
197480  int iIdx,
197481  int *piPhrase,
197482  int *piCol,
197483  int *piOff
197484){
197485  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197486  int rc = SQLITE_OK;
197487  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
197488   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
197489  ){
197490    if( iIdx<0 || iIdx>=pCsr->nInstCount ){
197491      rc = SQLITE_RANGE;
197492#if 0
197493    }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
197494      *piPhrase = pCsr->aInst[iIdx*3];
197495      *piCol = pCsr->aInst[iIdx*3 + 2];
197496      *piOff = -1;
197497#endif
197498    }else{
197499      *piPhrase = pCsr->aInst[iIdx*3];
197500      *piCol = pCsr->aInst[iIdx*3 + 1];
197501      *piOff = pCsr->aInst[iIdx*3 + 2];
197502    }
197503  }
197504  return rc;
197505}
197506
197507static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
197508  return fts5CursorRowid((Fts5Cursor*)pCtx);
197509}
197510
197511static int fts5ColumnSizeCb(
197512  void *pContext,                 /* Pointer to int */
197513  int tflags,
197514  const char *pUnused,            /* Buffer containing token */
197515  int nUnused,                    /* Size of token in bytes */
197516  int iUnused1,                   /* Start offset of token */
197517  int iUnused2                    /* End offset of token */
197518){
197519  int *pCnt = (int*)pContext;
197520  UNUSED_PARAM2(pUnused, nUnused);
197521  UNUSED_PARAM2(iUnused1, iUnused2);
197522  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
197523    (*pCnt)++;
197524  }
197525  return SQLITE_OK;
197526}
197527
197528static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
197529  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197530  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
197531  Fts5Config *pConfig = pTab->pConfig;
197532  int rc = SQLITE_OK;
197533
197534  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
197535    if( pConfig->bColumnsize ){
197536      i64 iRowid = fts5CursorRowid(pCsr);
197537      rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
197538    }else if( pConfig->zContent==0 ){
197539      int i;
197540      for(i=0; i<pConfig->nCol; i++){
197541        if( pConfig->abUnindexed[i]==0 ){
197542          pCsr->aColumnSize[i] = -1;
197543        }
197544      }
197545    }else{
197546      int i;
197547      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
197548        if( pConfig->abUnindexed[i]==0 ){
197549          const char *z; int n;
197550          void *p = (void*)(&pCsr->aColumnSize[i]);
197551          pCsr->aColumnSize[i] = 0;
197552          rc = fts5ApiColumnText(pCtx, i, &z, &n);
197553          if( rc==SQLITE_OK ){
197554            rc = sqlite3Fts5Tokenize(
197555                pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
197556            );
197557          }
197558        }
197559      }
197560    }
197561    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
197562  }
197563  if( iCol<0 ){
197564    int i;
197565    *pnToken = 0;
197566    for(i=0; i<pConfig->nCol; i++){
197567      *pnToken += pCsr->aColumnSize[i];
197568    }
197569  }else if( iCol<pConfig->nCol ){
197570    *pnToken = pCsr->aColumnSize[iCol];
197571  }else{
197572    *pnToken = 0;
197573    rc = SQLITE_RANGE;
197574  }
197575  return rc;
197576}
197577
197578/*
197579** Implementation of the xSetAuxdata() method.
197580*/
197581static int fts5ApiSetAuxdata(
197582  Fts5Context *pCtx,              /* Fts5 context */
197583  void *pPtr,                     /* Pointer to save as auxdata */
197584  void(*xDelete)(void*)           /* Destructor for pPtr (or NULL) */
197585){
197586  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197587  Fts5Auxdata *pData;
197588
197589  /* Search through the cursors list of Fts5Auxdata objects for one that
197590  ** corresponds to the currently executing auxiliary function.  */
197591  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
197592    if( pData->pAux==pCsr->pAux ) break;
197593  }
197594
197595  if( pData ){
197596    if( pData->xDelete ){
197597      pData->xDelete(pData->pPtr);
197598    }
197599  }else{
197600    int rc = SQLITE_OK;
197601    pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
197602    if( pData==0 ){
197603      if( xDelete ) xDelete(pPtr);
197604      return rc;
197605    }
197606    pData->pAux = pCsr->pAux;
197607    pData->pNext = pCsr->pAuxdata;
197608    pCsr->pAuxdata = pData;
197609  }
197610
197611  pData->xDelete = xDelete;
197612  pData->pPtr = pPtr;
197613  return SQLITE_OK;
197614}
197615
197616static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
197617  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197618  Fts5Auxdata *pData;
197619  void *pRet = 0;
197620
197621  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
197622    if( pData->pAux==pCsr->pAux ) break;
197623  }
197624
197625  if( pData ){
197626    pRet = pData->pPtr;
197627    if( bClear ){
197628      pData->pPtr = 0;
197629      pData->xDelete = 0;
197630    }
197631  }
197632
197633  return pRet;
197634}
197635
197636static void fts5ApiPhraseNext(
197637  Fts5Context *pUnused,
197638  Fts5PhraseIter *pIter,
197639  int *piCol, int *piOff
197640){
197641  UNUSED_PARAM(pUnused);
197642  if( pIter->a>=pIter->b ){
197643    *piCol = -1;
197644    *piOff = -1;
197645  }else{
197646    int iVal;
197647    pIter->a += fts5GetVarint32(pIter->a, iVal);
197648    if( iVal==1 ){
197649      pIter->a += fts5GetVarint32(pIter->a, iVal);
197650      *piCol = iVal;
197651      *piOff = 0;
197652      pIter->a += fts5GetVarint32(pIter->a, iVal);
197653    }
197654    *piOff += (iVal-2);
197655  }
197656}
197657
197658static int fts5ApiPhraseFirst(
197659  Fts5Context *pCtx,
197660  int iPhrase,
197661  Fts5PhraseIter *pIter,
197662  int *piCol, int *piOff
197663){
197664  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197665  int n;
197666  int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
197667  if( rc==SQLITE_OK ){
197668    pIter->b = &pIter->a[n];
197669    *piCol = 0;
197670    *piOff = 0;
197671    fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
197672  }
197673  return rc;
197674}
197675
197676static void fts5ApiPhraseNextColumn(
197677  Fts5Context *pCtx,
197678  Fts5PhraseIter *pIter,
197679  int *piCol
197680){
197681  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197682  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
197683
197684  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
197685    if( pIter->a>=pIter->b ){
197686      *piCol = -1;
197687    }else{
197688      int iIncr;
197689      pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
197690      *piCol += (iIncr-2);
197691    }
197692  }else{
197693    while( 1 ){
197694      int dummy;
197695      if( pIter->a>=pIter->b ){
197696        *piCol = -1;
197697        return;
197698      }
197699      if( pIter->a[0]==0x01 ) break;
197700      pIter->a += fts5GetVarint32(pIter->a, dummy);
197701    }
197702    pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
197703  }
197704}
197705
197706static int fts5ApiPhraseFirstColumn(
197707  Fts5Context *pCtx,
197708  int iPhrase,
197709  Fts5PhraseIter *pIter,
197710  int *piCol
197711){
197712  int rc = SQLITE_OK;
197713  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197714  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
197715
197716  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
197717    Fts5Sorter *pSorter = pCsr->pSorter;
197718    int n;
197719    if( pSorter ){
197720      int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
197721      n = pSorter->aIdx[iPhrase] - i1;
197722      pIter->a = &pSorter->aPoslist[i1];
197723    }else{
197724      rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
197725    }
197726    if( rc==SQLITE_OK ){
197727      pIter->b = &pIter->a[n];
197728      *piCol = 0;
197729      fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
197730    }
197731  }else{
197732    int n;
197733    rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
197734    if( rc==SQLITE_OK ){
197735      pIter->b = &pIter->a[n];
197736      if( n<=0 ){
197737        *piCol = -1;
197738      }else if( pIter->a[0]==0x01 ){
197739        pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
197740      }else{
197741        *piCol = 0;
197742      }
197743    }
197744  }
197745
197746  return rc;
197747}
197748
197749
197750static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
197751    int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
197752);
197753
197754static const Fts5ExtensionApi sFts5Api = {
197755  2,                            /* iVersion */
197756  fts5ApiUserData,
197757  fts5ApiColumnCount,
197758  fts5ApiRowCount,
197759  fts5ApiColumnTotalSize,
197760  fts5ApiTokenize,
197761  fts5ApiPhraseCount,
197762  fts5ApiPhraseSize,
197763  fts5ApiInstCount,
197764  fts5ApiInst,
197765  fts5ApiRowid,
197766  fts5ApiColumnText,
197767  fts5ApiColumnSize,
197768  fts5ApiQueryPhrase,
197769  fts5ApiSetAuxdata,
197770  fts5ApiGetAuxdata,
197771  fts5ApiPhraseFirst,
197772  fts5ApiPhraseNext,
197773  fts5ApiPhraseFirstColumn,
197774  fts5ApiPhraseNextColumn,
197775};
197776
197777/*
197778** Implementation of API function xQueryPhrase().
197779*/
197780static int fts5ApiQueryPhrase(
197781  Fts5Context *pCtx,
197782  int iPhrase,
197783  void *pUserData,
197784  int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
197785){
197786  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
197787  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
197788  int rc;
197789  Fts5Cursor *pNew = 0;
197790
197791  rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
197792  if( rc==SQLITE_OK ){
197793    pNew->ePlan = FTS5_PLAN_MATCH;
197794    pNew->iFirstRowid = SMALLEST_INT64;
197795    pNew->iLastRowid = LARGEST_INT64;
197796    pNew->base.pVtab = (sqlite3_vtab*)pTab;
197797    rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
197798  }
197799
197800  if( rc==SQLITE_OK ){
197801    for(rc = fts5CursorFirst(pTab, pNew, 0);
197802        rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
197803        rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
197804    ){
197805      rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
197806      if( rc!=SQLITE_OK ){
197807        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
197808        break;
197809      }
197810    }
197811  }
197812
197813  fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
197814  return rc;
197815}
197816
197817static void fts5ApiInvoke(
197818  Fts5Auxiliary *pAux,
197819  Fts5Cursor *pCsr,
197820  sqlite3_context *context,
197821  int argc,
197822  sqlite3_value **argv
197823){
197824  assert( pCsr->pAux==0 );
197825  pCsr->pAux = pAux;
197826  pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
197827  pCsr->pAux = 0;
197828}
197829
197830static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
197831  Fts5Cursor *pCsr;
197832  for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
197833    if( pCsr->iCsrId==iCsrId ) break;
197834  }
197835  return pCsr;
197836}
197837
197838static void fts5ApiCallback(
197839  sqlite3_context *context,
197840  int argc,
197841  sqlite3_value **argv
197842){
197843
197844  Fts5Auxiliary *pAux;
197845  Fts5Cursor *pCsr;
197846  i64 iCsrId;
197847
197848  assert( argc>=1 );
197849  pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
197850  iCsrId = sqlite3_value_int64(argv[0]);
197851
197852  pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
197853  if( pCsr==0 ){
197854    char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
197855    sqlite3_result_error(context, zErr, -1);
197856    sqlite3_free(zErr);
197857  }else{
197858    fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
197859  }
197860}
197861
197862
197863/*
197864** Given cursor id iId, return a pointer to the corresponding Fts5Index
197865** object. Or NULL If the cursor id does not exist.
197866**
197867** If successful, set *ppConfig to point to the associated config object
197868** before returning.
197869*/
197870static Fts5Index *sqlite3Fts5IndexFromCsrid(
197871  Fts5Global *pGlobal,            /* FTS5 global context for db handle */
197872  i64 iCsrId,                     /* Id of cursor to find */
197873  Fts5Config **ppConfig           /* OUT: Configuration object */
197874){
197875  Fts5Cursor *pCsr;
197876  Fts5Table *pTab;
197877
197878  pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
197879  pTab = (Fts5Table*)pCsr->base.pVtab;
197880  *ppConfig = pTab->pConfig;
197881
197882  return pTab->pIndex;
197883}
197884
197885/*
197886** Return a "position-list blob" corresponding to the current position of
197887** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
197888** the current position-list for each phrase in the query associated with
197889** cursor pCsr.
197890**
197891** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
197892** the number of phrases in the query. Following the varints are the
197893** concatenated position lists for each phrase, in order.
197894**
197895** The first varint (if it exists) contains the size of the position list
197896** for phrase 0. The second (same disclaimer) contains the size of position
197897** list 1. And so on. There is no size field for the final position list,
197898** as it can be derived from the total size of the blob.
197899*/
197900static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
197901  int i;
197902  int rc = SQLITE_OK;
197903  int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
197904  Fts5Buffer val;
197905
197906  memset(&val, 0, sizeof(Fts5Buffer));
197907  switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
197908    case FTS5_DETAIL_FULL:
197909
197910      /* Append the varints */
197911      for(i=0; i<(nPhrase-1); i++){
197912        const u8 *dummy;
197913        int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
197914        sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
197915      }
197916
197917      /* Append the position lists */
197918      for(i=0; i<nPhrase; i++){
197919        const u8 *pPoslist;
197920        int nPoslist;
197921        nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
197922        sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
197923      }
197924      break;
197925
197926    case FTS5_DETAIL_COLUMNS:
197927
197928      /* Append the varints */
197929      for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
197930        const u8 *dummy;
197931        int nByte;
197932        rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
197933        sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
197934      }
197935
197936      /* Append the position lists */
197937      for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
197938        const u8 *pPoslist;
197939        int nPoslist;
197940        rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
197941        sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
197942      }
197943      break;
197944
197945    default:
197946      break;
197947  }
197948
197949  sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
197950  return rc;
197951}
197952
197953/*
197954** This is the xColumn method, called by SQLite to request a value from
197955** the row that the supplied cursor currently points to.
197956*/
197957static int fts5ColumnMethod(
197958  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
197959  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
197960  int iCol                        /* Index of column to read value from */
197961){
197962  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
197963  Fts5Config *pConfig = pTab->pConfig;
197964  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
197965  int rc = SQLITE_OK;
197966
197967  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
197968
197969  if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
197970    if( iCol==pConfig->nCol ){
197971      sqlite3_result_int64(pCtx, pCsr->iSpecial);
197972    }
197973  }else
197974
197975  if( iCol==pConfig->nCol ){
197976    /* User is requesting the value of the special column with the same name
197977    ** as the table. Return the cursor integer id number. This value is only
197978    ** useful in that it may be passed as the first argument to an FTS5
197979    ** auxiliary function.  */
197980    sqlite3_result_int64(pCtx, pCsr->iCsrId);
197981  }else if( iCol==pConfig->nCol+1 ){
197982
197983    /* The value of the "rank" column. */
197984    if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
197985      fts5PoslistBlob(pCtx, pCsr);
197986    }else if(
197987        pCsr->ePlan==FTS5_PLAN_MATCH
197988     || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
197989    ){
197990      if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
197991        fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
197992      }
197993    }
197994  }else if( !fts5IsContentless(pTab) ){
197995    rc = fts5SeekCursor(pCsr, 1);
197996    if( rc==SQLITE_OK ){
197997      sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
197998    }
197999  }
198000  return rc;
198001}
198002
198003
198004/*
198005** This routine implements the xFindFunction method for the FTS3
198006** virtual table.
198007*/
198008static int fts5FindFunctionMethod(
198009  sqlite3_vtab *pVtab,            /* Virtual table handle */
198010  int nUnused,                    /* Number of SQL function arguments */
198011  const char *zName,              /* Name of SQL function */
198012  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
198013  void **ppArg                    /* OUT: User data for *pxFunc */
198014){
198015  Fts5Table *pTab = (Fts5Table*)pVtab;
198016  Fts5Auxiliary *pAux;
198017
198018  UNUSED_PARAM(nUnused);
198019  pAux = fts5FindAuxiliary(pTab, zName);
198020  if( pAux ){
198021    *pxFunc = fts5ApiCallback;
198022    *ppArg = (void*)pAux;
198023    return 1;
198024  }
198025
198026  /* No function of the specified name was found. Return 0. */
198027  return 0;
198028}
198029
198030/*
198031** Implementation of FTS5 xRename method. Rename an fts5 table.
198032*/
198033static int fts5RenameMethod(
198034  sqlite3_vtab *pVtab,            /* Virtual table handle */
198035  const char *zName               /* New name of table */
198036){
198037  Fts5Table *pTab = (Fts5Table*)pVtab;
198038  return sqlite3Fts5StorageRename(pTab->pStorage, zName);
198039}
198040
198041/*
198042** The xSavepoint() method.
198043**
198044** Flush the contents of the pending-terms table to disk.
198045*/
198046static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
198047  Fts5Table *pTab = (Fts5Table*)pVtab;
198048  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
198049  fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
198050  fts5TripCursors(pTab);
198051  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
198052}
198053
198054/*
198055** The xRelease() method.
198056**
198057** This is a no-op.
198058*/
198059static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
198060  Fts5Table *pTab = (Fts5Table*)pVtab;
198061  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
198062  fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
198063  fts5TripCursors(pTab);
198064  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
198065}
198066
198067/*
198068** The xRollbackTo() method.
198069**
198070** Discard the contents of the pending terms table.
198071*/
198072static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
198073  Fts5Table *pTab = (Fts5Table*)pVtab;
198074  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
198075  fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
198076  fts5TripCursors(pTab);
198077  return sqlite3Fts5StorageRollback(pTab->pStorage);
198078}
198079
198080/*
198081** Register a new auxiliary function with global context pGlobal.
198082*/
198083static int fts5CreateAux(
198084  fts5_api *pApi,                 /* Global context (one per db handle) */
198085  const char *zName,              /* Name of new function */
198086  void *pUserData,                /* User data for aux. function */
198087  fts5_extension_function xFunc,  /* Aux. function implementation */
198088  void(*xDestroy)(void*)          /* Destructor for pUserData */
198089){
198090  Fts5Global *pGlobal = (Fts5Global*)pApi;
198091  int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
198092  if( rc==SQLITE_OK ){
198093    Fts5Auxiliary *pAux;
198094    int nName;                      /* Size of zName in bytes, including \0 */
198095    int nByte;                      /* Bytes of space to allocate */
198096
198097    nName = (int)strlen(zName) + 1;
198098    nByte = sizeof(Fts5Auxiliary) + nName;
198099    pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
198100    if( pAux ){
198101      memset(pAux, 0, nByte);
198102      pAux->zFunc = (char*)&pAux[1];
198103      memcpy(pAux->zFunc, zName, nName);
198104      pAux->pGlobal = pGlobal;
198105      pAux->pUserData = pUserData;
198106      pAux->xFunc = xFunc;
198107      pAux->xDestroy = xDestroy;
198108      pAux->pNext = pGlobal->pAux;
198109      pGlobal->pAux = pAux;
198110    }else{
198111      rc = SQLITE_NOMEM;
198112    }
198113  }
198114
198115  return rc;
198116}
198117
198118/*
198119** Register a new tokenizer. This is the implementation of the
198120** fts5_api.xCreateTokenizer() method.
198121*/
198122static int fts5CreateTokenizer(
198123  fts5_api *pApi,                 /* Global context (one per db handle) */
198124  const char *zName,              /* Name of new function */
198125  void *pUserData,                /* User data for aux. function */
198126  fts5_tokenizer *pTokenizer,     /* Tokenizer implementation */
198127  void(*xDestroy)(void*)          /* Destructor for pUserData */
198128){
198129  Fts5Global *pGlobal = (Fts5Global*)pApi;
198130  Fts5TokenizerModule *pNew;
198131  int nName;                      /* Size of zName and its \0 terminator */
198132  int nByte;                      /* Bytes of space to allocate */
198133  int rc = SQLITE_OK;
198134
198135  nName = (int)strlen(zName) + 1;
198136  nByte = sizeof(Fts5TokenizerModule) + nName;
198137  pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
198138  if( pNew ){
198139    memset(pNew, 0, nByte);
198140    pNew->zName = (char*)&pNew[1];
198141    memcpy(pNew->zName, zName, nName);
198142    pNew->pUserData = pUserData;
198143    pNew->x = *pTokenizer;
198144    pNew->xDestroy = xDestroy;
198145    pNew->pNext = pGlobal->pTok;
198146    pGlobal->pTok = pNew;
198147    if( pNew->pNext==0 ){
198148      pGlobal->pDfltTok = pNew;
198149    }
198150  }else{
198151    rc = SQLITE_NOMEM;
198152  }
198153
198154  return rc;
198155}
198156
198157static Fts5TokenizerModule *fts5LocateTokenizer(
198158  Fts5Global *pGlobal,
198159  const char *zName
198160){
198161  Fts5TokenizerModule *pMod = 0;
198162
198163  if( zName==0 ){
198164    pMod = pGlobal->pDfltTok;
198165  }else{
198166    for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
198167      if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
198168    }
198169  }
198170
198171  return pMod;
198172}
198173
198174/*
198175** Find a tokenizer. This is the implementation of the
198176** fts5_api.xFindTokenizer() method.
198177*/
198178static int fts5FindTokenizer(
198179  fts5_api *pApi,                 /* Global context (one per db handle) */
198180  const char *zName,              /* Name of new function */
198181  void **ppUserData,
198182  fts5_tokenizer *pTokenizer      /* Populate this object */
198183){
198184  int rc = SQLITE_OK;
198185  Fts5TokenizerModule *pMod;
198186
198187  pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
198188  if( pMod ){
198189    *pTokenizer = pMod->x;
198190    *ppUserData = pMod->pUserData;
198191  }else{
198192    memset(pTokenizer, 0, sizeof(fts5_tokenizer));
198193    rc = SQLITE_ERROR;
198194  }
198195
198196  return rc;
198197}
198198
198199static int sqlite3Fts5GetTokenizer(
198200  Fts5Global *pGlobal,
198201  const char **azArg,
198202  int nArg,
198203  Fts5Tokenizer **ppTok,
198204  fts5_tokenizer **ppTokApi,
198205  char **pzErr
198206){
198207  Fts5TokenizerModule *pMod;
198208  int rc = SQLITE_OK;
198209
198210  pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
198211  if( pMod==0 ){
198212    assert( nArg>0 );
198213    rc = SQLITE_ERROR;
198214    *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
198215  }else{
198216    rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
198217    *ppTokApi = &pMod->x;
198218    if( rc!=SQLITE_OK && pzErr ){
198219      *pzErr = sqlite3_mprintf("error in tokenizer constructor");
198220    }
198221  }
198222
198223  if( rc!=SQLITE_OK ){
198224    *ppTokApi = 0;
198225    *ppTok = 0;
198226  }
198227
198228  return rc;
198229}
198230
198231static void fts5ModuleDestroy(void *pCtx){
198232  Fts5TokenizerModule *pTok, *pNextTok;
198233  Fts5Auxiliary *pAux, *pNextAux;
198234  Fts5Global *pGlobal = (Fts5Global*)pCtx;
198235
198236  for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
198237    pNextAux = pAux->pNext;
198238    if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
198239    sqlite3_free(pAux);
198240  }
198241
198242  for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
198243    pNextTok = pTok->pNext;
198244    if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
198245    sqlite3_free(pTok);
198246  }
198247
198248  sqlite3_free(pGlobal);
198249}
198250
198251static void fts5Fts5Func(
198252  sqlite3_context *pCtx,          /* Function call context */
198253  int nArg,                       /* Number of args */
198254  sqlite3_value **apUnused        /* Function arguments */
198255){
198256  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
198257  char buf[8];
198258  UNUSED_PARAM2(nArg, apUnused);
198259  assert( nArg==0 );
198260  assert( sizeof(buf)>=sizeof(pGlobal) );
198261  memcpy(buf, (void*)&pGlobal, sizeof(pGlobal));
198262  sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT);
198263}
198264
198265/*
198266** Implementation of fts5_source_id() function.
198267*/
198268static void fts5SourceIdFunc(
198269  sqlite3_context *pCtx,          /* Function call context */
198270  int nArg,                       /* Number of args */
198271  sqlite3_value **apUnused        /* Function arguments */
198272){
198273  assert( nArg==0 );
198274  UNUSED_PARAM2(nArg, apUnused);
198275  sqlite3_result_text(pCtx, "fts5: 2017-06-17 09:59:36 036ebf729e4b21035d7f4f8e35a6f705e6bf99887889e2dc14ebf2242e7930dd", -1, SQLITE_TRANSIENT);
198276}
198277
198278static int fts5Init(sqlite3 *db){
198279  static const sqlite3_module fts5Mod = {
198280    /* iVersion      */ 2,
198281    /* xCreate       */ fts5CreateMethod,
198282    /* xConnect      */ fts5ConnectMethod,
198283    /* xBestIndex    */ fts5BestIndexMethod,
198284    /* xDisconnect   */ fts5DisconnectMethod,
198285    /* xDestroy      */ fts5DestroyMethod,
198286    /* xOpen         */ fts5OpenMethod,
198287    /* xClose        */ fts5CloseMethod,
198288    /* xFilter       */ fts5FilterMethod,
198289    /* xNext         */ fts5NextMethod,
198290    /* xEof          */ fts5EofMethod,
198291    /* xColumn       */ fts5ColumnMethod,
198292    /* xRowid        */ fts5RowidMethod,
198293    /* xUpdate       */ fts5UpdateMethod,
198294    /* xBegin        */ fts5BeginMethod,
198295    /* xSync         */ fts5SyncMethod,
198296    /* xCommit       */ fts5CommitMethod,
198297    /* xRollback     */ fts5RollbackMethod,
198298    /* xFindFunction */ fts5FindFunctionMethod,
198299    /* xRename       */ fts5RenameMethod,
198300    /* xSavepoint    */ fts5SavepointMethod,
198301    /* xRelease      */ fts5ReleaseMethod,
198302    /* xRollbackTo   */ fts5RollbackToMethod,
198303  };
198304
198305  int rc;
198306  Fts5Global *pGlobal = 0;
198307
198308  pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
198309  if( pGlobal==0 ){
198310    rc = SQLITE_NOMEM;
198311  }else{
198312    void *p = (void*)pGlobal;
198313    memset(pGlobal, 0, sizeof(Fts5Global));
198314    pGlobal->db = db;
198315    pGlobal->api.iVersion = 2;
198316    pGlobal->api.xCreateFunction = fts5CreateAux;
198317    pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
198318    pGlobal->api.xFindTokenizer = fts5FindTokenizer;
198319    rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
198320    if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
198321    if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
198322    if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
198323    if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
198324    if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
198325    if( rc==SQLITE_OK ){
198326      rc = sqlite3_create_function(
198327          db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
198328      );
198329    }
198330    if( rc==SQLITE_OK ){
198331      rc = sqlite3_create_function(
198332          db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
198333      );
198334    }
198335  }
198336
198337  /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
198338  ** fts5_test_mi.c is compiled and linked into the executable. And call
198339  ** its entry point to enable the matchinfo() demo.  */
198340#ifdef SQLITE_FTS5_ENABLE_TEST_MI
198341  if( rc==SQLITE_OK ){
198342    extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
198343    rc = sqlite3Fts5TestRegisterMatchinfo(db);
198344  }
198345#endif
198346
198347  return rc;
198348}
198349
198350/*
198351** The following functions are used to register the module with SQLite. If
198352** this module is being built as part of the SQLite core (SQLITE_CORE is
198353** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
198354**
198355** Or, if this module is being built as a loadable extension,
198356** sqlite3Fts5Init() is omitted and the two standard entry points
198357** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
198358*/
198359#ifndef SQLITE_CORE
198360#ifdef _WIN32
198361__declspec(dllexport)
198362#endif
198363SQLITE_API int sqlite3_fts_init(
198364  sqlite3 *db,
198365  char **pzErrMsg,
198366  const sqlite3_api_routines *pApi
198367){
198368  SQLITE_EXTENSION_INIT2(pApi);
198369  (void)pzErrMsg;  /* Unused parameter */
198370  return fts5Init(db);
198371}
198372
198373#ifdef _WIN32
198374__declspec(dllexport)
198375#endif
198376SQLITE_API int sqlite3_fts5_init(
198377  sqlite3 *db,
198378  char **pzErrMsg,
198379  const sqlite3_api_routines *pApi
198380){
198381  SQLITE_EXTENSION_INIT2(pApi);
198382  (void)pzErrMsg;  /* Unused parameter */
198383  return fts5Init(db);
198384}
198385#else
198386SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
198387  return fts5Init(db);
198388}
198389#endif
198390
198391/*
198392** 2014 May 31
198393**
198394** The author disclaims copyright to this source code.  In place of
198395** a legal notice, here is a blessing:
198396**
198397**    May you do good and not evil.
198398**    May you find forgiveness for yourself and forgive others.
198399**    May you share freely, never taking more than you give.
198400**
198401******************************************************************************
198402**
198403*/
198404
198405
198406
198407/* #include "fts5Int.h" */
198408
198409struct Fts5Storage {
198410  Fts5Config *pConfig;
198411  Fts5Index *pIndex;
198412  int bTotalsValid;               /* True if nTotalRow/aTotalSize[] are valid */
198413  i64 nTotalRow;                  /* Total number of rows in FTS table */
198414  i64 *aTotalSize;                /* Total sizes of each column */
198415  sqlite3_stmt *aStmt[11];
198416};
198417
198418
198419#if FTS5_STMT_SCAN_ASC!=0
198420# error "FTS5_STMT_SCAN_ASC mismatch"
198421#endif
198422#if FTS5_STMT_SCAN_DESC!=1
198423# error "FTS5_STMT_SCAN_DESC mismatch"
198424#endif
198425#if FTS5_STMT_LOOKUP!=2
198426# error "FTS5_STMT_LOOKUP mismatch"
198427#endif
198428
198429#define FTS5_STMT_INSERT_CONTENT  3
198430#define FTS5_STMT_REPLACE_CONTENT 4
198431#define FTS5_STMT_DELETE_CONTENT  5
198432#define FTS5_STMT_REPLACE_DOCSIZE  6
198433#define FTS5_STMT_DELETE_DOCSIZE  7
198434#define FTS5_STMT_LOOKUP_DOCSIZE  8
198435#define FTS5_STMT_REPLACE_CONFIG 9
198436#define FTS5_STMT_SCAN 10
198437
198438/*
198439** Prepare the two insert statements - Fts5Storage.pInsertContent and
198440** Fts5Storage.pInsertDocsize - if they have not already been prepared.
198441** Return SQLITE_OK if successful, or an SQLite error code if an error
198442** occurs.
198443*/
198444static int fts5StorageGetStmt(
198445  Fts5Storage *p,                 /* Storage handle */
198446  int eStmt,                      /* FTS5_STMT_XXX constant */
198447  sqlite3_stmt **ppStmt,          /* OUT: Prepared statement handle */
198448  char **pzErrMsg                 /* OUT: Error message (if any) */
198449){
198450  int rc = SQLITE_OK;
198451
198452  /* If there is no %_docsize table, there should be no requests for
198453  ** statements to operate on it.  */
198454  assert( p->pConfig->bColumnsize || (
198455        eStmt!=FTS5_STMT_REPLACE_DOCSIZE
198456     && eStmt!=FTS5_STMT_DELETE_DOCSIZE
198457     && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
198458  ));
198459
198460  assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
198461  if( p->aStmt[eStmt]==0 ){
198462    const char *azStmt[] = {
198463      "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
198464      "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
198465      "SELECT %s FROM %s T WHERE T.%Q=?",               /* LOOKUP  */
198466
198467      "INSERT INTO %Q.'%q_content' VALUES(%s)",         /* INSERT_CONTENT  */
198468      "REPLACE INTO %Q.'%q_content' VALUES(%s)",        /* REPLACE_CONTENT */
198469      "DELETE FROM %Q.'%q_content' WHERE id=?",         /* DELETE_CONTENT  */
198470      "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",       /* REPLACE_DOCSIZE  */
198471      "DELETE FROM %Q.'%q_docsize' WHERE id=?",         /* DELETE_DOCSIZE  */
198472
198473      "SELECT sz FROM %Q.'%q_docsize' WHERE id=?",      /* LOOKUP_DOCSIZE  */
198474
198475      "REPLACE INTO %Q.'%q_config' VALUES(?,?)",        /* REPLACE_CONFIG */
198476      "SELECT %s FROM %s AS T",                         /* SCAN */
198477    };
198478    Fts5Config *pC = p->pConfig;
198479    char *zSql = 0;
198480
198481    switch( eStmt ){
198482      case FTS5_STMT_SCAN:
198483        zSql = sqlite3_mprintf(azStmt[eStmt],
198484            pC->zContentExprlist, pC->zContent
198485        );
198486        break;
198487
198488      case FTS5_STMT_SCAN_ASC:
198489      case FTS5_STMT_SCAN_DESC:
198490        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
198491            pC->zContent, pC->zContentRowid, pC->zContentRowid,
198492            pC->zContentRowid
198493        );
198494        break;
198495
198496      case FTS5_STMT_LOOKUP:
198497        zSql = sqlite3_mprintf(azStmt[eStmt],
198498            pC->zContentExprlist, pC->zContent, pC->zContentRowid
198499        );
198500        break;
198501
198502      case FTS5_STMT_INSERT_CONTENT:
198503      case FTS5_STMT_REPLACE_CONTENT: {
198504        int nCol = pC->nCol + 1;
198505        char *zBind;
198506        int i;
198507
198508        zBind = sqlite3_malloc(1 + nCol*2);
198509        if( zBind ){
198510          for(i=0; i<nCol; i++){
198511            zBind[i*2] = '?';
198512            zBind[i*2 + 1] = ',';
198513          }
198514          zBind[i*2-1] = '\0';
198515          zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
198516          sqlite3_free(zBind);
198517        }
198518        break;
198519      }
198520
198521      default:
198522        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
198523        break;
198524    }
198525
198526    if( zSql==0 ){
198527      rc = SQLITE_NOMEM;
198528    }else{
198529      rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0);
198530      sqlite3_free(zSql);
198531      if( rc!=SQLITE_OK && pzErrMsg ){
198532        *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
198533      }
198534    }
198535  }
198536
198537  *ppStmt = p->aStmt[eStmt];
198538  sqlite3_reset(*ppStmt);
198539  return rc;
198540}
198541
198542
198543static int fts5ExecPrintf(
198544  sqlite3 *db,
198545  char **pzErr,
198546  const char *zFormat,
198547  ...
198548){
198549  int rc;
198550  va_list ap;                     /* ... printf arguments */
198551  char *zSql;
198552
198553  va_start(ap, zFormat);
198554  zSql = sqlite3_vmprintf(zFormat, ap);
198555
198556  if( zSql==0 ){
198557    rc = SQLITE_NOMEM;
198558  }else{
198559    rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
198560    sqlite3_free(zSql);
198561  }
198562
198563  va_end(ap);
198564  return rc;
198565}
198566
198567/*
198568** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
198569** code otherwise.
198570*/
198571static int sqlite3Fts5DropAll(Fts5Config *pConfig){
198572  int rc = fts5ExecPrintf(pConfig->db, 0,
198573      "DROP TABLE IF EXISTS %Q.'%q_data';"
198574      "DROP TABLE IF EXISTS %Q.'%q_idx';"
198575      "DROP TABLE IF EXISTS %Q.'%q_config';",
198576      pConfig->zDb, pConfig->zName,
198577      pConfig->zDb, pConfig->zName,
198578      pConfig->zDb, pConfig->zName
198579  );
198580  if( rc==SQLITE_OK && pConfig->bColumnsize ){
198581    rc = fts5ExecPrintf(pConfig->db, 0,
198582        "DROP TABLE IF EXISTS %Q.'%q_docsize';",
198583        pConfig->zDb, pConfig->zName
198584    );
198585  }
198586  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
198587    rc = fts5ExecPrintf(pConfig->db, 0,
198588        "DROP TABLE IF EXISTS %Q.'%q_content';",
198589        pConfig->zDb, pConfig->zName
198590    );
198591  }
198592  return rc;
198593}
198594
198595static void fts5StorageRenameOne(
198596  Fts5Config *pConfig,            /* Current FTS5 configuration */
198597  int *pRc,                       /* IN/OUT: Error code */
198598  const char *zTail,              /* Tail of table name e.g. "data", "config" */
198599  const char *zName               /* New name of FTS5 table */
198600){
198601  if( *pRc==SQLITE_OK ){
198602    *pRc = fts5ExecPrintf(pConfig->db, 0,
198603        "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
198604        pConfig->zDb, pConfig->zName, zTail, zName, zTail
198605    );
198606  }
198607}
198608
198609static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
198610  Fts5Config *pConfig = pStorage->pConfig;
198611  int rc = sqlite3Fts5StorageSync(pStorage, 1);
198612
198613  fts5StorageRenameOne(pConfig, &rc, "data", zName);
198614  fts5StorageRenameOne(pConfig, &rc, "idx", zName);
198615  fts5StorageRenameOne(pConfig, &rc, "config", zName);
198616  if( pConfig->bColumnsize ){
198617    fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
198618  }
198619  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
198620    fts5StorageRenameOne(pConfig, &rc, "content", zName);
198621  }
198622  return rc;
198623}
198624
198625/*
198626** Create the shadow table named zPost, with definition zDefn. Return
198627** SQLITE_OK if successful, or an SQLite error code otherwise.
198628*/
198629static int sqlite3Fts5CreateTable(
198630  Fts5Config *pConfig,            /* FTS5 configuration */
198631  const char *zPost,              /* Shadow table to create (e.g. "content") */
198632  const char *zDefn,              /* Columns etc. for shadow table */
198633  int bWithout,                   /* True for without rowid */
198634  char **pzErr                    /* OUT: Error message */
198635){
198636  int rc;
198637  char *zErr = 0;
198638
198639  rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
198640      pConfig->zDb, pConfig->zName, zPost, zDefn,
198641#ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
198642      bWithout?" WITHOUT ROWID":
198643#endif
198644      ""
198645  );
198646  if( zErr ){
198647    *pzErr = sqlite3_mprintf(
198648        "fts5: error creating shadow table %q_%s: %s",
198649        pConfig->zName, zPost, zErr
198650    );
198651    sqlite3_free(zErr);
198652  }
198653
198654  return rc;
198655}
198656
198657/*
198658** Open a new Fts5Index handle. If the bCreate argument is true, create
198659** and initialize the underlying tables
198660**
198661** If successful, set *pp to point to the new object and return SQLITE_OK.
198662** Otherwise, set *pp to NULL and return an SQLite error code.
198663*/
198664static int sqlite3Fts5StorageOpen(
198665  Fts5Config *pConfig,
198666  Fts5Index *pIndex,
198667  int bCreate,
198668  Fts5Storage **pp,
198669  char **pzErr                    /* OUT: Error message */
198670){
198671  int rc = SQLITE_OK;
198672  Fts5Storage *p;                 /* New object */
198673  int nByte;                      /* Bytes of space to allocate */
198674
198675  nByte = sizeof(Fts5Storage)               /* Fts5Storage object */
198676        + pConfig->nCol * sizeof(i64);      /* Fts5Storage.aTotalSize[] */
198677  *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
198678  if( !p ) return SQLITE_NOMEM;
198679
198680  memset(p, 0, nByte);
198681  p->aTotalSize = (i64*)&p[1];
198682  p->pConfig = pConfig;
198683  p->pIndex = pIndex;
198684
198685  if( bCreate ){
198686    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
198687      int nDefn = 32 + pConfig->nCol*10;
198688      char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
198689      if( zDefn==0 ){
198690        rc = SQLITE_NOMEM;
198691      }else{
198692        int i;
198693        int iOff;
198694        sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
198695        iOff = (int)strlen(zDefn);
198696        for(i=0; i<pConfig->nCol; i++){
198697          sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
198698          iOff += (int)strlen(&zDefn[iOff]);
198699        }
198700        rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
198701      }
198702      sqlite3_free(zDefn);
198703    }
198704
198705    if( rc==SQLITE_OK && pConfig->bColumnsize ){
198706      rc = sqlite3Fts5CreateTable(
198707          pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
198708      );
198709    }
198710    if( rc==SQLITE_OK ){
198711      rc = sqlite3Fts5CreateTable(
198712          pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
198713      );
198714    }
198715    if( rc==SQLITE_OK ){
198716      rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
198717    }
198718  }
198719
198720  if( rc ){
198721    sqlite3Fts5StorageClose(p);
198722    *pp = 0;
198723  }
198724  return rc;
198725}
198726
198727/*
198728** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
198729*/
198730static int sqlite3Fts5StorageClose(Fts5Storage *p){
198731  int rc = SQLITE_OK;
198732  if( p ){
198733    int i;
198734
198735    /* Finalize all SQL statements */
198736    for(i=0; i<ArraySize(p->aStmt); i++){
198737      sqlite3_finalize(p->aStmt[i]);
198738    }
198739
198740    sqlite3_free(p);
198741  }
198742  return rc;
198743}
198744
198745typedef struct Fts5InsertCtx Fts5InsertCtx;
198746struct Fts5InsertCtx {
198747  Fts5Storage *pStorage;
198748  int iCol;
198749  int szCol;                      /* Size of column value in tokens */
198750};
198751
198752/*
198753** Tokenization callback used when inserting tokens into the FTS index.
198754*/
198755static int fts5StorageInsertCallback(
198756  void *pContext,                 /* Pointer to Fts5InsertCtx object */
198757  int tflags,
198758  const char *pToken,             /* Buffer containing token */
198759  int nToken,                     /* Size of token in bytes */
198760  int iUnused1,                   /* Start offset of token */
198761  int iUnused2                    /* End offset of token */
198762){
198763  Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
198764  Fts5Index *pIdx = pCtx->pStorage->pIndex;
198765  UNUSED_PARAM2(iUnused1, iUnused2);
198766  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
198767  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
198768    pCtx->szCol++;
198769  }
198770  return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
198771}
198772
198773/*
198774** If a row with rowid iDel is present in the %_content table, add the
198775** delete-markers to the FTS index necessary to delete it. Do not actually
198776** remove the %_content row at this time though.
198777*/
198778static int fts5StorageDeleteFromIndex(
198779  Fts5Storage *p,
198780  i64 iDel,
198781  sqlite3_value **apVal
198782){
198783  Fts5Config *pConfig = p->pConfig;
198784  sqlite3_stmt *pSeek = 0;        /* SELECT to read row iDel from %_data */
198785  int rc;                         /* Return code */
198786  int rc2;                        /* sqlite3_reset() return code */
198787  int iCol;
198788  Fts5InsertCtx ctx;
198789
198790  if( apVal==0 ){
198791    rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
198792    if( rc!=SQLITE_OK ) return rc;
198793    sqlite3_bind_int64(pSeek, 1, iDel);
198794    if( sqlite3_step(pSeek)!=SQLITE_ROW ){
198795      return sqlite3_reset(pSeek);
198796    }
198797  }
198798
198799  ctx.pStorage = p;
198800  ctx.iCol = -1;
198801  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
198802  for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
198803    if( pConfig->abUnindexed[iCol-1]==0 ){
198804      const char *zText;
198805      int nText;
198806      if( pSeek ){
198807        zText = (const char*)sqlite3_column_text(pSeek, iCol);
198808        nText = sqlite3_column_bytes(pSeek, iCol);
198809      }else{
198810        zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
198811        nText = sqlite3_value_bytes(apVal[iCol-1]);
198812      }
198813      ctx.szCol = 0;
198814      rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
198815          zText, nText, (void*)&ctx, fts5StorageInsertCallback
198816      );
198817      p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
198818    }
198819  }
198820  p->nTotalRow--;
198821
198822  rc2 = sqlite3_reset(pSeek);
198823  if( rc==SQLITE_OK ) rc = rc2;
198824  return rc;
198825}
198826
198827
198828/*
198829** Insert a record into the %_docsize table. Specifically, do:
198830**
198831**   INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
198832**
198833** If there is no %_docsize table (as happens if the columnsize=0 option
198834** is specified when the FTS5 table is created), this function is a no-op.
198835*/
198836static int fts5StorageInsertDocsize(
198837  Fts5Storage *p,                 /* Storage module to write to */
198838  i64 iRowid,                     /* id value */
198839  Fts5Buffer *pBuf                /* sz value */
198840){
198841  int rc = SQLITE_OK;
198842  if( p->pConfig->bColumnsize ){
198843    sqlite3_stmt *pReplace = 0;
198844    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
198845    if( rc==SQLITE_OK ){
198846      sqlite3_bind_int64(pReplace, 1, iRowid);
198847      sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
198848      sqlite3_step(pReplace);
198849      rc = sqlite3_reset(pReplace);
198850    }
198851  }
198852  return rc;
198853}
198854
198855/*
198856** Load the contents of the "averages" record from disk into the
198857** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
198858** argument bCache is true, set the p->bTotalsValid flag to indicate
198859** that the contents of aTotalSize[] and nTotalRow are valid until
198860** further notice.
198861**
198862** Return SQLITE_OK if successful, or an SQLite error code if an error
198863** occurs.
198864*/
198865static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
198866  int rc = SQLITE_OK;
198867  if( p->bTotalsValid==0 ){
198868    rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
198869    p->bTotalsValid = bCache;
198870  }
198871  return rc;
198872}
198873
198874/*
198875** Store the current contents of the p->nTotalRow and p->aTotalSize[]
198876** variables in the "averages" record on disk.
198877**
198878** Return SQLITE_OK if successful, or an SQLite error code if an error
198879** occurs.
198880*/
198881static int fts5StorageSaveTotals(Fts5Storage *p){
198882  int nCol = p->pConfig->nCol;
198883  int i;
198884  Fts5Buffer buf;
198885  int rc = SQLITE_OK;
198886  memset(&buf, 0, sizeof(buf));
198887
198888  sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
198889  for(i=0; i<nCol; i++){
198890    sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
198891  }
198892  if( rc==SQLITE_OK ){
198893    rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
198894  }
198895  sqlite3_free(buf.p);
198896
198897  return rc;
198898}
198899
198900/*
198901** Remove a row from the FTS table.
198902*/
198903static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
198904  Fts5Config *pConfig = p->pConfig;
198905  int rc;
198906  sqlite3_stmt *pDel = 0;
198907
198908  assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
198909  rc = fts5StorageLoadTotals(p, 1);
198910
198911  /* Delete the index records */
198912  if( rc==SQLITE_OK ){
198913    rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
198914  }
198915
198916  /* Delete the %_docsize record */
198917  if( rc==SQLITE_OK && pConfig->bColumnsize ){
198918    rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
198919    if( rc==SQLITE_OK ){
198920      sqlite3_bind_int64(pDel, 1, iDel);
198921      sqlite3_step(pDel);
198922      rc = sqlite3_reset(pDel);
198923    }
198924  }
198925
198926  /* Delete the %_content record */
198927  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
198928    if( rc==SQLITE_OK ){
198929      rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
198930    }
198931    if( rc==SQLITE_OK ){
198932      sqlite3_bind_int64(pDel, 1, iDel);
198933      sqlite3_step(pDel);
198934      rc = sqlite3_reset(pDel);
198935    }
198936  }
198937
198938  return rc;
198939}
198940
198941/*
198942** Delete all entries in the FTS5 index.
198943*/
198944static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
198945  Fts5Config *pConfig = p->pConfig;
198946  int rc;
198947
198948  /* Delete the contents of the %_data and %_docsize tables. */
198949  rc = fts5ExecPrintf(pConfig->db, 0,
198950      "DELETE FROM %Q.'%q_data';"
198951      "DELETE FROM %Q.'%q_idx';",
198952      pConfig->zDb, pConfig->zName,
198953      pConfig->zDb, pConfig->zName
198954  );
198955  if( rc==SQLITE_OK && pConfig->bColumnsize ){
198956    rc = fts5ExecPrintf(pConfig->db, 0,
198957        "DELETE FROM %Q.'%q_docsize';",
198958        pConfig->zDb, pConfig->zName
198959    );
198960  }
198961
198962  /* Reinitialize the %_data table. This call creates the initial structure
198963  ** and averages records.  */
198964  if( rc==SQLITE_OK ){
198965    rc = sqlite3Fts5IndexReinit(p->pIndex);
198966  }
198967  if( rc==SQLITE_OK ){
198968    rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
198969  }
198970  return rc;
198971}
198972
198973static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
198974  Fts5Buffer buf = {0,0,0};
198975  Fts5Config *pConfig = p->pConfig;
198976  sqlite3_stmt *pScan = 0;
198977  Fts5InsertCtx ctx;
198978  int rc;
198979
198980  memset(&ctx, 0, sizeof(Fts5InsertCtx));
198981  ctx.pStorage = p;
198982  rc = sqlite3Fts5StorageDeleteAll(p);
198983  if( rc==SQLITE_OK ){
198984    rc = fts5StorageLoadTotals(p, 1);
198985  }
198986
198987  if( rc==SQLITE_OK ){
198988    rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
198989  }
198990
198991  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
198992    i64 iRowid = sqlite3_column_int64(pScan, 0);
198993
198994    sqlite3Fts5BufferZero(&buf);
198995    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
198996    for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
198997      ctx.szCol = 0;
198998      if( pConfig->abUnindexed[ctx.iCol]==0 ){
198999        rc = sqlite3Fts5Tokenize(pConfig,
199000            FTS5_TOKENIZE_DOCUMENT,
199001            (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
199002            sqlite3_column_bytes(pScan, ctx.iCol+1),
199003            (void*)&ctx,
199004            fts5StorageInsertCallback
199005        );
199006      }
199007      sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
199008      p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
199009    }
199010    p->nTotalRow++;
199011
199012    if( rc==SQLITE_OK ){
199013      rc = fts5StorageInsertDocsize(p, iRowid, &buf);
199014    }
199015  }
199016  sqlite3_free(buf.p);
199017
199018  /* Write the averages record */
199019  if( rc==SQLITE_OK ){
199020    rc = fts5StorageSaveTotals(p);
199021  }
199022  return rc;
199023}
199024
199025static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
199026  return sqlite3Fts5IndexOptimize(p->pIndex);
199027}
199028
199029static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
199030  return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
199031}
199032
199033static int sqlite3Fts5StorageReset(Fts5Storage *p){
199034  return sqlite3Fts5IndexReset(p->pIndex);
199035}
199036
199037/*
199038** Allocate a new rowid. This is used for "external content" tables when
199039** a NULL value is inserted into the rowid column. The new rowid is allocated
199040** by inserting a dummy row into the %_docsize table. The dummy will be
199041** overwritten later.
199042**
199043** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
199044** this case the user is required to provide a rowid explicitly.
199045*/
199046static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
199047  int rc = SQLITE_MISMATCH;
199048  if( p->pConfig->bColumnsize ){
199049    sqlite3_stmt *pReplace = 0;
199050    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
199051    if( rc==SQLITE_OK ){
199052      sqlite3_bind_null(pReplace, 1);
199053      sqlite3_bind_null(pReplace, 2);
199054      sqlite3_step(pReplace);
199055      rc = sqlite3_reset(pReplace);
199056    }
199057    if( rc==SQLITE_OK ){
199058      *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
199059    }
199060  }
199061  return rc;
199062}
199063
199064/*
199065** Insert a new row into the FTS content table.
199066*/
199067static int sqlite3Fts5StorageContentInsert(
199068  Fts5Storage *p,
199069  sqlite3_value **apVal,
199070  i64 *piRowid
199071){
199072  Fts5Config *pConfig = p->pConfig;
199073  int rc = SQLITE_OK;
199074
199075  /* Insert the new row into the %_content table. */
199076  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
199077    if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
199078      *piRowid = sqlite3_value_int64(apVal[1]);
199079    }else{
199080      rc = fts5StorageNewRowid(p, piRowid);
199081    }
199082  }else{
199083    sqlite3_stmt *pInsert = 0;    /* Statement to write %_content table */
199084    int i;                        /* Counter variable */
199085    rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
199086    for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
199087      rc = sqlite3_bind_value(pInsert, i, apVal[i]);
199088    }
199089    if( rc==SQLITE_OK ){
199090      sqlite3_step(pInsert);
199091      rc = sqlite3_reset(pInsert);
199092    }
199093    *piRowid = sqlite3_last_insert_rowid(pConfig->db);
199094  }
199095
199096  return rc;
199097}
199098
199099/*
199100** Insert new entries into the FTS index and %_docsize table.
199101*/
199102static int sqlite3Fts5StorageIndexInsert(
199103  Fts5Storage *p,
199104  sqlite3_value **apVal,
199105  i64 iRowid
199106){
199107  Fts5Config *pConfig = p->pConfig;
199108  int rc = SQLITE_OK;             /* Return code */
199109  Fts5InsertCtx ctx;              /* Tokenization callback context object */
199110  Fts5Buffer buf;                 /* Buffer used to build up %_docsize blob */
199111
199112  memset(&buf, 0, sizeof(Fts5Buffer));
199113  ctx.pStorage = p;
199114  rc = fts5StorageLoadTotals(p, 1);
199115
199116  if( rc==SQLITE_OK ){
199117    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
199118  }
199119  for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
199120    ctx.szCol = 0;
199121    if( pConfig->abUnindexed[ctx.iCol]==0 ){
199122      rc = sqlite3Fts5Tokenize(pConfig,
199123          FTS5_TOKENIZE_DOCUMENT,
199124          (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
199125          sqlite3_value_bytes(apVal[ctx.iCol+2]),
199126          (void*)&ctx,
199127          fts5StorageInsertCallback
199128      );
199129    }
199130    sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
199131    p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
199132  }
199133  p->nTotalRow++;
199134
199135  /* Write the %_docsize record */
199136  if( rc==SQLITE_OK ){
199137    rc = fts5StorageInsertDocsize(p, iRowid, &buf);
199138  }
199139  sqlite3_free(buf.p);
199140
199141  return rc;
199142}
199143
199144static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
199145  Fts5Config *pConfig = p->pConfig;
199146  char *zSql;
199147  int rc;
199148
199149  zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
199150      pConfig->zDb, pConfig->zName, zSuffix
199151  );
199152  if( zSql==0 ){
199153    rc = SQLITE_NOMEM;
199154  }else{
199155    sqlite3_stmt *pCnt = 0;
199156    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
199157    if( rc==SQLITE_OK ){
199158      if( SQLITE_ROW==sqlite3_step(pCnt) ){
199159        *pnRow = sqlite3_column_int64(pCnt, 0);
199160      }
199161      rc = sqlite3_finalize(pCnt);
199162    }
199163  }
199164
199165  sqlite3_free(zSql);
199166  return rc;
199167}
199168
199169/*
199170** Context object used by sqlite3Fts5StorageIntegrity().
199171*/
199172typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
199173struct Fts5IntegrityCtx {
199174  i64 iRowid;
199175  int iCol;
199176  int szCol;
199177  u64 cksum;
199178  Fts5Termset *pTermset;
199179  Fts5Config *pConfig;
199180};
199181
199182
199183/*
199184** Tokenization callback used by integrity check.
199185*/
199186static int fts5StorageIntegrityCallback(
199187  void *pContext,                 /* Pointer to Fts5IntegrityCtx object */
199188  int tflags,
199189  const char *pToken,             /* Buffer containing token */
199190  int nToken,                     /* Size of token in bytes */
199191  int iUnused1,                   /* Start offset of token */
199192  int iUnused2                    /* End offset of token */
199193){
199194  Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
199195  Fts5Termset *pTermset = pCtx->pTermset;
199196  int bPresent;
199197  int ii;
199198  int rc = SQLITE_OK;
199199  int iPos;
199200  int iCol;
199201
199202  UNUSED_PARAM2(iUnused1, iUnused2);
199203  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
199204
199205  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
199206    pCtx->szCol++;
199207  }
199208
199209  switch( pCtx->pConfig->eDetail ){
199210    case FTS5_DETAIL_FULL:
199211      iPos = pCtx->szCol-1;
199212      iCol = pCtx->iCol;
199213      break;
199214
199215    case FTS5_DETAIL_COLUMNS:
199216      iPos = pCtx->iCol;
199217      iCol = 0;
199218      break;
199219
199220    default:
199221      assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
199222      iPos = 0;
199223      iCol = 0;
199224      break;
199225  }
199226
199227  rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
199228  if( rc==SQLITE_OK && bPresent==0 ){
199229    pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
199230        pCtx->iRowid, iCol, iPos, 0, pToken, nToken
199231    );
199232  }
199233
199234  for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
199235    const int nChar = pCtx->pConfig->aPrefix[ii];
199236    int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
199237    if( nByte ){
199238      rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
199239      if( bPresent==0 ){
199240        pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
199241            pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
199242        );
199243      }
199244    }
199245  }
199246
199247  return rc;
199248}
199249
199250/*
199251** Check that the contents of the FTS index match that of the %_content
199252** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
199253** some other SQLite error code if an error occurs while attempting to
199254** determine this.
199255*/
199256static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
199257  Fts5Config *pConfig = p->pConfig;
199258  int rc;                         /* Return code */
199259  int *aColSize;                  /* Array of size pConfig->nCol */
199260  i64 *aTotalSize;                /* Array of size pConfig->nCol */
199261  Fts5IntegrityCtx ctx;
199262  sqlite3_stmt *pScan;
199263
199264  memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
199265  ctx.pConfig = p->pConfig;
199266  aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
199267  if( !aTotalSize ) return SQLITE_NOMEM;
199268  aColSize = (int*)&aTotalSize[pConfig->nCol];
199269  memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
199270
199271  /* Generate the expected index checksum based on the contents of the
199272  ** %_content table. This block stores the checksum in ctx.cksum. */
199273  rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
199274  if( rc==SQLITE_OK ){
199275    int rc2;
199276    while( SQLITE_ROW==sqlite3_step(pScan) ){
199277      int i;
199278      ctx.iRowid = sqlite3_column_int64(pScan, 0);
199279      ctx.szCol = 0;
199280      if( pConfig->bColumnsize ){
199281        rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
199282      }
199283      if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
199284        rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
199285      }
199286      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
199287        if( pConfig->abUnindexed[i] ) continue;
199288        ctx.iCol = i;
199289        ctx.szCol = 0;
199290        if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
199291          rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
199292        }
199293        if( rc==SQLITE_OK ){
199294          rc = sqlite3Fts5Tokenize(pConfig,
199295              FTS5_TOKENIZE_DOCUMENT,
199296              (const char*)sqlite3_column_text(pScan, i+1),
199297              sqlite3_column_bytes(pScan, i+1),
199298              (void*)&ctx,
199299              fts5StorageIntegrityCallback
199300          );
199301        }
199302        if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
199303          rc = FTS5_CORRUPT;
199304        }
199305        aTotalSize[i] += ctx.szCol;
199306        if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
199307          sqlite3Fts5TermsetFree(ctx.pTermset);
199308          ctx.pTermset = 0;
199309        }
199310      }
199311      sqlite3Fts5TermsetFree(ctx.pTermset);
199312      ctx.pTermset = 0;
199313
199314      if( rc!=SQLITE_OK ) break;
199315    }
199316    rc2 = sqlite3_reset(pScan);
199317    if( rc==SQLITE_OK ) rc = rc2;
199318  }
199319
199320  /* Test that the "totals" (sometimes called "averages") record looks Ok */
199321  if( rc==SQLITE_OK ){
199322    int i;
199323    rc = fts5StorageLoadTotals(p, 0);
199324    for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
199325      if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
199326    }
199327  }
199328
199329  /* Check that the %_docsize and %_content tables contain the expected
199330  ** number of rows.  */
199331  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
199332    i64 nRow = 0;
199333    rc = fts5StorageCount(p, "content", &nRow);
199334    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
199335  }
199336  if( rc==SQLITE_OK && pConfig->bColumnsize ){
199337    i64 nRow = 0;
199338    rc = fts5StorageCount(p, "docsize", &nRow);
199339    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
199340  }
199341
199342  /* Pass the expected checksum down to the FTS index module. It will
199343  ** verify, amongst other things, that it matches the checksum generated by
199344  ** inspecting the index itself.  */
199345  if( rc==SQLITE_OK ){
199346    rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
199347  }
199348
199349  sqlite3_free(aTotalSize);
199350  return rc;
199351}
199352
199353/*
199354** Obtain an SQLite statement handle that may be used to read data from the
199355** %_content table.
199356*/
199357static int sqlite3Fts5StorageStmt(
199358  Fts5Storage *p,
199359  int eStmt,
199360  sqlite3_stmt **pp,
199361  char **pzErrMsg
199362){
199363  int rc;
199364  assert( eStmt==FTS5_STMT_SCAN_ASC
199365       || eStmt==FTS5_STMT_SCAN_DESC
199366       || eStmt==FTS5_STMT_LOOKUP
199367  );
199368  rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
199369  if( rc==SQLITE_OK ){
199370    assert( p->aStmt[eStmt]==*pp );
199371    p->aStmt[eStmt] = 0;
199372  }
199373  return rc;
199374}
199375
199376/*
199377** Release an SQLite statement handle obtained via an earlier call to
199378** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
199379** must match that passed to the sqlite3Fts5StorageStmt() call.
199380*/
199381static void sqlite3Fts5StorageStmtRelease(
199382  Fts5Storage *p,
199383  int eStmt,
199384  sqlite3_stmt *pStmt
199385){
199386  assert( eStmt==FTS5_STMT_SCAN_ASC
199387       || eStmt==FTS5_STMT_SCAN_DESC
199388       || eStmt==FTS5_STMT_LOOKUP
199389  );
199390  if( p->aStmt[eStmt]==0 ){
199391    sqlite3_reset(pStmt);
199392    p->aStmt[eStmt] = pStmt;
199393  }else{
199394    sqlite3_finalize(pStmt);
199395  }
199396}
199397
199398static int fts5StorageDecodeSizeArray(
199399  int *aCol, int nCol,            /* Array to populate */
199400  const u8 *aBlob, int nBlob      /* Record to read varints from */
199401){
199402  int i;
199403  int iOff = 0;
199404  for(i=0; i<nCol; i++){
199405    if( iOff>=nBlob ) return 1;
199406    iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
199407  }
199408  return (iOff!=nBlob);
199409}
199410
199411/*
199412** Argument aCol points to an array of integers containing one entry for
199413** each table column. This function reads the %_docsize record for the
199414** specified rowid and populates aCol[] with the results.
199415**
199416** An SQLite error code is returned if an error occurs, or SQLITE_OK
199417** otherwise.
199418*/
199419static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
199420  int nCol = p->pConfig->nCol;    /* Number of user columns in table */
199421  sqlite3_stmt *pLookup = 0;      /* Statement to query %_docsize */
199422  int rc;                         /* Return Code */
199423
199424  assert( p->pConfig->bColumnsize );
199425  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
199426  if( rc==SQLITE_OK ){
199427    int bCorrupt = 1;
199428    sqlite3_bind_int64(pLookup, 1, iRowid);
199429    if( SQLITE_ROW==sqlite3_step(pLookup) ){
199430      const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
199431      int nBlob = sqlite3_column_bytes(pLookup, 0);
199432      if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
199433        bCorrupt = 0;
199434      }
199435    }
199436    rc = sqlite3_reset(pLookup);
199437    if( bCorrupt && rc==SQLITE_OK ){
199438      rc = FTS5_CORRUPT;
199439    }
199440  }
199441
199442  return rc;
199443}
199444
199445static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
199446  int rc = fts5StorageLoadTotals(p, 0);
199447  if( rc==SQLITE_OK ){
199448    *pnToken = 0;
199449    if( iCol<0 ){
199450      int i;
199451      for(i=0; i<p->pConfig->nCol; i++){
199452        *pnToken += p->aTotalSize[i];
199453      }
199454    }else if( iCol<p->pConfig->nCol ){
199455      *pnToken = p->aTotalSize[iCol];
199456    }else{
199457      rc = SQLITE_RANGE;
199458    }
199459  }
199460  return rc;
199461}
199462
199463static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
199464  int rc = fts5StorageLoadTotals(p, 0);
199465  if( rc==SQLITE_OK ){
199466    *pnRow = p->nTotalRow;
199467  }
199468  return rc;
199469}
199470
199471/*
199472** Flush any data currently held in-memory to disk.
199473*/
199474static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit){
199475  int rc = SQLITE_OK;
199476  i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
199477  if( p->bTotalsValid ){
199478    rc = fts5StorageSaveTotals(p);
199479    if( bCommit ) p->bTotalsValid = 0;
199480  }
199481  if( rc==SQLITE_OK ){
199482    rc = sqlite3Fts5IndexSync(p->pIndex, bCommit);
199483  }
199484  sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
199485  return rc;
199486}
199487
199488static int sqlite3Fts5StorageRollback(Fts5Storage *p){
199489  p->bTotalsValid = 0;
199490  return sqlite3Fts5IndexRollback(p->pIndex);
199491}
199492
199493static int sqlite3Fts5StorageConfigValue(
199494  Fts5Storage *p,
199495  const char *z,
199496  sqlite3_value *pVal,
199497  int iVal
199498){
199499  sqlite3_stmt *pReplace = 0;
199500  int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
199501  if( rc==SQLITE_OK ){
199502    sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
199503    if( pVal ){
199504      sqlite3_bind_value(pReplace, 2, pVal);
199505    }else{
199506      sqlite3_bind_int(pReplace, 2, iVal);
199507    }
199508    sqlite3_step(pReplace);
199509    rc = sqlite3_reset(pReplace);
199510  }
199511  if( rc==SQLITE_OK && pVal ){
199512    int iNew = p->pConfig->iCookie + 1;
199513    rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
199514    if( rc==SQLITE_OK ){
199515      p->pConfig->iCookie = iNew;
199516    }
199517  }
199518  return rc;
199519}
199520
199521/*
199522** 2014 May 31
199523**
199524** The author disclaims copyright to this source code.  In place of
199525** a legal notice, here is a blessing:
199526**
199527**    May you do good and not evil.
199528**    May you find forgiveness for yourself and forgive others.
199529**    May you share freely, never taking more than you give.
199530**
199531******************************************************************************
199532*/
199533
199534
199535/* #include "fts5Int.h" */
199536
199537/**************************************************************************
199538** Start of ascii tokenizer implementation.
199539*/
199540
199541/*
199542** For tokenizers with no "unicode" modifier, the set of token characters
199543** is the same as the set of ASCII range alphanumeric characters.
199544*/
199545static unsigned char aAsciiTokenChar[128] = {
199546  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00..0x0F */
199547  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x10..0x1F */
199548  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20..0x2F */
199549  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30..0x3F */
199550  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40..0x4F */
199551  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x50..0x5F */
199552  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60..0x6F */
199553  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x70..0x7F */
199554};
199555
199556typedef struct AsciiTokenizer AsciiTokenizer;
199557struct AsciiTokenizer {
199558  unsigned char aTokenChar[128];
199559};
199560
199561static void fts5AsciiAddExceptions(
199562  AsciiTokenizer *p,
199563  const char *zArg,
199564  int bTokenChars
199565){
199566  int i;
199567  for(i=0; zArg[i]; i++){
199568    if( (zArg[i] & 0x80)==0 ){
199569      p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
199570    }
199571  }
199572}
199573
199574/*
199575** Delete a "ascii" tokenizer.
199576*/
199577static void fts5AsciiDelete(Fts5Tokenizer *p){
199578  sqlite3_free(p);
199579}
199580
199581/*
199582** Create an "ascii" tokenizer.
199583*/
199584static int fts5AsciiCreate(
199585  void *pUnused,
199586  const char **azArg, int nArg,
199587  Fts5Tokenizer **ppOut
199588){
199589  int rc = SQLITE_OK;
199590  AsciiTokenizer *p = 0;
199591  UNUSED_PARAM(pUnused);
199592  if( nArg%2 ){
199593    rc = SQLITE_ERROR;
199594  }else{
199595    p = sqlite3_malloc(sizeof(AsciiTokenizer));
199596    if( p==0 ){
199597      rc = SQLITE_NOMEM;
199598    }else{
199599      int i;
199600      memset(p, 0, sizeof(AsciiTokenizer));
199601      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
199602      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
199603        const char *zArg = azArg[i+1];
199604        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
199605          fts5AsciiAddExceptions(p, zArg, 1);
199606        }else
199607        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
199608          fts5AsciiAddExceptions(p, zArg, 0);
199609        }else{
199610          rc = SQLITE_ERROR;
199611        }
199612      }
199613      if( rc!=SQLITE_OK ){
199614        fts5AsciiDelete((Fts5Tokenizer*)p);
199615        p = 0;
199616      }
199617    }
199618  }
199619
199620  *ppOut = (Fts5Tokenizer*)p;
199621  return rc;
199622}
199623
199624
199625static void asciiFold(char *aOut, const char *aIn, int nByte){
199626  int i;
199627  for(i=0; i<nByte; i++){
199628    char c = aIn[i];
199629    if( c>='A' && c<='Z' ) c += 32;
199630    aOut[i] = c;
199631  }
199632}
199633
199634/*
199635** Tokenize some text using the ascii tokenizer.
199636*/
199637static int fts5AsciiTokenize(
199638  Fts5Tokenizer *pTokenizer,
199639  void *pCtx,
199640  int iUnused,
199641  const char *pText, int nText,
199642  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
199643){
199644  AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
199645  int rc = SQLITE_OK;
199646  int ie;
199647  int is = 0;
199648
199649  char aFold[64];
199650  int nFold = sizeof(aFold);
199651  char *pFold = aFold;
199652  unsigned char *a = p->aTokenChar;
199653
199654  UNUSED_PARAM(iUnused);
199655
199656  while( is<nText && rc==SQLITE_OK ){
199657    int nByte;
199658
199659    /* Skip any leading divider characters. */
199660    while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
199661      is++;
199662    }
199663    if( is==nText ) break;
199664
199665    /* Count the token characters */
199666    ie = is+1;
199667    while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
199668      ie++;
199669    }
199670
199671    /* Fold to lower case */
199672    nByte = ie-is;
199673    if( nByte>nFold ){
199674      if( pFold!=aFold ) sqlite3_free(pFold);
199675      pFold = sqlite3_malloc(nByte*2);
199676      if( pFold==0 ){
199677        rc = SQLITE_NOMEM;
199678        break;
199679      }
199680      nFold = nByte*2;
199681    }
199682    asciiFold(pFold, &pText[is], nByte);
199683
199684    /* Invoke the token callback */
199685    rc = xToken(pCtx, 0, pFold, nByte, is, ie);
199686    is = ie+1;
199687  }
199688
199689  if( pFold!=aFold ) sqlite3_free(pFold);
199690  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
199691  return rc;
199692}
199693
199694/**************************************************************************
199695** Start of unicode61 tokenizer implementation.
199696*/
199697
199698
199699/*
199700** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
199701** from the sqlite3 source file utf.c. If this file is compiled as part
199702** of the amalgamation, they are not required.
199703*/
199704#ifndef SQLITE_AMALGAMATION
199705
199706static const unsigned char sqlite3Utf8Trans1[] = {
199707  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
199708  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
199709  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
199710  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
199711  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
199712  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
199713  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
199714  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
199715};
199716
199717#define READ_UTF8(zIn, zTerm, c)                           \
199718  c = *(zIn++);                                            \
199719  if( c>=0xc0 ){                                           \
199720    c = sqlite3Utf8Trans1[c-0xc0];                         \
199721    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
199722      c = (c<<6) + (0x3f & *(zIn++));                      \
199723    }                                                      \
199724    if( c<0x80                                             \
199725        || (c&0xFFFFF800)==0xD800                          \
199726        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
199727  }
199728
199729
199730#define WRITE_UTF8(zOut, c) {                          \
199731  if( c<0x00080 ){                                     \
199732    *zOut++ = (unsigned char)(c&0xFF);                 \
199733  }                                                    \
199734  else if( c<0x00800 ){                                \
199735    *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F);     \
199736    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
199737  }                                                    \
199738  else if( c<0x10000 ){                                \
199739    *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F);    \
199740    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
199741    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
199742  }else{                                               \
199743    *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07);  \
199744    *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F);  \
199745    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
199746    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
199747  }                                                    \
199748}
199749
199750#endif /* ifndef SQLITE_AMALGAMATION */
199751
199752typedef struct Unicode61Tokenizer Unicode61Tokenizer;
199753struct Unicode61Tokenizer {
199754  unsigned char aTokenChar[128];  /* ASCII range token characters */
199755  char *aFold;                    /* Buffer to fold text into */
199756  int nFold;                      /* Size of aFold[] in bytes */
199757  int bRemoveDiacritic;           /* True if remove_diacritics=1 is set */
199758  int nException;
199759  int *aiException;
199760};
199761
199762static int fts5UnicodeAddExceptions(
199763  Unicode61Tokenizer *p,          /* Tokenizer object */
199764  const char *z,                  /* Characters to treat as exceptions */
199765  int bTokenChars                 /* 1 for 'tokenchars', 0 for 'separators' */
199766){
199767  int rc = SQLITE_OK;
199768  int n = (int)strlen(z);
199769  int *aNew;
199770
199771  if( n>0 ){
199772    aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
199773    if( aNew ){
199774      int nNew = p->nException;
199775      const unsigned char *zCsr = (const unsigned char*)z;
199776      const unsigned char *zTerm = (const unsigned char*)&z[n];
199777      while( zCsr<zTerm ){
199778        int iCode;
199779        int bToken;
199780        READ_UTF8(zCsr, zTerm, iCode);
199781        if( iCode<128 ){
199782          p->aTokenChar[iCode] = (unsigned char)bTokenChars;
199783        }else{
199784          bToken = sqlite3Fts5UnicodeIsalnum(iCode);
199785          assert( (bToken==0 || bToken==1) );
199786          assert( (bTokenChars==0 || bTokenChars==1) );
199787          if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
199788            int i;
199789            for(i=0; i<nNew; i++){
199790              if( aNew[i]>iCode ) break;
199791            }
199792            memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
199793            aNew[i] = iCode;
199794            nNew++;
199795          }
199796        }
199797      }
199798      p->aiException = aNew;
199799      p->nException = nNew;
199800    }else{
199801      rc = SQLITE_NOMEM;
199802    }
199803  }
199804
199805  return rc;
199806}
199807
199808/*
199809** Return true if the p->aiException[] array contains the value iCode.
199810*/
199811static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
199812  if( p->nException>0 ){
199813    int *a = p->aiException;
199814    int iLo = 0;
199815    int iHi = p->nException-1;
199816
199817    while( iHi>=iLo ){
199818      int iTest = (iHi + iLo) / 2;
199819      if( iCode==a[iTest] ){
199820        return 1;
199821      }else if( iCode>a[iTest] ){
199822        iLo = iTest+1;
199823      }else{
199824        iHi = iTest-1;
199825      }
199826    }
199827  }
199828
199829  return 0;
199830}
199831
199832/*
199833** Delete a "unicode61" tokenizer.
199834*/
199835static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
199836  if( pTok ){
199837    Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
199838    sqlite3_free(p->aiException);
199839    sqlite3_free(p->aFold);
199840    sqlite3_free(p);
199841  }
199842  return;
199843}
199844
199845/*
199846** Create a "unicode61" tokenizer.
199847*/
199848static int fts5UnicodeCreate(
199849  void *pUnused,
199850  const char **azArg, int nArg,
199851  Fts5Tokenizer **ppOut
199852){
199853  int rc = SQLITE_OK;             /* Return code */
199854  Unicode61Tokenizer *p = 0;      /* New tokenizer object */
199855
199856  UNUSED_PARAM(pUnused);
199857
199858  if( nArg%2 ){
199859    rc = SQLITE_ERROR;
199860  }else{
199861    p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
199862    if( p ){
199863      int i;
199864      memset(p, 0, sizeof(Unicode61Tokenizer));
199865      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
199866      p->bRemoveDiacritic = 1;
199867      p->nFold = 64;
199868      p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
199869      if( p->aFold==0 ){
199870        rc = SQLITE_NOMEM;
199871      }
199872      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
199873        const char *zArg = azArg[i+1];
199874        if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
199875          if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
199876            rc = SQLITE_ERROR;
199877          }
199878          p->bRemoveDiacritic = (zArg[0]=='1');
199879        }else
199880        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
199881          rc = fts5UnicodeAddExceptions(p, zArg, 1);
199882        }else
199883        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
199884          rc = fts5UnicodeAddExceptions(p, zArg, 0);
199885        }else{
199886          rc = SQLITE_ERROR;
199887        }
199888      }
199889    }else{
199890      rc = SQLITE_NOMEM;
199891    }
199892    if( rc!=SQLITE_OK ){
199893      fts5UnicodeDelete((Fts5Tokenizer*)p);
199894      p = 0;
199895    }
199896    *ppOut = (Fts5Tokenizer*)p;
199897  }
199898  return rc;
199899}
199900
199901/*
199902** Return true if, for the purposes of tokenizing with the tokenizer
199903** passed as the first argument, codepoint iCode is considered a token
199904** character (not a separator).
199905*/
199906static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
199907  assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
199908  return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
199909}
199910
199911static int fts5UnicodeTokenize(
199912  Fts5Tokenizer *pTokenizer,
199913  void *pCtx,
199914  int iUnused,
199915  const char *pText, int nText,
199916  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
199917){
199918  Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
199919  int rc = SQLITE_OK;
199920  unsigned char *a = p->aTokenChar;
199921
199922  unsigned char *zTerm = (unsigned char*)&pText[nText];
199923  unsigned char *zCsr = (unsigned char *)pText;
199924
199925  /* Output buffer */
199926  char *aFold = p->aFold;
199927  int nFold = p->nFold;
199928  const char *pEnd = &aFold[nFold-6];
199929
199930  UNUSED_PARAM(iUnused);
199931
199932  /* Each iteration of this loop gobbles up a contiguous run of separators,
199933  ** then the next token.  */
199934  while( rc==SQLITE_OK ){
199935    int iCode;                    /* non-ASCII codepoint read from input */
199936    char *zOut = aFold;
199937    int is;
199938    int ie;
199939
199940    /* Skip any separator characters. */
199941    while( 1 ){
199942      if( zCsr>=zTerm ) goto tokenize_done;
199943      if( *zCsr & 0x80 ) {
199944        /* A character outside of the ascii range. Skip past it if it is
199945        ** a separator character. Or break out of the loop if it is not. */
199946        is = zCsr - (unsigned char*)pText;
199947        READ_UTF8(zCsr, zTerm, iCode);
199948        if( fts5UnicodeIsAlnum(p, iCode) ){
199949          goto non_ascii_tokenchar;
199950        }
199951      }else{
199952        if( a[*zCsr] ){
199953          is = zCsr - (unsigned char*)pText;
199954          goto ascii_tokenchar;
199955        }
199956        zCsr++;
199957      }
199958    }
199959
199960    /* Run through the tokenchars. Fold them into the output buffer along
199961    ** the way.  */
199962    while( zCsr<zTerm ){
199963
199964      /* Grow the output buffer so that there is sufficient space to fit the
199965      ** largest possible utf-8 character.  */
199966      if( zOut>pEnd ){
199967        aFold = sqlite3_malloc(nFold*2);
199968        if( aFold==0 ){
199969          rc = SQLITE_NOMEM;
199970          goto tokenize_done;
199971        }
199972        zOut = &aFold[zOut - p->aFold];
199973        memcpy(aFold, p->aFold, nFold);
199974        sqlite3_free(p->aFold);
199975        p->aFold = aFold;
199976        p->nFold = nFold = nFold*2;
199977        pEnd = &aFold[nFold-6];
199978      }
199979
199980      if( *zCsr & 0x80 ){
199981        /* An non-ascii-range character. Fold it into the output buffer if
199982        ** it is a token character, or break out of the loop if it is not. */
199983        READ_UTF8(zCsr, zTerm, iCode);
199984        if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
199985 non_ascii_tokenchar:
199986          iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
199987          if( iCode ) WRITE_UTF8(zOut, iCode);
199988        }else{
199989          break;
199990        }
199991      }else if( a[*zCsr]==0 ){
199992        /* An ascii-range separator character. End of token. */
199993        break;
199994      }else{
199995 ascii_tokenchar:
199996        if( *zCsr>='A' && *zCsr<='Z' ){
199997          *zOut++ = *zCsr + 32;
199998        }else{
199999          *zOut++ = *zCsr;
200000        }
200001        zCsr++;
200002      }
200003      ie = zCsr - (unsigned char*)pText;
200004    }
200005
200006    /* Invoke the token callback */
200007    rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
200008  }
200009
200010 tokenize_done:
200011  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
200012  return rc;
200013}
200014
200015/**************************************************************************
200016** Start of porter stemmer implementation.
200017*/
200018
200019/* Any tokens larger than this (in bytes) are passed through without
200020** stemming. */
200021#define FTS5_PORTER_MAX_TOKEN 64
200022
200023typedef struct PorterTokenizer PorterTokenizer;
200024struct PorterTokenizer {
200025  fts5_tokenizer tokenizer;       /* Parent tokenizer module */
200026  Fts5Tokenizer *pTokenizer;      /* Parent tokenizer instance */
200027  char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
200028};
200029
200030/*
200031** Delete a "porter" tokenizer.
200032*/
200033static void fts5PorterDelete(Fts5Tokenizer *pTok){
200034  if( pTok ){
200035    PorterTokenizer *p = (PorterTokenizer*)pTok;
200036    if( p->pTokenizer ){
200037      p->tokenizer.xDelete(p->pTokenizer);
200038    }
200039    sqlite3_free(p);
200040  }
200041}
200042
200043/*
200044** Create a "porter" tokenizer.
200045*/
200046static int fts5PorterCreate(
200047  void *pCtx,
200048  const char **azArg, int nArg,
200049  Fts5Tokenizer **ppOut
200050){
200051  fts5_api *pApi = (fts5_api*)pCtx;
200052  int rc = SQLITE_OK;
200053  PorterTokenizer *pRet;
200054  void *pUserdata = 0;
200055  const char *zBase = "unicode61";
200056
200057  if( nArg>0 ){
200058    zBase = azArg[0];
200059  }
200060
200061  pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
200062  if( pRet ){
200063    memset(pRet, 0, sizeof(PorterTokenizer));
200064    rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
200065  }else{
200066    rc = SQLITE_NOMEM;
200067  }
200068  if( rc==SQLITE_OK ){
200069    int nArg2 = (nArg>0 ? nArg-1 : 0);
200070    const char **azArg2 = (nArg2 ? &azArg[1] : 0);
200071    rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
200072  }
200073
200074  if( rc!=SQLITE_OK ){
200075    fts5PorterDelete((Fts5Tokenizer*)pRet);
200076    pRet = 0;
200077  }
200078  *ppOut = (Fts5Tokenizer*)pRet;
200079  return rc;
200080}
200081
200082typedef struct PorterContext PorterContext;
200083struct PorterContext {
200084  void *pCtx;
200085  int (*xToken)(void*, int, const char*, int, int, int);
200086  char *aBuf;
200087};
200088
200089typedef struct PorterRule PorterRule;
200090struct PorterRule {
200091  const char *zSuffix;
200092  int nSuffix;
200093  int (*xCond)(char *zStem, int nStem);
200094  const char *zOutput;
200095  int nOutput;
200096};
200097
200098#if 0
200099static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
200100  int ret = -1;
200101  int nBuf = *pnBuf;
200102  PorterRule *p;
200103
200104  for(p=aRule; p->zSuffix; p++){
200105    assert( strlen(p->zSuffix)==p->nSuffix );
200106    assert( strlen(p->zOutput)==p->nOutput );
200107    if( nBuf<p->nSuffix ) continue;
200108    if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
200109  }
200110
200111  if( p->zSuffix ){
200112    int nStem = nBuf - p->nSuffix;
200113    if( p->xCond==0 || p->xCond(aBuf, nStem) ){
200114      memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
200115      *pnBuf = nStem + p->nOutput;
200116      ret = p - aRule;
200117    }
200118  }
200119
200120  return ret;
200121}
200122#endif
200123
200124static int fts5PorterIsVowel(char c, int bYIsVowel){
200125  return (
200126      c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
200127  );
200128}
200129
200130static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
200131  int i;
200132  int bCons = bPrevCons;
200133
200134  /* Scan for a vowel */
200135  for(i=0; i<nStem; i++){
200136    if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
200137  }
200138
200139  /* Scan for a consonent */
200140  for(i++; i<nStem; i++){
200141    if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
200142  }
200143  return 0;
200144}
200145
200146/* porter rule condition: (m > 0) */
200147static int fts5Porter_MGt0(char *zStem, int nStem){
200148  return !!fts5PorterGobbleVC(zStem, nStem, 0);
200149}
200150
200151/* porter rule condition: (m > 1) */
200152static int fts5Porter_MGt1(char *zStem, int nStem){
200153  int n;
200154  n = fts5PorterGobbleVC(zStem, nStem, 0);
200155  if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
200156    return 1;
200157  }
200158  return 0;
200159}
200160
200161/* porter rule condition: (m = 1) */
200162static int fts5Porter_MEq1(char *zStem, int nStem){
200163  int n;
200164  n = fts5PorterGobbleVC(zStem, nStem, 0);
200165  if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
200166    return 1;
200167  }
200168  return 0;
200169}
200170
200171/* porter rule condition: (*o) */
200172static int fts5Porter_Ostar(char *zStem, int nStem){
200173  if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
200174    return 0;
200175  }else{
200176    int i;
200177    int mask = 0;
200178    int bCons = 0;
200179    for(i=0; i<nStem; i++){
200180      bCons = !fts5PorterIsVowel(zStem[i], bCons);
200181      assert( bCons==0 || bCons==1 );
200182      mask = (mask << 1) + bCons;
200183    }
200184    return ((mask & 0x0007)==0x0005);
200185  }
200186}
200187
200188/* porter rule condition: (m > 1 and (*S or *T)) */
200189static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
200190  assert( nStem>0 );
200191  return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
200192      && fts5Porter_MGt1(zStem, nStem);
200193}
200194
200195/* porter rule condition: (*v*) */
200196static int fts5Porter_Vowel(char *zStem, int nStem){
200197  int i;
200198  for(i=0; i<nStem; i++){
200199    if( fts5PorterIsVowel(zStem[i], i>0) ){
200200      return 1;
200201    }
200202  }
200203  return 0;
200204}
200205
200206
200207/**************************************************************************
200208***************************************************************************
200209** GENERATED CODE STARTS HERE (mkportersteps.tcl)
200210*/
200211
200212static int fts5PorterStep4(char *aBuf, int *pnBuf){
200213  int ret = 0;
200214  int nBuf = *pnBuf;
200215  switch( aBuf[nBuf-2] ){
200216
200217    case 'a':
200218      if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
200219        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
200220          *pnBuf = nBuf - 2;
200221        }
200222      }
200223      break;
200224
200225    case 'c':
200226      if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
200227        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
200228          *pnBuf = nBuf - 4;
200229        }
200230      }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
200231        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
200232          *pnBuf = nBuf - 4;
200233        }
200234      }
200235      break;
200236
200237    case 'e':
200238      if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
200239        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
200240          *pnBuf = nBuf - 2;
200241        }
200242      }
200243      break;
200244
200245    case 'i':
200246      if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
200247        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
200248          *pnBuf = nBuf - 2;
200249        }
200250      }
200251      break;
200252
200253    case 'l':
200254      if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
200255        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
200256          *pnBuf = nBuf - 4;
200257        }
200258      }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
200259        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
200260          *pnBuf = nBuf - 4;
200261        }
200262      }
200263      break;
200264
200265    case 'n':
200266      if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
200267        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
200268          *pnBuf = nBuf - 3;
200269        }
200270      }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
200271        if( fts5Porter_MGt1(aBuf, nBuf-5) ){
200272          *pnBuf = nBuf - 5;
200273        }
200274      }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
200275        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
200276          *pnBuf = nBuf - 4;
200277        }
200278      }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
200279        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
200280          *pnBuf = nBuf - 3;
200281        }
200282      }
200283      break;
200284
200285    case 'o':
200286      if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
200287        if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
200288          *pnBuf = nBuf - 3;
200289        }
200290      }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
200291        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
200292          *pnBuf = nBuf - 2;
200293        }
200294      }
200295      break;
200296
200297    case 's':
200298      if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
200299        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
200300          *pnBuf = nBuf - 3;
200301        }
200302      }
200303      break;
200304
200305    case 't':
200306      if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
200307        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
200308          *pnBuf = nBuf - 3;
200309        }
200310      }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
200311        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
200312          *pnBuf = nBuf - 3;
200313        }
200314      }
200315      break;
200316
200317    case 'u':
200318      if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
200319        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
200320          *pnBuf = nBuf - 3;
200321        }
200322      }
200323      break;
200324
200325    case 'v':
200326      if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
200327        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
200328          *pnBuf = nBuf - 3;
200329        }
200330      }
200331      break;
200332
200333    case 'z':
200334      if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
200335        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
200336          *pnBuf = nBuf - 3;
200337        }
200338      }
200339      break;
200340
200341  }
200342  return ret;
200343}
200344
200345
200346static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
200347  int ret = 0;
200348  int nBuf = *pnBuf;
200349  switch( aBuf[nBuf-2] ){
200350
200351    case 'a':
200352      if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
200353        memcpy(&aBuf[nBuf-2], "ate", 3);
200354        *pnBuf = nBuf - 2 + 3;
200355        ret = 1;
200356      }
200357      break;
200358
200359    case 'b':
200360      if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
200361        memcpy(&aBuf[nBuf-2], "ble", 3);
200362        *pnBuf = nBuf - 2 + 3;
200363        ret = 1;
200364      }
200365      break;
200366
200367    case 'i':
200368      if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
200369        memcpy(&aBuf[nBuf-2], "ize", 3);
200370        *pnBuf = nBuf - 2 + 3;
200371        ret = 1;
200372      }
200373      break;
200374
200375  }
200376  return ret;
200377}
200378
200379
200380static int fts5PorterStep2(char *aBuf, int *pnBuf){
200381  int ret = 0;
200382  int nBuf = *pnBuf;
200383  switch( aBuf[nBuf-2] ){
200384
200385    case 'a':
200386      if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
200387        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
200388          memcpy(&aBuf[nBuf-7], "ate", 3);
200389          *pnBuf = nBuf - 7 + 3;
200390        }
200391      }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
200392        if( fts5Porter_MGt0(aBuf, nBuf-6) ){
200393          memcpy(&aBuf[nBuf-6], "tion", 4);
200394          *pnBuf = nBuf - 6 + 4;
200395        }
200396      }
200397      break;
200398
200399    case 'c':
200400      if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
200401        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
200402          memcpy(&aBuf[nBuf-4], "ence", 4);
200403          *pnBuf = nBuf - 4 + 4;
200404        }
200405      }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
200406        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
200407          memcpy(&aBuf[nBuf-4], "ance", 4);
200408          *pnBuf = nBuf - 4 + 4;
200409        }
200410      }
200411      break;
200412
200413    case 'e':
200414      if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
200415        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
200416          memcpy(&aBuf[nBuf-4], "ize", 3);
200417          *pnBuf = nBuf - 4 + 3;
200418        }
200419      }
200420      break;
200421
200422    case 'g':
200423      if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
200424        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
200425          memcpy(&aBuf[nBuf-4], "log", 3);
200426          *pnBuf = nBuf - 4 + 3;
200427        }
200428      }
200429      break;
200430
200431    case 'l':
200432      if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
200433        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
200434          memcpy(&aBuf[nBuf-3], "ble", 3);
200435          *pnBuf = nBuf - 3 + 3;
200436        }
200437      }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
200438        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
200439          memcpy(&aBuf[nBuf-4], "al", 2);
200440          *pnBuf = nBuf - 4 + 2;
200441        }
200442      }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
200443        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
200444          memcpy(&aBuf[nBuf-5], "ent", 3);
200445          *pnBuf = nBuf - 5 + 3;
200446        }
200447      }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
200448        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
200449          memcpy(&aBuf[nBuf-3], "e", 1);
200450          *pnBuf = nBuf - 3 + 1;
200451        }
200452      }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
200453        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
200454          memcpy(&aBuf[nBuf-5], "ous", 3);
200455          *pnBuf = nBuf - 5 + 3;
200456        }
200457      }
200458      break;
200459
200460    case 'o':
200461      if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
200462        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
200463          memcpy(&aBuf[nBuf-7], "ize", 3);
200464          *pnBuf = nBuf - 7 + 3;
200465        }
200466      }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
200467        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
200468          memcpy(&aBuf[nBuf-5], "ate", 3);
200469          *pnBuf = nBuf - 5 + 3;
200470        }
200471      }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
200472        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
200473          memcpy(&aBuf[nBuf-4], "ate", 3);
200474          *pnBuf = nBuf - 4 + 3;
200475        }
200476      }
200477      break;
200478
200479    case 's':
200480      if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
200481        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
200482          memcpy(&aBuf[nBuf-5], "al", 2);
200483          *pnBuf = nBuf - 5 + 2;
200484        }
200485      }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
200486        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
200487          memcpy(&aBuf[nBuf-7], "ive", 3);
200488          *pnBuf = nBuf - 7 + 3;
200489        }
200490      }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
200491        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
200492          memcpy(&aBuf[nBuf-7], "ful", 3);
200493          *pnBuf = nBuf - 7 + 3;
200494        }
200495      }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
200496        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
200497          memcpy(&aBuf[nBuf-7], "ous", 3);
200498          *pnBuf = nBuf - 7 + 3;
200499        }
200500      }
200501      break;
200502
200503    case 't':
200504      if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
200505        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
200506          memcpy(&aBuf[nBuf-5], "al", 2);
200507          *pnBuf = nBuf - 5 + 2;
200508        }
200509      }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
200510        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
200511          memcpy(&aBuf[nBuf-5], "ive", 3);
200512          *pnBuf = nBuf - 5 + 3;
200513        }
200514      }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
200515        if( fts5Porter_MGt0(aBuf, nBuf-6) ){
200516          memcpy(&aBuf[nBuf-6], "ble", 3);
200517          *pnBuf = nBuf - 6 + 3;
200518        }
200519      }
200520      break;
200521
200522  }
200523  return ret;
200524}
200525
200526
200527static int fts5PorterStep3(char *aBuf, int *pnBuf){
200528  int ret = 0;
200529  int nBuf = *pnBuf;
200530  switch( aBuf[nBuf-2] ){
200531
200532    case 'a':
200533      if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
200534        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
200535          memcpy(&aBuf[nBuf-4], "ic", 2);
200536          *pnBuf = nBuf - 4 + 2;
200537        }
200538      }
200539      break;
200540
200541    case 's':
200542      if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
200543        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
200544          *pnBuf = nBuf - 4;
200545        }
200546      }
200547      break;
200548
200549    case 't':
200550      if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
200551        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
200552          memcpy(&aBuf[nBuf-5], "ic", 2);
200553          *pnBuf = nBuf - 5 + 2;
200554        }
200555      }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
200556        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
200557          memcpy(&aBuf[nBuf-5], "ic", 2);
200558          *pnBuf = nBuf - 5 + 2;
200559        }
200560      }
200561      break;
200562
200563    case 'u':
200564      if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
200565        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
200566          *pnBuf = nBuf - 3;
200567        }
200568      }
200569      break;
200570
200571    case 'v':
200572      if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
200573        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
200574          *pnBuf = nBuf - 5;
200575        }
200576      }
200577      break;
200578
200579    case 'z':
200580      if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
200581        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
200582          memcpy(&aBuf[nBuf-5], "al", 2);
200583          *pnBuf = nBuf - 5 + 2;
200584        }
200585      }
200586      break;
200587
200588  }
200589  return ret;
200590}
200591
200592
200593static int fts5PorterStep1B(char *aBuf, int *pnBuf){
200594  int ret = 0;
200595  int nBuf = *pnBuf;
200596  switch( aBuf[nBuf-2] ){
200597
200598    case 'e':
200599      if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
200600        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
200601          memcpy(&aBuf[nBuf-3], "ee", 2);
200602          *pnBuf = nBuf - 3 + 2;
200603        }
200604      }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
200605        if( fts5Porter_Vowel(aBuf, nBuf-2) ){
200606          *pnBuf = nBuf - 2;
200607          ret = 1;
200608        }
200609      }
200610      break;
200611
200612    case 'n':
200613      if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
200614        if( fts5Porter_Vowel(aBuf, nBuf-3) ){
200615          *pnBuf = nBuf - 3;
200616          ret = 1;
200617        }
200618      }
200619      break;
200620
200621  }
200622  return ret;
200623}
200624
200625/*
200626** GENERATED CODE ENDS HERE (mkportersteps.tcl)
200627***************************************************************************
200628**************************************************************************/
200629
200630static void fts5PorterStep1A(char *aBuf, int *pnBuf){
200631  int nBuf = *pnBuf;
200632  if( aBuf[nBuf-1]=='s' ){
200633    if( aBuf[nBuf-2]=='e' ){
200634      if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
200635       || (nBuf>3 && aBuf[nBuf-3]=='i' )
200636      ){
200637        *pnBuf = nBuf-2;
200638      }else{
200639        *pnBuf = nBuf-1;
200640      }
200641    }
200642    else if( aBuf[nBuf-2]!='s' ){
200643      *pnBuf = nBuf-1;
200644    }
200645  }
200646}
200647
200648static int fts5PorterCb(
200649  void *pCtx,
200650  int tflags,
200651  const char *pToken,
200652  int nToken,
200653  int iStart,
200654  int iEnd
200655){
200656  PorterContext *p = (PorterContext*)pCtx;
200657
200658  char *aBuf;
200659  int nBuf;
200660
200661  if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
200662  aBuf = p->aBuf;
200663  nBuf = nToken;
200664  memcpy(aBuf, pToken, nBuf);
200665
200666  /* Step 1. */
200667  fts5PorterStep1A(aBuf, &nBuf);
200668  if( fts5PorterStep1B(aBuf, &nBuf) ){
200669    if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
200670      char c = aBuf[nBuf-1];
200671      if( fts5PorterIsVowel(c, 0)==0
200672       && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
200673      ){
200674        nBuf--;
200675      }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
200676        aBuf[nBuf++] = 'e';
200677      }
200678    }
200679  }
200680
200681  /* Step 1C. */
200682  if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
200683    aBuf[nBuf-1] = 'i';
200684  }
200685
200686  /* Steps 2 through 4. */
200687  fts5PorterStep2(aBuf, &nBuf);
200688  fts5PorterStep3(aBuf, &nBuf);
200689  fts5PorterStep4(aBuf, &nBuf);
200690
200691  /* Step 5a. */
200692  assert( nBuf>0 );
200693  if( aBuf[nBuf-1]=='e' ){
200694    if( fts5Porter_MGt1(aBuf, nBuf-1)
200695     || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
200696    ){
200697      nBuf--;
200698    }
200699  }
200700
200701  /* Step 5b. */
200702  if( nBuf>1 && aBuf[nBuf-1]=='l'
200703   && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
200704  ){
200705    nBuf--;
200706  }
200707
200708  return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
200709
200710 pass_through:
200711  return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
200712}
200713
200714/*
200715** Tokenize using the porter tokenizer.
200716*/
200717static int fts5PorterTokenize(
200718  Fts5Tokenizer *pTokenizer,
200719  void *pCtx,
200720  int flags,
200721  const char *pText, int nText,
200722  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
200723){
200724  PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
200725  PorterContext sCtx;
200726  sCtx.xToken = xToken;
200727  sCtx.pCtx = pCtx;
200728  sCtx.aBuf = p->aBuf;
200729  return p->tokenizer.xTokenize(
200730      p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
200731  );
200732}
200733
200734/*
200735** Register all built-in tokenizers with FTS5.
200736*/
200737static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
200738  struct BuiltinTokenizer {
200739    const char *zName;
200740    fts5_tokenizer x;
200741  } aBuiltin[] = {
200742    { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
200743    { "ascii",     {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
200744    { "porter",    {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
200745  };
200746
200747  int rc = SQLITE_OK;             /* Return code */
200748  int i;                          /* To iterate through builtin functions */
200749
200750  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
200751    rc = pApi->xCreateTokenizer(pApi,
200752        aBuiltin[i].zName,
200753        (void*)pApi,
200754        &aBuiltin[i].x,
200755        0
200756    );
200757  }
200758
200759  return rc;
200760}
200761
200762
200763
200764/*
200765** 2012 May 25
200766**
200767** The author disclaims copyright to this source code.  In place of
200768** a legal notice, here is a blessing:
200769**
200770**    May you do good and not evil.
200771**    May you find forgiveness for yourself and forgive others.
200772**    May you share freely, never taking more than you give.
200773**
200774******************************************************************************
200775*/
200776
200777/*
200778** DO NOT EDIT THIS MACHINE GENERATED FILE.
200779*/
200780
200781
200782/* #include <assert.h> */
200783
200784/*
200785** Return true if the argument corresponds to a unicode codepoint
200786** classified as either a letter or a number. Otherwise false.
200787**
200788** The results are undefined if the value passed to this function
200789** is less than zero.
200790*/
200791static int sqlite3Fts5UnicodeIsalnum(int c){
200792  /* Each unsigned integer in the following array corresponds to a contiguous
200793  ** range of unicode codepoints that are not either letters or numbers (i.e.
200794  ** codepoints for which this function should return 0).
200795  **
200796  ** The most significant 22 bits in each 32-bit value contain the first
200797  ** codepoint in the range. The least significant 10 bits are used to store
200798  ** the size of the range (always at least 1). In other words, the value
200799  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
200800  ** C. It is not possible to represent a range larger than 1023 codepoints
200801  ** using this format.
200802  */
200803  static const unsigned int aEntry[] = {
200804    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
200805    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
200806    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
200807    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
200808    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
200809    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
200810    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
200811    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
200812    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
200813    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
200814    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
200815    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
200816    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
200817    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
200818    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
200819    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
200820    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
200821    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
200822    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
200823    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
200824    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
200825    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
200826    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
200827    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
200828    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
200829    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
200830    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
200831    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
200832    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
200833    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
200834    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
200835    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
200836    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
200837    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
200838    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
200839    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
200840    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
200841    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
200842    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
200843    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
200844    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
200845    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
200846    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
200847    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
200848    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
200849    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
200850    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
200851    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
200852    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
200853    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
200854    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
200855    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
200856    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
200857    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
200858    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
200859    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
200860    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
200861    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
200862    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
200863    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
200864    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
200865    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
200866    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
200867    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
200868    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
200869    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
200870    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
200871    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
200872    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
200873    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
200874    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
200875    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
200876    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
200877    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
200878    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
200879    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
200880    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
200881    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
200882    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
200883    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
200884    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
200885    0x380400F0,
200886  };
200887  static const unsigned int aAscii[4] = {
200888    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
200889  };
200890
200891  if( (unsigned int)c<128 ){
200892    return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
200893  }else if( (unsigned int)c<(1<<22) ){
200894    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
200895    int iRes = 0;
200896    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
200897    int iLo = 0;
200898    while( iHi>=iLo ){
200899      int iTest = (iHi + iLo) / 2;
200900      if( key >= aEntry[iTest] ){
200901        iRes = iTest;
200902        iLo = iTest+1;
200903      }else{
200904        iHi = iTest-1;
200905      }
200906    }
200907    assert( aEntry[0]<key );
200908    assert( key>=aEntry[iRes] );
200909    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
200910  }
200911  return 1;
200912}
200913
200914
200915/*
200916** If the argument is a codepoint corresponding to a lowercase letter
200917** in the ASCII range with a diacritic added, return the codepoint
200918** of the ASCII letter only. For example, if passed 235 - "LATIN
200919** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
200920** E"). The resuls of passing a codepoint that corresponds to an
200921** uppercase letter are undefined.
200922*/
200923static int fts5_remove_diacritic(int c){
200924  unsigned short aDia[] = {
200925        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
200926     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
200927     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
200928     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
200929     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
200930     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
200931     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
200932     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
200933    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
200934    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
200935    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
200936    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
200937    62924, 63050, 63082, 63274, 63390,
200938  };
200939  char aChar[] = {
200940    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
200941    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
200942    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
200943    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
200944    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
200945    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
200946    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
200947    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
200948    'e',  'i',  'o',  'u',  'y',
200949  };
200950
200951  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
200952  int iRes = 0;
200953  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
200954  int iLo = 0;
200955  while( iHi>=iLo ){
200956    int iTest = (iHi + iLo) / 2;
200957    if( key >= aDia[iTest] ){
200958      iRes = iTest;
200959      iLo = iTest+1;
200960    }else{
200961      iHi = iTest-1;
200962    }
200963  }
200964  assert( key>=aDia[iRes] );
200965  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
200966}
200967
200968
200969/*
200970** Return true if the argument interpreted as a unicode codepoint
200971** is a diacritical modifier character.
200972*/
200973static int sqlite3Fts5UnicodeIsdiacritic(int c){
200974  unsigned int mask0 = 0x08029FDF;
200975  unsigned int mask1 = 0x000361F8;
200976  if( c<768 || c>817 ) return 0;
200977  return (c < 768+32) ?
200978      (mask0 & (1 << (c-768))) :
200979      (mask1 & (1 << (c-768-32)));
200980}
200981
200982
200983/*
200984** Interpret the argument as a unicode codepoint. If the codepoint
200985** is an upper case character that has a lower case equivalent,
200986** return the codepoint corresponding to the lower case version.
200987** Otherwise, return a copy of the argument.
200988**
200989** The results are undefined if the value passed to this function
200990** is less than zero.
200991*/
200992static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
200993  /* Each entry in the following array defines a rule for folding a range
200994  ** of codepoints to lower case. The rule applies to a range of nRange
200995  ** codepoints starting at codepoint iCode.
200996  **
200997  ** If the least significant bit in flags is clear, then the rule applies
200998  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
200999  ** need to be folded). Or, if it is set, then the rule only applies to
201000  ** every second codepoint in the range, starting with codepoint C.
201001  **
201002  ** The 7 most significant bits in flags are an index into the aiOff[]
201003  ** array. If a specific codepoint C does require folding, then its lower
201004  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
201005  **
201006  ** The contents of this array are generated by parsing the CaseFolding.txt
201007  ** file distributed as part of the "Unicode Character Database". See
201008  ** http://www.unicode.org for details.
201009  */
201010  static const struct TableEntry {
201011    unsigned short iCode;
201012    unsigned char flags;
201013    unsigned char nRange;
201014  } aEntry[] = {
201015    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
201016    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
201017    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
201018    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
201019    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
201020    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
201021    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
201022    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
201023    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
201024    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
201025    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
201026    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
201027    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
201028    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
201029    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
201030    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
201031    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
201032    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
201033    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
201034    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
201035    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
201036    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
201037    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
201038    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
201039    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
201040    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
201041    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
201042    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
201043    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
201044    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
201045    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
201046    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
201047    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
201048    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
201049    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
201050    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
201051    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
201052    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
201053    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
201054    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
201055    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
201056    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
201057    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
201058    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
201059    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
201060    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
201061    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
201062    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
201063    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
201064    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
201065    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
201066    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
201067    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
201068    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
201069    {65313, 14, 26},
201070  };
201071  static const unsigned short aiOff[] = {
201072   1,     2,     8,     15,    16,    26,    28,    32,
201073   37,    38,    40,    48,    63,    64,    69,    71,
201074   79,    80,    116,   202,   203,   205,   206,   207,
201075   209,   210,   211,   213,   214,   217,   218,   219,
201076   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
201077   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
201078   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
201079   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
201080   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
201081   65514, 65521, 65527, 65528, 65529,
201082  };
201083
201084  int ret = c;
201085
201086  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
201087
201088  if( c<128 ){
201089    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
201090  }else if( c<65536 ){
201091    const struct TableEntry *p;
201092    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
201093    int iLo = 0;
201094    int iRes = -1;
201095
201096    assert( c>aEntry[0].iCode );
201097    while( iHi>=iLo ){
201098      int iTest = (iHi + iLo) / 2;
201099      int cmp = (c - aEntry[iTest].iCode);
201100      if( cmp>=0 ){
201101        iRes = iTest;
201102        iLo = iTest+1;
201103      }else{
201104        iHi = iTest-1;
201105      }
201106    }
201107
201108    assert( iRes>=0 && c>=aEntry[iRes].iCode );
201109    p = &aEntry[iRes];
201110    if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
201111      ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
201112      assert( ret>0 );
201113    }
201114
201115    if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
201116  }
201117
201118  else if( c>=66560 && c<66600 ){
201119    ret = c + 40;
201120  }
201121
201122  return ret;
201123}
201124
201125/*
201126** 2015 May 30
201127**
201128** The author disclaims copyright to this source code.  In place of
201129** a legal notice, here is a blessing:
201130**
201131**    May you do good and not evil.
201132**    May you find forgiveness for yourself and forgive others.
201133**    May you share freely, never taking more than you give.
201134**
201135******************************************************************************
201136**
201137** Routines for varint serialization and deserialization.
201138*/
201139
201140
201141/* #include "fts5Int.h" */
201142
201143/*
201144** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
201145** Except, this version does handle the single byte case that the core
201146** version depends on being handled before its function is called.
201147*/
201148static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
201149  u32 a,b;
201150
201151  /* The 1-byte case. Overwhelmingly the most common. */
201152  a = *p;
201153  /* a: p0 (unmasked) */
201154  if (!(a&0x80))
201155  {
201156    /* Values between 0 and 127 */
201157    *v = a;
201158    return 1;
201159  }
201160
201161  /* The 2-byte case */
201162  p++;
201163  b = *p;
201164  /* b: p1 (unmasked) */
201165  if (!(b&0x80))
201166  {
201167    /* Values between 128 and 16383 */
201168    a &= 0x7f;
201169    a = a<<7;
201170    *v = a | b;
201171    return 2;
201172  }
201173
201174  /* The 3-byte case */
201175  p++;
201176  a = a<<14;
201177  a |= *p;
201178  /* a: p0<<14 | p2 (unmasked) */
201179  if (!(a&0x80))
201180  {
201181    /* Values between 16384 and 2097151 */
201182    a &= (0x7f<<14)|(0x7f);
201183    b &= 0x7f;
201184    b = b<<7;
201185    *v = a | b;
201186    return 3;
201187  }
201188
201189  /* A 32-bit varint is used to store size information in btrees.
201190  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
201191  ** A 3-byte varint is sufficient, for example, to record the size
201192  ** of a 1048569-byte BLOB or string.
201193  **
201194  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
201195  ** rare larger cases can be handled by the slower 64-bit varint
201196  ** routine.
201197  */
201198  {
201199    u64 v64;
201200    u8 n;
201201    p -= 2;
201202    n = sqlite3Fts5GetVarint(p, &v64);
201203    *v = (u32)v64;
201204    assert( n>3 && n<=9 );
201205    return n;
201206  }
201207}
201208
201209
201210/*
201211** Bitmasks used by sqlite3GetVarint().  These precomputed constants
201212** are defined here rather than simply putting the constant expressions
201213** inline in order to work around bugs in the RVT compiler.
201214**
201215** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
201216**
201217** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
201218*/
201219#define SLOT_2_0     0x001fc07f
201220#define SLOT_4_2_0   0xf01fc07f
201221
201222/*
201223** Read a 64-bit variable-length integer from memory starting at p[0].
201224** Return the number of bytes read.  The value is stored in *v.
201225*/
201226static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
201227  u32 a,b,s;
201228
201229  a = *p;
201230  /* a: p0 (unmasked) */
201231  if (!(a&0x80))
201232  {
201233    *v = a;
201234    return 1;
201235  }
201236
201237  p++;
201238  b = *p;
201239  /* b: p1 (unmasked) */
201240  if (!(b&0x80))
201241  {
201242    a &= 0x7f;
201243    a = a<<7;
201244    a |= b;
201245    *v = a;
201246    return 2;
201247  }
201248
201249  /* Verify that constants are precomputed correctly */
201250  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
201251  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
201252
201253  p++;
201254  a = a<<14;
201255  a |= *p;
201256  /* a: p0<<14 | p2 (unmasked) */
201257  if (!(a&0x80))
201258  {
201259    a &= SLOT_2_0;
201260    b &= 0x7f;
201261    b = b<<7;
201262    a |= b;
201263    *v = a;
201264    return 3;
201265  }
201266
201267  /* CSE1 from below */
201268  a &= SLOT_2_0;
201269  p++;
201270  b = b<<14;
201271  b |= *p;
201272  /* b: p1<<14 | p3 (unmasked) */
201273  if (!(b&0x80))
201274  {
201275    b &= SLOT_2_0;
201276    /* moved CSE1 up */
201277    /* a &= (0x7f<<14)|(0x7f); */
201278    a = a<<7;
201279    a |= b;
201280    *v = a;
201281    return 4;
201282  }
201283
201284  /* a: p0<<14 | p2 (masked) */
201285  /* b: p1<<14 | p3 (unmasked) */
201286  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
201287  /* moved CSE1 up */
201288  /* a &= (0x7f<<14)|(0x7f); */
201289  b &= SLOT_2_0;
201290  s = a;
201291  /* s: p0<<14 | p2 (masked) */
201292
201293  p++;
201294  a = a<<14;
201295  a |= *p;
201296  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
201297  if (!(a&0x80))
201298  {
201299    /* we can skip these cause they were (effectively) done above in calc'ing s */
201300    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
201301    /* b &= (0x7f<<14)|(0x7f); */
201302    b = b<<7;
201303    a |= b;
201304    s = s>>18;
201305    *v = ((u64)s)<<32 | a;
201306    return 5;
201307  }
201308
201309  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
201310  s = s<<7;
201311  s |= b;
201312  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
201313
201314  p++;
201315  b = b<<14;
201316  b |= *p;
201317  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
201318  if (!(b&0x80))
201319  {
201320    /* we can skip this cause it was (effectively) done above in calc'ing s */
201321    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
201322    a &= SLOT_2_0;
201323    a = a<<7;
201324    a |= b;
201325    s = s>>18;
201326    *v = ((u64)s)<<32 | a;
201327    return 6;
201328  }
201329
201330  p++;
201331  a = a<<14;
201332  a |= *p;
201333  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
201334  if (!(a&0x80))
201335  {
201336    a &= SLOT_4_2_0;
201337    b &= SLOT_2_0;
201338    b = b<<7;
201339    a |= b;
201340    s = s>>11;
201341    *v = ((u64)s)<<32 | a;
201342    return 7;
201343  }
201344
201345  /* CSE2 from below */
201346  a &= SLOT_2_0;
201347  p++;
201348  b = b<<14;
201349  b |= *p;
201350  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
201351  if (!(b&0x80))
201352  {
201353    b &= SLOT_4_2_0;
201354    /* moved CSE2 up */
201355    /* a &= (0x7f<<14)|(0x7f); */
201356    a = a<<7;
201357    a |= b;
201358    s = s>>4;
201359    *v = ((u64)s)<<32 | a;
201360    return 8;
201361  }
201362
201363  p++;
201364  a = a<<15;
201365  a |= *p;
201366  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
201367
201368  /* moved CSE2 up */
201369  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
201370  b &= SLOT_2_0;
201371  b = b<<8;
201372  a |= b;
201373
201374  s = s<<4;
201375  b = p[-4];
201376  b &= 0x7f;
201377  b = b>>3;
201378  s |= b;
201379
201380  *v = ((u64)s)<<32 | a;
201381
201382  return 9;
201383}
201384
201385/*
201386** The variable-length integer encoding is as follows:
201387**
201388** KEY:
201389**         A = 0xxxxxxx    7 bits of data and one flag bit
201390**         B = 1xxxxxxx    7 bits of data and one flag bit
201391**         C = xxxxxxxx    8 bits of data
201392**
201393**  7 bits - A
201394** 14 bits - BA
201395** 21 bits - BBA
201396** 28 bits - BBBA
201397** 35 bits - BBBBA
201398** 42 bits - BBBBBA
201399** 49 bits - BBBBBBA
201400** 56 bits - BBBBBBBA
201401** 64 bits - BBBBBBBBC
201402*/
201403
201404#ifdef SQLITE_NOINLINE
201405# define FTS5_NOINLINE SQLITE_NOINLINE
201406#else
201407# define FTS5_NOINLINE
201408#endif
201409
201410/*
201411** Write a 64-bit variable-length integer to memory starting at p[0].
201412** The length of data write will be between 1 and 9 bytes.  The number
201413** of bytes written is returned.
201414**
201415** A variable-length integer consists of the lower 7 bits of each byte
201416** for all bytes that have the 8th bit set and one byte with the 8th
201417** bit clear.  Except, if we get to the 9th byte, it stores the full
201418** 8 bits and is the last byte.
201419*/
201420static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
201421  int i, j, n;
201422  u8 buf[10];
201423  if( v & (((u64)0xff000000)<<32) ){
201424    p[8] = (u8)v;
201425    v >>= 8;
201426    for(i=7; i>=0; i--){
201427      p[i] = (u8)((v & 0x7f) | 0x80);
201428      v >>= 7;
201429    }
201430    return 9;
201431  }
201432  n = 0;
201433  do{
201434    buf[n++] = (u8)((v & 0x7f) | 0x80);
201435    v >>= 7;
201436  }while( v!=0 );
201437  buf[0] &= 0x7f;
201438  assert( n<=9 );
201439  for(i=0, j=n-1; j>=0; j--, i++){
201440    p[i] = buf[j];
201441  }
201442  return n;
201443}
201444
201445static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
201446  if( v<=0x7f ){
201447    p[0] = v&0x7f;
201448    return 1;
201449  }
201450  if( v<=0x3fff ){
201451    p[0] = ((v>>7)&0x7f)|0x80;
201452    p[1] = v&0x7f;
201453    return 2;
201454  }
201455  return fts5PutVarint64(p,v);
201456}
201457
201458
201459static int sqlite3Fts5GetVarintLen(u32 iVal){
201460#if 0
201461  if( iVal<(1 << 7 ) ) return 1;
201462#endif
201463  assert( iVal>=(1 << 7) );
201464  if( iVal<(1 << 14) ) return 2;
201465  if( iVal<(1 << 21) ) return 3;
201466  if( iVal<(1 << 28) ) return 4;
201467  return 5;
201468}
201469
201470
201471/*
201472** 2015 May 08
201473**
201474** The author disclaims copyright to this source code.  In place of
201475** a legal notice, here is a blessing:
201476**
201477**    May you do good and not evil.
201478**    May you find forgiveness for yourself and forgive others.
201479**    May you share freely, never taking more than you give.
201480**
201481******************************************************************************
201482**
201483** This is an SQLite virtual table module implementing direct access to an
201484** existing FTS5 index. The module may create several different types of
201485** tables:
201486**
201487** col:
201488**     CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
201489**
201490**   One row for each term/column combination. The value of $doc is set to
201491**   the number of fts5 rows that contain at least one instance of term
201492**   $term within column $col. Field $cnt is set to the total number of
201493**   instances of term $term in column $col (in any row of the fts5 table).
201494**
201495** row:
201496**     CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
201497**
201498**   One row for each term in the database. The value of $doc is set to
201499**   the number of fts5 rows that contain at least one instance of term
201500**   $term. Field $cnt is set to the total number of instances of term
201501**   $term in the database.
201502*/
201503
201504
201505/* #include "fts5Int.h" */
201506
201507
201508typedef struct Fts5VocabTable Fts5VocabTable;
201509typedef struct Fts5VocabCursor Fts5VocabCursor;
201510
201511struct Fts5VocabTable {
201512  sqlite3_vtab base;
201513  char *zFts5Tbl;                 /* Name of fts5 table */
201514  char *zFts5Db;                  /* Db containing fts5 table */
201515  sqlite3 *db;                    /* Database handle */
201516  Fts5Global *pGlobal;            /* FTS5 global object for this database */
201517  int eType;                      /* FTS5_VOCAB_COL or ROW */
201518};
201519
201520struct Fts5VocabCursor {
201521  sqlite3_vtab_cursor base;
201522  sqlite3_stmt *pStmt;            /* Statement holding lock on pIndex */
201523  Fts5Index *pIndex;              /* Associated FTS5 index */
201524
201525  int bEof;                       /* True if this cursor is at EOF */
201526  Fts5IndexIter *pIter;           /* Term/rowid iterator object */
201527
201528  int nLeTerm;                    /* Size of zLeTerm in bytes */
201529  char *zLeTerm;                  /* (term <= $zLeTerm) paramater, or NULL */
201530
201531  /* These are used by 'col' tables only */
201532  Fts5Config *pConfig;            /* Fts5 table configuration */
201533  int iCol;
201534  i64 *aCnt;
201535  i64 *aDoc;
201536
201537  /* Output values used by 'row' and 'col' tables */
201538  i64 rowid;                      /* This table's current rowid value */
201539  Fts5Buffer term;                /* Current value of 'term' column */
201540};
201541
201542#define FTS5_VOCAB_COL    0
201543#define FTS5_VOCAB_ROW    1
201544
201545#define FTS5_VOCAB_COL_SCHEMA  "term, col, doc, cnt"
201546#define FTS5_VOCAB_ROW_SCHEMA  "term, doc, cnt"
201547
201548/*
201549** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
201550*/
201551#define FTS5_VOCAB_TERM_EQ 0x01
201552#define FTS5_VOCAB_TERM_GE 0x02
201553#define FTS5_VOCAB_TERM_LE 0x04
201554
201555
201556/*
201557** Translate a string containing an fts5vocab table type to an
201558** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
201559** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
201560** and return SQLITE_ERROR.
201561*/
201562static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
201563  int rc = SQLITE_OK;
201564  char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
201565  if( rc==SQLITE_OK ){
201566    sqlite3Fts5Dequote(zCopy);
201567    if( sqlite3_stricmp(zCopy, "col")==0 ){
201568      *peType = FTS5_VOCAB_COL;
201569    }else
201570
201571    if( sqlite3_stricmp(zCopy, "row")==0 ){
201572      *peType = FTS5_VOCAB_ROW;
201573    }else
201574    {
201575      *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
201576      rc = SQLITE_ERROR;
201577    }
201578    sqlite3_free(zCopy);
201579  }
201580
201581  return rc;
201582}
201583
201584
201585/*
201586** The xDisconnect() virtual table method.
201587*/
201588static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
201589  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
201590  sqlite3_free(pTab);
201591  return SQLITE_OK;
201592}
201593
201594/*
201595** The xDestroy() virtual table method.
201596*/
201597static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
201598  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
201599  sqlite3_free(pTab);
201600  return SQLITE_OK;
201601}
201602
201603/*
201604** This function is the implementation of both the xConnect and xCreate
201605** methods of the FTS3 virtual table.
201606**
201607** The argv[] array contains the following:
201608**
201609**   argv[0]   -> module name  ("fts5vocab")
201610**   argv[1]   -> database name
201611**   argv[2]   -> table name
201612**
201613** then:
201614**
201615**   argv[3]   -> name of fts5 table
201616**   argv[4]   -> type of fts5vocab table
201617**
201618** or, for tables in the TEMP schema only.
201619**
201620**   argv[3]   -> name of fts5 tables database
201621**   argv[4]   -> name of fts5 table
201622**   argv[5]   -> type of fts5vocab table
201623*/
201624static int fts5VocabInitVtab(
201625  sqlite3 *db,                    /* The SQLite database connection */
201626  void *pAux,                     /* Pointer to Fts5Global object */
201627  int argc,                       /* Number of elements in argv array */
201628  const char * const *argv,       /* xCreate/xConnect argument array */
201629  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
201630  char **pzErr                    /* Write any error message here */
201631){
201632  const char *azSchema[] = {
201633    "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA  ")",
201634    "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA  ")"
201635  };
201636
201637  Fts5VocabTable *pRet = 0;
201638  int rc = SQLITE_OK;             /* Return code */
201639  int bDb;
201640
201641  bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
201642
201643  if( argc!=5 && bDb==0 ){
201644    *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
201645    rc = SQLITE_ERROR;
201646  }else{
201647    int nByte;                      /* Bytes of space to allocate */
201648    const char *zDb = bDb ? argv[3] : argv[1];
201649    const char *zTab = bDb ? argv[4] : argv[3];
201650    const char *zType = bDb ? argv[5] : argv[4];
201651    int nDb = (int)strlen(zDb)+1;
201652    int nTab = (int)strlen(zTab)+1;
201653    int eType = 0;
201654
201655    rc = fts5VocabTableType(zType, pzErr, &eType);
201656    if( rc==SQLITE_OK ){
201657      assert( eType>=0 && eType<ArraySize(azSchema) );
201658      rc = sqlite3_declare_vtab(db, azSchema[eType]);
201659    }
201660
201661    nByte = sizeof(Fts5VocabTable) + nDb + nTab;
201662    pRet = sqlite3Fts5MallocZero(&rc, nByte);
201663    if( pRet ){
201664      pRet->pGlobal = (Fts5Global*)pAux;
201665      pRet->eType = eType;
201666      pRet->db = db;
201667      pRet->zFts5Tbl = (char*)&pRet[1];
201668      pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
201669      memcpy(pRet->zFts5Tbl, zTab, nTab);
201670      memcpy(pRet->zFts5Db, zDb, nDb);
201671      sqlite3Fts5Dequote(pRet->zFts5Tbl);
201672      sqlite3Fts5Dequote(pRet->zFts5Db);
201673    }
201674  }
201675
201676  *ppVTab = (sqlite3_vtab*)pRet;
201677  return rc;
201678}
201679
201680
201681/*
201682** The xConnect() and xCreate() methods for the virtual table. All the
201683** work is done in function fts5VocabInitVtab().
201684*/
201685static int fts5VocabConnectMethod(
201686  sqlite3 *db,                    /* Database connection */
201687  void *pAux,                     /* Pointer to tokenizer hash table */
201688  int argc,                       /* Number of elements in argv array */
201689  const char * const *argv,       /* xCreate/xConnect argument array */
201690  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
201691  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
201692){
201693  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
201694}
201695static int fts5VocabCreateMethod(
201696  sqlite3 *db,                    /* Database connection */
201697  void *pAux,                     /* Pointer to tokenizer hash table */
201698  int argc,                       /* Number of elements in argv array */
201699  const char * const *argv,       /* xCreate/xConnect argument array */
201700  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
201701  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
201702){
201703  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
201704}
201705
201706/*
201707** Implementation of the xBestIndex method.
201708*/
201709static int fts5VocabBestIndexMethod(
201710  sqlite3_vtab *pUnused,
201711  sqlite3_index_info *pInfo
201712){
201713  int i;
201714  int iTermEq = -1;
201715  int iTermGe = -1;
201716  int iTermLe = -1;
201717  int idxNum = 0;
201718  int nArg = 0;
201719
201720  UNUSED_PARAM(pUnused);
201721
201722  for(i=0; i<pInfo->nConstraint; i++){
201723    struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
201724    if( p->usable==0 ) continue;
201725    if( p->iColumn==0 ){          /* term column */
201726      if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
201727      if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
201728      if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
201729      if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
201730      if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
201731    }
201732  }
201733
201734  if( iTermEq>=0 ){
201735    idxNum |= FTS5_VOCAB_TERM_EQ;
201736    pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
201737    pInfo->estimatedCost = 100;
201738  }else{
201739    pInfo->estimatedCost = 1000000;
201740    if( iTermGe>=0 ){
201741      idxNum |= FTS5_VOCAB_TERM_GE;
201742      pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
201743      pInfo->estimatedCost = pInfo->estimatedCost / 2;
201744    }
201745    if( iTermLe>=0 ){
201746      idxNum |= FTS5_VOCAB_TERM_LE;
201747      pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
201748      pInfo->estimatedCost = pInfo->estimatedCost / 2;
201749    }
201750  }
201751
201752  /* This virtual table always delivers results in ascending order of
201753  ** the "term" column (column 0). So if the user has requested this
201754  ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
201755  ** sqlite3_index_info.orderByConsumed flag to tell the core the results
201756  ** are already in sorted order.  */
201757  if( pInfo->nOrderBy==1
201758   && pInfo->aOrderBy[0].iColumn==0
201759   && pInfo->aOrderBy[0].desc==0
201760  ){
201761    pInfo->orderByConsumed = 1;
201762  }
201763
201764  pInfo->idxNum = idxNum;
201765  return SQLITE_OK;
201766}
201767
201768/*
201769** Implementation of xOpen method.
201770*/
201771static int fts5VocabOpenMethod(
201772  sqlite3_vtab *pVTab,
201773  sqlite3_vtab_cursor **ppCsr
201774){
201775  Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
201776  Fts5Index *pIndex = 0;
201777  Fts5Config *pConfig = 0;
201778  Fts5VocabCursor *pCsr = 0;
201779  int rc = SQLITE_OK;
201780  sqlite3_stmt *pStmt = 0;
201781  char *zSql = 0;
201782
201783  zSql = sqlite3Fts5Mprintf(&rc,
201784      "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
201785      pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
201786  );
201787  if( zSql ){
201788    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
201789  }
201790  sqlite3_free(zSql);
201791  assert( rc==SQLITE_OK || pStmt==0 );
201792  if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
201793
201794  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
201795    i64 iId = sqlite3_column_int64(pStmt, 0);
201796    pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
201797  }
201798
201799  if( rc==SQLITE_OK && pIndex==0 ){
201800    rc = sqlite3_finalize(pStmt);
201801    pStmt = 0;
201802    if( rc==SQLITE_OK ){
201803      pVTab->zErrMsg = sqlite3_mprintf(
201804          "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
201805      );
201806      rc = SQLITE_ERROR;
201807    }
201808  }
201809
201810  if( rc==SQLITE_OK ){
201811    int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
201812    pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
201813  }
201814
201815  if( pCsr ){
201816    pCsr->pIndex = pIndex;
201817    pCsr->pStmt = pStmt;
201818    pCsr->pConfig = pConfig;
201819    pCsr->aCnt = (i64*)&pCsr[1];
201820    pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
201821  }else{
201822    sqlite3_finalize(pStmt);
201823  }
201824
201825  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
201826  return rc;
201827}
201828
201829static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
201830  pCsr->rowid = 0;
201831  sqlite3Fts5IterClose(pCsr->pIter);
201832  pCsr->pIter = 0;
201833  sqlite3_free(pCsr->zLeTerm);
201834  pCsr->nLeTerm = -1;
201835  pCsr->zLeTerm = 0;
201836}
201837
201838/*
201839** Close the cursor.  For additional information see the documentation
201840** on the xClose method of the virtual table interface.
201841*/
201842static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
201843  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
201844  fts5VocabResetCursor(pCsr);
201845  sqlite3Fts5BufferFree(&pCsr->term);
201846  sqlite3_finalize(pCsr->pStmt);
201847  sqlite3_free(pCsr);
201848  return SQLITE_OK;
201849}
201850
201851
201852/*
201853** Advance the cursor to the next row in the table.
201854*/
201855static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
201856  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
201857  Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
201858  int rc = SQLITE_OK;
201859  int nCol = pCsr->pConfig->nCol;
201860
201861  pCsr->rowid++;
201862
201863  if( pTab->eType==FTS5_VOCAB_COL ){
201864    for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
201865      if( pCsr->aDoc[pCsr->iCol] ) break;
201866    }
201867  }
201868
201869  if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=nCol ){
201870    if( sqlite3Fts5IterEof(pCsr->pIter) ){
201871      pCsr->bEof = 1;
201872    }else{
201873      const char *zTerm;
201874      int nTerm;
201875
201876      zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
201877      if( pCsr->nLeTerm>=0 ){
201878        int nCmp = MIN(nTerm, pCsr->nLeTerm);
201879        int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
201880        if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
201881          pCsr->bEof = 1;
201882          return SQLITE_OK;
201883        }
201884      }
201885
201886      sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
201887      memset(pCsr->aCnt, 0, nCol * sizeof(i64));
201888      memset(pCsr->aDoc, 0, nCol * sizeof(i64));
201889      pCsr->iCol = 0;
201890
201891      assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
201892      while( rc==SQLITE_OK ){
201893        const u8 *pPos; int nPos;   /* Position list */
201894        i64 iPos = 0;               /* 64-bit position read from poslist */
201895        int iOff = 0;               /* Current offset within position list */
201896
201897        pPos = pCsr->pIter->pData;
201898        nPos = pCsr->pIter->nData;
201899        switch( pCsr->pConfig->eDetail ){
201900          case FTS5_DETAIL_FULL:
201901            pPos = pCsr->pIter->pData;
201902            nPos = pCsr->pIter->nData;
201903            if( pTab->eType==FTS5_VOCAB_ROW ){
201904              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
201905                pCsr->aCnt[0]++;
201906              }
201907              pCsr->aDoc[0]++;
201908            }else{
201909              int iCol = -1;
201910              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
201911                int ii = FTS5_POS2COLUMN(iPos);
201912                pCsr->aCnt[ii]++;
201913                if( iCol!=ii ){
201914                  if( ii>=nCol ){
201915                    rc = FTS5_CORRUPT;
201916                    break;
201917                  }
201918                  pCsr->aDoc[ii]++;
201919                  iCol = ii;
201920                }
201921              }
201922            }
201923            break;
201924
201925          case FTS5_DETAIL_COLUMNS:
201926            if( pTab->eType==FTS5_VOCAB_ROW ){
201927              pCsr->aDoc[0]++;
201928            }else{
201929              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
201930                assert_nc( iPos>=0 && iPos<nCol );
201931                if( iPos>=nCol ){
201932                  rc = FTS5_CORRUPT;
201933                  break;
201934                }
201935                pCsr->aDoc[iPos]++;
201936              }
201937            }
201938            break;
201939
201940          default:
201941            assert( pCsr->pConfig->eDetail==FTS5_DETAIL_NONE );
201942            pCsr->aDoc[0]++;
201943            break;
201944        }
201945
201946        if( rc==SQLITE_OK ){
201947          rc = sqlite3Fts5IterNextScan(pCsr->pIter);
201948        }
201949
201950        if( rc==SQLITE_OK ){
201951          zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
201952          if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
201953            break;
201954          }
201955          if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
201956        }
201957      }
201958    }
201959  }
201960
201961  if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
201962    while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
201963    assert( pCsr->iCol<pCsr->pConfig->nCol );
201964  }
201965  return rc;
201966}
201967
201968/*
201969** This is the xFilter implementation for the virtual table.
201970*/
201971static int fts5VocabFilterMethod(
201972  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
201973  int idxNum,                     /* Strategy index */
201974  const char *zUnused,            /* Unused */
201975  int nUnused,                    /* Number of elements in apVal */
201976  sqlite3_value **apVal           /* Arguments for the indexing scheme */
201977){
201978  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
201979  int rc = SQLITE_OK;
201980
201981  int iVal = 0;
201982  int f = FTS5INDEX_QUERY_SCAN;
201983  const char *zTerm = 0;
201984  int nTerm = 0;
201985
201986  sqlite3_value *pEq = 0;
201987  sqlite3_value *pGe = 0;
201988  sqlite3_value *pLe = 0;
201989
201990  UNUSED_PARAM2(zUnused, nUnused);
201991
201992  fts5VocabResetCursor(pCsr);
201993  if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
201994  if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
201995  if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
201996
201997  if( pEq ){
201998    zTerm = (const char *)sqlite3_value_text(pEq);
201999    nTerm = sqlite3_value_bytes(pEq);
202000    f = 0;
202001  }else{
202002    if( pGe ){
202003      zTerm = (const char *)sqlite3_value_text(pGe);
202004      nTerm = sqlite3_value_bytes(pGe);
202005    }
202006    if( pLe ){
202007      const char *zCopy = (const char *)sqlite3_value_text(pLe);
202008      pCsr->nLeTerm = sqlite3_value_bytes(pLe);
202009      pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
202010      if( pCsr->zLeTerm==0 ){
202011        rc = SQLITE_NOMEM;
202012      }else{
202013        memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
202014      }
202015    }
202016  }
202017
202018
202019  if( rc==SQLITE_OK ){
202020    rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
202021  }
202022  if( rc==SQLITE_OK ){
202023    rc = fts5VocabNextMethod(pCursor);
202024  }
202025
202026  return rc;
202027}
202028
202029/*
202030** This is the xEof method of the virtual table. SQLite calls this
202031** routine to find out if it has reached the end of a result set.
202032*/
202033static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
202034  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
202035  return pCsr->bEof;
202036}
202037
202038static int fts5VocabColumnMethod(
202039  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
202040  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
202041  int iCol                        /* Index of column to read value from */
202042){
202043  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
202044  int eDetail = pCsr->pConfig->eDetail;
202045  int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
202046  i64 iVal = 0;
202047
202048  if( iCol==0 ){
202049    sqlite3_result_text(
202050        pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
202051    );
202052  }else if( eType==FTS5_VOCAB_COL ){
202053    assert( iCol==1 || iCol==2 || iCol==3 );
202054    if( iCol==1 ){
202055      if( eDetail!=FTS5_DETAIL_NONE ){
202056        const char *z = pCsr->pConfig->azCol[pCsr->iCol];
202057        sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
202058      }
202059    }else if( iCol==2 ){
202060      iVal = pCsr->aDoc[pCsr->iCol];
202061    }else{
202062      iVal = pCsr->aCnt[pCsr->iCol];
202063    }
202064  }else{
202065    assert( iCol==1 || iCol==2 );
202066    if( iCol==1 ){
202067      iVal = pCsr->aDoc[0];
202068    }else{
202069      iVal = pCsr->aCnt[0];
202070    }
202071  }
202072
202073  if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
202074  return SQLITE_OK;
202075}
202076
202077/*
202078** This is the xRowid method. The SQLite core calls this routine to
202079** retrieve the rowid for the current row of the result set. The
202080** rowid should be written to *pRowid.
202081*/
202082static int fts5VocabRowidMethod(
202083  sqlite3_vtab_cursor *pCursor,
202084  sqlite_int64 *pRowid
202085){
202086  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
202087  *pRowid = pCsr->rowid;
202088  return SQLITE_OK;
202089}
202090
202091static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
202092  static const sqlite3_module fts5Vocab = {
202093    /* iVersion      */ 2,
202094    /* xCreate       */ fts5VocabCreateMethod,
202095    /* xConnect      */ fts5VocabConnectMethod,
202096    /* xBestIndex    */ fts5VocabBestIndexMethod,
202097    /* xDisconnect   */ fts5VocabDisconnectMethod,
202098    /* xDestroy      */ fts5VocabDestroyMethod,
202099    /* xOpen         */ fts5VocabOpenMethod,
202100    /* xClose        */ fts5VocabCloseMethod,
202101    /* xFilter       */ fts5VocabFilterMethod,
202102    /* xNext         */ fts5VocabNextMethod,
202103    /* xEof          */ fts5VocabEofMethod,
202104    /* xColumn       */ fts5VocabColumnMethod,
202105    /* xRowid        */ fts5VocabRowidMethod,
202106    /* xUpdate       */ 0,
202107    /* xBegin        */ 0,
202108    /* xSync         */ 0,
202109    /* xCommit       */ 0,
202110    /* xRollback     */ 0,
202111    /* xFindFunction */ 0,
202112    /* xRename       */ 0,
202113    /* xSavepoint    */ 0,
202114    /* xRelease      */ 0,
202115    /* xRollbackTo   */ 0,
202116  };
202117  void *p = (void*)pGlobal;
202118
202119  return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
202120}
202121
202122
202123
202124
202125
202126#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
202127
202128/************** End of fts5.c ************************************************/
202129